/**
 * ElectionMapView.js — نقشه read-only هوادار (Leaflet)
 */
const MARKER_COLORS = {
    station: '#ea580c',
    station_available: '#94a3b8',
    poi: '#2563eb',
    banner: '#9333ea',
    segment: '#16a34a',
};

export default class ElectionMapView {
    constructor(opts = {}) {
        this.container = opts.container;
        this.data = opts.data || {};
        this.onPickStation = opts.onPickStation || null;
        this._map = null;
        this._layer = null;
    }

    static async loadLeaflet() {
        if (window.L) return window.L;
        if (!document.querySelector('link[data-el-leaflet]')) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = '/acc-engine/assets/vendor/leaflet/leaflet.css';
            link.dataset.elLeaflet = '1';
            document.head.appendChild(link);
        }
        await new Promise((resolve, reject) => {
            const s = document.createElement('script');
            s.src = '/acc-engine/assets/vendor/leaflet/leaflet.js';
            s.onload = resolve;
            s.onerror = reject;
            document.head.appendChild(s);
        });
        return window.L;
    }

    async render(data) {
        if (data) this.data = data;
        if (!this.container) return;
        this.container.innerHTML = '<div class="el-map" id="el-map-canvas"></div><div class="el-map-legend" id="el-map-legend"></div>';
        const L = await ElectionMapView.loadLeaflet();
        const center = this.data.center || { lat: 29.5918, lng: 52.5837, zoom: 12 };
        const el = this.container.querySelector('#el-map-canvas');
        if (this._map) { this._map.remove(); this._map = null; }

        this._map = L.map(el, { scrollWheelZoom: true, maxZoom: 19 }).setView([center.lat, center.lng], center.zoom || 12);
        // Offline tiles — same pattern as ERP «نقشه هوشمند» (MapSection)
        const base = (window.ACC_CONFIG?.pluginUrl || '/acc-engine/').replace(/\/+$/, '');
        const blank = `${base}/assets/vendor/leaflet/tiles/blank.png`;
        L.tileLayer(`${base}/assets/vendor/leaflet/tiles_esri/{z}/{x}/{y}.png`, {
            attribution: '© Esri (local)',
            minZoom: 10, maxZoom: 19, maxNativeZoom: 16,
            errorTileUrl: blank,
        }).addTo(this._map);

        this._layer = L.layerGroup().addTo(this._map);
        (this.data.markers || []).forEach(m => {
            const color = MARKER_COLORS[m.type] || '#57534e';
            const icon = L.divIcon({
                className: 'el-map-pin',
                html: `<span style="background:${color}"></span>`,
                iconSize: [14, 14],
                iconAnchor: [7, 7],
            });
            const mk = L.marker([m.lat, m.lng], { icon }).addTo(this._layer);
            mk.bindPopup(`<strong>${this._esc(m.title)}</strong><br><small>${this._esc(m.meta || '')}</small>`);
            if (m.type === 'station_available' && this.onPickStation) {
                mk.on('click', () => this.onPickStation(m.id));
            }
        });

        (this.data.blocks || []).forEach(b => {
            if (!b.center_lat || !b.center_lng) return;
            L.circleMarker([b.center_lat, b.center_lng], {
                radius: 4, color: '#78716c', fillColor: '#d6d3d1', fillOpacity: 0.5, weight: 1,
            }).addTo(this._layer).bindPopup(`بلوک ${b.block_code}<br>${b.parcel_count ?? b.total_parcels ?? 0} پارسل`);
        });

        const legend = this.container.querySelector('#el-map-legend');
        if (legend) {
            legend.innerHTML = Object.entries(MARKER_COLORS).map(([k, c]) =>
                `<span><i style="background:${c}"></i>${this._typeLabel(k)}</span>`
            ).join('');
        }
        setTimeout(() => this._map?.invalidateSize(), 200);
    }

    _typeLabel(t) {
        return { station: 'صندوق من', station_available: 'قابل انتخاب', poi: 'شناسایی', banner: 'بنر', segment: 'پهنه' }[t] || t;
    }

    _esc(t) {
        return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;');
    }

    destroy() {
        if (this._map) { this._map.remove(); this._map = null; }
    }
}
