/**
 * melk-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 renderAccountingPanel(esc) {
    return `
<div class="ma-abc" dir="rtl">
    <div class="ma-abc__head">
        <div>
            <span class="ma-kicker">Activity Cost Graph</span>
            <h2>حسابداری مشارکت — پروژه ↔ فعالیت ↔ شریک</h2>
            <p>تخصیص بودجه پروژه به فعالیت‌های ساختمانی و سهم هر شریک روی گراف.</p>
        </div>
    </div>
    <div class="ma-abc__toolbar">
        <label>پروژه
            <select data-ref="abcProject"><option value="0">همه پروژه‌ها (نمای کلی)</option></select>
        </label>
        <button type="button" class="red-btn red-btn--primary" data-ref="abcReload">↻ بارگذاری</button>
        <button type="button" class="red-btn" data-ref="abcAllocate" style="display:none">💾 ذخیره تخصیص</button>
    </div>
    <div class="ma-abc__kpis" data-ref="abcKpis"></div>
    <div class="ma-abc__layout">
        <div>
            <div class="ma-abc__canvas" data-ref="abcCanvas"></div>
            <div class="ma-abc__table-wrap" data-ref="abcLines"></div>
        </div>
        <aside class="ma-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 bindAccountingPanel(panel, { request, esc, toast }) {
    const $ = (ref) => panel.querySelector(`[data-ref="${ref}"]`);
    let graph = { nodes: [], edges: [], person_shares: [], projects: [] };
    let alloc = null;
    let projectId = 0;

    async function loadProjects() {
        try {
            const res = await request('GET', 'melk/construction');
            const rows = res?.data || res || [];
            const sel = $('abcProject');
            if (!sel) return;
            const cur = sel.value;
            sel.innerHTML = '<option value="0">همه پروژه‌ها (نمای کلی)</option>' +
                rows.map(p => `<option value="${p.id}">${esc(p.project_key || '')} — ${esc(p.title || '')}</option>`).join('');
            if (cur) sel.value = cur;
        } catch (e) {
            toast?.(e.message || 'خطا در لیست پروژه‌ها', true);
        }
    }

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

        const projects = nodes.filter(n => 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, projects.length) * 42);
        const colX = { project: 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(projects, colX.project);
        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(201,162,77,.55)" stroke-width="${sw}"/>`;
        }).join('');

        const nodeEls = nodes.map(n => {
            const fill = n.type === 'project' ? '#071525' : n.type === 'activity' ? '#3A7CA5' : '#C9A24D';
            const color = n.type === 'person' ? '#071525' : '#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="#243447">${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="ma-abc__svg" viewBox="0 0 ${W} ${H}" role="img" aria-label="گراف هزینه">
                <text x="80" y="18" text-anchor="middle" font-size="11" fill="#6B7A8D" font-weight="700">پروژه</text>
                <text x="360" y="18" text-anchor="middle" font-size="11" fill="#6B7A8D" font-weight="700">فعالیت</text>
                <text x="640" y="18" text-anchor="middle" font-size="11" fill="#6B7A8D" 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="ma-abc__person">
                        <strong>${esc(p.name)}</strong>
                        <small>${esc(roles[p.role] || p.role || '')}</small>
                        <span>${fmtMoney(p.amount)}</span>
                    </div>`).join('')
                : '<p class="ma-abc__muted">شریکی محاسبه نشده</p>';
        }
        const acts = alloc?.activities || [];
        const aEl = $('abcActs');
        if (aEl) {
            aEl.innerHTML = acts.length
                ? acts.map(a => `<div class="ma-abc__act"><b>${esc(a.name)}</b><small>${esc(a.pool)} · ${a.driver}</small></div>`).join('')
                : '<p class="ma-abc__muted">فعالیت‌ها پس از انتخاب پروژه نمایش داده می‌شوند</p>';
        }
        const linesEl = $('abcLines');
        if (linesEl) {
            const lines = alloc?.lines || [];
            linesEl.innerHTML = lines.length ? `
                <table class="ma-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() {
        projectId = parseInt($('abcProject')?.value || '0', 10) || 0;
        const allocBtn = $('abcAllocate');
        if (allocBtn) allocBtn.style.display = projectId > 0 ? '' : 'none';
        try {
            const g = await request('GET', `melk/acct/cost-graph${projectId ? '?project_id=' + projectId : ''}`);
            graph = g?.data || g || {};
            alloc = null;
            if (projectId > 0) {
                const c = await request('GET', `melk/acct/activity-cost/${projectId}`);
                alloc = c?.data || null;
            }
            paintKpis();
            paintGraph();
            paintSide();
        } catch (e) {
            toast?.(e.message || 'خطا در گراف', true);
        }
    }

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

    await loadProjects();
    await reload();
}
