// Overview dashboard page — KPI summary, monthly trend, donut, house cards, recent txns.
function OverviewPage({ store, onOpenTxn, onAddTxn, onNav }) {
  const { transactions, houses, year, setYear } = store;
  const yearTxns = filterByYear(transactions, year);
  const income = yearTxns.filter(t => t.type === 'income').reduce((s, t) => s + t.amount, 0);
  const expense = yearTxns.filter(t => t.type === 'expense').reduce((s, t) => s + t.amount, 0);
  const net = income - expense;

  // Compare to previous year for delta
  const prevYear = year === 'all' ? null : year - 1;
  const prevTxns = prevYear ? filterByYear(transactions, prevYear) : [];
  const prevIncome = prevTxns.filter(t => t.type === 'income').reduce((s, t) => s + t.amount, 0);
  const prevExpense = prevTxns.filter(t => t.type === 'expense').reduce((s, t) => s + t.amount, 0);
  const incomeDelta = prevIncome ? ((income - prevIncome) / prevIncome * 100) : null;
  const expenseDelta = prevExpense ? ((expense - prevExpense) / prevExpense * 100) : null;
  const netDelta = (prevIncome - prevExpense) ? ((net - (prevIncome - prevExpense)) / Math.abs(prevIncome - prevExpense) * 100) : null;

  const byHouse = byHouseTotals(yearTxns, houses);

  // Monthly trend
  const currentYear = year === 'all' ? 2026 : year;
  const monthly = monthlyTotals(yearTxns, currentYear);
  const monthLabels = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

  const recent = transactions.slice(0, 8);

  return (
    <>
      <Topbar title="Overview" subtitle={`Portfolio snapshot · ${year === 'all' ? 'All time' : year}`}>
        <YearFilter value={year} onChange={setYear}/>
        <button className="btn accent" onClick={onAddTxn}>{Icon.plus} New transaction</button>
      </Topbar>

      <div className="content grid" style={{ gap: 20 }}>
        {/* Collected-through banner */}
        <div className="row" style={{ gap: 10, padding: '10px 14px', background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12.5 }}>
          <span style={{ display: 'inline-flex', color: 'var(--accent)' }}>
            {React.cloneElement(Icon.check, { style: { width: 14, height: 14 } })}
          </span>
          <span className="muted">Collected revenue through</span>
          <span className="tabular" style={{ fontWeight: 500, color: 'var(--text)' }}>{fmtDate(TODAY)}, {TODAY.slice(0, 4)}</span>
          <span className="muted">·</span>
          <span className="muted">Paid & checked in only — future bookings excluded</span>
          <button className="btn ghost" onClick={() => onNav({ name: 'connections' })}
                  style={{ marginLeft: 'auto', height: 22, padding: '0 8px', fontSize: 11.5 }}>
            View pipeline →
          </button>
        </div>

        {/* KPIs */}
        <div className="grid cols-4">
          <KpiCard label="Net profit" value={fmt$(net)} delta={netDelta} accent/>
          <KpiCard label="Revenue" value={fmt$(income)} delta={incomeDelta}/>
          <KpiCard label="Expenses" value={fmt$(expense)} delta={expenseDelta} invertDelta/>
          <KpiCard label="Profit margin" value={income ? `${(net / income * 100).toFixed(1)}%` : '—'}
                   delta={null} sublabel={`on ${fmt$(income, { compact: true })} revenue`}/>
        </div>

        {/* Main row: trend + donut */}
        <div className="grid" style={{ gridTemplateColumns: '1.8fr 1fr', gap: 20 }}>
          <div className="card">
            <div className="card-header">
              <div>
                <h3>Income vs expenses</h3>
                <div className="xs muted" style={{ marginTop: 2 }}>Monthly · {currentYear}</div>
              </div>
              <div className="row" style={{ gap: 16 }}>
                <Legend color="var(--income)" label="Income"/>
                <Legend color="var(--expense)" label="Expenses"/>
              </div>
            </div>
            <div style={{ padding: 20 }}>
              <LineChart
                labels={monthLabels}
                series={[
                  { name: 'Income', color: 'var(--income)', data: monthly.income.map((y, x) => ({ x, y })) },
                  { name: 'Expenses', color: 'var(--expense)', data: monthly.expense.map((y, x) => ({ x, y })) },
                ]}
                height={280}
              />
            </div>
          </div>

          <div className="card">
            <div className="card-header"><h3>Revenue by house</h3></div>
            <div style={{ padding: 24 }}>
              <DonutChart
                centerLabel="Total"
                centerValue={fmt$(income, { compact: true })}
                data={byHouse.map(h => ({ label: h.house.name, value: h.income, color: h.house.accentColor }))}
                size={168}
                thickness={22}
              />
            </div>
          </div>
        </div>

        {/* House cards */}
        <div>
          <div className="row between" style={{ marginBottom: 10 }}>
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>Properties</h3>
            <button className="btn ghost sm">View all {Icon.chevron_right}</button>
          </div>
          <div className="grid cols-3">
            {byHouse.map(({ house, income, expense, net }) => (
              <button key={house.id} className="card"
                      onClick={() => onNav({ name: 'house', houseId: house.id })}
                      style={{ padding: 0, textAlign: 'left', cursor: 'default', border: '1px solid var(--border)', background: 'var(--bg-elev)' }}>
                <HousePhoto house={house} size="md"/>
                <div style={{ padding: 18 }}>
                  <div className="row between" style={{ marginBottom: 12 }}>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 15 }}>{house.name}</div>
                      <div className="xs muted" style={{ marginTop: 2 }}>{house.address.split(',').slice(-2).join(',').trim()}</div>
                    </div>
                    <span className="dot" style={{ background: house.accentColor, width: 10, height: 10 }}/>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, borderTop: '1px solid var(--border)', paddingTop: 12 }}>
                    <div>
                      <div className="xs muted">Revenue</div>
                      <div className="tabular" style={{ fontWeight: 500, marginTop: 2 }}>{fmt$(income, { compact: true })}</div>
                    </div>
                    <div>
                      <div className="xs muted">Expenses</div>
                      <div className="tabular" style={{ fontWeight: 500, marginTop: 2 }}>{fmt$(expense, { compact: true })}</div>
                    </div>
                    <div>
                      <div className="xs muted">Net</div>
                      <div className="tabular" style={{ fontWeight: 600, marginTop: 2, color: net >= 0 ? 'var(--income)' : 'var(--expense)' }}>
                        {fmt$(net, { compact: true })}
                      </div>
                    </div>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Recent transactions */}
        <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 20 }}>
          <div className="card">
            <div className="card-header">
              <h3>Recent transactions</h3>
              <button className="btn ghost sm" onClick={() => onNav({ name: 'transactions' })}>
                See all {Icon.chevron_right}
              </button>
            </div>
            <table className="table">
              <tbody>
                {recent.map(t => {
                  const h = houses.find(x => x.id === t.houseId);
                  return (
                    <tr key={t.id} onClick={() => onOpenTxn(t)}>
                      <td style={{ width: 70, color: 'var(--text-tertiary)', fontSize: 12 }}>{fmtDate(t.date)}</td>
                      <td>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span className="dot" style={{ background: h?.accentColor }}/>
                          <div>
                            <div style={{ fontWeight: 450 }}>{t.description}</div>
                            <div className="xs muted">{h?.name} · {t.category}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{ width: 64 }}><SourceTag source={t.source || 'manual'}/></td>
                      <td className="num tabular" style={{ width: 110, color: t.type === 'income' ? 'var(--income)' : 'var(--text)', fontWeight: 500 }}>
                        {t.type === 'income' ? '+' : '-'}{fmt$(t.amount)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div className="card">
            <div className="card-header"><h3>This month</h3></div>
            <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <MiniStat label="Bookings logged" value="14" delta="+3 vs last month" trend={[3,5,2,4,6,5,7,4,5,6,8,14]}/>
              <MiniStat label="Cleanings completed" value="11" delta="3 pending" trend={[2,3,4,3,5,4,6,5,4,7,9,11]}/>
              <MiniStat label="Avg daily rate" value="$286" delta="+$12 vs last month" trend={[240,248,252,260,265,272,268,278,282,284,278,286]}/>
              <MiniStat label="Occupancy" value="72%" delta="+8pp vs last month" trend={[45,52,58,55,62,60,65,68,64,70,68,72]}/>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function Legend({ color, label }) {
  return (
    <div className="row" style={{ gap: 6, fontSize: 12, color: 'var(--text-secondary)' }}>
      <span style={{ width: 9, height: 9, borderRadius: 2, background: color }}/>{label}
    </div>
  );
}

function MiniStat({ label, value, delta, trend }) {
  return (
    <div className="row between" style={{ gap: 12 }}>
      <div>
        <div className="xs muted">{label}</div>
        <div className="row" style={{ gap: 8, marginTop: 2 }}>
          <div className="serif tabular" style={{ fontSize: 20, letterSpacing: '-0.01em' }}>{value}</div>
        </div>
        <div className="xs muted" style={{ marginTop: 2 }}>{delta}</div>
      </div>
      <Sparkline data={trend} color="var(--accent)" width={80} height={32}/>
    </div>
  );
}

Object.assign(window, { OverviewPage });
