(function () {
    'use strict';
    let history_pageinsize = 50;
    $(() => {
        // call_history_list
        drawCallHistory();

        // 통화이력 공통 콜 팝업
        $(document)
            .off('click.historyCall', '.call_cont ul.recent .call')
            .on('click.historyCall', '.call_cont ul.recent .call', function (e) {
                e.preventDefault();

                var $a = $(this);
                var $li = $a.closest('li');

                // 숫자 정리 유틸 (cleanPhoneNumber가 있으면 그걸 우선 사용)
                function onlyDigits(s) { return String(s == null ? '' : s).replace(/\D+/g, ''); }
                var rawNum = $a.data('number') || '';
                var cleanNum = (typeof cleanPhoneNumber === 'function') ? cleanPhoneNumber(rawNum) : onlyDigits(rawNum);
                if (!cleanNum) return;

                // 표시용 번호
                var displayNum = (typeof getKoreanNumber === 'function')
                    ? getKoreanNumber(cleanNum)
                    : (typeof gformatter !== 'undefined' && gformatter && gformatter.tel ? gformatter.tel(cleanNum) : cleanNum);

                var name = $.trim($li.find('.who .name').text()) || displayNum;

                var dialPrefix = '';
                try {
                    var region = (window.serverData && serverData.region_number) || '';
                    var svcPre = (window.serverData && serverData.svcPrefixNo) || '';
                    var umap = window.user_map || {};
                    for (var k in umap) {
                        if (!umap.hasOwnProperty(k)) continue;
                        var cid = onlyDigits(umap[k].cid_no);
                        if (!cid) continue;
                        if (cleanNum === cid || cleanNum === (region + cid) || (svcPre && cleanNum === (svcPre + cid))) {
                            dialPrefix = svcPre; // 대표번호(내선)로 판단되면 prefix 적용
                            break;
                        }
                    }
                } catch (_) { }

                // 팝업 호출 (단일 번호)
                openCallPopupByNumbers(name, [{
                    id: 'history_' + cleanNum,
                    number: cleanNum,
                    display: displayNum,
                    type: dialPrefix ? '대표번호' : '휴대폰'
                }], {
                    callId: 'history_' + cleanNum,
                    dialPrefix: dialPrefix
                });
            });

        $('.call_cont').bind('scroll', () => {
            if ($('.call_cont ul.recent>li').length >= history_pageinsize && $('.call_cont')[0].scrollHeight - Math.ceil($('.call_cont').scrollTop()) <= $('.call_cont').outerHeight()) {
                drawCallHistory($('.call_cont ul.recent>li').length);
            }
        });
    });

    function drawCallHistory(offset = 0){
        if(offset >= call_history_list.length) return;
        if(offset == 0){
            $('.call_cont ul.recent').empty();
        }

        let sublist = call_history_list.slice(offset, offset+history_pageinsize);
        sublist.forEach((callhistory, idx) => {

            let userMapArray = Object.values(user_map); // 수정: userMap을 배열로 변환
            let finduser = userMapArray.find(user => { // 수정: userMapArray에서 번호를 찾음
                return user.cid_no == nomalizeNumber(callhistory.number) || `${serverData.svcPrefixNo}${user.cid_no}` == nomalizeNumber(callhistory.number) || user.mobile_no == nomalizeNumber(callhistory.number);
            });

            if (finduser == undefined) {
                let contacts = localStorage.getArray("contact");
                finduser = contacts.find(contact => {
                    let phoneNumbers = contact.phoneNumbers;
                    let isFind = false;
                    for (let pnumber of phoneNumbers) {
                        if (pnumber.normalizedNumber == nomalizeNumber(callhistory.number)) {
                            isFind = true;
                            contact.name = contact.displayName;
                            break;
                        }
                    }
                    return isFind;
                });
            }

            $('.call_cont ul.recent').append(
                $('#li_call_history_template').text()
                    .replace(/{{name}}/g, (finduser?.name||''))
                    .replace(/{{number}}/g, gformatter.tel(callhistory.number))
                    .replace(/{{nomalizedNumber}}/g, callhistory.number)
                    .replace(/{{date_time}}/g, callhistory.date_time)
            );
        });
    }
})();
