/**
 * CrmDashSection.js — داشبورد CRM
 * یادآورهای امروز | لیدهای سرد | آمار
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_LABEL= {new_lead:'سرنخ',interested:'علاقه‌مند',visited:'بازدید',negotiating:'مذاکره',proposed:'پیشنهاد',reserved:'رزرو',converted:'تبدیل شد',lost:'از دست رفت'};
const STATUS_COLOR= {new_lead:'#94a3b8',interested:'#3b82f6',visited:'#8b5cf6',negotiating:'#f59e0b',proposed:'#f97316',reserved:'#10b981',converted:'#059669',lost:'#ef4444'};
const SOURCE_LABEL= {referral:'معرفی',website:'سایت',social:'شبکه اجتماعی',advertisement:'تبلیغات',exhibition:'نمایشگاه',cold_call:'تماس سرد',other:'سایر'};

export default class CrmDashSection 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('/crm/dashboard');
            this._render(root, res);
        } catch {
            root.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _render(root, d) {
        const byStatus = {};
        (d.by_status||[]).forEach(r=>{ byStatus[r.status]=(parseInt(r.cnt)||0); });

        const activeStages   = ['new_lead','interested','visited','negotiating','proposed','reserved'];
        const totalActive    = activeStages.reduce((s,k)=>s+(byStatus[k]||0),0);
        const totalConverted = byStatus['converted']||0;
        const totalLost      = byStatus['lost']||0;
        const convRate       = (totalConverted+totalLost) > 0
            ? Math.round(totalConverted/(totalConverted+totalLost)*100) : 0;

        // KPI
        const kpiHtml = `
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px;">
            <div class="permit-kpi-card" style="border-top:3px solid #3b82f6;">
                <div style="font-size:22px;font-weight:800;color:#3b82f6;">${totalActive}</div>
                <div style="font-size:11px;color:#64748b;">لید فعال</div>
            </div>
            <div class="permit-kpi-card" style="border-top:3px solid #10b981;">
                <div style="font-size:22px;font-weight:800;color:#10b981;">${totalConverted}</div>
                <div style="font-size:11px;color:#64748b;">تبدیل شده</div>
            </div>
            <div class="permit-kpi-card" style="border-top:3px solid #ef4444;">
                <div style="font-size:22px;font-weight:800;color:#ef4444;">${totalLost}</div>
                <div style="font-size:11px;color:#64748b;">از دست رفته</div>
            </div>
            <div class="permit-kpi-card" style="border-top:3px solid #8b5cf6;">
                <div style="font-size:22px;font-weight:800;color:#8b5cf6;">${convRate}٪</div>
                <div style="font-size:11px;color:#64748b;">نرخ تبدیل</div>
            </div>
        </div>`;

        // یادآورهای معوق
        const remHtml = (d.overdue_reminders||[]).length ? `
        <div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:10px;padding:14px;margin-bottom:16px;">
            <div style="font-weight:700;font-size:13px;margin-bottom:10px;">🔔 یادآورهای معوق (${d.overdue_reminders.length})</div>
            ${d.overdue_reminders.map(r=>`
            <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid rgba(0,0,0,.05);font-size:12px;">
                <div>
                    <b>${this.escape(r.title)}</b>
                    <div style="color:#64748b;">${this.escape(r.lead_name)} ${r.lead_phone?'— '+r.lead_phone:''}</div>
                </div>
                <span style="color:#ef4444;font-size:11px;">📅 ${r.due_date}</span>
            </div>`).join('')}
        </div>` : `<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;padding:14px;margin-bottom:16px;color:#166534;">✅ هیچ یادآور معوقی وجود ندارد</div>`;

        // لیدهای سرد
        const coldHtml = (d.cold_leads||[]).length ? `
        <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:10px;padding:14px;margin-bottom:16px;">
            <div style="font-weight:700;font-size:13px;margin-bottom:10px;">🧊 لیدهای سرد (بدون تماس +۷ روز)</div>
            ${d.cold_leads.map(l=>`
            <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid rgba(0,0,0,.05);font-size:12px;">
                <div>
                    <b>${this.escape(l.name)}</b>
                    ${l.phone?`<span style="color:#64748b;"> — ${l.phone}</span>`:''}
                </div>
                <span style="color:#f59e0b;font-weight:700;">${l.days} روز</span>
            </div>`).join('')}
        </div>` : '';

        // منابع
        const sourceHtml = (d.by_source||[]).length ? `
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:14px;margin-bottom:16px;">
            <div style="font-weight:700;font-size:13px;margin-bottom:10px;">📌 منبع آشنایی لیدها</div>
            ${d.by_source.map(s=>`
            <div style="display:flex;justify-content:space-between;align-items:center;padding:5px 0;font-size:12px;">
                <span>${SOURCE_LABEL[s.source]||s.source}</span>
                <div style="display:flex;align-items:center;gap:8px;">
                    <div style="background:#e2e8f0;border-radius:4px;height:8px;width:80px;overflow:hidden;">
                        <div style="height:100%;background:#3b82f6;border-radius:4px;width:${totalActive>0?Math.round(s.cnt/totalActive*100):0}%"></div>
                    </div>
                    <b>${s.cnt}</b>
                </div>
            </div>`).join('')}
        </div>` : '';

        // وضعیت‌ها
        const stageHtml = `
        <div style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:14px;margin-bottom:16px;">
            <div style="font-weight:700;font-size:13px;margin-bottom:10px;">📊 توزیع بر اساس مرحله</div>
            ${activeStages.map(k=>byStatus[k]>0?`
            <div style="display:flex;justify-content:space-between;align-items:center;padding:4px 0;font-size:12px;">
                <span style="color:${STATUS_COLOR[k]};">${STATUS_LABEL[k]}</span>
                <div style="display:flex;align-items:center;gap:8px;">
                    <div style="background:#e2e8f0;border-radius:4px;height:8px;width:80px;overflow:hidden;">
                        <div style="height:100%;background:${STATUS_COLOR[k]};border-radius:4px;width:${totalActive>0?Math.round((byStatus[k]||0)/totalActive*100):0}%"></div>
                    </div>
                    <b>${byStatus[k]||0}</b>
                </div>
            </div>`:'').join('')}
        </div>`;

        root.innerHTML = `
        ${kpiHtml}
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
            <div>${remHtml}${coldHtml}</div>
            <div>${stageHtml}${sourceHtml}</div>
        </div>`;
    }
}
