/**
 * TreasuryOverviewSection.js — نمای کلی همه پروژه‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class TreasuryOverviewSection 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('/treasury/overview');
            this._render(res?.data ?? []);
        } catch {
            root.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _render(projects) {
        const root = this.ref('root');
        const fmt  = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));

        if (!projects.length) {
            root.innerHTML = `<div class="acc-empty">پروژه‌ای یافت نشد.</div>`;
            return;
        }

        const totalIncome  = projects.reduce((s,p)=>s+parseFloat(p.total_income||0),0);
        const totalExpense = projects.reduce((s,p)=>s+parseFloat(p.total_expense||0),0);
        const totalNet     = totalIncome - totalExpense;
        const netColor     = totalNet>=0?'#10b981':'#ef4444';

        root.innerHTML = `
        <!-- KPI کلی شرکت -->
        <div class="treasury-kpi-grid" style="margin-bottom:24px;">
            <div class="treasury-kpi treasury-kpi--expense">
                <div class="treasury-kpi-icon">💸</div>
                <div class="treasury-kpi-label">کل هزینه‌ها</div>
                <div class="treasury-kpi-value">${fmt(totalExpense)}</div>
                <div class="treasury-kpi-sub">ریال — همه پروژه‌ها</div>
            </div>
            <div class="treasury-kpi treasury-kpi--income">
                <div class="treasury-kpi-icon">💰</div>
                <div class="treasury-kpi-label">کل درآمدها</div>
                <div class="treasury-kpi-value">${fmt(totalIncome)}</div>
                <div class="treasury-kpi-sub">ریال — همه پروژه‌ها</div>
            </div>
            <div class="treasury-kpi" style="border-top:3px solid ${netColor};">
                <div class="treasury-kpi-icon">${totalNet>=0?'📈':'📉'}</div>
                <div class="treasury-kpi-label">سود/زیان کل</div>
                <div class="treasury-kpi-value" style="color:${netColor};">${fmt(Math.abs(totalNet))}</div>
                <div class="treasury-kpi-sub">ریال</div>
            </div>
            <div class="treasury-kpi" style="border-top:3px solid #8b5cf6;">
                <div class="treasury-kpi-icon">🏢</div>
                <div class="treasury-kpi-label">پروژه فعال</div>
                <div class="treasury-kpi-value" style="color:#8b5cf6;">
                    ${projects.filter(p=>p.status==='active').length}
                </div>
                <div class="treasury-kpi-sub">از ${projects.length} پروژه</div>
            </div>
        </div>

        <!-- جدول پروژه‌ها -->
        <div class="treasury-overview-table">
            <div class="treasury-overview-header">
                <span>پروژه</span>
                <span>هزینه</span>
                <span>درآمد</span>
                <span>سود/زیان</span>
                <span>واحدها</span>
                <span>وضعیت</span>
            </div>
            ${projects.map(p=>{
                const net    = parseFloat(p.total_income||0) - parseFloat(p.total_expense||0);
                const nc     = net>=0?'#10b981':'#ef4444';
                const sellPct= p.unit_count>0?Math.round(p.sold_count/p.unit_count*100):0;
                const statusColor = {active:'#10b981',completed:'#3b82f6',planned:'#f59e0b',archived:'#94a3b8'}[p.status]||'#94a3b8';
                const statusLabel = {active:'فعال',completed:'تکمیل',planned:'برنامه‌ریزی',archived:'بایگانی'}[p.status]||p.status;
                return `
                <div class="treasury-overview-row">
                    <span style="font-weight:700;color:#1e293b;">${this.escape(p.name)}</span>
                    <span style="color:#ef4444;">${fmt(p.total_expense)}</span>
                    <span style="color:#10b981;">${fmt(p.total_income)}</span>
                    <span style="color:${nc};font-weight:700;">${net>=0?'+':''}${fmt(net)}</span>
                    <span>
                        ${p.unit_count>0?`
                        <div style="font-size:11px;">${p.sold_count}/${p.unit_count} (${sellPct}٪)</div>
                        <div class="treasury-bar-track" style="height:4px;margin-top:2px;">
                            <div style="height:100%;background:#3b82f6;border-radius:2px;width:${sellPct}%"></div>
                        </div>`:'-'}
                    </span>
                    <span>
                        <span style="background:${statusColor};color:#fff;padding:2px 8px;border-radius:6px;font-size:11px;">
                            ${statusLabel}
                        </span>
                    </span>
                </div>`;
            }).join('')}
        </div>`;
    }
}
