/* ============================================================
   P&L App (Lite) · Dashboard (from the US demo's: brief 27, redesigned in brief 28)
   Lite (17 Nov 2026): 'job costs' are called direct costs; nothing else changed.
   ------------------------------------------------------------
   Top to bottom (Ana, 27 Oct 2026):
   1. Revenue (the lime card), Expenses, Net income after overheads. (Costs with no job left the
      Dashboard on 9 Nov 2026, Ana: they are a to-do, so they show in Admin > To review as "No job".)
   2. Income vs costs (side-by-side bars, brief 29) and Where the money went (the 4 biggest
      categories, the rest as one "Other" line, so the card never grows).
   3. Accounts receivable and Accounts payable: what customers owe and what the business owes,
      each with its total, by days past due / days until due. These are always AS OF TODAY.
   Rows 1 and 2 follow the period button in the top bar (brief 29): year to date, this or last
   month, this or last quarter, last 12 months, a past year, or a custom range. Kept while the page
   is open, back to year to date on reload.
   Every figure opens the rows behind it in the side peek (showRows, rows.jsx). The maths is in
   jobs.jsx, the same functions the tests check.

   Left out on purpose: the 4-week cash card ("Will I make payroll?") is PARKED until Ana agrees
   how it is worked out; "How much can I safely take out?" was removed (Ana, 27 Oct 2026).
   ============================================================ */

/* This year, January 1 to today: what the P&L tab's dark band covers. */
function thisYearRows() { return periodRows({ key: 'ytd' }); }
/* The rows of a period (pickers.jsx works out the dates). */
function periodRows(p) {
  const r = periodRange(p, todayISO()), inP = x => x.data && x.data >= r.from && x.data <= r.to;
  return { incasari: DB.incasari.filter(inP), plati: DB.plati.filter(inP), from: r.from, to: r.to, label: r.label };
}
/* Past years that have rows, newest first: offered as whole years in the period button. */
function pastYears() {
  const now = todayISO().slice(0, 4), ys = new Set();
  DB.incasari.concat(DB.plati).forEach(r => { if (r.data && r.data.slice(0, 4) < now) ys.add(+r.data.slice(0, 4)); });
  return [...ys].sort((a, b) => b - a);
}
/* The bars of a period: one per month, or one per week when the period is a single month.
   Each knows its own from / to, so clicking it opens exactly its rows. */
function periodBars(from, to) {
  const months = periodMonths(from, to);
  if (months.length === 1) {
    const k = months[0], [y, m] = k.split('-').map(Number);
    const lastDay = new Date(Date.UTC(y, m, 0)).getUTCDate();          // 28 to 31
    // a week the period does not reach is left out; a week it cuts is named by the days it really covers
    return [[1, 7], [8, 14], [15, 21], [22, lastDay]].map(([a, b], i) => {
      const f = k + '-' + String(a).padStart(2, '0'), t = k + '-' + String(b).padStart(2, '0');
      const ff = f < from ? from : f, tt = t > to ? to : t;
      return { label: 'Wk ' + (i + 1), title: pickRangeText(ff, tt), from: ff, to: tt };
    }).filter(b => b.from <= b.to);
  }
  const twoYears = months[0].slice(0, 4) !== months[months.length - 1].slice(0, 4);
  return months.map(k => ({ label: twoYears ? monthLabel(k) : monthLabel(k).split(' ')[0], title: monthLabel(k), from: k + '-01', to: k + '-31' }));
}
/* The Dashboard's period: one value for the whole page, shared by the top bar button and the cards. */
let _dashPeriod = { key: 'ytd' };
const _dashSubs = new Set();
function useDashPeriod() {
  const [, force] = useState(0);
  useEffect(() => { const f = () => force(n => n + 1); _dashSubs.add(f); return () => { _dashSubs.delete(f); }; }, []);
  return [_dashPeriod, p => { _dashPeriod = p; _dashSubs.forEach(f => f()); }];
}
function DashPeriodButton() { useDB(); const [p, setP] = useDashPeriod(); return <PeriodButton value={p} onChange={setP} years={pastYears()} />; }
function DashPeriodLabel() { const [p] = useDashPeriod(); return <>{periodRange(p, todayISO()).label}</>; }
function sumNet(list) { return list.reduce((a, r) => a + (r.sumaNeta || 0), 0); }

/* One line of an ageing card: the bucket, a bar, the amount, how many. A late bucket is red. */
function AgeLine({ label, total, count, word, max, late, onOpen }) {
  return (
    <button type="button" onClick={onOpen}
      className="w-full grid grid-cols-[92px_1fr_80px_56px] sm:grid-cols-[124px_1fr_100px_74px] items-center gap-2 sm:gap-3 px-1 sm:px-2 py-[6px] rounded-xl text-[13px] text-left hover:bg-[#F6F8F3] transition-colors">
      <span className={late && count ? 'font-700' : 'text-ink'} style={late && count ? { color: 'var(--neg)' } : undefined}>{label}</span>
      <span className="h-2 rounded-full overflow-hidden" style={{ background: '#EEF1EA' }}>
        <span className="block h-full rounded-full" style={{ width: `${max ? total / max * 100 : 0}%`, background: late ? 'var(--neg)' : 'var(--sidebar)' }} />
      </span>
      <span className="text-right font-800 num">{count ? money0USD(total) : '—'}</span>
      <span className="text-right text-[12px] text-muted">{count} {plural(count, word)}</span>
    </button>
  );
}

/* Accounts receivable (kind 'ar') or Accounts payable (kind 'ap'), with its total. */
function AgingCard({ kind }) {
  const today = todayISO(), isAR = kind === 'ar';
  const word = isAR ? 'invoice' : 'bill';
  const buckets = isAR ? owedAgeing(DB.incasari, today) : payablesAgeing(DB.plati, today).buckets;
  const ap = isAR ? null : payablesAgeing(DB.plati, today);
  const amountOf = r => isAR ? owedOn(r) : owedOut(r);
  const isLate = (b, i) => isAR ? i > 0 : b.key === 'overdue';
  const all = buckets.flatMap(b => b.rows).concat(isAR ? [] : ap.noDueDate);
  const total = all.reduce((s, r) => s + amountOf(r), 0);
  const lateTotal = buckets.filter(isLate).reduce((s, b) => s + b.total, 0);
  const max = Math.max(0, ...buckets.map(b => b.total));
  const line = r => isAR
    ? { ...rowLineIn(r, owedOn(r)), detail: (r.dataScadenta ? 'due ' + fmtDate(r.dataScadenta) : 'no due date') + (daysLate(r, today) > 0 ? ' · ' + daysLate(r, today) + ' days late' : '') }
    : { ...rowLineOut(r, owedOut(r)), detail: r.dataScadenta ? 'due ' + fmtDate(r.dataScadenta) : 'no due date' };
  const head = ['Date', isAR ? 'Customer' : 'Vendor', 'Category', 'Due', isAR ? 'Owed to you' : 'You owe'];
  const title = isAR ? 'Accounts receivable' : 'Accounts payable';
  const open = (rows, what) => showRows({ title: title + ' · ' + what, sub: isAR ? 'What customers still owe, sales tax included' : 'What the business still owes on its bills', head, lines: rows.map(line), totalLabel: isAR ? 'Owed to you' : 'You owe' });
  return (
    <Card className="px-[22px] py-5 min-w-0">
      <div className="flex items-start justify-between gap-3 mb-1.5">
        <div className="min-w-0">
          <h3 className="text-[15.5px] text-ink">{title}</h3>
          <p className="text-[12.5px] text-muted mt-0.5">{isAR ? 'Unpaid invoices by days past due · as of today · sales tax included' : 'Unpaid bills by due date · as of today'}</p>
        </div>
        <button type="button" onClick={() => open(all, 'all')} className="text-right rounded-xl px-2 py-1 hover:bg-[#F6F8F3] shrink-0">
          <div className="text-[12px] font-700 text-muted">{isAR ? 'Total owed to you' : 'Total you owe'} · {all.length} {plural(all.length, word)}</div>
          <div className="text-[26px] font-800 num tracking-[-0.02em] text-ink leading-tight">{money0USD(total)}</div>
        </button>
      </div>
      {buckets.map((b, i) => (
        <AgeLine key={b.key} label={b.label} total={b.total} count={b.rows.length} word={word} max={max} late={isLate(b, i)} onOpen={() => open(b.rows, b.label)} />
      ))}
      <div className="flex items-center justify-between text-[12px] text-muted mt-1 px-2">
        <span>{isAR ? 'Late' : 'Overdue'}: <b style={{ color: 'var(--neg)' }}>{money0USD(lateTotal)}</b> of {money0USD(total)}</span>
        {!isAR && ap.noDueDate.length > 0 && (
          <button type="button" className="hover:underline" style={{ color: 'var(--primary)' }} onClick={() => open(ap.noDueDate, 'no due date')}>
            + {ap.noDueDate.length} {plural(ap.noDueDate.length, 'bill')} with no due date ({money0USD(ap.noDueTotal)})
          </button>
        )}
      </div>
    </Card>
  );
}

const _CAT_COLORS = ['#0F3B2C', '#D1F470', '#4E7D62', '#E6F4BE', '#C9CFC6'];

function Dashboard() {
  useDB();
  const [period] = useDashPeriod();
  const yr = periodRows(period);
  const st = incomeStatement(yr.plati, yr.incasari);
  const expenses = st.jobCosts + st.overheads;

  const bars = periodBars(yr.from, yr.to);
  const inBar = (b, r) => r.data >= b.from && r.data <= b.to;
  const series = bars.map(b => ({ label: b.label, title: b.title, income: sumNet(yr.incasari.filter(r => inBar(b, r))), cost: sumNet(yr.plati.filter(r => inBar(b, r))) }));
  const openBar = i => {
    const b = bars[i];
    showRows({ title: 'Money in and out · ' + b.title, sub: 'Money out shows as a minus. Amounts before sales tax.', totalLabel: 'Net',
      lines: [...yr.incasari.filter(r => inBar(b, r)).map(r => rowLineIn(r)), ...yr.plati.filter(r => inBar(b, r)).map(r => rowLineOut(r, -r.sumaNeta))] });
  };

  // Where the money went: the 4 biggest categories by name, everything else as one "Other" line (Ana, 27 Oct 2026)
  const byCat = {};
  partRows(yr.plati).forEach(p => { (byCat[p.categorie] = byCat[p.categorie] || []).push(p); });   // a split bill: each part in its own category
  let cats = Object.entries(byCat).map(([label, rows]) => ({ label, rows, value: sumNet(rows) })).sort((a, b) => b.value - a.value);
  if (cats.length > 5) {
    const rest = cats.slice(4);
    cats = cats.slice(0, 4).concat([{ label: `Other (${rest.length} categories)`, rows: rest.flatMap(c => c.rows), value: sumNet(rest.flatMap(c => c.rows)), other: rest.map(c => c.label) }]);
  }
  const openCat = c => showRows({ title: c.label, sub: yr.label + (c.other ? ' · ' + c.other.join(', ') : catTypeOf(c.label) === 'overhead' ? ' · an overhead' : ' · a direct cost'), lines: c.rows.map(r => rowLineOut(r)) });
  let acc = 0;

  return (
    <div className="flex flex-col gap-[18px]">
      {/* 1. the period's figures */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-[1.15fr_1fr_1fr] gap-[18px]">
        <FigureCard size="lg" tone="hero" icon="in" label={'Revenue · ' + yr.label} value={money0USD(st.revenue)} sub={`${yr.incasari.length} ${plural(yr.incasari.length, 'invoice')} · before sales tax`}
          onOpen={() => showRows({ title: 'Revenue', sub: yr.label + ', before sales tax', lines: yr.incasari.map(r => rowLineIn(r)) })} />
        <FigureCard size="lg" icon="out" label="Expenses" value={money0USD(expenses)}
          sub={<span className="inline-flex gap-1.5"><span className="px-2 rounded-full text-[11px] font-700" style={{ background: 'var(--sidebar)', color: 'var(--lime)' }}>direct costs {money0USD(st.jobCosts)}</span><span className="px-2 rounded-full text-[11px] font-700" style={{ background: 'var(--lime-soft)', color: '#3D5A0E' }}>overheads {money0USD(st.overheads)}</span></span>}
          onOpen={() => showRows({ title: 'Expenses', sub: yr.label + ': direct costs and overheads', lines: yr.plati.map(r => rowLineOut(r)) })} />
        <FigureCard className="sm:col-span-2 lg:col-span-1" size="lg" tone={st.net >= 0 ? 'pos' : 'neg'} icon="chart" label="Net income after overheads" value={money0USD(st.net)} sub={`margin ${pct(st.revenue ? st.net / st.revenue * 100 : 0)} · before income tax`}
          onOpen={() => showRows({ title: 'Net income after overheads', sub: 'Revenue minus every expense, ' + yr.label + '. Expenses show as a minus.', totalLabel: 'Net income',
            lines: [...yr.incasari.map(r => rowLineIn(r)), ...yr.plati.map(r => rowLineOut(r, -r.sumaNeta))] })} />
      </div>

      {/* 2. the charts */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-[18px]">
        <Card className="lg:col-span-2 px-[22px] py-5 h-[320px] flex flex-col min-w-0">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="text-[15.5px] text-ink">Income vs costs</h3>
              <p className="text-[12.5px] text-muted mt-0.5">{bars.length && bars[0].label.startsWith('Wk ') ? 'By week' : 'By month'}, before sales tax · {yr.label} · click a bar to see its rows</p>
            </div>
            <div className="flex items-center gap-3.5 text-[12px] font-700 text-muted shrink-0">
              <span className="inline-flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-[3px]" style={{ background: 'var(--sidebar)' }} />Income</span>
              <span className="inline-flex items-center gap-1.5"><span className="w-2.5 h-2.5 rounded-[3px]" style={{ background: 'var(--lime)' }} />Costs</span>
            </div>
          </div>
          <div className="flex-1 min-h-0 mt-2"><PairBars data={series} onPick={openBar} /></div>
        </Card>

        <Card className="px-[22px] py-5 h-[320px] flex flex-col min-w-0">
          <h3 className="text-[15.5px] text-ink">Where the money went</h3>
          <p className="text-[12.5px] text-muted mt-0.5">Expenses by category · {yr.label}</p>
          <div className="flex items-center gap-3 flex-1 min-h-0">
            <svg width="128" height="128" viewBox="0 0 42 42" className="shrink-0">
              {cats.map((c, i) => { const p = expenses ? c.value / expenses * 100 : 0, el = (
                <circle key={i} r="15.9155" cx="21" cy="21" fill="none" stroke={_CAT_COLORS[i]} strokeWidth="6" strokeDasharray={`${p} ${100 - p}`} strokeDashoffset={25 - acc}
                        style={{ cursor: 'pointer' }} onClick={() => openCat(c)}><title>{c.label}</title></circle>); acc += p; return el; })}
              <text x="21" y="20" textAnchor="middle" fontSize="3.2" fill="#7B847C" fontWeight="700">Total</text>
              <text x="21" y="25" textAnchor="middle" fontSize="5" fill="#16201A" fontWeight="800">{expenses >= 1000 ? '$' + money0(expenses / 1000) + 'k' : money0USD(expenses)}</text>
            </svg>
            <div className="flex-1 min-w-0 flex flex-col gap-0.5">
              {cats.map((c, i) => (
                <button key={c.label} type="button" onClick={() => openCat(c)}
                  className="grid grid-cols-[44px_1fr_auto] items-center gap-2 px-1.5 py-[5px] rounded-xl text-[13px] text-left hover:bg-[#F6F8F3]">
                  <span className="inline-flex justify-center px-1.5 h-5 items-center rounded-full text-[11px] font-800 num" style={{ background: _CAT_COLORS[i], color: i === 0 || i === 2 ? '#fff' : 'var(--sidebar)' }}>{expenses ? Math.round(c.value / expenses * 100) : 0}%</span>
                  <span className="truncate text-ink" title={c.label}>{c.label}</span>
                  <span className="font-800 num">{money0USD(c.value)}</span>
                </button>
              ))}
              {!cats.length && <span className="text-[12.5px] text-muted px-1.5">No expenses in this period.</span>}
            </div>
          </div>
        </Card>
      </div>

      {/* 3. receivable and payable, with their totals */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-[18px]">
        <AgingCard kind="ar" />
        <AgingCard kind="ap" />
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, thisYearRows, periodRows, pastYears, periodBars, useDashPeriod, DashPeriodButton, DashPeriodLabel, sumNet, AgingCard });
