/**
 * EducationMapView — نقشه مؤسسات و جلسات (Leaflet + کاشی آفلاین محلی)
 */
const MARKER_COLORS = {
    school: '#7c3aed',
    institute: '#2563eb',
    home_session: '#ea580c',
};

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

    static async loadLeaflet() {
        if (window.L) return window.L;
        if (!document.querySelector('link[data-edu-leaflet]')) {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = '/acc-engine/assets/vendor/leaflet/leaflet.css';
            link.dataset.eduLeaflet = '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="edu-map-wrap">
                <div class="edu-map" id="edu-map-canvas"></div>
                <div class="edu-map-legend" id="edu-map-legend"></div>
            </div>`;
        const L = await EducationMapView.loadLeaflet();
        const center = this.data.center || { lat: 35.6892, lng: 51.389, zoom: 11 };
        const el = this.container.querySelector('#edu-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 || 11
        );
        // 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`;
        const tileUrl = this.data.tile_url
            || `${base}/assets/vendor/leaflet/tiles_esri/{z}/{x}/{y}.png`;
        L.tileLayer(tileUrl, {
            attribution: this.data.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: 'edu-map-pin',
                html: `<span style="background:${color}"></span>`,
                iconSize: [16, 16],
                iconAnchor: [8, 8],
            });
            L.marker([m.lat, m.lng], { icon }).addTo(this._layer)
                .bindPopup(`<strong>${this._esc(m.title)}</strong><br><small>${this._esc(m.meta || '')}</small>`);
        });

        const legend = this.container.querySelector('#edu-map-legend');
        const leg = this.data.legend || MARKER_COLORS;
        if (legend) {
            legend.innerHTML = Object.entries(leg).map(([k, label]) => {
                const c = MARKER_COLORS[k] || '#666';
                const text = typeof label === 'string' ? label : k;
                return `<span class="edu-map-legend__item"><i style="background:${c}"></i>${text}</span>`;
            }).join('');
        }
        setTimeout(() => this._map?.invalidateSize(), 200);
    }

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

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