
(function () {
	// 페이지 당 렌더 개수
	let address_pageinsize = 50;

	function bindAccordion() {
		$(".contact")
			.off("click.contactAccordion")
			.on("click.contactAccordion", ".accordion", function () {
				var $head = $(this);
				var $panel = $head.next(".accordion_panel");
				$head.toggleClass("open");
				$panel.stop(true, true).slideToggle(150);
			});
		$(".contact .accordion").addClass("open");
		$(".contact .accordion_panel").show();
	}

	const printFavorites = () => {
		if (!Array.isArray(favoriteContact)) {
			try { favoriteContact = window.localStorage.getArray("favorite") || []; } catch (e) { favoriteContact = []; }
		}
		var $wrap = $("#address_list_favorites");
		$wrap.empty();
		if (!Array.isArray(newContact) || newContact.length === 0) return;

		// id → contact 맵
		var map = {};
		for (var i = 0; i < newContact.length; i++) {
			var contact = newContact[i];
			if (contact && contact.id != null) map[String(contact.id)] = contact;
		}

		for (var k = 0; k < favoriteContact.length; k++) {
			var favId = String(favoriteContact[k] || "");
			var contact = map[favId];
			if (!contact || !contact.displayName || !Array.isArray(contact.phoneNumbers) || contact.phoneNumbers.length === 0) continue;

			var p = contact.phoneNumbers[0] || {};
			var numDisp = p.number || p.normalizedNumber || "";

			var favInputId = "fav_" + contact.id; // ★ label for 연결

			var html = $('#li_address_item_template').text()
				.replace(/{{id}}/g, String(contact.id))
				.replace(/{{favInputId}}/g, favInputId)
				.replace(/{{thumb}}/g, getThumbImage(contact.thumbnail))
				.replace(/{{name}}/g, contact.displayName || "")
				.replace(/{{num}}/g, numDisp || "")
				.replace(/{{checkedAttr}}/g, 'checked');
			var $li = $(html);
			$li.attr('data-contact', JSON.stringify(contact));
			$wrap.append($li);
		}
	}

	const drawAddressList = (offset = 0) => {
		let allContacts = window.localStorage.getArray('contact', 'list');
		let favoriteIds = window.localStorage.getArray('favorite', 'list');
		let favoriteSet = {};
		for (let i = 0; i < favoriteIds.length; i++) favoriteSet[String(favoriteIds[i])] = true;

		// 범위 체크
		if (offset >= allContacts.length) return;

		// 처음 호출이면 비우기
		if (offset === 0) {
			$('#address_list_favorites').empty()
			$('#address_list_all').empty();
		}

		let q = $.trim($('#inp_board_search_address').val());
		let nodes = [];
		let contactSlice;

		function isHit(contact) {
			var name = (contact.displayName||'').toLowerCase();
			var cho = (contact.nameCho||'');
			if (name.indexOf(q.toLowerCase()) > -1) return true;
			if (cho && cho.indexOf(q) > -1) return true;
			if (!Array.isArray(contact.phoneNumbers)) return false;
			// if (!qDigits) return false;
			for (var j = 0; j < contact.phoneNumbers.length; j++) {
				var phoneNumberInfo = contact.phoneNumbers[j] || {};
				if (gformatter.number(phoneNumberInfo.normalizedNumber || phoneNumberInfo.number).indexOf(q) > -1) return true;
			}
			return false;
		}

		if(q != ''){
			let filterdContacts = [];
			allContacts.map(item => {
				if (!isHit(item)) return;
				filterdContacts.push(item);
			});
			contactSlice = filterdContacts.slice(offset, offset + address_pageinsize);
		}else{
			printFavorites();
			contactSlice = allContacts.slice(offset, offset + address_pageinsize);   
		}
		
		for (let k = 0; k < contactSlice.length; k++) {
			var contact = contactSlice[k];
			if (!contact || !contact.displayName || !Array.isArray(contact.phoneNumbers) || !contact.phoneNumbers.length) continue;

			let isFavoriteChecked = !!favoriteSet[String(contact.id || '')];
			let $item = createAddressItem(contact, isFavoriteChecked);
			
			if ($item) nodes.push($item[0]);
		}
		console.log('address append list ::', nodes.length);
		if (nodes.length) {
			$('#address_list_all').append(nodes);
			console.log('address list length :: ',$('#address_list_all > li').length);
		}
	}

	const createAddressItem = (contact, checked) => {
		if (!contact || !Array.isArray(contact.phoneNumbers) || !contact.phoneNumbers.length) return null;

		var firstPhone = contact.phoneNumbers[0] || {};
		var displayNumber = firstPhone.number || firstPhone.normalizedNumber || '';
		var favoriteInputId = 'fav_' + contact.id;

		var tpl = $('#li_address_item_template').text() || '';
		var html = tpl
			.replace(/{{id}}/g, String(contact.id))
			.replace(/{{favInputId}}/g, favoriteInputId)
			.replace(/{{checkedAttr}}/g, checked ? ' checked' : '')
			.replace(/{{thumb}}/g, getThumbImage(contact.thumbnail))
			.replace(/{{name}}/g, contact.displayName || '')
			.replace(/{{num}}/g, displayNumber || '');

		// 문자열 → jQuery 엘리먼트로 변환한 뒤, data 저장
		var $li = $(html);
		$li.attr('data-contact', JSON.stringify(contact));

		return $li;
	}

	$(function () {
		$('div.accordion').addClass('open');
		$(".contact .accordion_panel").show();
		drawAddressList();
		bindAccordion();
	
		$("#address_list_favorites, #address_list_all")
		.on("change.addrFav", ".favchk", function (e) {
			e.stopPropagation();
			favoriteContact = localStorage.getArray("favorite", 'list');
			var id = String($(this).closest("li").data("id") || "");
			if (!id) return;
			var idx = favoriteContact.indexOf(id);
			if (idx === -1) favoriteContact.push(id);
			else favoriteContact.splice(idx, 1);
			window.localStorage.setArray("favorite", favoriteContact);
			printFavorites();
			// 전체 목록에도 체크 반영
			$("#address_list_all li[data-id='" + id + "'] .favchk").prop("checked", favoriteContact.indexOf(id) > -1);
		});
	
		// 주소록 검색
		$('#btn_search_address').off('click').on('click', ()=>{
			drawAddressList();
		});
		$('#inp_board_search_address').off('keyup').on('keyup', (e)=>{
			if(e.keyCode == 13)	{$('#btn_search_address').trigger('click')}
		});
	
		// 통화 버튼 공통 콜 팝업 열기
		$(document)
		.off('click.addrCall', '#address_list_favorites .call, #address_list_all .call')
		.on('click.addrCall', '#address_list_favorites .call, #address_list_all .call', function (e) {
			e.preventDefault();

			var $li = $(this).closest('li');
			var contact = $li.data('contact')||{};
			if (!contact) {
				try { contact = JSON.parse($li.attr('data-contact') || '{}'); } catch (err) { contact = null; }
			}
			if (!contact) return;

			var name = gformatter.string(contact.displayName);
			var phones = [];

			if (Array.isArray(contact.phoneNumbers)) {
				for (var i = 0; i < contact.phoneNumbers.length; i++) {
					var p = contact.phoneNumbers[i] || {};
					var raw = p.normalizedNumber || p.number || '';
					var clean = cleanPhoneNumber(raw);
					if (!clean) continue;

					var display = p.number || getKoreanNumber(clean) || clean;
					var type = p.type || '기타';

					phones.push({
						id: (contact.id != null ? String(contact.id) : '') + '_' + i,
						number: clean,
						display: display,
						type: type
					});
				}
			}

			// 공통 팝업 호출
			openCallPopupByNumbers(name, phones);
		});
	
		// 스크롤 바닥 도달 시 다음 페이지 로딩
		$('.call_cont').off('scroll').bind('scroll', () => {
			// 검색 중이면 페이징 중단
			var searchQuery = $.trim($('#inp_board_search_address').val() || '');
			var hasEnoughSearchText = (typeof getByteLengthOfString === 'function')
				? (getByteLengthOfString(searchQuery) > 1)
				: (searchQuery.length > 1);
			if (hasEnoughSearchText) return;
	
			var $cont = $('.call_cont');
			if (!$cont.length || !$cont[0]) return;
	
			var renderedCount = $('#address_list_all > li').length;
			var pageSize = Number(address_pageinsize || 30);
	
			// 바닥 판정
			var el = $cont[0];
			var atBottom = (el.scrollTop + $cont.innerHeight()) >= (el.scrollHeight - 2);
	
			if (renderedCount >= pageSize && atBottom) {
				drawAddressList(renderedCount);
			}
		});
	});
})();
