const PHONE_GEO=[["1684","as"],["1264","ai"],["1268","ag"],["1242","bs"],["1246","bb"],["1441","bm"],["1767","dm"],["1849","do"],["1473","gd"],["1671","gu"],["1876","jm"],["1664","ms"],["1670","mp"],["1939","pr"],["1869","kn"],["1758","lc"],["1784","vc"],["1868","tt"],["1649","tc"],["1284","vg"],["1340","vi"],["358","ax"],["355","al"],["213","dz"],["376","ad"],["244","ao"],["672","aq"],["374","am"],["297","aw"],["994","az"],["973","bh"],["880","bd"],["375","by"],["501","bz"],["229","bj"],["975","bt"],["591","bo"],["387","ba"],["267","bw"],["246","io"],["673","bn"],["359","bg"],["226","bf"],["257","bi"],["855","kh"],["237","cm"],["238","cv"],["345","ky"],["236","cf"],["235","td"],["269","km"],["242","cg"],["243","cd"],["682","ck"],["506","cr"],["225","ci"],["385","hr"],["357","cy"],["420","cz"],["253","dj"],["593","ec"],["503","sv"],["240","gq"],["291","er"],["372","ee"],["251","et"],["500","fk"],["298","fo"],["679","fj"],["358","fi"],["594","gf"],["689","pf"],["241","ga"],["220","gm"],["995","ge"],["233","gh"],["350","gi"],["299","gl"],["590","gp"],["502","gt"],["224","gn"],["245","gw"],["595","gy"],["509","ht"],["379","va"],["504","hn"],["852","hk"],["354","is"],["964","iq"],["353","ie"],["972","il"],["962","jo"],["254","ke"],["686","ki"],["850","kp"],["965","kw"],["996","kg"],["856","la"],["371","lv"],["961","lb"],["266","ls"],["231","lr"],["218","ly"],["423","li"],["370","lt"],["352","lu"],["853","mo"],["389","mk"],["261","mg"],["265","mw"],["960","mv"],["223","ml"],["356","mt"],["692","mh"],["596","mq"],["222","mr"],["230","mu"],["262","yt"],["691","fm"],["373","md"],["377","mc"],["976","mn"],["382","me"],["212","ma"],["258","mz"],["264","na"],["674","nr"],["977","np"],["599","an"],["687","nc"],["505","ni"],["227","ne"],["234","ng"],["683","nu"],["672","nf"],["968","om"],["680","pw"],["970","ps"],["507","pa"],["675","pg"],["595","py"],["872","pn"],["351","pt"],["974","qa"],["262","re"],["250","rw"],["590","bl"],["290","sh"],["590","mf"],["508","pm"],["685","ws"],["378","sm"],["239","st"],["966","sa"],["221","sn"],["381","rs"],["248","sc"],["232","sl"],["421","sk"],["386","si"],["677","sb"],["252","so"],["500","gs"],["211","ss"],["249","sd"],["597","sr"],["268","sz"],["963","sy"],["886","tw"],["992","tj"],["255","tz"],["670","tl"],["228","tg"],["690","tk"],["676","to"],["216","tn"],["993","tm"],["688","tv"],["256","ug"],["380","ua"],["971","ae"],["598","uy"],["998","uz"],["678","vu"],["681","wf"],["967","ye"],["260","zm"],["263","zw"],["93","af"],["54","ar"],["61","au"],["43","at"],["32","be"],["55","br"],["56","cl"],["86","cn"],["61","cx"],["61","cc"],["57","co"],["53","cu"],["45","dk"],["20","eg"],["33","fr"],["49","de"],["30","gr"],["44","gg"],["36","hu"],["91","in"],["62","id"],["98","ir"],["44","im"],["39","it"],["81","jp"],["44","je"],["77","kz"],["82","kr"],["60","my"],["52","mx"],["95","mm"],["31","nl"],["64","nz"],["47","no"],["92","pk"],["51","pe"],["63","ph"],["48","pl"],["40","ro"],["65","sg"],["27","za"],["34","es"],["94","lk"],["47","sj"],["46","se"],["41","ch"],["66","th"],["90","tr"],["44","gb"],["58","ve"],["84","vn"],["1","us"],["7","ru"],["1","ca"]];

const GEO_NAMES = {ru:"Россия",us:"США",ua:"Украина",kz:"Казахстан",by:"Беларусь",id:"Индонезия",vn:"Вьетнам",br:"Бразилия",in:"Индия",pk:"Пакистан",ng:"Нигерия",bd:"Бангладеш",mx:"Мексика",ph:"Филиппины",eg:"Египет",et:"Эфиопия",ir:"Иран",tr:"Турция",de:"Германия",th:"Таиланд",gb:"Великобритания",fr:"Франция",it:"Италия",za:"ЮАР",ke:"Кения",co:"Колумбия",es:"Испания",ar:"Аргентина",ca:"Канада",pe:"Перу",ve:"Венесуэла",ma:"Марокко",pl:"Польша",ht:"Гаити",cn:"Китай",jp:"Япония",kr:"Южная Корея",af:"Афганистан",al:"Албания",dz:"Алжир",ad:"Андорра",ao:"Ангола",am:"Армения",au:"Австралия",at:"Австрия",az:"Азербайджан",bh:"Бахрейн",be:"Бельгия",bj:"Бенин",bo:"Боливия",ba:"Босния",bw:"Ботсвана",bg:"Болгария",cm:"Камерун",cl:"Чили",cr:"Коста-Рика",hr:"Хорватия",cu:"Куба",cy:"Кипр",cz:"Чехия",dk:"Дания",ec:"Эквадор",ee:"Эстония",fi:"Финляндия",gh:"Гана",gr:"Греция",hk:"Гонконг",hu:"Венгрия",ie:"Ирландия",il:"Израиль",jo:"Иордания",my:"Малайзия",nl:"Нидерланды",nz:"Новая Зеландия",no:"Норвегия",ro:"Румыния",sg:"Сингапур",lk:"Шри-Ланка",se:"Швеция",ch:"Швейцария"};

function getGeoCodeFromPhone(phone) {
    if (!phone || typeof phone !== 'string') return null;
    let num = phone.replace(/\D/g, '');
    if (num.length < 6) return null;
    for (let i = 0; i < PHONE_GEO.length; i++) {
        let [prefix, code] = PHONE_GEO[i];
        if (num === prefix || num.startsWith(prefix)) return code.toLowerCase();
    }
    return null;
}

function getGeoFromPhone(phone) {
    let code = getGeoCodeFromPhone(phone);
    if (!code) return {html: '—', code: null};

    let up = code.toUpperCase();
    let flag = '<img src="img/geo_flags/' + code + '.png" alt="' + up + '" class="geo-flag" loading="lazy" decoding="async">';
    return {
        html: '<span class="geo-code">' + up + '</span> ' + flag,
        code: code
    };
}

function getGeoName(code) {
    return GEO_NAMES[code] || (code ? code.toUpperCase() : '—');
}

function injectGeoColumn($list) {
    $list = $list && $list.length ? $list : $('#list').first();
    if (!$list.length) return;

    $list.find('tr').each(function() {
        let $phone = $(this).find('td#phone');
        if ($phone.length && !$(this).find('td.geo-cell').length) {
            let g = getGeoFromPhone($phone.text().trim());
            let dataGeo = g.code ? ' data-geo="' + g.code + '"' : '';
            $phone.after('<td class="geo-cell notranslate"' + dataGeo + '>' + g.html + '</td>');
        }
    });
}

function getGeoStats($list) {
    $list = $list || $('#list').first();
    let stats = {};
    $list.find('tr').each(function() {
        let code = $(this).find('td.geo-cell').attr('data-geo');
        if (code) { stats[code] = (stats[code] || 0) + 1; }
    });
    return stats;
}

function getGeoFilterApplied() { return typeof geoFilterApplied !== 'undefined' ? geoFilterApplied : []; }

function applyGeoFilter(codes) {
    let $list = $('#list').first();
    if (!codes || codes.length === 0) {
        $list.find('tr').removeClass('d-none');
        return;
    }
    $list.find('tr').each(function() {
        let code = $(this).find('td.geo-cell').attr('data-geo');
        $(this).toggleClass('d-none', !code || codes.indexOf(code) === -1);
    });
}

let geoFilterSelected = [];
let geoFilterApplied = [];

function initGeoFilter() {
    if ($('#geo_filter_modal').length === 0) return;

    $(document).on('click', '.geo-filter-btn', function() {
        let stats = getGeoStats();
        let items = Object.entries(stats).sort((a,b)=>b[1]-a[1]);
        geoFilterSelected = geoFilterApplied.slice();
        let html = '';

        items.forEach(function([code, cnt]) {
            code = String(code).toLowerCase();
            html += '<div class="geo-filter-item d-flex align-items-center p-2 border-bottom" data-code="'+code+'" style="cursor:pointer">';
            html += '<img src="img/geo_flags/'+code+'.png" alt="' + code.toUpperCase() + '" class="geo-flag geo-flag-lg mr-2" loading="lazy" decoding="async">';
            html += '<span class="flex-grow-1">'+getGeoName(code)+'</span>';
            html += '<span class="badge badge-secondary" style="font-size:0.83em;">'+cnt+'</span>';
            html += '</div>';
        });

        $('#geo_filter_list').html(html || '<div class="p-3 text-muted">Нет данных</div>');
        renderGeoFilterTags();
        $('#geo_filter_modal').modal('show');
    });

    $(document).on('click', '.geo-filter-item', function() {
        let code = String($(this).data('code')).toLowerCase();
        let idx = geoFilterSelected.indexOf(code);
        if (idx >= 0) geoFilterSelected.splice(idx, 1);
        else geoFilterSelected.push(code);
        $(this).toggleClass('bg-primary text-white', geoFilterSelected.indexOf(code) >= 0);
        renderGeoFilterTags();
    });

    $('#geo_filter_clear').on('click', function() {
        geoFilterSelected = [];
        geoFilterApplied = [];
        $('.geo-filter-item').removeClass('bg-primary text-white');
        renderGeoFilterTags();
        applyGeoFilter([]);
        $('#geo_filter_modal').modal('hide');
        if (typeof table_mark === 'function') table_mark();
    });

    $('#geo_filter_apply').on('click', function() {
        geoFilterApplied = geoFilterSelected.slice();
        applyGeoFilter(geoFilterSelected);
        $('#geo_filter_modal').modal('hide');
        if (typeof table_mark === 'function') table_mark();
    });
}

function renderGeoFilterTags() {
    let html = '';
    geoFilterSelected.forEach(function(code) {
        code = String(code).toLowerCase();
        html += '<span class="badge badge-primary mr-1 mb-1 d-inline-flex align-items-center">';
        html += '<img src="img/geo_flags/'+code+'.png" alt="' + code.toUpperCase() + '" class="geo-flag geo-flag-sm mr-1" loading="lazy" decoding="async">';
        html += code.toUpperCase() + ' <i class="fas fa-times ml-1 geo-tag-remove" data-code="'+code+'" style="cursor:pointer"></i>';
        html += '</span>';
    });
    $('#geo_filter_tags').html(html);
    $('.geo-filter-item').removeClass('bg-primary text-white');
    geoFilterSelected.forEach(function(code) {
        $('.geo-filter-item[data-code="'+String(code).toLowerCase()+'"]').addClass('bg-primary text-white');
    });
}

$(function() {
    $(document).on('click', '.geo-tag-remove', function(e) {
        e.stopPropagation();
        let code = String($(this).data('code')).toLowerCase();
        geoFilterSelected = geoFilterSelected.filter(c=>c!==code);
        renderGeoFilterTags();
    });
    initGeoFilter();
});