/**
 * ANUNAKI Popup Engine v2.0.0
 * Matches React MapPopup.tsx preview exactly
 */
;(function() {
    // Local flag image base — falls back to FlagCDN only if plugin config not available.
    var FLAG_W20 = (window.parcselectAnunakiConfig && window.parcselectAnunakiConfig.flagBaseW20) || '';
    var FLAG_W40 = (window.parcselectAnunakiConfig && window.parcselectAnunakiConfig.flagBaseW40) || '';
    var MASCOT   = (window.parcselectAnunakiConfig && window.parcselectAnunakiConfig.mascotUrl) || '';

    'use strict';

    console.log(
        '%c ANUNAKI Parcel Selector v2.0.0 %c parcelselector.com ',
        'background:#f97316;color:white;font-weight:bold;padding:4px 8px;border-radius:4px 0 0 4px',
        'background:#0f172a;color:#f97316;padding:4px 8px;border-radius:0 4px 4px 0'
    );

    var COUNTRIES = window.ANUNAKI_COUNTRIES || {};
    var TRANSLATIONS = window.ANUNAKI_TRANSLATIONS || {};
    
    // Warstwa 12: Izolacja obiektów - jeśli Themer ma swoje (stare) biblioteki mapowe, 
    // my pobieramy świeży odnośnik i zamykamy w naszym prywatnym Scope
    var L = window.L; 

    var FLAG_CODES = {};
    Object.keys(COUNTRIES).forEach(function(cc) {
        FLAG_CODES[cc] = COUNTRIES[cc].flagCode || cc;
    });

    // Ghost mode: countries visible on map but not selectable.
    // When the shop's WC shipping zones only cover PL, other countries
    // show greyed-out pins. Clicking opens info panel with "ask shop owner".
    var _allowedCC = (window.parcselectAnunakiConfig && window.parcselectAnunakiConfig.allowedCountries) || [];
    function _isGhostCountry(cc) {
        if (!_allowedCC.length) return false; // no restriction configured
        return _allowedCC.indexOf(cc.toUpperCase()) === -1 && _allowedCC.indexOf(cc.toLowerCase()) === -1;
    }

    function t(key) {
        var lang = AnunakiPopup._currentCountry || 'pl';
        var tr = TRANSLATIONS[lang] || TRANSLATIONS['pl'] || {};
        return tr[key] || key;
    }

    function esc(str) {
        var d = document.createElement('div');
        d.textContent = str || '';
        return d.innerHTML;
    }

    var SVG = {
        package: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>',
        search: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>',
        x: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',
        mapPin: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>',
        check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"/></svg>',
        loader: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>'
    };

    var AnunakiPopup = {
        _map: null,
        _markers: null,
        _allPoints: [],
        _currentCountry: 'pl',
        _isOpen: false,
        _selectedPoint: null,
        _confirmed: false,
        _overlay: null,
        _container: null,
        _searchInput: null,
        _searchResultsEl: null,
        _statusBarEl: null,
        _detailPanelEl: null,
        _zoomOverlayEl: null,
        _confettiEl: null,
        _searchTimer: null,
        _isFirstLoad: true,
        _loadRequestId: 0,

        open: function(countryCode) {
            countryCode = (countryCode || 'pl').toLowerCase();
            this._currentCountry = countryCode;
            this._isOpen = true;
            this._selectedPoint = null;
            this._confirmed = false;
            this._isFirstLoad = true;
            this._openTime = Date.now();
            this._countdownTimer = null;

            document.body.style.overflow = 'hidden';
            this._buildDOM();
            this._initMap();
        },

        close: function() {
            if (!this._isOpen) return;
            this._isOpen = false;
            document.body.style.overflow = '';

            if (this._countdownTimer) {
                clearInterval(this._countdownTimer);
                this._countdownTimer = null;
            }

            if (this._overlay) {
                this._overlay.classList.add('ank-closing');
                var overlay = this._overlay;
                setTimeout(function() {
 if (overlay.parentNode) overlay.remove(); }, 300);
            }

            if (this._map) {
                this._map.remove();
                this._map = null;
            }
            this._markers = null;
            this._allPoints = [];
        },

        switchCountry: function(cc) {
            if (cc === this._currentCountry) return;
            this._currentCountry = cc;
            this._selectedPoint = null;
            this._confirmed = false;
            this._isFirstLoad = false;
            this._clearDetailPanel();
            this._updateFlagButtons();
            this._updateSubtitle();
            this._showZoomOverlay(cc);
            this._loadPoints(cc);
        },

        scrollFlags: function(amount) {
            var container = document.getElementById('ankFlags');
            if (container) {
                container.scrollBy({ left: amount, behavior: 'smooth' });
            }
        },

        _buildDOM: function() {
            var self = this;
            var cc = this._currentCountry;
            var country = COUNTRIES[cc] || COUNTRIES['pl'] || {};

            var overlay = document.createElement('div');
            overlay.className = 'ank-overlay';
            overlay.onclick = function(e) { if (e.target === overlay || e.target.classList.contains('ank-backdrop')) self.close(); };

            var backdrop = document.createElement('div');
            backdrop.className = 'ank-backdrop';
            overlay.appendChild(backdrop);

            var container = document.createElement('div');
            container.className = 'ank-container';

            /* ═══ HEADER ═══ */
            var header = document.createElement('div');
            header.className = 'ank-header';

            var headerTop = document.createElement('div');
            headerTop.className = 'ank-header-top';

            // Logo
            var logo = document.createElement('div');
            logo.className = 'ank-logo';
            logo.innerHTML =
                ( MASCOT
                    ? '<img class="ank-mascot-logo" src="' + MASCOT + '" alt="ParcelSelector">'
                    : '<div class="ank-logo-icon">' + SVG.package + '</div>' ) +
                '<div class="ank-logo-text-wrap">' +
                    '<div class="ank-logo-title">PARCEL<span>SELECTOR</span></div>' +
                    '<div class="ank-logo-subtitle" id="ankSubtitle">' +
                        '<img src="' + FLAG_W20 + (FLAG_CODES[cc] || cc) + '.png" alt="' + esc(country.name) + '"> ' +
                        esc(country.name) + ' • <span id="ankPointCount">...</span>' +
                    '</div>' +
                '</div>';

            // Search
            var searchWrap = document.createElement('div');
            searchWrap.className = 'ank-search-wrap';

            var searchField = document.createElement('div');
            searchField.className = 'ank-search-field';

            var searchIcon = document.createElement('div');
            searchIcon.className = 'ank-search-icon';
            searchIcon.innerHTML = SVG.search;

            var searchInput = document.createElement('input');
            searchInput.type = 'text';
            searchInput.className = 'ank-search-input';
            searchInput.placeholder = t('searchPlaceholder') || 'Wpisz miasto, ulicę lub nazwę punktu...';
            searchInput.oninput = function() {
                clearTimeout(self._searchTimer);
                self._searchTimer = setTimeout(function() {
 self._handleSearch(searchInput.value); }, 300);
            };
            searchInput.onkeydown = function(e) {
                if (e.key === 'Enter') {
                    clearTimeout(self._searchTimer);
                    self._handleSearch(searchInput.value);
                }
            };
            searchInput.onfocus = function() {
                if (self._searchResultsEl && self._searchResultsEl.children.length > 1) {
                    self._searchResultsEl.classList.add('active');
                }
            };

            searchField.appendChild(searchIcon);
            searchField.appendChild(searchInput);

            var searchBtn = document.createElement('button');
            searchBtn.type = 'button';
            searchBtn.className = 'ank-search-btn';
            searchBtn.innerHTML = SVG.search + '<span>Szukaj</span>';
            searchBtn.onclick = function() {
                clearTimeout(self._searchTimer);
                self._handleSearch(searchInput.value);
            };

            var searchResults = document.createElement('div');
            searchResults.className = 'ank-search-results';
            searchResults.id = 'ankSearchResults';

            searchWrap.appendChild(searchField);
            searchWrap.appendChild(searchBtn);
            searchWrap.appendChild(searchResults);

            // Close btn
            var closeBtn = document.createElement('button');
            closeBtn.type = 'button';
            closeBtn.className = 'ank-close-btn';
            closeBtn.innerHTML = SVG.x;
            closeBtn.onclick = function() { self.close(); };

            headerTop.appendChild(logo);
            headerTop.appendChild(searchWrap);
            headerTop.appendChild(closeBtn);
            header.appendChild(headerTop);

            // Flags bar
            var flagsContainer = document.createElement('div');
            flagsContainer.className = 'ank-flags-container';

            var leftBtn = document.createElement('button');
            leftBtn.className = 'ank-flag-arrow left';
            leftBtn.innerHTML = '&#10094;';
            leftBtn.onclick = function() { self.scrollFlags(-100); };

            var rightBtn = document.createElement('button');
            rightBtn.className = 'ank-flag-arrow right';
            rightBtn.innerHTML = '&#10095;';
            rightBtn.onclick = function() { self.scrollFlags(100); };

            var flagsBar = document.createElement('div');
            flagsBar.className = 'ank-flags';
            flagsBar.id = 'ankFlags';

            var ccList = Object.keys(COUNTRIES);
            ccList.forEach(function(code) {
                if (_isGhostCountry(code)) return; // FREE — skip non-allowed countries entirely
                var c = COUNTRIES[code];
                var btn = document.createElement('button');
                btn.type = 'button';
                var flagGhost = _isGhostCountry(code);
                btn.className = 'ank-flag-btn' + (code === cc ? ' active' : '') + (flagGhost ? ' ghost' : '');
                btn.dataset.cc = code;
                if (flagGhost) btn.style.opacity = '0.45';
                if (flagGhost) btn.style.filter = 'grayscale(80%)';
                btn.innerHTML =
                    '<img class="ank-flag-img" src="' + FLAG_W20 + (c.flagCode || code) + '.png" ' +
                    'srcset="' + FLAG_W40 + (c.flagCode || code) + '.png 2x" alt="' + esc(c.name) + '">' +
                    '<span class="ank-flag-name">' + esc(c.name) + '</span>';
                btn.onclick = function() { self.switchCountry(code); };
                flagsBar.appendChild(btn);
            });
            
            flagsContainer.appendChild(leftBtn);
            flagsContainer.appendChild(flagsBar);
            flagsContainer.appendChild(rightBtn);
            // Country selector sits inline in the header row, between the points count and the search field.
            headerTop.insertBefore(flagsContainer, searchWrap);

            /* ═══ MAP BODY ═══ */
            var body = document.createElement('div');
            body.className = 'ank-body';

            var mapDiv = document.createElement('div');
            mapDiv.className = 'ank-map';
            mapDiv.id = 'ankMap';

            var confettiEl = document.createElement('div');
            confettiEl.className = 'ank-confetti-container';

            body.appendChild(mapDiv);
            body.appendChild(confettiEl);

            container.appendChild(header);
            container.appendChild(body);
            overlay.appendChild(container);
            var root = document.getElementById('ps-popup-root') || document.body;
            root.appendChild(overlay);

            this._overlay = overlay;
            this._container = container;
            this._searchInput = searchInput;
            this._searchResultsEl = searchResults;
            this._confettiEl = confettiEl;

            // Blinking cursor — focus the search field on pointer/desktop devices only,
            // so the on-screen keyboard is not forced open on touch devices.
            if ( window.matchMedia && window.matchMedia('(pointer: fine)').matches ) {
                requestAnimationFrame(function() {
                    try { searchInput.focus({ preventScroll: true }); } catch (e) {}
                });
            }

            // Close search results on outside click
            document.addEventListener('click', function handler(e) {
                if (!self._isOpen) { document.removeEventListener('click', handler); return; }
                if (searchResults && !searchWrap.contains(e.target)) {
                    searchResults.classList.remove('active');
                }
            });
        },

        _initMap: function() {
            var self = this;
            var EUROPE_CENTER = [50.0, 10.0];
            var EUROPE_ZOOM = 4;

            try {
                this._map = L.map('ankMap', {
                    zoomControl: false,
                    zoomAnimation: true,
                    fadeAnimation: true,
                    markerZoomAnimation: true
                }).setView(EUROPE_CENTER, EUROPE_ZOOM);

                L.control.zoom({ position: 'bottomright' }).addTo(this._map);

                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://openstreetmap.org">OpenStreetMap</a>',
                    maxZoom: 19
                }).addTo(this._map);

            this._markers = L.markerClusterGroup({
                maxClusterRadius: 60,
                spiderfyOnMaxZoom: true,
                showCoverageOnHover: false,
                zoomToBoundsOnClick: true,
                animateAddingMarkers: true,
                disableClusteringAtZoom: 16,
                iconCreateFunction: function(cluster) {
                    var count = cluster.getChildCount();
                    var sz = count > 500 ? 56 : count > 100 ? 48 : count > 10 ? 40 : 34;
                    var fs = count > 500 ? 15 : count > 100 ? 14 : count > 10 ? 12 : 11;
                    return L.divIcon({
                        html: '<div style="' +
                            'background:linear-gradient(135deg,#f97316,#f59e0b);' +
                            'color:white;border-radius:50%;width:100%;height:100%;' +
                            'display:flex;align-items:center;justify-content:center;' +
                            'font-weight:900;font-size:' + fs + 'px;' +
                            'box-shadow:0 4px 20px rgba(249,115,22,0.5);' +
                            'border:3px solid white;' +
                            'transition:transform 0.2s;cursor:pointer;' +
                        '">' + count + '</div>',
                        className: 'custom-cluster-icon',
                        iconSize: L.point(sz, sz)
                    });
                }
            });

                this._map.addLayer(this._markers);

                // Start cinematic zoom
                this._showZoomOverlay(this._currentCountry);
                this._loadPoints(this._currentCountry);

            } catch (error) {
                console.error("🚨 [Layer 12: Map Izolator] Błąd krytyczny mapy Anunaki. Kolizja z innym themerem na stronie. Zwróć uwagę na konflikty Leaflet/GoogleMaps:", error);
                var mapDiv = document.getElementById('ankMap');
                if (mapDiv) {
                    mapDiv.innerHTML = '<div style="padding:40px;text-align:center;color:red;background:#fee2e2;border:2px solid #ef4444;border-radius:12px;margin:20px;">' +
                        '<strong>Wykryto kolizję skryptów (Warstwa 12)</strong><br><br>' +
                        'Inna wtyczka nadpisała mapę ParcelSelector! Wyłącz tymczasowo kreatory stron/inne mapy dla strony Kasy.' +
                    '</div>';
                }
            }
        },

        _loadPoints: function(cc) {
            var self = this;
            var country = COUNTRIES[cc];
            if (!country) return;

            this._allPoints = [];
            this._updatePointCount('...');
            var requestId = ++this._loadRequestId;

            // Exponential backoff fetch — 3 attempts: 0ms, 1000ms, 3000ms
            function attemptFetch(attempt) {
                if (requestId !== self._loadRequestId) return;
                var delay = attempt === 0 ? 0 : (attempt === 1 ? 1000 : 3000);

                setTimeout(function() {

                    if (requestId !== self._loadRequestId) return;
                    if (attempt > 0) {
                        self._updatePointCount('Ponawiam (' + attempt + '/2)...');
                    }

                    var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
                    var timeoutId = controller ? setTimeout(function() {
 controller.abort(); }, 10000) : null;

                    var fetchOpts = { signal: controller ? controller.signal : undefined };

                    fetch(country.api, fetchOpts)
                        .then(function(r) {
                            if (timeoutId) clearTimeout(timeoutId);
                            if (!r.ok) throw new Error('HTTP ' + r.status);
                            return r.json();
                        })
                        .then(function(data) {
                            if (requestId !== self._loadRequestId) return;

                            // FREE plugin — InPost-only enforcement: keep all InPost point types
                            // (paczkomat + POP + POK + Pudo + cooled lockers) by filtering the
                            // response to InPost-known tags as a defensive measure.
                            if (Array.isArray(data)) {
                                var INPOST_TAGS = ['parcel_locker', 'parcel_locker_superpop',
                                                   'refrigerated_locker_machine', 'pop', 'pok', 'pudo_mini'];
                                data = data.filter(function(p) {
                                    var tags = (p && p.t) ? p.t : [];
                                    if (!tags || !tags.length) return false;
                                    // Match jesli choc jeden tag jest InPost-known
                                    for (var i = 0; i < tags.length; i++) {
                                        if (INPOST_TAGS.indexOf(tags[i]) !== -1) return true;
                                    }
                                    return false;
                                });
                            }

                            // Warstwa 14: Mobile Point Limit
                            if (window.PS_MOBILE && typeof window.PS_MOBILE.applyLimit === 'function') {
                                data = window.PS_MOBILE.applyLimit(data);
                            }

                            self._allPoints = data;
                            self._updatePointCount(data.length.toLocaleString() + ' punktów');

                            if (window.AnunakiSearch) {
                                window.AnunakiSearch.init(data);
                            }

                            // Cinematic zoom to country then render markers
                            var info = country;
                            if (self._map) {
                                var isFirst = self._isFirstLoad;
                                self._isFirstLoad = false;
                                self._renderMarkers(data);
                                self._map.flyTo(info.center, info.zoom, {
                                    duration: 1.2,
                                    easeLinearity: 0.20
                                });
                                self._map.once('moveend', function() {
                                    self._hideZoomOverlay();
                                });
                            }
                        })
                        .catch(function(err) {
                            if (timeoutId) clearTimeout(timeoutId);
                            if (requestId !== self._loadRequestId) return;
                            if (attempt < 2) {
                                // Retry with backoff
                                attemptFetch(attempt + 1);
                            } else {
                                // All 3 attempts failed — show user-visible error
                                console.error('[ANUNAKI] Load failed after 3 attempts:', err);
                                self._hideZoomOverlay();
                                self._updatePointCount('Błąd połączenia');
                                // Show in-map error notice
                                var mapEl = document.getElementById('ankMap');
                                if (mapEl) {
                                    var errDiv = document.createElement('div');
                                    errDiv.style.cssText = 'position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);' +
                                        'background:rgba(239,68,68,0.95);color:#fff;padding:16px 24px;border-radius:10px;' +
                                        'font-size:14px;text-align:center;z-index:9999;max-width:300px;box-shadow:0 4px 20px rgba(0,0,0,0.3);';
                                    errDiv.innerHTML = '<strong>⚠️ Nie można załadować punktów</strong><br>' +
                                        '<small>Sprawdź połączenie internetowe i odśwież stronę.</small><br>' +
                                        '<button onclick="this.parentNode.remove();AnunakiPopup._loadPoints(\'' + cc + '\');" ' +
                                        'style="margin-top:8px;background:#fff;color:#ef4444;border:none;padding:6px 14px;border-radius:6px;cursor:pointer;font-weight:700;">' +
                                        '🔄 Spróbuj ponownie</button>';
                                    mapEl.style.position = 'relative';
                                    mapEl.appendChild(errDiv);
                                }
                            }
                        });
                }, delay);
            }

            attemptFetch(0);
        },

        _renderMarkers: function(points) {
            var self = this;
            if (!this._markers) return;
            this._markers.clearLayers();

            var isGhost = _isGhostCountry(this._currentCountry);
            var pinColor = isGhost ? '#94a3b8' : '#f97316'; // grey for ghost, orange for active
            var pinShadow = isGhost ? 'rgba(0,0,0,0.15)' : 'rgba(0,0,0,0.35)';
            var pinOpacity = isGhost ? 'opacity:0.6;' : '';

            var icon = L.divIcon({
                html: '<div style="' +
                    'background:' + pinColor + ';width:32px;height:32px;border-radius:50%;' +
                    'border:3px solid white;box-shadow:0 3px 12px ' + pinShadow + ';' +
                    'display:flex;align-items:center;justify-content:center;' +
                    'cursor:pointer;transition:transform 0.2s,box-shadow 0.2s;' + pinOpacity +
                '">' + SVG.mapPin.replace('stroke="currentColor"', 'stroke="white"').replace('stroke-width="2"', 'stroke-width="2.5"').replace('<svg', '<svg width="16" height="16"') + '</div>',
                className: 'locker-marker-icon' + (isGhost ? ' ghost-pin' : ''),
                iconSize: [32, 32],
                iconAnchor: [16, 16]
            });

            var batch = [];
            points.forEach(function(p) {
                if (!p.lat || !p.lng) return;
                var marker = L.marker([p.lat, p.lng], { icon: icon });
                marker.on('click', function() {
                    self._selectPoint(p);
                    var latlng = [p.lat, p.lng];
                    if (window.PS_MOBILE && window.PS_MOBILE.isMobile) {
                        // Offset: marker at ~25% from top (0.25)
                        var targetPoint = self._map.project(latlng, 17).add([0, self._map.getSize().y * 0.25]);
                        var targetLatLng = self._map.unproject(targetPoint, 17);
                        self._map.flyTo(targetLatLng, 17, { duration: 1.5, easeLinearity: 0.2 });
                    } else {
                        self._map.flyTo(latlng, 17, { duration: 2.0, easeLinearity: 0.15 });
                    }
                });
                batch.push(marker);
            });

            this._markers.addLayers(batch);
        },

        _handleSearch: function(query) {
            if (!query || query.trim().length < 2) {
                if (this._searchResultsEl) {
                    this._searchResultsEl.innerHTML = '';
                    this._searchResultsEl.classList.remove('active');
                }
                if (this._allPoints.length > 0 && this._markers) {
                    this._renderMarkers(this._allPoints);
                }
                return;
            }

            var results = [];
            if (window.AnunakiSearch) {
                results = window.AnunakiSearch.search(query, 10);
            } else {
                var q = query.toLowerCase();
                results = this._allPoints.filter(function(p) {
                    return (p.n || '').toLowerCase().indexOf(q) !== -1 ||
                           (p.l || '').toLowerCase().indexOf(q) !== -1 ||
                           (p.a || '').toLowerCase().indexOf(q) !== -1;
                }).slice(0, 10);
            }

            this._showSearchResults(results);

            if (results.length > 0 && this._map) {
                if (results.length === 1 && results[0].lat && results[0].lng) {
                    this._map.flyTo([results[0].lat, results[0].lng], 15, { duration: 1.0 });
                } else {
                    var bounds = [];
                    results.forEach(function(p) { if (p.lat && p.lng) bounds.push([p.lat, p.lng]); });
                    if (bounds.length > 1) {
                        this._map.flyToBounds(L.latLngBounds(bounds), { duration: 1.0, padding: [60, 60], maxZoom: 14 });
                    }
                }
            }
        },

        _showSearchResults: function(results) {
            var self = this;
            var el = this._searchResultsEl;
            if (!el) return;

            el.innerHTML = '';

            if (results.length === 0) {
                el.classList.remove('active');
                return;
            }

            var headerDiv = document.createElement('div');
            headerDiv.className = 'ank-search-results-header';
            headerDiv.innerHTML = '<span>Wyniki wyszukiwania</span><span class="ank-search-results-count">' + results.length + '</span>';
            el.appendChild(headerDiv);

            results.forEach(function(p) {
                var item = document.createElement('button');
                item.type = 'button';
                item.className = 'ank-result-item';
                item.innerHTML =
                    '<div class="ank-result-icon">' + SVG.mapPin.replace('stroke="currentColor"', 'stroke="#ea580c"') + '</div>' +
                    '<div style="min-width:0;flex-grow:1">' +
                        '<div class="ank-result-name">' + esc(p.n) + '</div>' +
                        '<div class="ank-result-addr">' + esc(p.a) + ', ' + esc(p.l) + '</div>' +
                    '</div>' +
                    '<span style="font-size:10px;color:#cbd5e1;flex-shrink:0;margin-top:4px">↗</span>';
                item.onclick = function() {
                    self._selectPoint(p);
                    el.classList.remove('active');
                    if (self._searchInput) self._searchInput.value = p.n || '';
                    if (self._map && p.lat && p.lng) {
                        self._map.flyTo([p.lat, p.lng], 17, { duration: 1.2, easeLinearity: 0.25 });
                    }
                };
                el.appendChild(item);
            });

            el.classList.add('active');
        },

        _selectPoint: function(point) {
            var self = this;
            this._selectedPoint = point;
            this._confirmed = false;
            this._showDetailPanel(point);
        },

        _showDetailPanel: function(point) {
            var self = this;
            this._clearDetailPanel();

            var panel = document.createElement('div');
            panel.className = 'ank-detail-panel';
            panel.id = 'ankDetailPanel';
            panel.innerHTML =
                '<div class="ank-detail-header">' +
                    '<h3>📦 ' + esc(point.n) + '</h3>' +
                    '<p>' + esc(point.a) + ', ' + esc(point.l) + '</p>' +
                '</div>' +
                '<div class="ank-detail-body">' +
                    '<div class="ank-detail-row"><span class="icon">📦</span><span class="name">' + esc(point.n) + '</span></div>' +
                    '<div class="ank-detail-row"><span class="icon">📍</span><span class="ank-detail-address">' + esc(point.a) + ', ' + esc(point.l) + '</span></div>' +
                    '<div class="ank-status-row-multi">' +
                        '<div class="ank-detail-row small"><span class="icon">⏰</span><span>' + esc(point.oh || '24/7') + '</span></div>' +
                        '<div class="ank-detail-row small"><span class="icon">🟢</span><span>' + esc(point.s || t('operating') || 'Aktywny') + '</span></div>' +
                        '<button class="ank-btn-cancel-inline" id="ankCancelBtn">↩ Zmień</button>' +
                    '</div>' +
                '</div>' +
                '<div class="ank-detail-actions">' +
                    (_isGhostCountry(this._currentCountry)
                        ? '<div style="background:linear-gradient(135deg,#fef3c7,#fde68a);border:2px solid #f59e0b;border-radius:10px;padding:14px 16px;text-align:center;color:#78350f;font-size:13px;line-height:1.6">' +
                            '<div style="font-size:20px;margin-bottom:6px">🌍</div>' +
                            '<strong>Wysyłka do tego kraju jest możliwa!</strong><br>' +
                            'Zapytaj właściciela sklepu o włączenie dostawy do paczkomatów w tym kraju.' +
                            '<div style="margin-top:10px"><a href="https://parcelselector.com/international" target="_blank" rel="noopener" ' +
                            'style="display:inline-block;padding:6px 14px;background:#f59e0b;color:#fff;border-radius:6px;text-decoration:none;font-weight:700;font-size:12px">Dowiedz się więcej →</a></div>' +
                          '</div>'
                        : '<button class="ank-btn-confirm" id="ankConfirmBtn">✓ Wybierz ten punkt</button>'
                    ) +
                '</div>';

            var body = this._container.querySelector('.ank-body');
            if (body) body.appendChild(panel);

            var confirmBtn = document.getElementById('ankConfirmBtn');
            if (confirmBtn) confirmBtn.onclick = function() { self._confirmSelection(); };
            var cancelBtn = document.getElementById('ankCancelBtn');
            if (cancelBtn) cancelBtn.onclick = function() { self._clearDetailPanel(); };
        },

        _clearDetailPanel: function() {
            var panel = document.getElementById('ankDetailPanel');
            if (panel) panel.remove();
            var confirmed = document.getElementById('ankConfirmedOverlay');
            if (confirmed) confirmed.remove();
        },

        _confirmSelection: function() {
            var self = this;
            var point = this._selectedPoint;
            if (!point) return;

            this._confirmed = true;
            this._clearDetailPanel();

            // Calculate elapsed time
            var elapsedMs = Date.now() - (this._openTime || Date.now());
            var elapsedSec = Math.round(elapsedMs / 1000);
            var elapsedText = elapsedSec < 60
                ? elapsedSec + ' sek'
                : Math.floor(elapsedSec / 60) + ' min ' + (elapsedSec % 60) + ' sek';

            var cc = this._currentCountry;
            var countryData = (window.ANUNAKI_COUNTRIES || {})[cc] || {};
            var COUNTDOWN_SEC = 18;
            var circumference = 2 * Math.PI * 20; // r=20 → ≈125.66

            // Dispatch event for WC integration (immediately so bridge can save)
            document.dispatchEvent(new CustomEvent('anunaki-point-selected', {
                detail: {
                    name:    point.n,
                    address: point.a,
                    city:    point.l,
                    lat:     point.lat,
                    lng:     point.lng,
                    hours:   point.oh,
                    status:  point.s,
                    country: cc,
                    carrier: point.carrier || 'inpost',
                    selection_time: elapsedSec,
                    device_type: window.PS_MOBILE ? window.PS_MOBILE.deviceType() : 'Desktop PC'
                }
            }));

            // Build success overlay (transparent — map + confetti show through)
            var overlay = document.createElement('div');
            overlay.className = 'ank-confirmed-overlay';
            overlay.id = 'ankConfirmedOverlay';
            overlay.onclick = function(e) {
                if (e.target === overlay) self.close();
            };

            var card = document.createElement('div');
            card.className = 'ank-success-card';
            card.innerHTML =
                // Check circle
                '<div class="ank-success-check-wrap">' +
                    '<div class="ank-confirmed-check">' + SVG.check + '</div>' +
                '</div>' +

                // Main title
                '<div class="ank-confirmed-title">' + (t('successTitle') || 'Paczkomat wybrany!') + '</div>' +
                '<div class="ank-confirmed-subtitle">' + (t('successSubtitle') || 'Punkt odbioru wybrany') + '</div>' +

                // Divider
                '<div class="ank-success-divider"></div>' +

                // Point details
                '<div class="ank-success-point-name">' + esc(point.n) + '</div>' +
                '<div class="ank-success-rows">' +
                    '<div class="ank-success-row">' +
                        '<span class="ank-success-row-icon">📍</span>' +
                        '<span>' + esc(point.a || '') + (point.l ? ', ' + esc(point.l) : '') + '</span>' +
                    '</div>' +
                    (point.oh ? '<div class="ank-success-row"><span class="ank-success-row-icon">⏰</span><span>' + esc(point.oh) + '</span></div>' : '') +
                    '<div class="ank-success-row">' +
                        '<span class="ank-success-row-icon">🌍</span>' +
                        '<span>' + (countryData.flag || '') + ' ' + esc(countryData.name || cc.toUpperCase()) + '</span>' +
                    '</div>' +
                '</div>' +

                // Divider
                '<div class="ank-success-divider"></div>' +

                // Race flags — elapsed time
                '<div class="ank-success-race">' +
                    '<div class="ank-race-flag">🚩</div>' +
                    '<div class="ank-race-info">' +
                        '<span class="ank-race-label">Czas wyboru</span>' +
                        '<span class="ank-race-time">' + elapsedText + '</span>' +
                    '</div>' +
                    '<div class="ank-race-flag">🏁</div>' +
                '</div>' +

                // Countdown
                '<div class="ank-success-countdown">' +
                    '<svg class="ank-countdown-svg" viewBox="0 0 44 44">' +
                        '<circle class="ank-countdown-track" cx="22" cy="22" r="20"/>' +
                        '<circle class="ank-countdown-progress" id="ankCdCircle" cx="22" cy="22" r="20"/>' +
                    '</svg>' +
                    '<span class="ank-countdown-num" id="ankCdNum">' + COUNTDOWN_SEC + '</span>' +
                '</div>' +
                '<div class="ank-success-close-hint">Kliknij aby zamknąć • Auto za ' + COUNTDOWN_SEC + 's</div>';

            card.onclick = function() { self.close(); };
            overlay.appendChild(card);

            var body = this._container.querySelector('.ank-body');
            if (body) body.appendChild(overlay);

            // Fire confetti AFTER overlay (higher z-index in CSS)
            this._createConfetti();

            // Animate countdown ring
            var cdNum = document.getElementById('ankCdNum');
            var cdCircle = document.getElementById('ankCdCircle');
            if (cdCircle) {
                cdCircle.style.strokeDasharray = circumference;
                cdCircle.style.strokeDashoffset = '0';
            }
            var remaining = COUNTDOWN_SEC;
            this._countdownTimer = setInterval(function() {

                remaining--;
                if (cdNum) cdNum.textContent = remaining;
                if (cdCircle) {
                    var offset = circumference * (1 - remaining / COUNTDOWN_SEC);
                    cdCircle.style.strokeDashoffset = offset;
                }
                if (remaining <= 0) {
                    clearInterval(self._countdownTimer);
                    self._countdownTimer = null;
                    self.close();
                }
            }, 1000);
        },

        _createConfetti: function() {
            var container = this._confettiEl;
            if (!container) return;

            var colors = ['#f97316','#eab308','#22c55e','#3b82f6','#ef4444','#8b5cf6','#ec4899','#14b8a6'];
            var shapes = ['circle','rect','triangle'];
            for (var i = 0; i < 80; i++) {
                var el = document.createElement('div');
                var color = colors[Math.floor(Math.random() * colors.length)];
                var shape = shapes[Math.floor(Math.random() * shapes.length)];
                var size = 6 + Math.random() * 8;
                var x = 50 + (Math.random() - 0.5) * 60;
                var delay = Math.random() * 0.5;
                var duration = 1.5 + Math.random() * 1.5;
                var drift = (Math.random() - 0.5) * 200;
                var rot = Math.random() * 720 - 360;

                var clip = '';
                if (shape === 'circle') clip = 'border-radius:50%;';
                else if (shape === 'triangle') clip = 'clip-path:polygon(50% 0%,0% 100%,100% 100%);height:' + (size * 1.2) + 'px;';
                else clip = 'border-radius:2px;';

                el.style.cssText =
                    'position:absolute;left:' + x + '%;top:40%;width:' + size + 'px;height:' + size + 'px;' +
                    'background:' + color + ';z-index:9999;pointer-events:none;opacity:1;' +
                    clip +
                    '--drift:' + drift + 'px;--rot:' + rot + 'deg;' +
                    'animation:ankConfettiFall ' + duration + 's cubic-bezier(0.25,0.46,0.45,0.94) ' + delay + 's forwards;';
                container.appendChild(el);
            }

            setTimeout(function() {
 container.innerHTML = ''; }, 3500);
        },

        _showZoomOverlay: function(cc) {
            this._hideZoomOverlay();
            var country = COUNTRIES[cc] || {};
            var overlay = document.createElement('div');
            overlay.className = 'ank-zoom-overlay';
            overlay.id = 'ankZoomOverlay';
            overlay.innerHTML =
                '<div class="ank-zoom-spinner">' + SVG.loader + '</div>' +
                '<div class="ank-zoom-text">Ładowanie mapy...</div>' +
                '<div class="ank-zoom-country">' +
                    '<img class="ank-zoom-flag" src="' + FLAG_W20 + (FLAG_CODES[cc] || cc) + '.png"> ' +
                    esc(country.name) +
                '</div>';

            var body = this._container ? this._container.querySelector('.ank-body') : null;
            if (body) body.appendChild(overlay);
        },

        _hideZoomOverlay: function() {
            var el = document.getElementById('ankZoomOverlay');
            if (el) {
                el.style.opacity = '0';
                el.style.transition = 'opacity 0.5s';
                setTimeout(function() {
 if (el.parentNode) el.remove(); }, 500);
            }
        },

        _updateFlagButtons: function() {
            var self = this;
            document.querySelectorAll('.ank-flag-btn').forEach(function(btn) {
                var isActive = btn.dataset.cc === self._currentCountry;
                var isGhost = _isGhostCountry(btn.dataset.cc);
                btn.classList.toggle('active', isActive);
                btn.classList.toggle('ghost', isGhost);
                btn.style.opacity = isGhost && !isActive ? '0.45' : '';
                btn.style.filter = isGhost ? 'grayscale(80%)' : '';
            });
        },

        _updateSubtitle: function() {
            var cc = this._currentCountry;
            var country = COUNTRIES[cc] || {};
            var el = document.getElementById('ankSubtitle');
            if (el) {
                el.innerHTML =
                    '<img src="' + FLAG_W20 + (FLAG_CODES[cc] || cc) + '.png" alt="' + esc(country.name) + '"> ' +
                    esc(country.name) + ' • <span id="ankPointCount">...</span>';
            }
        },

        _updatePointCount: function(text) {
            var el = document.getElementById('ankPointCount');
            if (el) el.textContent = text;
        }
    };

    window.AnunakiPopup = AnunakiPopup;
})();
