/**
 * HrMapSection.js — نقشه پرسنل (محل سکونت/کار)
 */
import SectionBase from "../../accounting/SectionBase.js";

const TYPE_COLORS = {
    office:'#3b82f6', warehouse:'#f59e0b', home:'#10b981',
    site:'#ef4444', meeting:'#8b5cf6', branch:'#06b6d4',
    factory:'#dc2626', other:'#64748b',
};

export default class HrMapSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🗺️ نقشه پرسنل</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="mapEl" style="height:600px;border:1px solid #cbd5e1;border-radius:8px;background:#f8fafc;">
                <div style="padding:40px;text-align:center;color:#64748b;">⏳ بارگذاری نقشه...</div>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._loadLeaflet();
        this._initMap();
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
    }

    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");
        el.innerHTML = '';
        this._map = L.map(el).setView([29.5926, 52.5836], 12);
        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);
    }

    async _load() {
        try {
            const res = await this.api.get("/gis/locations/map", { entity_type: 'employee' });
            this._renderMarkers(res?.data ?? []);
        } catch {
            this._toast('❌ خطا در بارگذاری', '#ef4444');
        }
    }

    async _renderMarkers(locations) {
        const L = window.L;
        this._layer.clearLayers();

        if (!locations.length) {
            this._toast('موقعیتی برای پرسنل ثبت نشده', '#f59e0b');
            return;
        }

        // برای نمایش نام، اطلاعات کارمندان را هم بگیریم
        const empMap = {};
        try {
            const r = await this.api.get("/hr/employees");
            (r?.data ?? []).forEach(e => empMap[e.id] = e);
        } catch {}

        const bounds = [];
        locations.forEach(loc => {
            const lat = parseFloat(loc.lat), lng = parseFloat(loc.lng);
            if (isNaN(lat) || isNaN(lng)) return;
            const color = TYPE_COLORS[loc.location_type] ?? TYPE_COLORS.other;
            const emp = empMap[loc.entity_id];

            const m = L.circleMarker([lat, lng], {
                radius: 8, fillColor: color, color: '#fff', weight: 2, fillOpacity: 0.9,
            });
            const name = emp ? `${emp.first_name} ${emp.last_name}` : `#${loc.entity_id}`;
            m.bindTooltip(`
                <b>👤 ${this.escape(name)}</b>
                ${loc.label ? `<br>${this.escape(loc.label)}` : ''}
                ${loc.address ? `<br><small>${this.escape(loc.address)}</small>` : ''}
            `, { direction: 'top' });
            m.addTo(this._layer);
            bounds.push([lat, lng]);
        });

        if (bounds.length) this._map.fitBounds(bounds, { padding: [40, 40], maxZoom: 15 });
    }

    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);
    }
}
