(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');

            var rawNum = $a.data('to') || '';
            var cleanNum = cleanPhoneNumber(rawNum);
            if (!cleanNum) return;

            // 표시용 번호
            var displayNum = getKoreanNumber(cleanNum);

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


            // 팝업 호출 (단일 번호)
            openCallPopupByNumbers(name, [{
                id: 'history_' + cleanNum,
                number: cleanNum,
                display: displayNum
            }]);
        });

        //검색
		$('#btn_search_history').off('click').on('click', ()=>{
			drawCallHistory();
		});
		$('#inp_board_search_history').off('keyup').on('keyup', (e)=>{
			if(e.keyCode == 13)	{$('#btn_search_history').trigger('click')}
		});


        $('.call_cont').off('scroll').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 searchval = $('#inp_board_search_history').val();
        let sublist = null;

        if($.trim(searchval) == ''){
            sublist = call_history_list.slice(offset, offset+history_pageinsize);
        }else{
            sublist = call_history_list.filter(item => gformatter.number(item.number).indexOf(searchval)>-1).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)
            );
        });
    }
})();
