/**
 * Shipping rules admin UI — AfriRegions
 *
 * Depends on scpwoo_shipping_params (via wp_localize_script).
 */
jQuery(function($){
    'use strict';

    if (typeof scpwoo_shipping_params === 'undefined') return;

    var p = scpwoo_shipping_params;
    var RbyC = p.regions_by_country;
    var PbyC = p.places_by_country;
    var HbyC = p.neighborhoods_by_country;
    var countries = Array.isArray(p.countries) ? p.countries : [];
    var countryNames = p.country_names;
    var multiCountry = countries.length > 1;
    var rules = Array.isArray(p.rules) ? p.rules : [];
    var cur = p.currency;
    var i18n = p.i18n;
    var editingIdx = -1;
    var pendingUndo = null;

    /* ── Helpers ── */
    function findCountryForRegion(rc) {
        for (var cc in RbyC) { if (RbyC[cc] && RbyC[cc][rc] !== undefined) return cc; }
        return countries.length === 1 ? countries[0] : '';
    }
    function getRegionName(cc, rc) {
        if (cc && RbyC[cc] && RbyC[cc][rc]) return RbyC[cc][rc];
        for (var c in RbyC) { if (RbyC[c] && RbyC[c][rc]) return RbyC[c][rc]; }
        return rc;
    }
    function getCities(cc, rc) { return (cc && PbyC[cc] && PbyC[cc][rc]) ? PbyC[cc][rc] : []; }
    function getHoods(cc, city) { return (cc && HbyC[cc] && HbyC[cc][city]) ? HbyC[cc][city] : []; }

    function esc(s) { return $('<span>').text(s).html(); }
    function sync() { $('#scpwoo-json').val(JSON.stringify(rules)); updateCount(); }

    function toast(msg, type) {
        type = type || 'success';
        if (window.scpwooToast) { window.scpwooToast(msg, type); return; }
        var wpCls = type === 'error' ? 'notice-error' : (type === 'warning' ? 'notice-warning' : 'notice-success');
        var $n = $('<div class="notice ' + wpCls + ' is-dismissible"><p>' + esc(msg) + '</p></div>');
        $('#scpwoo-wrap').prepend($n);
        setTimeout(function () { $n.fadeOut(300, function () { $n.remove(); }); }, 5000);
    }

    function updateCount() {
        var $h = $('.scpwoo-rules-title');
        var $badge = $h.find('.scpwoo-rules-count');
        if (!$badge.length) $badge = $('<span class="scpwoo-rules-count"></span>').appendTo($h);
        $badge.text(i18n.rulesCount.replace('%d', rules.length));
    }

    function typeLabel(t) {
        if (t === 'region') return i18n.typeRegion;
        if (t === 'city') return i18n.typeCity;
        return i18n.typeNeighborhood;
    }

    /* ── Field validation helpers ── */
    function showFieldError(sel, msg) {
        var $f = $(sel);
        $f.addClass('scpwoo-field-invalid');
        var $e = $f.next('.scpwoo-field-error');
        if (!$e.length) $e = $('<small class="scpwoo-field-error"></small>').insertAfter($f);
        $e.text(msg);
        $f.one('change input', function() { clearFieldError(sel); });
    }
    function clearFieldError(sel) {
        $(sel).removeClass('scpwoo-field-invalid').next('.scpwoo-field-error').remove();
    }
    function clearFieldErrors() {
        clearFieldError('#sc-add-region');
        clearFieldError('#sc-add-rate');
    }

    /* ── Render table ── */
    function render() {
        var $tb = $('#scpwoo-tbody').empty();
        if (!rules.length) {
            $tb.append('<tr><td colspan="4" class="scpwoo-no-rules">' + i18n.noRules + '</td></tr>');
            return;
        }
        var disp = rules.map(function (r, i) { return { r: r, i: i }; });
        disp.sort(function (a, b) {
            var aCC = a.r.country || findCountryForRegion(a.r.region);
            var bCC = b.r.country || findCountryForRegion(b.r.region);
            if (aCC !== bCC) return aCC < bCC ? -1 : 1;
            var aRN = getRegionName(aCC, a.r.region), bRN = getRegionName(bCC, b.r.region);
            if (aRN !== bRN) return aRN.localeCompare(bRN);
            var pr = { region: 0, city: 1, neighborhood: 2 };
            if ((pr[a.r.type] || 0) !== (pr[b.r.type] || 0)) return (pr[a.r.type] || 0) - (pr[b.r.type] || 0);
            return (a.r.city || '').localeCompare(b.r.city || '');
        });

        var lastGroupCC = null;
        for (var d = 0; d < disp.length; d++) {
            var r = disp[d].r, idx = disp[d].i;
            var zone = '', bcls = r.type;
            var rCountry = r.country || findCountryForRegion(r.region);

            if (multiCountry && rCountry !== lastGroupCC) {
                lastGroupCC = rCountry;
                var cLabel = countryNames[rCountry] || rCountry;
                $tb.append('<tr class="scpwoo-group-header"><td colspan="4">' + esc(cLabel) + '</td></tr>');
            }

            var countryLabel = '';
            var rName = getRegionName(rCountry, r.region);

            var badgeHtml = ' <span class="scpwoo-badge scpwoo-badge-' + bcls + '">' + esc(typeLabel(r.type)) + '</span>';

            if (r.type === 'region') {
                zone = countryLabel + '<span class="scpwoo-zone-region">' + esc(rName) + '</span>' + badgeHtml;
            } else if (r.type === 'city') {
                zone = countryLabel + '<span class="scpwoo-zone-region">' + esc(rName) + '</span>' + badgeHtml
                    + '<span class="scpwoo-zone-sub">' + esc(r.city) + '</span>';
            } else {
                var hoods = (r.neighborhoods || []).join(', ');
                zone = countryLabel + '<span class="scpwoo-zone-region">' + esc(rName) + '</span>' + badgeHtml
                    + '<span class="scpwoo-zone-sub">' + esc(r.city) + '</span>'
                    + '<span class="scpwoo-zone-hoods">' + esc(hoods) + '</span>';
            }

            var fv = (r.free_from !== '' && r.free_from !== undefined) ? r.free_from : '';
            var $tr = $('<tr>').attr('data-idx', idx);
            $tr.append($('<td class="scpwoo-zone">').html(zone));
            $tr.append($('<td>').html('<span class="scpwoo-cell-num"><span class="scpwoo-rate-val">' + esc(r.rate) + '</span><span class="scpwoo-cur">' + esc(cur) + '</span></span>'));
            $tr.append($('<td>').html('<span class="scpwoo-cell-num"><span class="' + (fv !== '' ? 'scpwoo-free-val' : 'scpwoo-free-val scpwoo-free-empty') + '">' + (fv !== '' ? esc(fv) : '—') + '</span>' + (fv !== '' ? '<span class="scpwoo-cur">' + esc(cur) + '</span>' : '') + '</span>'));
            $tr.append($('<td>').html('<button type="button" class="scpwoo-edit" title="' + esc(i18n.edit) + '" aria-label="' + esc(i18n.edit) + '"><span class="dashicons dashicons-edit" aria-hidden="true"></span></button> <button type="button" class="scpwoo-del" aria-label="' + esc(i18n.deleteRule || 'Delete rule') + '">&times;</button>'));
            $tb.append($tr);
        }
    }

    /* ── Delete (with 5-second undo) ── */
    $(document).on('click', '.scpwoo-del', function () {
        var idx = +$(this).closest('tr').attr('data-idx');
        if (idx < 0 || idx >= rules.length) return;

        var savedRule = rules[idx];
        var savedIdx  = idx;

        rules.splice(idx, 1);
        sync(); render(); resetForm(); markUsedInRegionSelect();

        if (pendingUndo) { clearTimeout(pendingUndo.timer); $('#scpwoo-undo-toast').remove(); pendingUndo = null; }

        var $t = $('<div id="scpwoo-undo-toast" class="scpwoo-undo-toast">' +
            '<span>' + esc(i18n.ruleDeleted) + '</span>' +
            '<button type="button" class="scpwoo-undo-btn">' + esc(i18n.undo || 'Undo') + '</button>' +
            '</div>');
        $('#scpwoo-wrap').prepend($t);

        pendingUndo = {
            timer: setTimeout(function() { $t.fadeOut(300, function() { $t.remove(); }); pendingUndo = null; }, 5000)
        };

        $t.find('.scpwoo-undo-btn').on('click', function() {
            clearTimeout(pendingUndo.timer); pendingUndo = null;
            $t.remove();
            rules.splice(savedIdx, 0, savedRule);
            sync(); render(); markUsedInRegionSelect();
        });
    });

    /* ── Edit ── */
    $(document).on('click', '.scpwoo-edit', function () {
        var idx = +$(this).closest('tr').attr('data-idx');
        if (idx < 0 || idx >= rules.length) return;
        var r = rules[idx];

        editingIdx = idx;
        $('#sc-add-btn').text(i18n.update);
        $('#sc-cancel-btn').removeClass('scpwoo-hidden');
        $('.scpwoo-add').addClass('scpwoo-editing');

        var editCC = r.country || findCountryForRegion(r.region);
        if (multiCountry) { $('#sc-add-country').val(editCC).trigger('change'); }
        setTimeout(function () { $('#sc-add-region').val(r.region).trigger('change'); }, 50);
        setTimeout(function () {
            if (r.city) {
                $('#sc-add-city').val(r.city).trigger('change');
                setTimeout(function () {
                    if (r.neighborhoods && r.neighborhoods.length) {
                        r.neighborhoods.forEach(function (h) {
                            $('#sc-add-hoods input').filter(function () { return $(this).val() === h; }).prop('checked', true);
                        });
                    }
                }, 50);
            }
        }, 100);

        $('#sc-add-rate').val(r.rate);
        $('#sc-add-free').val(r.free_from !== '' && r.free_from !== undefined ? r.free_from : '');
        $('html,body').animate({ scrollTop: $('.scpwoo-add').offset().top - 100 }, 300);
    });

    /* ── Cancel edit ── */
    $('#sc-cancel-btn').on('click', function () { resetForm(); });

    function resetForm() {
        editingIdx = -1;
        clearFieldErrors();
        $('#sc-add-btn').text(i18n.add);
        $('#sc-cancel-btn').addClass('scpwoo-hidden');
        $('.scpwoo-add').removeClass('scpwoo-editing');
        $('#sc-add-rate,#sc-add-free').val('');
        $('#sc-add-hoods input').prop('checked', false);
        $('.scpwoo-hood-filter').remove();
        if (multiCountry) { $('#sc-add-country').val('').trigger('change'); }
        else { $('#sc-add-region').val('').trigger('change'); }
        markUsedInRegionSelect();
    }

    /* ── Used destinations helper ── */
    function getUsedRegions(cc) {
        var used = [];
        for (var i = 0; i < rules.length; i++) {
            if (i === editingIdx) continue;
            var r = rules[i], rCC = r.country || findCountryForRegion(r.region);
            if (r.type === 'region' && rCC === cc) used.push(r.region);
        }
        return used;
    }
    function getUsedCities(cc, rc) {
        var used = [];
        for (var i = 0; i < rules.length; i++) {
            if (i === editingIdx) continue;
            var r = rules[i], rCC = r.country || findCountryForRegion(r.region);
            if (r.type === 'city' && rCC === cc && r.region === rc) used.push(r.city);
        }
        return used;
    }
    function getUsedHoods(cc, city) {
        var used = [];
        for (var i = 0; i < rules.length; i++) {
            if (i === editingIdx) continue;
            var r = rules[i], rCC = r.country || findCountryForRegion(r.region);
            if (r.type === 'neighborhood' && rCC === cc && r.city === city) {
                used = used.concat(r.neighborhoods || []);
            }
        }
        return used;
    }

    /* ── Country -> Region cascade ── */
    $('#sc-add-country').on('change', function () {
        var cc = $(this).val(), $r = $('#sc-add-region');
        $r.empty().append('<option value="">' + i18n.choose + '</option>');
        $('#sc-add-city').empty().html('<option value="">—</option>').prop('disabled', true);
        $('#sc-add-city-wrap').addClass('scpwoo-hidden');
        $('#sc-add-hoods-wrap').addClass('scpwoo-hidden');
        if (!cc || !RbyC[cc]) return;
        var regs = RbyC[cc];
        var usedRegs = getUsedRegions(cc);
        var sorted = Object.keys(regs).sort(function (a, b) { return regs[a].localeCompare(regs[b]); });
        for (var i = 0; i < sorted.length; i++) {
            var isUsed = usedRegs.indexOf(sorted[i]) !== -1;
            $r.append($('<option>').val(sorted[i]).text(regs[sorted[i]] + (isUsed ? ' — ✓' : '')));
        }
    });

    /* ── Region -> City cascade ── */
    $('#sc-add-region').on('change', function () {
        var rc = $(this).val(), $c = $('#sc-add-city'), $hw = $('#sc-add-hoods');
        var cc = $('#sc-add-country').val() || (countries.length === 1 ? countries[0] : '');
        $c.empty(); $hw.empty();
        $('#sc-add-hoods-wrap').addClass('scpwoo-hidden');
        var cities = getCities(cc, rc);
        if (!rc || !cities.length) {
            $c.html('<option value="">—</option>').prop('disabled', true);
            $('#sc-add-city-wrap').addClass('scpwoo-hidden');
            return;
        }
        $('#sc-add-city-wrap').removeClass('scpwoo-hidden');
        $c.prop('disabled', false).append('<option value="">—</option>');
        var usedCities = getUsedCities(cc, rc);
        cities = cities.slice().sort();
        for (var i = 0; i < cities.length; i++) {
            var isUsed = usedCities.indexOf(cities[i]) !== -1;
            $c.append($('<option>').val(cities[i]).text(cities[i] + (isUsed ? ' — ✓' : '')));
        }
    });

    $('#sc-add-city').on('change', function () {
        var city = $(this).val(), $hw = $('#sc-add-hoods');
        var cc = $('#sc-add-country').val() || (countries.length === 1 ? countries[0] : '');
        $hw.empty();
        $('.scpwoo-hood-filter').remove();
        var hoods = getHoods(cc, city);
        if (!city || !hoods.length) { $('#sc-add-hoods-wrap').addClass('scpwoo-hidden'); return; }
        $('#sc-add-hoods-wrap').removeClass('scpwoo-hidden');
        var usedHoods = getUsedHoods(cc, city);
        hoods = hoods.slice().sort();
        for (var i = 0; i < hoods.length; i++) {
            var isUsed = usedHoods.indexOf(hoods[i]) !== -1;
            var $cb = $('<input type="checkbox">').val(hoods[i]);
            var $lbl = $('<label>').append($cb).append(' ' + hoods[i]);
            if (isUsed) {
                $cb.prop('disabled', true);
                $lbl.css({ opacity: 0.4, cursor: 'not-allowed' }).attr('title', hoods[i] + ' — ' + i18n.alreadyUsed);
            }
            $hw.append($lbl);
        }
        if (hoods.length > 8) {
            var $filter = $('<input type="text" class="scpwoo-hood-filter" placeholder="' + esc(i18n.filterHoods || 'Filter...') + '">');
            $filter.on('input', function() {
                var q = $(this).val().toLowerCase();
                $hw.find('label').each(function() {
                    $(this).toggle(!q || $(this).text().toLowerCase().indexOf(q) !== -1);
                });
            });
            $hw.before($filter);
        }
    });

    /* ── Add / Update rule ── */
    $('#sc-add-btn').on('click', function () {
        var country = $('#sc-add-country').val() || '';
        var region = $('#sc-add-region').val();
        var city = $('#sc-add-city').val() || '';
        var rate = $('#sc-add-rate').val();
        var free = $('#sc-add-free').val() || '';

        clearFieldErrors();
        var hasError = false;
        if (!region) { showFieldError('#sc-add-region', i18n.selectRegion); hasError = true; }
        if (rate === '') { showFieldError('#sc-add-rate', i18n.invalidRate); hasError = true; }
        if (hasError) return;
        if (multiCountry && !country) return;
        if (isNaN(parseFloat(rate))) { showFieldError('#sc-add-rate', i18n.invalidRate); return; }

        var hoods = [];
        $('#sc-add-hoods input:checked').each(function () { hoods.push($(this).val()); });

        var type = hoods.length ? 'neighborhood' : (city ? 'city' : 'region');
        var ruleCountry = country || findCountryForRegion(region);

        var isDup = false;
        for (var di = 0; di < rules.length; di++) {
            if (di === editingIdx) continue;
            var ex = rules[di];
            var exCC = ex.country || findCountryForRegion(ex.region);
            if (ex.type !== type || ex.region !== region || exCC !== ruleCountry) continue;
            if (type === 'region') { isDup = true; break; }
            if (type === 'city' && ex.city === city) { isDup = true; break; }
            if (type === 'neighborhood' && ex.city === city) {
                var overlap = hoods.filter(function (h) { return (ex.neighborhoods || []).indexOf(h) !== -1; });
                if (overlap.length) { isDup = true; break; }
            }
        }
        if (isDup) { toast(i18n.duplicateRule, 'error'); return; }

        var rule = { type: type, country: ruleCountry, region: region, rate: parseFloat(rate), free_from: free !== '' ? parseFloat(free) : '' };
        if (type === 'city' || type === 'neighborhood') rule.city = city;
        if (type === 'neighborhood') rule.neighborhoods = hoods;

        var isUpdate = editingIdx >= 0 && editingIdx < rules.length;
        var updatedIdx = editingIdx;
        if (isUpdate) { rules[editingIdx] = rule; } else { rules.push(rule); }
        sync(); render(); resetForm(); markUsedInRegionSelect();
        toast(isUpdate ? i18n.ruleUpdated : i18n.ruleAdded);
        if (isUpdate) {
            setTimeout(function() {
                var $row = $('#scpwoo-tbody tr[data-idx="' + updatedIdx + '"]');
                $row.removeClass('scpwoo-flash');
                $row[0] && void $row[0].offsetWidth;
                $row.addClass('scpwoo-flash');
            }, 0);
        }
    });

    /* ── Mark used regions ── */
    function markUsedInRegionSelect() {
        var cc = $('#sc-add-country').val() || (countries.length === 1 ? countries[0] : '');
        if (!cc) return;
        var usedRegs = getUsedRegions(cc);
        $('#sc-add-region option').each(function () {
            var val = $(this).val();
            if (!val) return;
            var cleanText = $(this).text().replace(/ — ✓$/, '');
            var isUsed = usedRegs.indexOf(val) !== -1;
            $(this).text(cleanText + (isUsed ? ' — ✓' : '')).removeAttr('style');
        });
    }

    /* ── Init ── */
    render(); sync(); updateCount(); markUsedInRegionSelect();
});
