/* ============================================================
   P&L App (Lite) · "See the rows": what is inside a figure (from the US demo's)
   Lite: the third column shows the CATEGORY (the demo showed the job, a paid-plan feature).
   ------------------------------------------------------------
   Ana, 26 Oct 2026: every card and figure opens the rows behind it, across
   the whole app, because people will not trust a number they cannot see
   the inside of. A screen calls showRows() with the SAME rows it added up
   (from jobs.jsx), so the total at the bottom of the drawer always matches
   the card. Clicking a row opens it in the usual detail card.
   ============================================================ */

/* Rows for the drawer. Each line: { date, name, job, detail, amount, rec, kind }. */
const rowLineIn = (r, amount, detail) => ({ date: r.data, name: r.client, job: r.categorie || '—', detail: detail || r.nrFactura || '', amount: amount == null ? r.sumaNeta : amount, rec: r, kind: 'in' });
// r can be a PART of a split bill (partRows): it shows the part's job, category and amount, and opens the whole bill
const rowLineOut = (r, amount, job) => ({ date: r.data, name: r.furnizor, job: job || r.categorie || '—', detail: r.nrFactura || '', amount: amount == null ? r.sumaNeta : amount, rec: wholeOf(r), kind: 'out' });

/* Open the drawer. `lines` are made with the helpers above (or by hand with the same shape). */
function showRows(spec) { window.dispatchEvent(new CustomEvent('show-rows', { detail: spec })); }

function RowsDrawer() {
  const [spec, setSpec] = useState(null);
  const [open, setOpen] = useState(null);       // the row opened in the detail card
  useEffect(() => {
    const on = e => setSpec(e.detail);
    window.addEventListener('show-rows', on);
    return () => window.removeEventListener('show-rows', on);
  }, []);
  useEffect(() => {
    if (!spec) return;
    const onKey = e => { if (e.key === 'Escape' && !open) setSpec(null); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [spec, open]);
  if (!spec) return null;
  // newest first; a line marked `top` (e.g. the contract a figure starts from) stays at the top
  const lines = (spec.lines || []).slice().sort((a, b) => (b.top ? 1 : 0) - (a.top ? 1 : 0) || String(b.date || '').localeCompare(String(a.date || '')));
  const total = spec.total != null ? spec.total : lines.reduce((s, l) => s + (l.amount || 0), 0);
  const head = spec.head || ['Date', 'Name', 'Category', 'Invoice / bill #', 'Amount'];
  return (
    <>
      <div className="fixed inset-0 z-[40] fade-in" style={{ background: 'rgba(16,32,24,0.28)' }} onClick={() => setSpec(null)} />
      <div className="fixed top-0 right-0 bottom-0 z-[41] w-full max-w-[720px] bg-surface shadow-pop flex flex-col panel-in rounded-l-2xl">
        <div className="flex items-start justify-between gap-4 px-6 pt-5 pb-4 border-b border-line">
          <div className="min-w-0">
            <h3 className="text-[16px] font-700 text-ink font-display">{spec.title}</h3>
            {spec.sub && <p className="text-[12.5px] text-muted mt-0.5">{spec.sub}</p>}
          </div>
          <IconButton icon="x" title="Close" onClick={() => setSpec(null)} />
        </div>
        <div className="flex-1 overflow-auto scroll-area px-6 py-3">
          {lines.length === 0 ? (
            <div className="text-[13px] text-muted py-10 text-center">No rows behind this figure.</div>
          ) : (
            <table className="w-full border-collapse" style={{ tableLayout: 'fixed' }}>
              <colgroup><col style={{ width: '96px' }} /><col /><col style={{ width: '24%' }} /><col style={{ width: '20%' }} /><col style={{ width: '112px' }} /></colgroup>
              <thead><tr className="text-[11px] uppercase tracking-wide text-muted">
                {head.map((h, i) => <th key={i} className={'font-600 pb-2 ' + (i === head.length - 1 ? 'text-right' : 'text-left pr-2')}>{h}</th>)}
              </tr></thead>
              <tbody>
                {lines.map((l, i) => (
                  <tr key={i} className={'border-t border-line ' + (l.rec ? 'cursor-pointer hover:bg-[#F6F8F3]' : '')} onClick={() => l.rec && setOpen(l)}>
                    <td className="py-2 pr-2 text-[12.5px] num text-muted whitespace-nowrap">{l.date ? fmtDate(l.date) : '—'}</td>
                    <td className="py-2 pr-2 text-[13px] text-ink truncate" title={l.name}>{l.name}</td>
                    <td className="py-2 pr-2 text-[12.5px] text-muted truncate" title={l.job}>{l.job}</td>
                    <td className="py-2 pr-2 text-[12.5px] text-muted truncate" title={l.detail}>{l.detail}</td>
                    <td className="py-2 text-right text-[13px] num text-ink whitespace-nowrap">{moneyUSD(l.amount)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {spec.note && <div className="text-[12px] text-muted mt-3 px-3 py-2 rounded-lg" style={{ background: '#F6F8F3', border: '1px dashed var(--line)' }}>{spec.note}</div>}
        </div>
        <div className="flex items-center justify-between px-6 py-3.5 border-t-2" style={{ borderColor: '#D9DED5' }}>
          <span className="text-[13px] font-700 text-ink">{spec.totalLabel || 'Total'} <span className="text-muted font-400 text-[12px]">· {lines.length} {plural(lines.length, 'row')}</span></span>
          <span className="text-[15px] font-700 num text-ink">{moneyUSD(total)}</span>
        </div>
      </div>
      <TransactionDetail record={open && open.rec} kind={open ? open.kind : 'out'} onClose={() => setOpen(null)} />
    </>
  );
}

/* A clickable figure card (brief 28 look): a small icon chip and the label, the value, a line under it.
   The whole card opens the rows behind it. tone: 'hero' (the lime card), 'pos', 'neg', 'warn'. */
function FigureCard({ label, value, sub, onOpen, tone, icon, className = '', size }) {
  const tones = {
    hero: { bg: 'var(--lime)', bd: 'var(--lime)', v: 'var(--sidebar)', l: 'rgba(15,59,44,0.72)', chip: 'rgba(255,255,255,0.6)' },
    pos: { v: 'var(--sidebar)' },
    neg: { bg: '#FCEDEA', bd: '#F4D3CD', v: 'var(--neg)', l: 'var(--neg)', chip: '#fff' },
    warn: { bg: '#FFF4DF', bd: '#F3E1B8', v: '#B7791F', l: '#9A6B12', chip: '#fff' },
  }[tone] || {};
  const lg = size === 'lg';   // the Dashboard's first row: more air (Ana, brief 29)
  return (
    <button type="button" onClick={onOpen} title="See the rows behind this figure"
      className={'relative overflow-hidden text-left rounded-2xl border bg-surface shadow-card hover:shadow-pop hover:-translate-y-px transition-all min-w-0 flex flex-col '
        + (lg ? 'px-6 py-5 min-h-[148px] ' : 'px-[18px] py-3.5 ') + className}
      style={{ background: tones.bg, borderColor: tones.bd || 'var(--line)' }}>
      {tone === 'hero' && <span className="absolute -right-10 -top-12 w-[190px] h-[190px] rounded-full pointer-events-none" style={{ border: '28px solid rgba(255,255,255,0.28)' }} />}
      <div className={'relative flex items-center gap-2 font-700 truncate w-full ' + (lg ? 'text-[13.5px]' : 'text-[13px]')} style={{ color: tones.l || 'var(--muted)' }}>
        {icon && <span className={'inline-flex items-center justify-center shrink-0 ' + (lg ? 'w-[30px] h-[30px] rounded-[10px]' : 'w-[26px] h-[26px] rounded-[9px]')} style={{ background: tones.chip || 'var(--lime-soft)', color: 'var(--sidebar)' }}><Icon name={icon} size={lg ? 16 : 14} /></span>}
        <span className="truncate">{label}</span>
      </div>
      <div className={'relative font-800 num truncate tracking-[-0.02em] w-full ' + (lg ? 'text-[32px] mt-2.5' : 'text-[26px] mt-1')} style={{ color: tones.v || 'var(--ink)' }}>{value}</div>
      {sub && <div className={'relative text-[12.5px] truncate w-full ' + (lg ? 'mt-auto pt-2' : 'mt-0.5')} style={{ color: tones.l || 'var(--muted)' }} title={typeof sub === 'string' ? sub : undefined}>{sub}</div>}
    </button>
  );
}

/* A figure inside a sentence or a statement line: underlined on hover, opens its rows. */
function FigureLink({ children, onOpen, className = '', style }) {
  return <button type="button" onClick={onOpen} className={'num font-600 hover:underline underline-offset-2 ' + className} style={{ color: 'var(--primary)', ...style }}>{children}</button>;
}

Object.assign(window, { showRows, RowsDrawer, FigureCard, FigureLink, rowLineIn, rowLineOut });
