// expenses.jsx — per-project expense report
//   • Dashboard mode  (interactive, on-screen charts & cards)
//   • Statement mode  (formal accounting document — this is what prints / exports to PDF)

const { useState: useStateE } = React;
const { STAGES: STAGES_E, PRIORITIES: PRI_E } = window.SEED;

const ISSUE_DATE = '13 Jun 2026';
const COMPANY = {
  name: 'IdeaPipeline System',
  addr: '',
  meta: '',
};

function numToWords(num) {
  num = Math.round(num || 0);
  if (num === 0) return 'Zero';
  const a = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
  const b = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
  const g = ['', 'Thousand', 'Million', 'Billion'];
  const three = (n) => {
    let s = '';
    const h = Math.floor(n / 100), r = n % 100;
    if (h) s += a[h] + ' Hundred' + (r ? ' ' : '');
    if (r < 20) s += a[r];
    else s += b[Math.floor(r / 10)] + (r % 10 ? '-' + a[r % 10] : '');
    return s;
  };
  let res = '', i = 0;
  while (num > 0) {
    const chunk = num % 1000;
    if (chunk) res = three(chunk) + (g[i] ? ' ' + g[i] : '') + (res ? ' ' + res : '');
    num = Math.floor(num / 1000); i++;
  }
  return res.trim();
}

const money2 = (n) => window.fmtMoney(n, { bare: true, dp: 2 });

function ExpenseReport({ project }) {
  const [mode, setMode] = useStateE('dashboard');
  const tasks = project.tasks;
  const total = tasks.reduce((n, t) => n + (t.cost || 0), 0);
  const byStage = {};
  STAGES_E.forEach((s) => { byStage[s.id] = tasks.filter((t) => t.stage === s.id).reduce((n, t) => n + (t.cost || 0), 0); });

  const people = {};
  tasks.forEach((t) => { people[t.assignee] = (people[t.assignee] || 0) + (t.cost || 0); });
  const peopleRows = Object.entries(people).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);

  const stageMeta = {
    pending:   { label: 'Pending',    hue: 38,   note: 'Budgeted / not started' },
    inprocess: { label: 'In Process', hue: null, note: 'Committed & in progress' },
    complete:  { label: 'Complete',   hue: 152,  note: 'Spent & verified' },
  };
  const stageColor = (id) => id === 'inprocess' ? 'var(--primary)' : `oklch(0.62 0.15 ${stageMeta[id].hue})`;
  const pct = (v) => total ? (v / total) * 100 : 0;

  return (
    <div className={'view-pad report mode-' + mode}>
      {/* toolbar — screen only */}
      <div className="report-toolbar">
        <div className="seg report-mode">
          <button className={'seg-btn' + (mode === 'dashboard' ? ' on' : '')} onClick={() => setMode('dashboard')}>Dashboard</button>
          <button className={'seg-btn' + (mode === 'statement' ? ' on' : '')} onClick={() => setMode('statement')}>Statement</button>
        </div>
        <span className="report-hint">{mode === 'statement' ? 'Formal document — this is what exports to PDF' : 'Interactive overview'}</span>
        <div style={{ flex: 1 }} />
        <button className="btn-primary" onClick={() => window.print()}>
          <window.Icon name="download" size={16} /> Save as PDF
        </button>
      </div>

      {/* ---------- dashboard ---------- */}
      <div className="report-dashboard">
        <div className="report-head">
          <div>
            <span className="proj-mono" style={{ color: 'var(--text-faint)' }}>Cost overview · as of {ISSUE_DATE}</span>
            <h1 className="view-title" style={{ marginTop: 4 }}>{project.name} — Cost Breakdown</h1>
          </div>
        </div>
        <div className="report-summary">
          <div className="sum-card hero">
            <span className="sum-lbl"><window.Icon name="wallet" size={15} /> Total project cost</span>
            <span className="sum-val big">{window.fmtMoney(total)}</span>
            <span className="sum-sub">{tasks.filter((t) => t.cost > 0).length} of {tasks.length} tasks have a cost</span>
          </div>
          {STAGES_E.map((s) => (
            <div key={s.id} className="sum-card">
              <span className="sum-lbl"><span className="sum-dot" style={{ background: stageColor(s.id) }} />{stageMeta[s.id].label}</span>
              <span className="sum-val">{window.fmtMoney(byStage[s.id])}</span>
              <span className="sum-sub">{stageMeta[s.id].note} · {Math.round(pct(byStage[s.id]))}%</span>
            </div>
          ))}
        </div>
        <div className="report-bar-wrap">
          <div className="report-bar">
            {STAGES_E.map((s) => byStage[s.id] > 0 && (
              <div key={s.id} className="report-bar-seg" title={`${stageMeta[s.id].label}: ${window.fmtMoney(byStage[s.id])}`}
                style={{ width: pct(byStage[s.id]) + '%', background: stageColor(s.id) }} />
            ))}
          </div>
          <div className="report-bar-legend">
            {STAGES_E.map((s) => (
              <span key={s.id}><span className="sum-dot" style={{ background: stageColor(s.id) }} />{stageMeta[s.id].label}</span>
            ))}
          </div>
        </div>
        <div className="report-cols">
          <div className="report-table-card">
            <div className="rt-title">Line items</div>
            <table className="rt">
              <thead><tr><th>Task</th><th>Owner</th><th>Priority</th><th>Date</th><th className="num">Cost</th></tr></thead>
              {STAGES_E.map((s) => {
                const rows = tasks.filter((t) => t.stage === s.id);
                if (!rows.length) return null;
                return (
                  <tbody key={s.id}>
                    <tr className="rt-group"><td colSpan={5}>
                      <span className="sum-dot" style={{ background: stageColor(s.id) }} />{stageMeta[s.id].label}
                    </td></tr>
                    {rows.map((t) => {
                      const u = window.userById(t.assignee);
                      return (
                        <tr key={t.id}>
                          <td className="rt-task">{t.title}</td>
                          <td><span className="rt-owner"><window.Avatar id={t.assignee} size={20} />{u.name.split(' ')[0]}</span></td>
                          <td><window.PriorityTag level={t.priority} /></td>
                          <td className="rt-date">{window.fmtDate(t.spentOn) || <span className="muted">—</span>}</td>
                          <td className="num mono">{t.cost > 0 ? window.fmtMoney(t.cost) : <span className="muted">—</span>}</td>
                        </tr>
                      );
                    })}
                    <tr className="rt-subtotal">
                      <td colSpan={4}>{stageMeta[s.id].label} subtotal</td>
                      <td className="num mono">{window.fmtMoney(byStage[s.id])}</td>
                    </tr>
                  </tbody>
                );
              })}
              <tfoot><tr><td colSpan={4}>Project total</td><td className="num mono">{window.fmtMoney(total)}</td></tr></tfoot>
            </table>
          </div>
          <div className="report-side">
            <div className="report-table-card">
              <div className="rt-title">By team member</div>
              <div className="person-list">
                {peopleRows.map(([id, v]) => {
                  const u = window.userById(id);
                  return (
                    <div key={id} className="person-row">
                      <window.Avatar id={id} size={30} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="person-top">
                          <span className="person-name">{u.name}</span>
                          <span className="mono person-amt">{window.fmtMoney(v)}</span>
                        </div>
                        <div className="person-track"><div className="person-fill" style={{ width: pct(v) + '%' }} /></div>
                      </div>
                    </div>
                  );
                })}
                {peopleRows.length === 0 && <div className="muted" style={{ padding: 8 }}>No costs recorded yet.</div>}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ---------- formal statement (prints to PDF) ---------- */}
      <div className="acct-doc-frame">
        <AccountingStatement project={project} byStage={byStage} total={total} stageMeta={stageMeta} />
      </div>
    </div>
  );
}

function AccountingStatement({ project, total }) {
  const tasks = project.tasks;
  const incurred = tasks.filter((t) => t.cost > 0 && t.spentOn)
    .sort((a, b) => (a.spentOn < b.spentOn ? -1 : 1));
  const committed = tasks.filter((t) => t.cost > 0 && !t.spentOn);
  const incurredTotal = incurred.reduce((n, t) => n + t.cost, 0);
  const committedTotal = committed.reduce((n, t) => n + t.cost, 0);
  const stmtNo = `EXP-${project.id.toUpperCase()}-2026-06`;
  const owner = window.userById(project.owner);
  const me = window.userById(window.SEED.ME);
  const statusLabel = window.SEED.IDEA_STATUS[project.status].label;

  return (
    <div className="acct-doc">
      <header className="ad-letterhead">
        <div className="ad-brand">
          <div className="ad-logo">IP</div>
          <div>
            <div className="ad-co">{COMPANY.name}</div>
            {COMPANY.addr && <div className="ad-co-meta">{COMPANY.addr}</div>}
            {COMPANY.meta && <div className="ad-co-meta">{COMPANY.meta}</div>}
          </div>
        </div>
        <div className="ad-doctitle">
          <h1>Expense Statement</h1>
          <table className="ad-docmeta"><tbody>
            <tr><td>Statement No.</td><td>{stmtNo}</td></tr>
            <tr><td>Date issued</td><td>{ISSUE_DATE}</td></tr>
            <tr><td>Currency</td><td>LKR (Rs)</td></tr>
          </tbody></table>
        </div>
      </header>

      <div className="ad-rule" />

      <section className="ad-meta">
        <div><span className="ad-k">Project</span><span className="ad-v">{project.name}</span></div>
        <div><span className="ad-k">Status</span><span>{statusLabel}</span></div>
        <div><span className="ad-k">Category</span><span>{project.category}</span></div>
        <div><span className="ad-k">Reporting period</span><span>Up to {ISSUE_DATE}</span></div>
        <div><span className="ad-k">Project owner</span><span>{owner.name}</span></div>
        <div><span className="ad-k">Prepared by</span><span>{me.name}, {me.role}</span></div>
      </section>

      <h2 className="ad-sec">A.  Expenses Incurred</h2>
      <table className="ad-table">
        <thead><tr><th className="c-no">#</th><th className="c-date">Date</th><th>Description</th><th>Incurred by</th><th className="r">Amount (Rs)</th></tr></thead>
        <tbody>
          {incurred.map((t, i) => (
            <tr key={t.id}>
              <td className="c-no">{String(i + 1).padStart(2, '0')}</td>
              <td className="c-date">{window.fmtDate(t.spentOn)}</td>
              <td>{t.title}</td>
              <td>{window.userById(t.assignee).name}</td>
              <td className="r mono">{money2(t.cost)}</td>
            </tr>
          ))}
          {incurred.length === 0 && <tr><td colSpan={5} className="ad-none">No expenses incurred to date.</td></tr>}
        </tbody>
        {incurred.length > 0 && (
          <tfoot><tr><td colSpan={4}>Total expenses incurred</td><td className="r mono">{money2(incurredTotal)}</td></tr></tfoot>
        )}
      </table>

      {committed.length > 0 && (
        <>
          <h2 className="ad-sec">B.  Committed &amp; Budgeted <span className="ad-sec-note">(not yet incurred)</span></h2>
          <table className="ad-table">
            <thead><tr><th className="c-no">#</th><th>Description</th><th>Stage</th><th>Owner</th><th className="r">Est. amount (Rs)</th></tr></thead>
            <tbody>
              {committed.map((t, i) => (
                <tr key={t.id}>
                  <td className="c-no">{String(i + 1).padStart(2, '0')}</td>
                  <td>{t.title}</td>
                  <td>{t.stage === 'inprocess' ? 'In Process' : 'Pending'}</td>
                  <td>{window.userById(t.assignee).name}</td>
                  <td className="r mono">{money2(t.cost)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot><tr><td colSpan={4}>Total committed &amp; budgeted</td><td className="r mono">{money2(committedTotal)}</td></tr></tfoot>
          </table>
        </>
      )}

      <div className="ad-totals">
        <table><tbody>
          <tr><td>Total expenses incurred (A)</td><td className="r mono">{money2(incurredTotal)}</td></tr>
          <tr><td>Total committed &amp; budgeted (B)</td><td className="r mono">{money2(committedTotal)}</td></tr>
          <tr className="ad-grand"><td>Total project cost (A + B)</td><td className="r mono">Rs {money2(total)}</td></tr>
        </tbody></table>
      </div>

      <p className="ad-words"><span className="ad-k">Amount in words:</span> {numToWords(total)} Sri Lanka Rupees only.</p>

      <p className="ad-note"><strong>Notes.</strong> This statement summarises all task-level expenses recorded against the above project as of the date issued. Items under "Committed &amp; Budgeted" represent estimates for work not yet completed and are subject to revision. Figures are stated in Sri Lanka Rupees (LKR), exclusive of applicable taxes unless otherwise noted.</p>

      <div className="ad-sign">
        <div className="ad-sign-col"><div className="ad-sign-line" /><span>Prepared by — {me.name}</span><span className="ad-sign-role">{me.role}</span></div>
        <div className="ad-sign-col"><div className="ad-sign-line" /><span>Approved by — {owner.name}</span><span className="ad-sign-role">{owner.role}</span></div>
      </div>

      <footer className="ad-foot">
        {COMPANY.name} · Confidential — for internal use only · Statement {stmtNo} · Page 1 of 1
      </footer>
    </div>
  );
}

Object.assign(window, { ExpenseReport, AccountingStatement });
