/**
 * PermitDashSection.js — داشبورد مجوزها
 * هشدار انقضا | عوارض معوق | آمار
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_LABEL= {draft:'پیش‌نویس',submitted:'ارسال‌شده',under_review:'در بررسی',approved:'تأیید',active:'فعال',completed:'پایان کار',rejected:'رد',expired:'منقضی'};
const STATUS_COLOR= {draft:'#94a3b8',submitted:'#3b82f6',under_review:'#f59e0b',approved:'#8b5cf6',active:'#10b981',completed:'#059669',rejected:'#ef4444',expired:'#dc2626'};
const TYPE_LABEL  = {build:'پروانه ساخت',renovation:'بازسازی',demolish:'تخریب',use_change:'تغییر کاربری',completion:'پایان کار'};

export default class PermitDashSection extends SectionBase {

    async template() { return `<div data-ref="root"></div>`; }
    async afterRender() { await this._load(); }

    async _load() {
        const root = this.ref('root');
        root.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get('/permits/dashboard');
            this._render(root, res);
        } catch {
            root.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _render(root, d) {
        const fmt  = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const byStatus = {};
        (d.by_status||[]).forEach(r=>{ byStatus[r.status]=(parseInt(r.cnt)||0); });
        const total = Object.values(byStatus).reduce((s,v)=>s+v,0);

        const kpiHtml = `
        <div class="permit-kpi-grid">
            ${Object.entries(STATUS_LABEL).map(([k,v])=>byStatus[k]>0?`
            <div class="permit-kpi-card" style="border-top:3px solid ${STATUS_COLOR[k]};">
                <div style="font-size:22px;font-weight:800;color:${STATUS_COLOR[k]};">${byStatus[k]||0}</div>
                <div style="font-size:11px;color:#64748b;">${v}</div>
            </div>`:''
            ).join('')}
            <div class="permit-kpi-card" style="border-top:3px solid #1e293b;">
                <div style="font-size:22px;font-weight:800;color:#1e293b;">${total}</div>
                <div style="font-size:11px;color:#64748b;">کل پروانه‌ها</div>
            </div>
        </div>`;

        const expiringHtml = (d.expiring||[]).length ? `
        <div class="permit-alert-card permit-alert-card--warning">
            <div class="permit-alert-title">⏰ پروانه‌های رو به انقضا (۶۰ روز آینده)</div>
            ${d.expiring.map(pm=>`
            <div class="permit-alert-row">
                <div>
                    <b>${pm.permit_number||'—'}</b>
                    <span style="font-size:11px;color:#64748b;margin-right:6px;">${TYPE_LABEL[pm.type]||pm.type}</span>
                </div>
                <span style="color:${pm.days_left<=14?'#ef4444':'#f59e0b'};font-weight:700;font-size:12px;">
                    ${pm.days_left} روز — ${pm.expiry_date}
                </span>
            </div>`).join('')}
        </div>` : `<div class="permit-alert-card permit-alert-card--ok">✅ هیچ پروانه‌ای در ۶۰ روز آینده منقضی نمی‌شود</div>`;

        const feesHtml = (d.pending_fees||[]).length ? `
        <div class="permit-alert-card permit-alert-card--danger">
            <div class="permit-alert-title">💳 عوارض معوق</div>
            ${d.pending_fees.map(f=>`
            <div class="permit-alert-row">
                <div>
                    <div style="font-size:12px;font-weight:700;">${this.escape(f.description)}</div>
                    <div style="font-size:11px;color:#64748b;">${f.permit_number||'—'} | ${TYPE_LABEL[f.permit_type]||f.permit_type}</div>
                </div>
                <div style="text-align:left;">
                    <div style="font-weight:700;color:#ef4444;">${fmt(f.amount)} ریال</div>
                    ${f.due_date?`<div style="font-size:10px;color:#94a3b8;">${f.due_date}</div>`:''}
                </div>
            </div>`).join('')}
        </div>` : `<div class="permit-alert-card permit-alert-card--ok">✅ هیچ عارضه معوقی وجود ندارد</div>`;

        root.innerHTML = `
        ${kpiHtml}
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px;">
            <div>${expiringHtml}</div>
            <div>${feesHtml}</div>
        </div>`;
    }
}
