/**
 * election-accounting-panel.js — گراف بهای تمام‌شده فعالیت‌های کمپین انتخابات
 */

function fmtMoney(n) {
    const v = Number(n) || 0;
    if (v >= 1e12) return (v / 1e12).toFixed(1) + ' ه.ت';
    if (v >= 1e9) return (v / 1e9).toFixed(1) + ' م.ت';
    if (v >= 1e6) return (v / 1e6).toFixed(0) + ' میلیون';
    return new Intl.NumberFormat('fa-IR').format(Math.round(v));
}

export function renderElectionAbcPanel(esc) {
    return `
<div class="ea-abc" dir="rtl">
    <div class="ea-abc__head">
        <div>
            <span class="ea-kicker">Activity Cost Graph</span>
            <h2>حسابداری فعالیت — کمپین ↔ فعالیت ↔ خدمه</h2>
            <p>تخصیص بودجه ستاد به فعالیت‌های انتخاباتی و سهم هر واحد/هوادار روی گراف.</p>
        </div>
    </div>
    <div class="ea-abc__toolbar">
        <label>کمپین
            <select data-ref="abcCampaign"><option value="0">همه کمپین‌ها (نمای کلی)</option></select>
        </label>
        <button type="button" class="el-btn el-btn--primary" data-ref="abcReload">↻ بارگذاری</button>
        <button type="button" class="el-btn" data-ref="abcAllocate" style="display:none">💾 ذخیره تخصیص</button>
        <a href="/acc-engine/election-accounting.php" class="el-btn el-btn--sm" target="_blank" rel="noopener">دفتر کل →</a>
    </div>
    <div class="ea-abc__kpis" data-ref="abcKpis"></div>
    <div class="ea-abc__layout">
        <div>
            <div class="ea-abc__canvas" data-ref="abcCanvas"></div>
            <div class="ea-abc__table-wrap" data-ref="abcLines"></div>
        </div>
        <aside class="ea-abc__side">
            <h3>سهم خدمه / هواداران</h3>
            <div data-ref="abcPersons"></div>
            <h3 style="margin-top:20px">فعالیت‌ها</h3>
            <div data-ref="abcActs"></div>
        </aside>
    </div>
</div>`;
}

export async function bindElectionAbcPanel(panel, { request, esc, toast }) {
    const $ = (ref) => panel.querySelector(`[data-ref="${ref}"]`);
    let graph = { nodes: [], edges: [], person_shares: [], campaigns: [] };
    let alloc = null;
    let campaignId = 0;

    async function loadCampaigns() {
        try {
            const res = await request('GET', 'election/acct/campaigns');
            const rows = res?.data || res || [];
            const sel = $('abcCampaign');
            if (!sel) return;
            const cur = sel.value;
            sel.innerHTML = '<option value="0">همه کمپین‌ها (نمای کلی)</option>' +
                rows.map(c => `<option value="${c.id}">${esc(c.campaign_key || '')} — ${esc(c.title || '')}</option>`).join('');
            if (cur) sel.value = cur;
            else if (rows.length === 1) sel.value = String(rows[0].id);
        } catch (e) {
            toast?.(e.message || 'خطا در لیست کمپین‌ها', true);
        }
    }

    function paintKpis() {
        const el = $('abcKpis');
        if (!el) return;
        const campaigns = graph.campaigns || [];
        const persons = graph.person_shares || [];
        const budget = campaigns.reduce((s, p) => s + (Number(p.budget) || 0), 0);
        const cost = campaigns.reduce((s, p) => s + (Number(p.cost) || 0), 0);
        if (alloc?.totals) {
            el.innerHTML = `
                <div class="ea-abc__kpi"><strong>${fmtMoney(alloc.totals.budget)}</strong><span>بودجه کمپین</span></div>
                <div class="ea-abc__kpi"><strong>${fmtMoney(alloc.totals.activity_cost)}</strong><span>هزینه فعالیت</span></div>
                <div class="ea-abc__kpi"><strong>${(alloc.totals.coverage || 0).toFixed?.(1) ?? alloc.totals.coverage}%</strong><span>پوشش بودجه</span></div>
                <div class="ea-abc__kpi"><strong>${(alloc.person_shares || []).length}</strong><span>عضو خدمه</span></div>`;
            return;
        }
        el.innerHTML = `
            <div class="ea-abc__kpi"><strong>${campaigns.length}</strong><span>کمپین</span></div>
            <div class="ea-abc__kpi"><strong>${fmtMoney(budget)}</strong><span>جمع بودجه</span></div>
            <div class="ea-abc__kpi"><strong>${fmtMoney(cost)}</strong><span>جمع هزینه</span></div>
            <div class="ea-abc__kpi"><strong>${persons.length}</strong><span>در گراف</span></div>`;
    }

    function paintGraph() {
        const canvas = $('abcCanvas');
        if (!canvas) return;
        const nodes = graph.nodes || [];
        const edges = graph.edges || [];
        if (!nodes.length) {
            canvas.innerHTML = '<div class="el-msg">کمپینی برای گراف نیست — ابتدا نصب ABC را اجرا کنید.</div>';
            return;
        }

        const campaigns = nodes.filter(n => n.type === 'campaign' || n.type === 'project');
        const acts = nodes.filter(n => n.type === 'activity');
        const people = nodes.filter(n => n.type === 'person');
        const W = 720, H = Math.max(360, 80 + Math.max(acts.length, people.length, campaigns.length) * 42);
        const colX = { campaign: 80, activity: 360, person: 640 };
        const place = (list, x) => {
            const gap = list.length > 1 ? (H - 60) / (list.length - 1) : 0;
            list.forEach((n, i) => {
                n._x = x;
                n._y = 40 + (list.length === 1 ? (H - 80) / 2 : i * gap);
            });
        };
        place(campaigns, colX.campaign);
        place(acts, colX.activity);
        place(people, colX.person);
        const byId = Object.fromEntries(nodes.map(n => [n.id, n]));

        const edgePaths = edges.map(e => {
            const a = byId[e.from], b = byId[e.to];
            if (!a || !b) return '';
            const mid = (a._x + b._x) / 2;
            const sw = Math.max(1.2, Math.min(6, Math.log10((e.amount || 1) + 10)));
            return `<path d="M${a._x},${a._y} C${mid},${a._y} ${mid},${b._y} ${b._x},${b._y}"
                fill="none" stroke="rgba(196,30,58,.45)" stroke-width="${sw}"/>`;
        }).join('');

        const nodeEls = nodes.map(n => {
            const fill = (n.type === 'campaign' || n.type === 'project') ? '#141A22'
                : n.type === 'activity' ? '#4A6FA5' : '#C41E3A';
            const color = n.type === 'person' ? '#fff' : '#fff';
            const label = String(n.label || '').slice(0, 22);
            return `<g>
                <circle cx="${n._x}" cy="${n._y}" r="14" fill="${fill}"/>
                <text x="${n._x}" y="${n._y + 28}" text-anchor="middle" font-size="10" fill="#2A3441">${esc(label)}</text>
                <text x="${n._x}" y="${n._y + 4}" text-anchor="middle" font-size="8" fill="${color}" font-weight="700">${n.type === 'person' ? '◆' : n.type === 'activity' ? '◇' : '●'}</text>
            </g>`;
        }).join('');

        canvas.innerHTML = `
            <svg class="ea-abc__svg" viewBox="0 0 ${W} ${H}" role="img" aria-label="گراف هزینه کمپین">
                <text x="80" y="18" text-anchor="middle" font-size="11" fill="#6A7585" font-weight="700">کمپین</text>
                <text x="360" y="18" text-anchor="middle" font-size="11" fill="#6A7585" font-weight="700">فعالیت</text>
                <text x="640" y="18" text-anchor="middle" font-size="11" fill="#6A7585" font-weight="700">خدمه</text>
                ${edgePaths}${nodeEls}
            </svg>`;
    }

    function paintSide() {
        const persons = alloc?.person_shares || graph.person_shares || [];
        const roles = alloc?.role_labels || graph.role_labels || {};
        const pEl = $('abcPersons');
        if (pEl) {
            pEl.innerHTML = persons.length
                ? persons.map(p => `
                    <div class="ea-abc__person">
                        <strong>${esc(p.name)}</strong>
                        <small>${esc(roles[p.role] || p.role || '')}</small>
                        <span>${fmtMoney(p.amount)}</span>
                    </div>`).join('')
                : '<p class="ea-abc__muted">خدمه‌ای محاسبه نشده</p>';
        }
        const acts = alloc?.activities || [];
        const aEl = $('abcActs');
        if (aEl) {
            aEl.innerHTML = acts.length
                ? acts.map(a => `<div class="ea-abc__act"><b>${esc(a.name)}</b><small>${esc(a.pool)} · ${a.driver}</small></div>`).join('')
                : '<p class="ea-abc__muted">فعالیت‌ها پس از انتخاب کمپین نمایش داده می‌شوند</p>';
        }
        const linesEl = $('abcLines');
        if (linesEl) {
            const lines = alloc?.lines || [];
            linesEl.innerHTML = lines.length ? `
                <table class="ea-abc__table">
                    <thead><tr><th>فعالیت</th><th>عضو</th><th>سهم</th><th>مبلغ</th></tr></thead>
                    <tbody>${lines.map(l => `<tr>
                        <td>${esc(l.activity_name)}</td>
                        <td>${esc(l.person_label)}</td>
                        <td>${Number(l.share_pct || 0).toFixed(1)}%</td>
                        <td>${fmtMoney(l.amount)}</td>
                    </tr>`).join('')}</tbody>
                </table>` : '';
        }
    }

    async function reload() {
        campaignId = parseInt($('abcCampaign')?.value || '0', 10) || 0;
        const allocBtn = $('abcAllocate');
        if (allocBtn) allocBtn.style.display = campaignId > 0 ? '' : 'none';
        try {
            const g = await request('GET', `election/acct/cost-graph${campaignId ? '?campaign_id=' + campaignId : ''}`);
            graph = g?.data || g || {};
            alloc = null;
            if (campaignId > 0) {
                const c = await request('GET', `election/acct/activity-cost/${campaignId}`);
                alloc = c?.data || null;
            }
            paintKpis();
            paintGraph();
            paintSide();
        } catch (e) {
            toast?.(e.message || 'خطا در گراف', true);
        }
    }

    $('abcReload')?.addEventListener('click', () => reload());
    $('abcCampaign')?.addEventListener('change', () => reload());
    $('abcAllocate')?.addEventListener('click', async () => {
        if (!campaignId) return;
        try {
            const res = await request('POST', `election/acct/allocate/${campaignId}`, {});
            toast?.(res.message || 'ذخیره شد');
            await reload();
        } catch (e) {
            toast?.(e.message || 'خطا در ذخیره', true);
        }
    });

    await loadCampaigns();
    await reload();
}
