/**
 * UniversalMapSection.js — نقشه عمومی همه entityها
 * نمایش مشتری + تأمین‌کننده + کارمند + پروژه + انبار + پارسل روی یک نقشه
 * با فیلتر زنده
 */
import SectionBase from "../../accounting/SectionBase.js";

const ENTITY_CONFIG = {
    customer: { label: 'مشتریان',       icon: '🛒', color: '#10b981', api: '/sales/customers',     nameField: 'name' },
    supplier: { label: 'تأمین‌کنندگان', icon: '🏭', color: '#f59e0b', api: '/purchase/suppliers',  nameField: 'name' },
    employee: { label: 'کارمندان',       icon: '👤', color: '#3b82f6', api: '/hr/employees',        nameField: 'full_name' },
    project:  { label: 'پروژه‌ها',       icon: '🏗️', color: '#ef4444', api: '/pc/projects',         nameField: 'name' },
    warehouse:{ label: 'انبارها',         icon: '🏭', color: '#8b5cf6', api: '/inv/warehouses',      nameField: 'name' },
    lead:     { label: 'سرنخ‌ها',         icon: '🌱', color: '#06b6d4', api: '/crm/leads',           nameField: 'name' },
};

export default class UniversalMapSection extends SectionBase {

    constructor(p) {
        super(p);
        this._enabledTypes = new Set(['customer', 'supplier', 'employee', 'warehouse']);
        this._entityCache  = {};  // type → { id → entity }
        this._allLocations = [];
        this._markers      = [];
    }

    async template() {
        const filterChips = Object.entries(ENTITY_CONFIG).map(([k, v]) => `
            <label class="umap-filter-chip" data-type="${k}" style="display:inline-flex;align-items:center;gap:6px;padding:6px 12px;border:2px solid ${v.color};border-radius:20px;cursor:pointer;font-size:12px;font-weight:600;color:${v.color};background:#fff;user-select:none;">
                <input type="checkbox" value="${k}" ${this._enabledTypes.has(k) ? 'checked' : ''} style="margin:0;">
                ${v.icon} ${v.label}
                <span class="umap-count" style="background:${v.color}1a;color:${v.color};border-radius:10px;padding:0 6px;font-size:10px;">0</span>
            </label>
        `).join('');

        return `
        <div class="acc-section-wrap" style="display:flex;flex-direction:column;height:calc(100vh - 200px);">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🗺️ نقشه عمومی</h2>
                <div style="display:flex;gap:8px;align-items:center;">
                    <input type="text" data-ref="search" placeholder="🔍 جستجو..." class="acc-input" style="width:200px;">
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>

            <!-- فیلتر چیپ‌ها -->
            <div data-ref="filterBar" style="display:flex;flex-wrap:wrap;gap:8px;margin:12px 0;padding:10px;background:#f8fafc;border-radius:8px;">
                ${filterChips}
            </div>

            <!-- نقشه -->
            <div style="flex:1;border:1px solid #cbd5e1;border-radius:8px;overflow:hidden;position:relative;">
                <div data-ref="mapEl" style="width:100%;height:100%;min-height:500px;"></div>
                <div data-ref="loading" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,.8);font-size:14px;color:#64748b;">
                    ⏳ بارگذاری...
                </div>
            </div>

            <!-- نوار آمار پایین -->
            <div data-ref="statusBar" style="display:flex;gap:16px;padding:8px 12px;background:#f8fafc;border-radius:8px;margin-top:8px;font-size:12px;color:#64748b;">
                <span data-ref="totalLbl">📍 مجموع: 0</span>
                <span data-ref="coordsLbl">🌐 —</span>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._loadLeaflet();
        this._initMap();
        await this._loadAll();

        this.on(this.ref('refreshBtn'), 'click', () => this._loadAll());
        this.on(this.ref('search'),     'input', () => { clearTimeout(this._t); this._t = setTimeout(() => this._render(), 300); });

        this.ref('filterBar').querySelectorAll('input[type=checkbox]').forEach(chk => {
            chk.addEventListener('change', () => {
                if (chk.checked) this._enabledTypes.add(chk.value);
                else             this._enabledTypes.delete(chk.value);
                this._render();
            });
        });
    }

    async _loadLeaflet() {
        if (window.L) return;
        const base = (window.ACC_CONFIG?.pluginUrl ?? '').replace(/\/+$/, '');
        const local = base ? `${base}/assets/vendor/leaflet` : '/wp-content/plugins/acc-engine/assets/vendor/leaflet';
        if (!document.querySelector('link[href*="leaflet"]')) {
            const l = document.createElement('link'); l.rel='stylesheet'; l.href=`${local}/leaflet.css`;
            document.head.appendChild(l);
        }
        await new Promise((res, rej) => {
            const s = document.createElement('script'); s.src=`${local}/leaflet.js`;
            s.onload=res; s.onerror=rej; document.head.appendChild(s);
        });
    }

    _initMap() {
        const L = window.L;
        const el = this.ref('mapEl');
        this._map = L.map(el, { zoomControl: true }).setView([29.5926, 52.5836], 11);

        const base = (window.ACC_CONFIG?.pluginUrl ?? '').replace(/\/+$/, '');
        L.tileLayer(`${base || '/wp-content/plugins/acc-engine'}/assets/vendor/leaflet/tiles_esri/{z}/{x}/{y}.png`, {
            attribution: '© Esri', minZoom: 10, maxZoom: 19, maxNativeZoom: 16,
        }).addTo(this._map);

        this._layer = L.layerGroup().addTo(this._map);

        this._map.on('mousemove', e => {
            const lbl = this.ref('coordsLbl');
            if (lbl) lbl.textContent = `🌐 ${e.latlng.lat.toFixed(5)}, ${e.latlng.lng.toFixed(5)}`;
        });

        this.ref('loading').style.display = 'none';
    }

    /** لود همه موقعیت‌ها + همه entityها برای دستیابی به نام */
    async _loadAll() {
        this.ref('loading').style.display = 'flex';

        try {
            // 1) همه موقعیت‌ها
            const locRes = await this.api.get('/gis/locations/map');
            this._allLocations = locRes?.data ?? [];

            // 2) موازی: همه entityها برای دسترسی به نام
            const promises = Object.entries(ENTITY_CONFIG).map(async ([type, cfg]) => {
                try {
                    const r = await this.api.get(cfg.api);
                    const items = r?.data ?? [];
                    const map = {};
                    items.forEach(it => { map[it.id] = it; });
                    this._entityCache[type] = map;
                } catch { this._entityCache[type] = {}; }
            });
            await Promise.all(promises);

            this._render();
        } catch (e) {
            this._toast('❌ خطا در بارگذاری', '#ef4444');
        } finally {
            this.ref('loading').style.display = 'none';
        }
    }

    _render() {
        const L = window.L;
        if (!this._map) return;

        this._layer.clearLayers();
        this._markers = [];

        const search = (this.ref('search')?.value ?? '').toLowerCase();
        const bounds = [];
        const counts = {};

        // پر کردن counts صفر برای همه types
        Object.keys(ENTITY_CONFIG).forEach(t => counts[t] = 0);

        this._allLocations.forEach(loc => {
            const type = loc.entity_type;
            const cfg  = ENTITY_CONFIG[type];
            if (!cfg) return;
            if (!this._enabledTypes.has(type)) return;

            const lat = parseFloat(loc.lat), lng = parseFloat(loc.lng);
            if (isNaN(lat) || isNaN(lng)) return;

            const entity = this._entityCache[type]?.[loc.entity_id];
            const name = entity?.[cfg.nameField] || entity?.name || loc.label || `${cfg.label} #${loc.entity_id}`;

            if (search && !`${name} ${loc.address ?? ''} ${loc.label ?? ''}`.toLowerCase().includes(search)) return;

            counts[type]++;
            bounds.push([lat, lng]);

            const m = L.marker([lat, lng], {
                icon: L.divIcon({
                    className: '',
                    iconSize: [32, 32],
                    html: `<div style="background:${cfg.color};color:#fff;border-radius:50%;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.3);font-size:14px;">${cfg.icon}</div>`,
                }),
            });

            m.bindTooltip(`
                <b>${cfg.icon} ${this.escape(name)}</b>
                <br><small style="color:#94a3b8;">${cfg.label}</small>
                ${loc.label ? '<br><b>📌 '+this.escape(loc.label)+'</b>' : ''}
                ${loc.address ? '<br><small>'+this.escape(loc.address)+'</small>' : ''}
            `, { direction: 'top' });

            m.on('click', () => this._showEntityPopup(type, loc.entity_id, name, loc));
            m.addTo(this._layer);
            this._markers.push(m);
        });

        // به‌روزرسانی count روی چیپ‌ها
        this.ref('filterBar').querySelectorAll('.umap-filter-chip').forEach(chip => {
            const type = chip.dataset.type;
            const span = chip.querySelector('.umap-count');
            if (span) span.textContent = counts[type] ?? 0;
        });

        const total = Object.values(counts).reduce((s, n) => s + n, 0);
        this.ref('totalLbl').textContent = `📍 مجموع: ${total} نقطه`;

        // fit bounds
        if (bounds.length && bounds.length < 200) {
            this._map.fitBounds(bounds, { padding: [40, 40], maxZoom: 14 });
        }
    }

    _showEntityPopup(type, id, name, loc) {
        const cfg = ENTITY_CONFIG[type];
        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${cfg.icon} ${this.escape(name)}</div>
            <div style="background:${cfg.color}1a;padding:8px 12px;border-radius:6px;font-size:12px;color:${cfg.color};margin-bottom:12px;font-weight:600;">
                ${cfg.label}
            </div>
            ${loc.label   ? `<div style="margin-bottom:6px;"><b>📌 برچسب:</b> ${this.escape(loc.label)}</div>` : ''}
            ${loc.address ? `<div style="margin-bottom:6px;"><b>📍 آدرس:</b> ${this.escape(loc.address)}</div>` : ''}
            <div style="margin-bottom:6px;"><b>🌐 مختصات:</b> <bdi dir="ltr">${loc.lat}, ${loc.lng}</bdi></div>
            ${loc.parcel_id ? `<div style="margin-bottom:6px;color:#3b82f6;"><b>🔗 پارسل:</b> #${loc.parcel_id}</div>` : ''}
            <div class="acc-modal__actions">
                <button class="acc-btn acc-btn--secondary" data-action="close">بستن</button>
            </div>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click', close);
        ov.querySelector('[data-action=close]').addEventListener('click', close);
        ov.addEventListener('click', e => { if (e.target === ov) close(); });
    }

    escape(s) { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
    _toast(m, b = '#10b981') {
        const t = document.createElement('div');
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${b};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;z-index:9999;`;
        t.textContent = m; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
