// P&L page — full income/expense table with house breakdown.
function PnlPage({ store }) {
  const { transactions, houses, year, setYear } = store;
  const [houseFilter, setHouseFilter] = React.useState('all');

  let txns = filterByYear(transactions, year);
  if (houseFilter !== 'all') txns = txns.filter(t => t.houseId === houseFilter);

  const income = txns.filter(t => t.type === 'income');
  const expense = txns.filter(t => t.type === 'expense');

  // Revenue by house
  const revByHouse = houses.map(h => ({
    house: h,
    total: income.filter(t => t.houseId === h.id).reduce((s, t) => s + t.amount, 0),
    bySource: CATEGORIES.income.map(src => ({
      source: src,
      value: income.filter(t => t.houseId === h.id && t.category === src).reduce((s, t) => s + t.amount, 0),
    })),
  }));

  // Revenue by source overall
  const revBySource = CATEGORIES.income.map(src => ({
    source: src,
    value: income.filter(t => t.category === src).reduce((s, t) => s + t.amount, 0),
  }));

  // Expense by category
  const expByCat = CATEGORIES.expense.map(c => ({
    category: c,
    value: expense.filter(t => t.category === c).reduce((s, t) => s + t.amount, 0),
  })).filter(c => c.value > 0);

  const totalIncome = income.reduce((s, t) => s + t.amount, 0);
  const totalExpense = expense.reduce((s, t) => s + t.amount, 0);
  const net = totalIncome - totalExpense;
  const margin = totalIncome ? (net / totalIncome * 100) : 0;

  return (
    <>
      <Topbar title="Profit & Loss" subtitle={`${year === 'all' ? 'All time' : year} · ${houseFilter === 'all' ? 'All properties' : houses.find(h => h.id === houseFilter)?.name}`}>
        <YearFilter value={year} onChange={setYear}/>
        <select className="select" style={{ width: 180, height: 32 }}
                value={houseFilter} onChange={e => setHouseFilter(e.target.value)}>
          <option value="all">All properties</option>
          {houses.map(h => <option key={h.id} value={h.id}>{h.name}</option>)}
        </select>
        <button className="btn">{Icon.download} CSV</button>
        <button className="btn">{Icon.download} PDF</button>
      </Topbar>

      <div className="content">
        <div className="card" style={{ overflow: 'hidden' }}>
          <div style={{ padding: '28px 32px 20px', borderBottom: '1px solid var(--border)', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24 }}>
            <PnlSummary label="Revenue" value={totalIncome} color="var(--income)"/>
            <PnlSummary label="Operating expenses" value={totalExpense} color="var(--expense)"/>
            <div>
              <div className="xs muted" style={{ fontWeight: 500, letterSpacing: 0.3, textTransform: 'uppercase' }}>Net income</div>
              <div className="serif tabular" style={{ fontSize: 32, letterSpacing: '-0.02em', marginTop: 6 }}>{fmt$(net)}</div>
              <div className="xs muted" style={{ marginTop: 6 }}>
                <span style={{ color: margin >= 0 ? 'var(--income)' : 'var(--expense)', fontWeight: 500 }}>
                  {margin.toFixed(1)}% margin
                </span> · {fmt$(totalIncome - totalExpense, { compact: true })} from {houseFilter === 'all' ? `${houses.length} properties` : '1 property'}
              </div>
            </div>
          </div>

          {/* Revenue section */}
          <table className="table" style={{ fontSize: 13.5 }}>
            <thead>
              <tr>
                <th style={{ fontSize: 12, textTransform: 'none', letterSpacing: 0, color: 'var(--text)', fontWeight: 600, background: 'transparent', padding: '18px 32px 10px', textAlign: 'left' }}>Revenue</th>
                {houseFilter === 'all' && houses.map(h => (
                  <th key={h.id} className="num" style={{ fontSize: 11, background: 'transparent', padding: '18px 16px 10px' }}>{h.name}</th>
                ))}
                <th className="num" style={{ fontSize: 11, background: 'transparent', padding: '18px 32px 10px', width: 140 }}>Total</th>
              </tr>
            </thead>
            <tbody>
              {CATEGORIES.income.map(src => (
                <tr key={src}>
                  <td style={{ padding: '10px 32px', color: 'var(--text-secondary)' }}>{src}</td>
                  {houseFilter === 'all' && houses.map(h => {
                    const v = income.filter(t => t.houseId === h.id && t.category === src).reduce((s, t) => s + t.amount, 0);
                    return <td key={h.id} className="num tabular" style={{ padding: '10px 16px', color: v ? 'var(--text)' : 'var(--text-quaternary)' }}>{v ? fmt$(v) : '—'}</td>;
                  })}
                  <td className="num tabular" style={{ padding: '10px 32px', fontWeight: 500 }}>{fmt$(revBySource.find(r => r.source === src)?.value || 0)}</td>
                </tr>
              ))}
              <tr style={{ background: 'var(--bg-sunken)' }}>
                <td style={{ padding: '12px 32px', fontWeight: 600 }}>Total revenue</td>
                {houseFilter === 'all' && houses.map(h => {
                  const v = revByHouse.find(r => r.house.id === h.id)?.total || 0;
                  return <td key={h.id} className="num tabular" style={{ padding: '12px 16px', fontWeight: 600 }}>{fmt$(v)}</td>;
                })}
                <td className="num tabular" style={{ padding: '12px 32px', fontWeight: 700 }}>{fmt$(totalIncome)}</td>
              </tr>

              {/* Expense header */}
              <tr>
                <td colSpan={houseFilter === 'all' ? houses.length + 2 : 2}
                    style={{ padding: '24px 32px 10px', fontWeight: 600, fontSize: 13, borderBottom: 0, color: 'var(--text)' }}>
                  Operating expenses
                </td>
              </tr>

              {expByCat.map(({ category, value }) => (
                <tr key={category}>
                  <td style={{ padding: '10px 32px', color: 'var(--text-secondary)' }}>{category}</td>
                  {houseFilter === 'all' && houses.map(h => {
                    const v = expense.filter(t => t.houseId === h.id && t.category === category).reduce((s, t) => s + t.amount, 0);
                    return <td key={h.id} className="num tabular" style={{ padding: '10px 16px', color: v ? 'var(--text)' : 'var(--text-quaternary)' }}>{v ? fmt$(v) : '—'}</td>;
                  })}
                  <td className="num tabular" style={{ padding: '10px 32px', fontWeight: 500 }}>{fmt$(value)}</td>
                </tr>
              ))}
              <tr style={{ background: 'var(--bg-sunken)' }}>
                <td style={{ padding: '12px 32px', fontWeight: 600 }}>Total expenses</td>
                {houseFilter === 'all' && houses.map(h => {
                  const v = expense.filter(t => t.houseId === h.id).reduce((s, t) => s + t.amount, 0);
                  return <td key={h.id} className="num tabular" style={{ padding: '12px 16px', fontWeight: 600 }}>{fmt$(v)}</td>;
                })}
                <td className="num tabular" style={{ padding: '12px 32px', fontWeight: 700 }}>{fmt$(totalExpense)}</td>
              </tr>

              {/* Net */}
              <tr style={{ borderTop: '2px solid var(--text)' }}>
                <td style={{ padding: '18px 32px', fontWeight: 700, fontSize: 15 }}>Net income</td>
                {houseFilter === 'all' && houses.map(h => {
                  const v = (revByHouse.find(r => r.house.id === h.id)?.total || 0) -
                            expense.filter(t => t.houseId === h.id).reduce((s, t) => s + t.amount, 0);
                  return (
                    <td key={h.id} className="num tabular" style={{ padding: '18px 16px', fontWeight: 700, fontSize: 14, color: v >= 0 ? 'var(--income)' : 'var(--expense)' }}>
                      {fmt$(v)}
                    </td>
                  );
                })}
                <td className="num tabular" style={{ padding: '18px 32px', fontWeight: 700, fontSize: 16, color: net >= 0 ? 'var(--income)' : 'var(--expense)' }}>
                  {fmt$(net)}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

function PnlSummary({ label, value, color }) {
  return (
    <div>
      <div className="xs muted" style={{ fontWeight: 500, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div className="serif tabular" style={{ fontSize: 32, letterSpacing: '-0.02em', marginTop: 6, color }}>{fmt$(value)}</div>
    </div>
  );
}

Object.assign(window, { PnlPage });
