/**
 * edu-accounting-panel.js — گراف بهای تمام‌شده فعالیت‌های جلسه آموزشی
 */

function fmtMoney(n) {
    const v = Number(n) || 0;
    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 renderEduAbcPanel(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="abcSession"><option value="0">همه جلسات (نمای کلی)</option></select>
        </label>
        <button type="button" class="ea-abc__btn ea-abc__btn--primary" data-ref="abcReload">↻ بارگذاری</button>
        <button type="button" class="ea-abc__btn" data-ref="abcAllocate" style="display:none">💾 ذخیره تخصیص</button>
    </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 bindEduAbcPanel(panel, { api, esc, toast }) {
    const $ = (ref) => panel.querySelector(`[data-ref="${ref}"]`);
    let graph = { nodes: [], edges: [], person_shares: [], sessions: [] };
    let alloc = null;
    let sessionId = 0;

    async function loadSessions() {
        try {
            const res = await api('/education/acct/sessions');
            const rows = res?.data || res || [];
            const sel = $('abcSession');
            if (!sel) return;
            const cur = sel.value;
            sel.innerHTML = '<option value="0">همه جلسات (نمای کلی)</option>' +
                rows.map(s => {
                    const label = `#${s.id} — ${esc(s.session_type || '')} · ${esc(s.domain || '')} (${esc(s.status || '')})`;
                    return `<option value="${s.id}">${label}</option>`;
                }).join('');
            if (cur) sel.value = cur;
        } catch (e) {
            toast?.(e.message || 'خطا در لیست جلسات');
        }
    }

    function paintKpis() {
        const el = $('abcKpis');
        if (!el) return;
        const sessions = graph.sessions || [];
        const persons = graph.person_shares || [];
        const budget = sessions.reduce((s, p) => s + (Number(p.budget) || 0), 0);
        const cost = sessions.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>${sessions.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="ea-abc__muted">جلسه‌ای برای گراف نیست — ابتدا جلسه رزرو یا seed کنید.</div>';
            return;
        }

        const sessions = nodes.filter(n => n.type === 'session');
        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, sessions.length) * 42);
        const colX = { session: 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(sessions, colX.session);
        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(142,47,62,.45)" stroke-width="${sw}"/>`;
        }).join('');

        const nodeEls = nodes.map(n => {
            const fill = n.type === 'session' ? '#12141A' : n.type === 'activity' ? '#4A6270' : '#8E2F3E';
            const color = '#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="#2C3A45">${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="#6B7580" font-weight="700">جلسه</text>
                <text x="360" y="18" text-anchor="middle" font-size="11" fill="#6B7580" font-weight="700">فعالیت</text>
                <text x="640" y="18" text-anchor="middle" font-size="11" fill="#6B7580" 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() {
        sessionId = parseInt($('abcSession')?.value || '0', 10) || 0;
        const allocBtn = $('abcAllocate');
        if (allocBtn) allocBtn.style.display = sessionId > 0 ? '' : 'none';
        try {
            const g = await api(`/education/acct/cost-graph${sessionId ? '?session_id=' + sessionId : ''}`);
            graph = g?.data || g || {};
            alloc = null;
            if (sessionId > 0) {
                const c = await api(`/education/acct/activity-cost/${sessionId}`);
                alloc = c?.data || null;
            }
            paintKpis();
            paintGraph();
            paintSide();
        } catch (e) {
            toast?.(e.message || 'خطا در گراف');
        }
    }

    $('abcReload')?.addEventListener('click', () => reload());
    $('abcSession')?.addEventListener('change', () => reload());
    $('abcAllocate')?.addEventListener('click', async () => {
        if (!sessionId) return;
        try {
            const res = await api(`/education/acct/allocate/${sessionId}`, { method: 'POST', body: '{}' });
            toast?.(res.message || 'ذخیره شد');
            await reload();
        } catch (e) {
            toast?.(e.message || 'خطا در ذخیره');
        }
    });

    await loadSessions();
    await reload();
}
