(function () {
	// 배열 읽기
	function readArray(key) {
		try { return window.localStorage.getArray(key) || []; }
		catch (e) { return []; }
	}

	// 배열 저장
	function saveArray(key, arr) {
		try { window.localStorage.setArray(key, arr); } catch (e) { }
	}

	// 상태
	var newContact = [];
	var favoriteContact = [];
	var contactMap = {}; // id -> contact

	// 데이터 보정
	function ensureData() {
		newContact = readArray("contact");
		favoriteContact = readArray("favorite");
		if (!Array.isArray(favoriteContact)) {
			favoriteContact = [];
			saveArray("favorite", favoriteContact);
		}
		buildContactMap(newContact);
	}

	// 맵 구성
	function buildContactMap(list) {
		contactMap = {};
		for (var i = 0; i < list.length; i++) {
			var c = list[i];
			if (!c) continue;
			var id = (c.id != null) ? String(c.id) : "";
			if (id) contactMap[id] = c;
		}
	}

	// 즐겨찾기 여부
	function isFavorite(id) {
		id = String(id || "");
		return favoriteContact.indexOf(id) > -1;
	}

	// 즐겨찾기 토글
	function toggleFavorite(id) {
		id = String(id || "");
		var i = favoriteContact.indexOf(id);
		if (i === -1) favoriteContact.push(id);
		else favoriteContact.splice(i, 1);
		saveArray("favorite", favoriteContact);
	}

	// 대표번호
	function getMainPhone(contact) {
		var list = Array.isArray(contact.phoneNumbers) ? contact.phoneNumbers : [];
		return list.length ? list[0] : null;
	}

	// 표시용 번호
	function displayNumber(p) {
		if (!p) return "";
		var raw = p.number || p.normalizedNumber || "";
		try {
			if (typeof getKoreanNumber === "function") {
				return p.number || getKoreanNumber(p.normalizedNumber || "") || raw;
			}
		} catch (e) { }
		return raw;
	}

	// 썸네일
	function thumb(contact) {
		try {
			if (typeof getThumbImage === "function") return getThumbImage(contact.thumbnail);
		} catch (e) { }
		return "images/thumb.png";
	}

	// li HTML
	function itemHTML(contact, inFavSection) {
		var id = String(contact.id || "");
		var main = getMainPhone(contact);
		var numText = main ? (main.number || displayNumber(main) || "") : "";
		var favInputId = "fav_" + id + (inFavSection ? "_f" : "_a");
		var checked = isFavorite(id) ? ' checked' : '';
		return '' +
			'<li data-id="' + id + '">' +
			'  <div class="accordion_list">' +
			'    <div class="fav">' +
			'      <input type="checkbox" id="' + favInputId + '"' + checked + '>' +
			'      <label for="' + favInputId + '"></label>' +
			'    </div>' +
			'    <div class="thumb" style="background-image:url(\'' + thumb(contact) + '\')"></div>' +
			'    <div class="who">' +
			'      <div class="name">' + (contact.displayName || "") + '</div>' +
			'      <div class="num">' + (numText || "") + '</div>' +
			'    </div>' +
			'  </div>' +
			'  <a href="#" class="call" aria-label="통화"></a>' +
			'</li>';
	}

	// 즐겨찾기 렌더
	function renderFavorites() {
		var html = "";
		for (var i = 0; i < favoriteContact.length; i++) {
			var id = String(favoriteContact[i] || "");
			var c = contactMap[id];
			if (!c || !c.displayName || !Array.isArray(c.phoneNumbers)) continue;
			html += itemHTML(c, true);
		}
		$("#list_favorites").html(html);
	}

	// 전체 렌더
	function renderAll() {
		var html = "";
		for (var i = 0; i < newContact.length; i++) {
			var c = newContact[i];
			if (!c || !c.displayName || !Array.isArray(c.phoneNumbers)) continue;
			html += itemHTML(c, false);
		}
		$("#list_all").html(html);
	}

	// 전체 새로고침
	function refreshLists() {
		renderFavorites();
		renderAll();
	}

	// 통화 팝업 DOM
	// function ensureCallPopup() {
	// 	var $layer = $(".dim_bg.call_pop");
	// 	if ($layer.length) return $layer;

	// 	$layer = $(
	// 		'<div class="dim_bg call_pop" style="display:none;">' +
	// 		'  <div class="popup" role="dialog" aria-modal="true">' +
	// 		'    <h3 class="call_title"></h3>' +
	// 		'    <span class="popup_close" aria-label="닫기"></span>' +
	// 		'    <div class="popup_container">' +
	// 		'      <form class="call_form" method="post" action="">' +
	// 		'        <div class="cont_box">' +
	// 		'          <ul class="call_num" id="call_num_list"></ul>' +
	// 		'        </div>' +
	// 		'        <p class="popup_btn">' +
	// 		'          <button type="button" class="btn blue" id="btn_callthrough">안심통화</button>' +
	// 		'          <button type="button" class="btn blue" id="btn_clicktocall">휴대폰 통화</button>' +
	// 		'        </p>' +
	// 		'      </form>' +
	// 		'    </div>' +
	// 		'  </div>' +
	// 		'</div>'
	// 	);
	// 	$("body").append($layer);
	// 	bindCallPopupEvents($layer);
	// 	return $layer;
	// }

	// 통화 팝업 이벤트
	// function bindCallPopupEvents($layer) {
	// 	$layer.on("click.addr", ".popup_close", function (e) {
	// 		e.preventDefault();
	// 		closeCallPopup();
	// 	});
	// 	$layer.on("click.addr", function (e) {
	// 		if (e.target !== this) return;
	// 		closeCallPopup();
	// 	});
	// 	$layer.on("click.addr", "#btn_callthrough", function (e) {
	// 		e.preventDefault();
	// 		var data = $layer.data("ctx") || {};
	// 		var sel = getSelectedNumber();
	// 		if (!sel) return;
	// 		try { callthrough(String(data.callId || sel.id), sel.number, sel.type || "기타"); } catch (_) { }
	// 		closeCallPopup();
	// 	});
	// 	$layer.on("click.addr", "#btn_clicktocall", function (e) {
	// 		e.preventDefault();
	// 		var data = $layer.data("ctx") || {};
	// 		var sel = getSelectedNumber();
	// 		if (!sel) return;
	// 		try { clickToCall(String(data.callId || sel.id), sel.number, sel.type || "기타"); } catch (_) { }
	// 		closeCallPopup();
	// 	});

	// 	function getSelectedNumber() {
	// 		var $checked = $layer.find('input[name="num"]:checked');
	// 		if ($checked.length === 0) return null;
	// 		return {
	// 			id: $checked.data("id") || "",
	// 			number: $checked.val() || "",
	// 			type: $checked.data("type") || "기타"
	// 		};
	// 	}
	// }

	// 통화 팝업 열기
	function openCallPopup(contact) {
		var $popup = $('.call_pop');
		var $list = $popup.find("#call_num_list").empty();

		var name = contact.displayName || "";
		var phones = Array.isArray(contact.phoneNumbers) ? contact.phoneNumbers : [];

		$popup.find(".call_title").text(name);
		$popup.removeClass("none None is-hidden");

		if (!phones.length) {
			$list.append('<li><span>번호 없음</span></li>');
			$popup.find("#btn_callthrough, #btn_clicktocall").prop("disabled", true);
		} else {
			$popup.find("#btn_callthrough, #btn_clicktocall").prop("disabled", false);
			var html = "";
			for (var i = 0; i < phones.length; i++) {
				var p = phones[i] || {};
				var raw = p.normalizedNumber || p.number || "";
				var disp = p.number || displayNumber(p) || raw || "";
				var typ = p.type || "기타";
				var radioId = "num_" + (contact.id || "c") + "_" + i;
				html += '' +
					'<li>' +
					'  <input type="radio" name="num" id="' + radioId + '" value="' + raw + '" data-id="' + (contact.id || '') + '" data-type="' + typ + '"' + (i === 0 ? ' checked' : '') + '>' +
					'  <label for="' + radioId + '">' + disp + (typ ? ' (' + typ + ')' : '') + '</label>' +
					'</li>';
			}
			$list.html(html);
		}
		$popup.data('dialPrefix', "");
		$popup.removeClass('none');
	}

	// 통화 팝업 닫기
	function closeCallPopup() {
		$(".dim_bg.call_pop").hide().removeClass("none");
	}

	// 아코디언
	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();
	}

	// 이벤트 위임
	function bindDelegates() {
		// 즐겨찾기 토글
		$("#list_favorites, #list_all").off("change.addrFav").on("change.addrFav", ".fav input[type=checkbox]", function (e) {
			e.stopPropagation();
			var $li = $(this).closest("li");
			var id = String($li.data("id") || "");
			if (!id) return;
			toggleFavorite(id);
			renderFavorites();  
			var inAll = $("#list_all li[data-id='" + id + "'] .fav input[type=checkbox']");
			if (inAll.length) inAll.prop("checked", isFavorite(id));
		});

		// 통화 버튼
		$("#list_favorites, #list_all").off("click.addrCall").on("click.addrCall", "a.call", function (e) {
			e.preventDefault();
			var $li = $(this).closest("li");
			var id = String($li.data("id") || "");
			var contact = contactMap[id];
			if (contact) openCallPopup(contact);
		});
	}

	// 초기
	$(function () {
		ensureData();
		bindAccordion();
		bindDelegates();
		renderFavorites();
		renderAll();
	});
})();
