// views/receivables.jsx — what's owed, how late, and how fast it comes in
function ReceivablesView() {
  const s = useStore();
  const [q, setQ] = React.useState('');
  const [bucket, setBucket] = React.useState('all');
  const ar = React.useMemo(() => arAgeing(s), [s.invoices, s.transactions]);

  const shown = ar.rows
    .filter(r => bucket === 'all' || r.bucket === bucket)
    .filter(r => !q || ((r.number || '') + ' ' + r.customer + ' ' + r.title).toLowerCase().includes(q.toLowerCase()));

  const pct = v => ar.outstanding > 0 ? (v / ar.outstanding * 100) : 0;

  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Receivables<em>.</em></h1>
          <p className="page-sub">
            {ar.rows.length} invoice{ar.rows.length === 1 ? '' : 's'} with money still on them, aged from the due date.
            {ar.dso != null ? ' DSO is on a trailing 90-day billing window.' : ' Bill something in the last 90 days and DSO appears.'}
          </p>
        </div>
        <div className="page-actions">
          <button className="btn btn-ghost" onClick={() => arDownloadCsv(ar)}>Export CSV</button>
        </div>
      </div>

      <div className="books-kpi-row">
        <div className="card"><div className="bk-label">Outstanding</div><div className="bk-val">{fmtINR(ar.outstanding)}</div></div>
        <div className="card">
          <div className="bk-label">Overdue</div>
          <div className={'bk-val ' + (ar.overdue > 0 ? 't-debit' : '')}>{fmtINR(ar.overdue)}</div>
          <div className="bk-note">{ar.outstanding > 0 ? Math.round(ar.overdue / ar.outstanding * 100) + '% of the book' : '—'}</div>
        </div>
        <div className="card">
          <div className="bk-label">DSO</div>
          <div className="bk-val">{ar.dso == null ? '—' : ar.dso + ' days'}</div>
          <div className="bk-note">{ar.billed90 ? fmtINR(ar.billed90) + ' billed in 90 days' : 'nothing billed in 90 days'}</div>
        </div>
        <div className="card">
          <div className="bk-label">Weighted days late</div>
          <div className="bk-val">{ar.avgDaysLate} days</div>
          <div className="bk-note">{ar.oldest > 0 ? 'oldest ' + ar.oldest + ' days past due' : 'nothing past due'}</div>
        </div>
      </div>

      {ar.outstanding > 0 && (
        <div className="card" style={{ marginTop: 16 }}>
          <div className="rule-label">Ageing</div>
          <div className="age-bar">
            {AR_BUCKETS.map(b => ar.totals[b.key] > 0 && (
              <div key={b.key} className={'age-seg age-' + b.key} style={{ width: pct(ar.totals[b.key]) + '%' }} title={b.label + ' — ' + fmtINR(ar.totals[b.key])}></div>
            ))}
          </div>
          <div className="age-legend">
            {AR_BUCKETS.map(b => (
              <button key={b.key} className={'age-key ' + (bucket === b.key ? 'on' : '')}
                onClick={() => setBucket(bucket === b.key ? 'all' : b.key)}>
                <span className={'age-dot age-' + b.key}></span>
                <span className="age-name">{b.label}</span>
                <span className="age-amt num">{fmtINR(ar.totals[b.key])}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {ar.customers.length > 0 && (
        <div className="card" style={{ padding: 0, marginTop: 16 }}>
          <table className="tbl">
            <thead><tr>
              <th>Client</th>
              <th style={{ width: 64, textAlign: 'right' }}>Inv</th>
              <th style={{ textAlign: 'right' }}>Not due</th>
              <th style={{ textAlign: 'right' }}>1–30</th>
              <th style={{ textAlign: 'right' }}>31–60</th>
              <th style={{ textAlign: 'right' }}>61–90</th>
              <th style={{ textAlign: 'right' }}>90+</th>
              <th style={{ textAlign: 'right' }}>Total due</th>
            </tr></thead>
            <tbody>
              {ar.customers.map(c => (
                <tr key={c.customer}>
                  <td style={{ fontWeight: 500 }}>{c.customer}
                    {c.worst > 90 && <span className="tag tag-expense" style={{ marginLeft: 8 }}>{c.worst}d</span>}
                  </td>
                  <td className="num" style={{ textAlign: 'right' }}>{c.n}</td>
                  <td className="num" style={{ textAlign: 'right' }}>{c.current ? fmtINR(c.current) : '—'}</td>
                  <td className="num" style={{ textAlign: 'right' }}>{c.b1 ? fmtINR(c.b1) : '—'}</td>
                  <td className="num" style={{ textAlign: 'right' }}>{c.b2 ? fmtINR(c.b2) : '—'}</td>
                  <td className="num t-debit" style={{ textAlign: 'right' }}>{c.b3 ? fmtINR(c.b3) : '—'}</td>
                  <td className="num t-debit" style={{ textAlign: 'right', fontWeight: 600 }}>{c.b4 ? fmtINR(c.b4) : '—'}</td>
                  <td className="num" style={{ textAlign: 'right', fontWeight: 700 }}>{fmtINR(c.due)}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr style={{ background: 'var(--paper)' }}>
                <td style={{ fontWeight: 700, padding: 12 }}>Total receivable</td>
                <td className="num" style={{ textAlign: 'right' }}>{ar.rows.length}</td>
                <td className="num" style={{ textAlign: 'right' }}>{fmtINR(ar.totals.current)}</td>
                <td className="num" style={{ textAlign: 'right' }}>{fmtINR(ar.totals.b1)}</td>
                <td className="num" style={{ textAlign: 'right' }}>{fmtINR(ar.totals.b2)}</td>
                <td className="num" style={{ textAlign: 'right' }}>{fmtINR(ar.totals.b3)}</td>
                <td className="num" style={{ textAlign: 'right' }}>{fmtINR(ar.totals.b4)}</td>
                <td className="num" style={{ textAlign: 'right', fontWeight: 700, fontSize: 15 }}>{fmtINR(ar.outstanding)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      )}

      <div className="toolbar" style={{ marginTop: 16 }}>
        <div className="search">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
          <input placeholder="Search number, client, trip…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div className="sep"></div>
        <select className="select" value={bucket} onChange={e => setBucket(e.target.value)}>
          <option value="all">All ages</option>
          {AR_BUCKETS.map(b => <option key={b.key} value={b.key}>{b.label}</option>)}
        </select>
        <div style={{ flex: 1 }}></div>
        <span className="muted" style={{ fontSize: 12 }}>{shown.length} shown</span>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ width: 130 }}>Number</th>
            <th style={{ width: 88 }}>Raised</th>
            <th style={{ width: 88 }}>Due</th>
            <th>Client / trip</th>
            <th style={{ width: 96, textAlign: 'right' }}>Age</th>
            <th style={{ width: 120, textAlign: 'right' }}>Total</th>
            <th style={{ width: 120, textAlign: 'right' }}>Received</th>
            <th style={{ width: 120, textAlign: 'right' }}>Outstanding</th>
          </tr></thead>
          <tbody>
            {shown.map(r => (
              <tr key={r.id} onClick={() => { location.hash = 'invoices'; }} style={{ cursor: 'pointer' }}>
                <td className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>{r.number || <span className="muted">—</span>}</td>
                <td className="num" style={{ fontSize: 12 }}>{fmtDate(r.date)}</td>
                <td className="num" style={{ fontSize: 12 }}>{fmtDate(r.dueDate)}</td>
                <td>
                  <div style={{ fontSize: 12.5, fontWeight: 500, lineHeight: 1.35 }}>{r.customer}</div>
                  <div className="muted" style={{ fontSize: 10.5 }}>{r.title || '—'}</div>
                </td>
                <td style={{ textAlign: 'right' }}>
                  {r.late <= 0
                    ? <span className="tag tag-empty">in {Math.abs(r.late)}d</span>
                    : <span className={'tag ' + (r.late > 60 ? 'tag-expense' : 'tag-transfer')}>{r.late}d late</span>}
                </td>
                <td className="num" style={{ textAlign: 'right', fontSize: 12 }}>{fmtINR(r.total)}</td>
                <td className="num t-credit" style={{ textAlign: 'right', fontSize: 12 }}>{r.paid ? fmtINR(r.paid) : '—'}</td>
                <td className="num" style={{ textAlign: 'right', fontSize: 12, fontWeight: 700, color: r.late > 0 ? 'var(--red)' : undefined }}>{fmtINR(r.due)}</td>
              </tr>
            ))}
            {!shown.length && (
              <tr><td colSpan={8} style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>
                {ar.rows.length ? 'Nothing in this age band.' : 'Nothing outstanding — every invoice is settled.'}
              </td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// Straight to a file your CA or your bank can open.
function arDownloadCsv(ar) {
  const head = ['Invoice', 'Raised', 'Due date', 'Client', 'Trip', 'Total', 'Received', 'Outstanding', 'Days late', 'Bucket'];
  const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
  const label = k => (AR_BUCKETS.find(b => b.key === k) || {}).label || k;
  const lines = [head.map(q).join(',')];
  ar.rows.forEach(r => lines.push([r.number, r.date, r.dueDate, r.customer, r.title, r.total, r.paid, r.due, r.late > 0 ? r.late : 0, label(r.bucket)].map(q).join(',')));
  lines.push([q('Total'), '', '', '', '', '', '', q(ar.outstanding), '', ''].join(','));
  const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = 'receivables-ageing-' + ar.asOn + '.csv';
  a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}

Object.assign(window, { ReceivablesView, arDownloadCsv });
