(function($){
    'use strict';

    $(document).ready(function(){
        
        // ── Tab switching — no fadeOut (tabs do full page reload) ──

        // ── Unified AJAX Save logic ──
        $(document).on('submit', '#ps-admin-panel form', function(e){
            // Skip for special forms if necessary
            if($(this).hasClass('ps-no-ajax')) return;
            
            e.preventDefault();
            var $form = $(this);
            var $btn  = $form.find('input[type="submit"]');
            var group = $form.find('input[name="ps_save_group"]').val() || 'parcselect_behavior_group';
            
            // Collect all data from the form
            var rawData = {};
            var formData = new FormData(this);
            for (var [key, value] of formData.entries()) {
                // Handle checkbox array syntax: name[subkey][] (e.g. ip_enabled_countries[])
                var matchArr = key.match(/^(.+?)\[(.+?)\]\[\]$/);
                if (matchArr) {
                    if (!rawData[matchArr[1]]) rawData[matchArr[1]] = {};
                    if (!Array.isArray(rawData[matchArr[1]][matchArr[2]])) {
                        rawData[matchArr[1]][matchArr[2]] = [];
                    }
                    rawData[matchArr[1]][matchArr[2]].push(value);
                    continue;
                }
                // Handle nested key syntax: name[subkey]
                var match = key.match(/^(.+?)\[(.+?)\]$/);
                if (match) {
                    if (!rawData[match[1]]) rawData[match[1]] = {};
                    rawData[match[1]][match[2]] = value;
                } else {
                    rawData[key] = value;
                }
            }

            $('body').addClass('ps-saving-active');
            $btn.prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'parcselect_save_panel_settings',
                    nonce: parcselectAdminVars.saveNonce,
                    group: group,
                    data: rawData
                },
                success: function(res) {
                    $('body').removeClass('ps-saving-active');
                    $btn.prop('disabled', false);
                    if (res.success) {
                        if (res.data && res.data.reload) {
                            window.location.reload();
                            return;
                        }
                        showNotice('success', (parcselectAdminVars.strings && parcselectAdminVars.strings.saved) || (parcselectAdminVars.i18n && parcselectAdminVars.i18n.saved) || 'Settings saved.');
                    } else {
                        showNotice('error', 'Error: ' + (res.data.message || 'Unknown error'));
                    }
                },
                error: function() {
                    $('body').removeClass('ps-saving-active');
                    $btn.prop('disabled', false);
                    showNotice('error', 'Server error.');
                }
            });
        });

        // ── Theme Switcher persistence ──
        $(document).on('click', '.ps-theme-card', function(){
            var theme = $(this).data('theme');
            if(!theme) return;

            $('#ps-admin-panel').removeClass('ps-theme-light ps-theme-dark').addClass('ps-theme-' + theme);
            
            // Save preference via AJAX
            $.post(ajaxurl, {
                action: 'parcselect_save_panel_settings',
                nonce: parcselectAdminVars.saveNonce,
                group: 'parcselect_appearance_group',
                data: { ps_admin_theme: theme }
            });
        });

        // ── Helper: Show Premium Toast Notice ──
        function showNotice(type, msg) {
            var icon = type === 'success' ? '&#10003;' : '&#x26A0;&#xFE0F;';
            var classAttr = type === 'success' ? 'parcelselector-notice-success' : 'parcelselector-notice-error';
            
            var $msg = $('<div class="parcelselector-notice ' + classAttr + '" style="position:fixed; top:40px; right:20px; z-index:100000; box-shadow:0 10px 25px rgba(0,0,0,0.15); font-weight:700; display:none; border:none; padding:15px 25px; border-radius:12px; backdrop-filter:blur(5px);">' + icon + ' ' + msg + '</div>');
            
            $('body').append($msg);
            $msg.fadeIn(300).delay(3000).fadeOut(400, function(){ $(this).remove(); });
        }

        // ── Behavior Tab: Pickup Toggle ──
        $(document).on('change', '#ps-pickup-toggle', function() {
            $('#ps-pickup-details').toggle(this.checked);
        });

        // ── Behavior Tab: Zoom Mode selection ──
        $(document).on('click', '.ps-zoom-mode-card', function() {
            var $card = $(this);
            $card.siblings().removeClass('ps-zoom-active').find('.ps-zoom-badge').remove();
            $card.addClass('ps-zoom-active');
            $card.find('input[type="radio"]').prop('checked', true);
            
            if (!$card.find('.ps-zoom-badge').length) {
                $card.append('<span class="ps-zoom-badge">&#x2714; ' + (parcselectAdminVars.i18n.active || 'Active') + '</span>');
            }
        });

        // ── Behavior Tab: Geocoding (Nominatim) ──
        $(document).on('click', '#ps-geocode-btn', function() {
            var $btn    = $(this);
            var street  = $('[name="ps_custom_pickup[street]"]').val().trim();
            var city    = $('[name="ps_custom_pickup[city]"]').val().trim();
            var postal  = $('[name="ps_custom_pickup[postal]"]').val().trim();
            var country = $('[name="ps_custom_pickup[country]"]').val().trim();
            var $status = $('#ps-geocode-status');

            var i18n = parcselectAdminVars.i18n || {};
            if (!street && !city) {
                $status.text(i18n.geocode_enter_address || 'Enter at least a street or city.').css('color', '#ef4444');
                return;
            }

            var q = [street, postal, city, country].filter(Boolean).join(', ');
            $btn.text(i18n.geocode_searching || 'Searching...').prop('disabled', true);
            $status.text('');

            fetch('https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(q), {
                headers: { 'Accept-Language': 'pl', 'User-Agent': 'ParcelSelector-WP-Plugin' }
            })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                $btn.text(i18n.geocode_fetch_btn || '📍 Fetch from address').prop('disabled', false);
                if (data && data[0]) {
                    $('#ps-pickup-lat').val(parseFloat(data[0].lat).toFixed(7));
                    $('#ps-pickup-lng').val(parseFloat(data[0].lon).toFixed(7));
                    $status.html((i18n.geocode_found || '✅ Found:') + ' <strong>' + (data[0].display_name || '') + '</strong>').css('color', '#10b981');
                } else {
                    $status.text(i18n.geocode_not_found || '❌ Not found. Check address or enter coordinates manually.').css('color', '#ef4444');
                }
            })
            .catch(function() {
                $btn.text(i18n.geocode_fetch_btn || '📍 Fetch from address').prop('disabled', false);
                $status.text(i18n.geocode_error || 'Connection error. Try later or enter coordinates manually.').css('color', '#ef4444');
            });
        });

        // ── Behavior Tab: Weight/Dim toggles ──
        $(document).on('change', '#ps-weight-limit-toggle', function(){
            var show = this.checked;
            $('#ps-weight-details, #ps-weight-action').toggle(show);
        });
        $(document).on('change', '#ps-dim-limit-toggle', function(){
            $('#ps-dim-details').toggle(this.checked);
        });

        // ── Maps Tab: Engine Selection ──
        window.parcselectSelectEngine = function(engine) {
            $('#ps_map_engine_input').val(engine);
            $('.ps-engine-card').each(function() {
                var $card = $(this);
                var isActive = $card.data('engine') === engine;
                $card.toggleClass('ps-engine-active', isActive);

                var $badge = $card.find('.ps-engine-badge');
                if (isActive) {
                    $badge.attr('class', 'ps-engine-badge ps-engine-badge-active').html('&#x2714; ' + (parcselectAdminVars.i18n.active || 'ACTIVE').toUpperCase());
                } else {
                    $badge.attr('class', 'ps-engine-badge ps-engine-badge-inactive').html(parcselectAdminVars.i18n.click_to_select || 'Click to select');
                }

                // Update SVG colors
                var $circle = $card.find('circle:first-child');
                var $shape  = $card.find('path, rect');
                var $dot    = $card.find('circle:last-child');
                if ($circle.length) $circle.attr('fill', isActive ? '#FECC01' : '#f0f0f0');
                if ($shape.length)  $shape.attr('fill',  isActive ? '#FF6600' : '#ccc');
                if ($dot.length)    $dot.attr('fill',    isActive ? '#fff'    : '#aaa');
            });
        };

        // ── Maps Tab: Country Checkbox/Grid ──
        $(document).on('change', '.parcelselector-country-cb', function() {
            var $card = $(this).closest('.parcelselector-country-card');
            $card.toggleClass('ps-active', this.checked);
            updateSelectedSummary();
        });

        function updateSelectedSummary() {
            var sel = [];
            $('.parcelselector-country-cb:checked').each(function() {
                var code = $(this).val().toUpperCase();
                if (code === 'UK') code = 'GB';
                sel.push(code);
            });
            $('#ps-selected-countries').text(sel.length ? sel.join(', ') : 'None');
        }

        // ── Maps Tab: Drag-to-reorder ──
        const grid = document.getElementById('ps-country-grid');
        if (grid) {
            let dragSrcEl = null;

            function handleDragStart(e) {
                dragSrcEl = this;
                e.dataTransfer.effectAllowed = 'move';
                this.style.opacity = '0.4';
            }

            function handleDragOver(e) {
                if (e.preventDefault) e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                return false;
            }

            function handleDrop(e) {
                if (e.stopPropagation) e.stopPropagation();
                if (dragSrcEl !== this) {
                    const rect = this.getBoundingClientRect();
                    const midpoint = rect.left + rect.width / 2;
                    if (e.clientX < midpoint) {
                        grid.insertBefore(dragSrcEl, this);
                    } else {
                        grid.insertBefore(dragSrcEl, this.nextSibling);
                    }
                    updateSelectedSummary();
                }
                return false;
            }

            function handleDragEnd(e) {
                this.style.opacity = '1.0';
            }

            const cards = grid.querySelectorAll('.parcelselector-country-card');
            cards.forEach(card => {
                card.addEventListener('dragstart', handleDragStart, false);
                card.addEventListener('dragover', handleDragOver, false);
                card.addEventListener('drop', handleDrop, false);
                card.addEventListener('dragend', handleDragEnd, false);
            });
        }

        // ── Testing Tab: API Test ──
        // "Test API connection" button was removed for WP.org compliance —
        // a phone-home ping pattern that requires per-request user consent.
        // The underlying parcselect_test_api AJAX endpoint is also gone.

        // Update notifications are handled by WordPress.org core (Plugin Directory).
        // The legacy "Check for updates" button was removed for WP.org compliance.

        // ── Testing Tab: Reset Activation ──
        $(document).on('click', '#ps-reset-activation-btn', function() {
            var $btn = $(this);
            var i18n = parcselectAdminVars.i18n || {};
            var msg_title = i18n.reset_confirm_title || 'Reset activation?';
            var msg_body  = i18n.reset_confirm_body  || 'Removes the license key and installation ID from the WordPress database. Server retains the data.';

            if (!confirm(msg_title + '\n\n' + msg_body)) return;

            var $result = $('#ps-reset-activation-result');
            $btn.prop('disabled', true).text(i18n.resetting || 'Resetting...');
            $result.show().html('<p>' + (i18n.please_wait || '⏳ Please wait...') + '</p>');

            $.post(parcselectAdminVars.ajaxurl, {
                action: 'parcselect_reset_activation',
                nonce: parcselectAdminVars.nonces.reset_activation
            }, function(response) {
                if (response.success) {
                    $result.html('<div class="parcelselector-notice parcelselector-notice-success"><p>✅ Zresetowano pomyślnie</p></div>');
                    setTimeout(function() { location.reload(); }, 1500);
                } else {
                    $result.html('<div class="parcelselector-notice parcelselector-notice-warning"><p>❌ Błąd: ' + (response.data.message || 'Error') + '</p></div>');
                    $btn.prop('disabled', false).html('🗑️ Resetuj aktywację');
                }
            }).fail(function() {
                $result.html('<div class="parcelselector-notice parcelselector-notice-warning"><p>❌ AJAX error.</p></div>');
                $btn.prop('disabled', false).html('🗑️ Resetuj aktywację');
            });
        });

        // ── Testing Tab: Admin Map Preview Functions ──
        window.parcselectAdminOpenClassic = function() {
            document.dispatchEvent(new CustomEvent('inpost-open-map', { detail: { country: 'pl' } }));
        };
        window.parcselectAdminOpenAnunaki = function() {
            if (window.AnunakiPopup && typeof AnunakiPopup.open === 'function') {
                AnunakiPopup.open('pl');
            } else {
                console.error('[PS] AnunakiPopup nie załadowany');
            }
        };

    });

})(jQuery);
