// customcode.js - GeoInsight Location Intelligence
// Compatible with Neshan SDK (Mapbox GL JS) + Supercluster
(function () {

    const style = document.createElement('style');
    style.textContent = `

        .dd-close-custom {
            position: absolute; left: 12px; top: 6px;
            background: #f0f0f0; border: none; border-radius: 50%;
            width: 30px; height: 30px; font-size: 30px;
            line-height: 30px; text-align: center;
            cursor: pointer; color: #555;
            transition: all 0.2s; z-index: 10;
        }
        .dd-close-custom:hover { background: #ff4d4d; color: #fff; }

        .custom-controls-wrapper {
            background: #fff; padding: 10px 15px; margin-bottom: 15px;
            border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            border: 1px solid #eee;
        }
        .custom-toggle-label {
            display: flex; align-items: center; gap: 10px;
            cursor: pointer; font-weight: bold; font-size: 0.9rem; color: #333;
        }

        .store-tooltip { display: none !important; }
        .map-show-labels .store-tooltip { display: block !important; opacity: 1 !important; }

        /* ====== مارکر موقعیت من — بدون وابستگی به Mapbox GL Marker ====== */
        #my-loc-marker {
            position: absolute;
            pointer-events: none;
            z-index: 900;
            width: 44px; height: 44px;
            transform: translate(-50%, -50%);
            display: none; /* تا وقتی موقعیت نداریم مخفیه */
        }

        .my-loc-pulse {
            position: absolute; inset: 0;
            border-radius: 50%;
            background: rgba(214, 0, 28, 0.13);
            animation: myLocPulse 2s ease-out infinite;
        }

        .my-loc-pulse-inner {
            position: absolute;
            top: 50%; left: 50%;
            width: 26px; height: 26px;
            transform: translate(-50%, -50%);
            border-radius: 50%;
            background: rgba(214, 0, 28, 0.09);
            animation: myLocPulse 2s ease-out 0.5s infinite;
        }

        .my-loc-dot {
            position: absolute;
            top: 50%; left: 50%;
            width: 14px; height: 14px;
            transform: translate(-50%, -50%);
            border-radius: 50%;
            background: #D6001C;
            border: 2.5px solid #fff;
            box-shadow: 0 0 6px rgba(214,0,28,0.55), 0 0 14px rgba(214,0,28,0.2);
            z-index: 2;
            animation: myLocDotPulse 2s ease-in-out infinite;
        }

        @keyframes myLocPulse {
            0%   { transform: scale(0.5); opacity: 0.8; }
            100% { transform: scale(1.9); opacity: 0; }
        }

        @keyframes myLocDotPulse {
            0%, 100% { transform: translate(-50%,-50%) scale(1);    box-shadow: 0 0 6px rgba(214,0,28,0.55), 0 0 14px rgba(214,0,28,0.2); }
            50%      { transform: translate(-50%,-50%) scale(1.15); box-shadow: 0 0 12px rgba(214,0,28,0.65), 0 0 22px rgba(214,0,28,0.3); }
        }

        /* دکمه لوکیشن */
        #my-location-btn.active {
            background: #D6001C !important; color: #fff !important;
            animation: btnPulse 1.5s ease-in-out infinite;
        }

        @keyframes btnPulse {
            0%, 100% { box-shadow: 0 2px 12px rgba(214,0,28,0.2); }
            50%      { box-shadow: 0 2px 24px rgba(214,0,28,0.5); }
        }
        @keyframes toastSlideIn {
            from { opacity: 0; transform: translateX(-30px); }
            to   { opacity: 1; transform: translateX(0); }
        }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }

        /* مودال PWA */
        .pwa-modal-overlay {
            position: fixed; inset: 0;
            background: rgba(0,0,0,0.4);
            backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
            display: none; justify-content: center; align-items: flex-end;
            z-index: 99999; animation: fadeIn 0.3s ease;
        }
        .pwa-modal {
            background: #f2f2f7; border-radius: 20px 20px 0 0;
            width: 100%; max-width: 500px; padding: 0;
            animation: slideUp 0.4s cubic-bezier(0.32,0.72,0,1);
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', sans-serif;
            direction: rtl;
        }
        .pwa-modal-handle { width: 36px; height: 5px; background: #c7c7cc; border-radius: 3px; margin: 8px auto 0; }
        .pwa-modal-header { display: flex; align-items: center; padding: 16px 20px; border-bottom: 0.5px solid rgba(0,0,0,0.1); }
        .pwa-app-icon {
            width: 60px; height: 60px; border-radius: 14px;
            background: linear-gradient(135deg, #007aff, #5856d6);
            display: flex; align-items: center; justify-content: center;
            margin-left: 14px; box-shadow: 0 4px 12px rgba(0,122,255,0.3);
        }
        .pwa-app-icon svg { width: 32px; height: 32px; fill: #fff; }
        .pwa-app-info h3 { margin: 0 0 4px; font-size: 17px; font-weight: 600; color: #000; }
        .pwa-app-info p  { margin: 0; font-size: 13px; color: #8e8e93; }
        .pwa-modal-actions { padding: 20px 20px 34px; display: flex; flex-direction: column; gap: 10px; }
        .pwa-btn-install {
            background: #007aff; color: #fff; border: none; border-radius: 14px;
            padding: 16px; font-size: 17px; font-weight: 600; cursor: pointer;
            transition: all 0.2s; font-family: inherit;
        }
        .pwa-btn-install:hover  { background: #0056b3; transform: scale(0.98); }
        .pwa-btn-install:active { transform: scale(0.96); }
        .pwa-btn-cancel {
            background: transparent; color: #007aff; border: none;
            padding: 14px; font-size: 17px; font-weight: 500; cursor: pointer; font-family: inherit;
        }
        .pwa-btn-cancel:hover { color: #0056b3; }

        #pwa-trigger-btn {
            position: fixed; bottom: 24px; left: 24px;
            width: 56px; height: 56px; border-radius: 16px;
            background: linear-gradient(135deg, #007aff, #5856d6);
            border: none; cursor: pointer; display: none;
            align-items: center; justify-content: center;
            box-shadow: 0 4px 20px rgba(0,122,255,0.4);
            z-index: 9999; transition: all 0.3s cubic-bezier(0.32,0.72,0,1);
        }
        #pwa-trigger-btn:hover  { transform: scale(1.08); box-shadow: 0 6px 24px rgba(0,122,255,0.5); }
        #pwa-trigger-btn:active { transform: scale(0.95); }
        #pwa-trigger-btn svg { width: 28px; height: 28px; fill: #fff; }

        @media (max-width: 768px) {
            #my-location-btn { bottom: 250px !important; left: 12px !important; width: 44px !important; height: 44px !important; }
            #loc-toast { bottom: 136px !important; left: 12px !important; right: 12px !important; max-width: unset !important; }
        }
    `;
    document.head.appendChild(style);


    /* ── SVG ICONS ── */
    const SVG_CROSSHAIR = `
        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24"
             fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="12" cy="12" r="3"/>
            <path d="M12 2v3"/><path d="M12 19v3"/>
            <path d="M2 12h3"/><path d="M19 12h3"/>
            <circle cx="12" cy="12" r="9" stroke-dasharray="4 2"/>
        </svg>`;

    const SVG_SPINNER = `
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="2"
                    stroke-dasharray="14 14" stroke-linecap="round">
                <animateTransform attributeName="transform" type="rotate"
                    from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite"/>
            </circle>
        </svg>`;

    const SVG_DOWNLOAD = `<svg viewBox="0 0 24 24"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>`;


    /* ── DAILY DETAILS CLOSE BUTTON ── */
    const checkAppInterval = setInterval(() => {
        if (typeof App === 'undefined' || !App.showDailyDetails) return;
        clearInterval(checkAppInterval);
        const original = App.showDailyDetails;
        App.showDailyDetails = function (data) {
            original.call(App, data);
            const box = document.getElementById('daily-details-box');
            if (!box || box.style.display === 'none' || box.querySelector('.dd-close-custom')) return;
            const closeBtn = document.createElement('button');
            closeBtn.className = 'dd-close-custom';
            closeBtn.innerHTML = '&times;';
            closeBtn.onclick = () => box.style.display = 'none';
            box.style.position = 'relative';
            box.appendChild(closeBtn);
        };
    }, 500);


    /* ── TOAST ── */
    function showToast(message, type = 'info') {
        const old = document.getElementById('loc-toast');
        if (old) old.remove();
        const palette = {
            info:    { bg: '#eff6ff', border: '#bfdbfe', text: '#1e40af', icon: '📡' },
            success: { bg: '#f0fdf4', border: '#bbf7d0', text: '#166534', icon: '✅' },
            error:   { bg: '#fef2f2', border: '#fecaca', text: '#991b1b', icon: '❌' }
        };
        const c = palette[type] || palette.info;
        const el = document.createElement('div');
        el.id = 'loc-toast';
        Object.assign(el.style, {
            position: 'fixed', bottom: '330px', left: '20px', zIndex: '1001',
            background: c.bg, border: `1px solid ${c.border}`, color: c.text,
            padding: '10px 16px', borderRadius: '12px', fontSize: '13px',
            fontWeight: '500', fontFamily: 'inherit', direction: 'rtl',
            boxShadow: '0 4px 16px rgba(0,0,0,0.1)',
            display: 'flex', alignItems: 'center', gap: '8px',
            maxWidth: '300px', animation: 'toastSlideIn 0.3s ease-out',
            transition: 'all 0.3s ease'
        });
        el.innerHTML = `<span>${c.icon}</span><span>${message}</span>`;
        document.body.appendChild(el);
        setTimeout(() => {
            el.style.opacity = '0'; el.style.transform = 'translateX(-20px)';
            setTimeout(() => el.remove(), 300);
        }, type === 'error' ? 5000 : 3000);
    }


    /* ── FIND MAP INSTANCE ── */
    function getMap() {
        if (typeof App !== 'undefined' && App.map) {
            const m = App.map;
            if (typeof m.flyTo === 'function') return m;
            if (m.map && typeof m.map.flyTo === 'function') return m.map;
        }
        if (window.map && typeof window.map.flyTo === 'function') return window.map;
        if (typeof App !== 'undefined' && App.mapManager && App.mapManager.map) return App.mapManager.map;
        if (window._mapInstance && typeof window._mapInstance.flyTo === 'function') return window._mapInstance;
        return null;
    }


    /* ══════════════════════════════════════════════════════
       MY LOCATION — بدون gl.Marker — مارکر خالص CSS
    ══════════════════════════════════════════════════════ */
    function createMyLocationButton() {
        const btn = document.createElement('button');
        btn.id = 'my-location-btn';
        btn.title = 'موقعیت من روی نقشه';
        btn.innerHTML = SVG_CROSSHAIR;
        Object.assign(btn.style, {
            position: 'fixed', bottom: '270px', left: '20px', zIndex: '1000',
            width: '48px', height: '48px', borderRadius: '50%', border: 'none',
            background: '#fff', color: '#475569', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 2px 12px rgba(0,0,0,0.2), 0 0 0 1px rgba(0,0,0,0.05)',
            transition: 'all 0.3s ease'
        });

        const setDefault = () => { btn.style.background='#fff'; btn.style.color='#475569'; btn.style.boxShadow='0 2px 12px rgba(0,0,0,0.2), 0 0 0 1px rgba(0,0,0,0.05)'; btn.style.transform='scale(1)'; };
        const setHover   = () => { btn.style.background='#D6001C'; btn.style.color='#fff'; btn.style.boxShadow='0 4px 20px rgba(214,0,28,0.35)'; btn.style.transform='scale(1.08)'; };
        const setActive  = () => { btn.style.background='#D6001C'; btn.style.color='#fff'; btn.style.boxShadow='0 4px 20px rgba(214,0,28,0.35)'; btn.style.transform='scale(1)'; };

        btn.addEventListener('mouseenter', setHover);
        btn.addEventListener('mouseleave', () => { if (!isTracking) setDefault(); else setActive(); });
        document.body.appendChild(btn);


        let markerEl = null;
        let isTracking = false;
        let firstFix = true;
        let watchId = null;
        let currentLngLat = null;   
        let rafId = null;


        function ensureMarkerElement() {
            if (markerEl) return markerEl;

            const mapContainer = document.getElementById('map')
                || document.querySelector('.map-container')
                || document.querySelector('.mapboxgl-canvas-container')?.parentElement;

            if (!mapContainer) {
                console.error('[loc] Map container not found!');
                return null;
            }

            markerEl = document.createElement('div');
            markerEl.id = 'my-loc-marker';
            markerEl.innerHTML = `
                <div class="my-loc-pulse"></div>
                <div class="my-loc-pulse-inner"></div>
                <div class="my-loc-dot"></div>
            `;

            mapContainer.style.position = 'relative'; // اطمینان
            mapContainer.appendChild(markerEl);

            console.log('[loc] ✅ Marker element created and appended to', mapContainer.id || mapContainer.className);
            return markerEl;
        }


        function syncMarkerPosition() {
            if (!currentLngLat || !markerEl) return;

            const map = getMap();
            if (!map) return;

            try {
                // project: [lng,lat] → {x, y} pixel on screen
                const point = map.project(currentLngLat);
                markerEl.style.left = point.x + 'px';
                markerEl.style.top = point.y + 'px';
                markerEl.style.display = 'block';
            } catch (e) {
                console.warn('[loc] project() failed:', e.message);
            }

            if (isTracking) {
                rafId = requestAnimationFrame(syncMarkerPosition);
            }
        }


        function startSyncLoop() {
            if (rafId) cancelAnimationFrame(rafId);
            rafId = requestAnimationFrame(syncMarkerPosition);
        }


        function updateLocation(pos) {
            const map = getMap();
            if (!map) { showToast('نقشه هنوز آماده نیست', 'error'); stopTracking(); return; }

            const { latitude: lat, longitude: lng } = pos.coords;
            currentLngLat = [lng, lat];

            console.log('[loc] 📍 Position update:', lat.toFixed(5), lng.toFixed(5));

            const el = ensureMarkerElement();
            if (!el) {
                showToast('خطا: container نقشه پیدا نشد', 'error');
                stopTracking();
                return;
            }

            syncMarkerPosition();

            if (firstFix) {
                try {
                    map.flyTo({ center: [lng, lat], zoom: 16, duration: 1500, essential: true });
                } catch (e) {
                    try { map.setCenter([lng, lat]); map.setZoom(16); } catch (_) {}
                }
                firstFix = false;

                btn.innerHTML = SVG_CROSSHAIR;
                setActive();
                showToast('ردیابی زنده فعال شد 🔴', 'success');

                startSyncLoop();

                try {
                    map.on('move', syncMarkerPosition);
                    map.on('zoom', syncMarkerPosition);
                    map.on('resize', syncMarkerPosition);
                } catch (_) {}
            }
        }


        function startTracking() {
            if (!navigator.geolocation) { showToast('مرورگر شما از مکان‌یابی پشتیبانی نمی‌کند', 'error'); return; }
            const map = getMap();
            if (!map) { showToast('نقشه هنوز لود نشده', 'error'); return; }

            console.log('[loc] 🟢 Starting tracking...');
            console.log('[loc] map.project:', typeof map.project);
            console.log('[loc] map.flyTo:', typeof map.flyTo);

            isTracking = true;
            firstFix = true;
            btn.classList.add('active');
            btn.innerHTML = SVG_SPINNER;
            showToast('در حال دریافت موقعیت...', 'info');

            watchId = navigator.geolocation.watchPosition(
                updateLocation,
                (err) => {
                    console.error('[loc] Geo error:', err);
                    stopTracking();
                    const msgs = { 1: 'دسترسی به مکان‌یابی رد شد.', 2: 'اطلاعات مکان در دسترس نیست.', 3: 'زمان دریافت موقعیت تمام شد.' };
                    showToast(msgs[err.code] || 'خطا در دریافت موقعیت', 'error');
                },
                { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
            );
        }


        function stopTracking() {
            isTracking = false;

            if (watchId !== null) { navigator.geolocation.clearWatch(watchId); watchId = null; }
            if (rafId) { cancelAnimationFrame(rafId); rafId = null; }

            const map = getMap();
            if (map) {
                try {
                    map.off('move', syncMarkerPosition);
                    map.off('zoom', syncMarkerPosition);
                    map.off('resize', syncMarkerPosition);
                } catch (_) {}
            }

            btn.classList.remove('active');
            btn.innerHTML = SVG_CROSSHAIR;
            setDefault();

            if (markerEl) markerEl.style.display = 'none';
            currentLngLat = null;

            showToast('ردیابی متوقف شد', 'info');
        }


        btn.addEventListener('click', () => {
            if (isTracking) stopTracking();
            else startTracking();
        });
    }


    /* ── TOOLTIP REMOVAL ── */
    function removeAllTooltips() {
        document.querySelectorAll('.store-tooltip').forEach(el => el.remove());
        document.querySelectorAll('.mapboxgl-popup.store-tooltip-popup').forEach(el => el.remove());
    }


    /* ══════════════════════════════════════════════════════
       DOM READY
    ══════════════════════════════════════════════════════ */
    document.addEventListener('DOMContentLoaded', () => {

        /* ── چک‌باکس نمایش دیتا ── */
        const target = document.querySelector('.filter-section') || document.body;
        const ctrl = document.createElement('div');
        ctrl.className = 'custom-controls-wrapper';
        ctrl.innerHTML = `
            <label class="custom-toggle-label">
                <input type="checkbox" id="custom-tooltip-toggle">
                نمایش دیتا روی نقشه
            </label>`;
        target.prepend(ctrl);

        document.getElementById('custom-tooltip-toggle').addEventListener('change', (e) => {
            const checked = e.target.checked;
            const mapContainer = document.getElementById('map');
            if (checked) {
                if (mapContainer) mapContainer.classList.add('map-show-labels');
                if (typeof App !== 'undefined' && App.state) App.state.showTooltips = true;
                if (typeof App !== 'undefined' && typeof App._refreshTooltips === 'function') App._refreshTooltips();
            } else {
                if (mapContainer) mapContainer.classList.remove('map-show-labels');
                if (typeof App !== 'undefined' && App.state) App.state.showTooltips = false;
                removeAllTooltips();
                if (typeof App !== 'undefined' && typeof App._refreshTooltips === 'function') App._refreshTooltips();
            }
        });


        /* ── مودال PWA ── */
        const overlay = document.createElement('div');
        overlay.className = 'pwa-modal-overlay';
        overlay.innerHTML = `
            <div class="pwa-modal">
                <div class="pwa-modal-handle"></div>
                <div class="pwa-modal-header">
                    <div class="pwa-app-icon">${SVG_DOWNLOAD}</div>
                    <div class="pwa-app-info">
                        <h3>GeoInsight</h3>
                        <p>Location Intelligence — اضافه به صفحه اصلی</p>
                    </div>
                </div>
                <div class="pwa-modal-actions">
                    <button class="pwa-btn-install" id="pwa-install-confirm">نصب GeoInsight</button>
                    <button class="pwa-btn-cancel"  id="pwa-install-cancel">بعداً</button>
                </div>
            </div>`;
        document.body.appendChild(overlay);

        const trigger = document.createElement('button');
        trigger.id = 'pwa-trigger-btn';
        trigger.innerHTML = SVG_DOWNLOAD;
        document.body.appendChild(trigger);

        let deferredPrompt = null;
        window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferredPrompt = e; trigger.style.display = 'flex'; });
        trigger.addEventListener('click', () => overlay.style.display = 'flex');
        document.getElementById('pwa-install-confirm').addEventListener('click', async () => {
            if (!deferredPrompt) return;
            overlay.style.display = 'none';
            deferredPrompt.prompt();
            const { outcome } = await deferredPrompt.userChoice;
            if (outcome === 'accepted') trigger.style.display = 'none';
            deferredPrompt = null;
        });
        document.getElementById('pwa-install-cancel').addEventListener('click', () => overlay.style.display = 'none');
        overlay.addEventListener('click', (e) => { if (e.target === overlay) overlay.style.display = 'none'; });
        window.addEventListener('appinstalled', () => { trigger.style.display = 'none'; overlay.style.display = 'none'; });


        /* ── دکمه موقعیت من ── */
        createMyLocationButton();
    });

})();


