/* ============================================================
   P&L App (Lite) · Profit & Loss (from the US demo's)
   ------------------------------------------------------------
   - The income statement: revenue, direct costs, GROSS PROFIT (new in Lite), overheads,
     net income, and an ESTIMATE of the income tax to set aside (25%). Sales tax collected
     is shown apart: it is owed to the state and is never income.
   - Profit by job is a paid-plan feature: shown locked, with made-up figures (lock.jsx).
   - Every figure opens its rows.
   ============================================================ */
function DarkBlock({ label, value, helper, tone, onOpen }) {
  const c = { pos: '#D1F470', neg: '#FF9A8F', primary: '#E3F3B0' }[tone] || '#FFFFFF';
  return (
    <button type="button" onClick={onOpen} className="px-5 py-4 first:pl-0 text-left hover:bg-[rgba(255,255,255,0.04)] transition-colors">
      <div className="text-[12px] font-medium" style={{ color: 'rgba(255,255,255,0.62)' }}>{label}</div>
      <div className="mt-2 font-display font-700 text-[24px] leading-none num" style={{ color: c }}>{value}</div>
      {helper && <div className="mt-1.5 text-[11.5px] num" style={{ color: 'rgba(255,255,255,0.5)' }}>{helper}</div>}
    </button>
  );
}

function StatementRow({ label, value, tone, indent, strong, divider, highlight, note, onOpen }) {
  const color = tone === 'pos' ? 'var(--pos)' : tone === 'neg' ? 'var(--neg)' : tone === 'primary' ? 'var(--primary)' : 'var(--ink)';
  return (
    <div className={`flex items-center justify-between gap-4 px-5 ${highlight ? 'py-4 rounded-xl my-1' : 'py-3'} ${divider ? 'border-t border-line' : ''}`}
      style={highlight ? { background: '#F1FBD4' } : undefined}>
      <div className={`${indent ? 'pl-5' : ''} ${strong || highlight ? 'font-600' : ''} ${highlight ? 'text-[15px]' : 'text-[13.5px]'} text-ink`}>
        {label}
        {note && <span className="block text-[11.5px] text-muted font-normal mt-0.5">{note}</span>}
      </div>
      {onOpen
        ? <FigureLink onOpen={onOpen} className={'whitespace-nowrap ' + (highlight ? 'text-[18px] font-700' : strong ? 'text-[14px]' : 'text-[13.5px]')} style={{ color }}>{value}</FigureLink>
        : <div className={`num whitespace-nowrap ${highlight ? 'text-[18px] font-700' : strong ? 'text-[14px] font-600' : 'text-[13.5px]'}`} style={{ color }}>{value}</div>}
    </div>
  );
}

/* The period of the statement card. Kept while the page is open. */
let _pnlPeriod = { key: 'ytd' };

function ProfitLoss() {
  useDB();
  const [period, setPeriod] = useState(_pnlPeriod);
  const pickPeriod = p => { _pnlPeriod = p; setPeriod(p); };
  // the dark band: always the year so far
  const ytd = thisYearRows();
  const stY = incomeStatement(ytd.plati, ytd.incasari);
  // the Profit & Loss card: the period chosen above it
  const yr = periodRows(period);
  const st = incomeStatement(yr.plati, yr.incasari);
  const periodSub = yr.label;

  const opensFor = (yr, st, periodSub) => ({
    revenue: () => showRows({ title: 'Revenue', sub: periodSub + ', before sales tax', lines: yr.incasari.map(r => rowLineIn(r)) }),
    salesTax: () => showRows({ title: 'Sales tax collected', sub: 'Charged to customers and owed to the state. Not income.',
      lines: yr.incasari.filter(r => vatOfRow(r) > 0).map(r => rowLineIn(r, vatOfRow(r), r.cotaTva + '% on ' + moneyUSD(r.sumaNeta))) }),
    jobCosts: () => showRows({ title: 'Direct costs', sub: 'The cost of doing the work: ' + periodSub, lines: st.jobCostRows.map(r => rowLineOut(r)) }),
    gross: () => showRows({ title: 'Gross profit', sub: 'Revenue minus direct costs, ' + periodSub + '. Costs show as a minus.', totalLabel: 'Gross profit',
      lines: [...yr.incasari.map(r => rowLineIn(r)), ...st.jobCostRows.map(r => rowLineOut(r, -r.sumaNeta))] }),
    overheads: () => showRows({ title: 'Overheads', sub: 'The cost of running the business', lines: st.ohRows.map(r => rowLineOut(r)) }),
    net: () => showRows({ title: 'Net income before tax', sub: 'Revenue minus every expense. Expenses show as a minus.', totalLabel: 'Net income',
      lines: [...yr.incasari.map(r => rowLineIn(r)), ...yr.plati.map(r => rowLineOut(r, -r.sumaNeta))] }),
  });
  const open = opensFor(yr, st, periodSub), openY = opensFor(ytd, stY, ytd.label);

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h3 className="text-[15.5px] font-700 text-ink font-display">Income statement</h3>
          <p className="text-[12.5px] text-muted mt-0.5">The band below is the year so far, {ytd.label}</p>
        </div>
        <ExportButton />
      </div>

      {/* Dark summary band */}
      <div className="rounded-2xl shadow-card overflow-hidden" style={{ background: 'var(--sidebar)' }}>
        <div className="grid grid-cols-2 lg:grid-cols-4 divide-x divide-[rgba(255,255,255,0.12)] px-6 py-2">
          <DarkBlock label="Revenue · year to date" tone="pos" value={money0USD(stY.revenue)} helper={`${ytd.incasari.length} ${plural(ytd.incasari.length, 'invoice')}`} onOpen={openY.revenue} />
          <DarkBlock label="Gross profit" tone={stY.gross >= 0 ? 'pos' : 'neg'} value={money0USD(stY.gross)} helper={`margin ${pct(stY.revenue ? stY.gross / stY.revenue * 100 : 0)}`} onOpen={openY.gross} />
          <DarkBlock label="Net income before tax" tone={stY.net >= 0 ? 'pos' : 'neg'} value={money0USD(stY.net)} helper={`margin ${pct(stY.revenue ? stY.net / stY.revenue * 100 : 0)}`} onOpen={openY.net} />
          <DarkBlock label="Sales tax owed to the state" tone="primary" value={money0USD(stY.salesTax)} helper="collected from customers, not income" onOpen={openY.salesTax} />
        </div>
      </div>

      <div className="rounded-[26px] border border-line p-3.5" style={{ background: 'rgba(255,255,255,0.45)' }}>
      <div className="flex flex-wrap items-center gap-2.5 px-1.5 pb-3">
        <span className="text-[12.5px] font-700 text-muted">The statement below shows</span>
        <PeriodButton value={period} onChange={pickPeriod} years={pastYears()} align="left" />
        <span className="text-[12.5px] text-muted">{yr.label}</span>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
        <Card className="lg:col-span-2 p-4 sm:p-6 self-start">
          <SectionTitle title="Profit & Loss" sub={periodSub + ' · click a figure to see its rows'} />
          <div className="-mx-1">
            <StatementRow label="Revenue" value={money0USD(st.revenue)} tone="pos" strong onOpen={open.revenue} />
            <StatementRow label="Sales tax collected" value={money0USD(st.salesTax)} indent note="Charged to customers, owed to the state. Not income." onOpen={open.salesTax} />
            <StatementRow label="Direct costs" value={'−' + money0USD(st.jobCosts)} tone="neg" strong divider note="The cost of doing the work: materials, subcontractors, labor" onOpen={open.jobCosts} />
            <StatementRow label="Gross profit" value={money0USD(st.gross)} tone={st.gross >= 0 ? 'pos' : 'neg'} strong divider
              note={'margin ' + pct(st.revenue ? st.gross / st.revenue * 100 : 0)} onOpen={open.gross} />
            <StatementRow label="Overheads" value={'−' + money0USD(st.overheads)} tone="neg" strong note="Running the business: rent, insurance, software, office" onOpen={open.overheads} />
            <StatementRow label="Net income before tax" value={money0USD(st.net)} tone={st.net >= 0 ? 'pos' : 'neg'} highlight onOpen={open.net} />
            <StatementRow label={`Set aside for income tax (${Math.round(INCOME_TAX_RATE * 100)}%)`} value={'−' + money0USD(st.taxSetAside)} tone="neg" indent
              note="An estimate only, not tax advice. Ask your accountant what to set aside." />
            <StatementRow label="Net income after the set-aside" value={money0USD(st.afterTax)} tone={st.afterTax >= 0 ? 'pos' : 'neg'} strong />
          </div>
        </Card>

        <LockedProfitByJob className="lg:col-span-3 self-start" />
      </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProfitLoss, StatementRow, DarkBlock });
