const { useState, useEffect, useMemo, useRef } = React;


// ============================================================
// 2026 Ontario + federal tax engine
// ============================================================

const FED_BRACKETS = [
  { upto: 58523, rate: 0.14 },
  { upto: 117045, rate: 0.205 },
  { upto: 181440, rate: 0.26 },
  { upto: 258482, rate: 0.29 },
  { upto: Infinity, rate: 0.33 },
];
const FED_BPA = 16452;

const ON_BRACKETS = [
  { upto: 52886, rate: 0.0505 },
  { upto: 105775, rate: 0.0915 },
  { upto: 150000, rate: 0.1116 },
  { upto: 220000, rate: 0.1216 },
  { upto: Infinity, rate: 0.1316 },
];
const ON_BPA = 12989;
const ON_SURTAX_T1 = 5554;
const ON_SURTAX_T2 = 7108;

const CPP_EXEMPTION = 3500;
const CPP_YMPE = 74600;
const CPP2_CEILING = 85000;
const CPP_RATE = 0.0595;
const CPP2_RATE = 0.04;

const EI_MAX_INSURABLE = 68900;
const EI_RATE = 0.0163;

function progressiveTax(income, brackets) {
  let tax = 0;
  let prev = 0;
  for (const b of brackets) {
    if (income <= prev) break;
    tax += (Math.min(income, b.upto) - prev) * b.rate;
    prev = b.upto;
  }
  return tax;
}

function ontarioHealthPremium(income) {
  if (income <= 20000) return 0;
  if (income <= 25000) return Math.min(300, 0.06 * (income - 20000));
  if (income <= 36000) return 300;
  if (income <= 38500) return 300 + Math.min(150, 0.06 * (income - 36000));
  if (income <= 48000) return 450;
  if (income <= 48600) return 450 + Math.min(150, 0.25 * (income - 48000));
  if (income <= 72000) return 600;
  if (income <= 72600) return 600 + Math.min(150, 0.25 * (income - 72000));
  if (income <= 200000) return 750;
  if (income <= 200600) return 750 + Math.min(150, 0.25 * (income - 200000));
  return 900;
}

function calcNet(gross) {
  const fedTax = Math.max(0, progressiveTax(gross, FED_BRACKETS) - FED_BPA * 0.14);
  const onBaseTax = Math.max(0, progressiveTax(gross, ON_BRACKETS) - ON_BPA * 0.0505);
  let surtax = 0;
  if (onBaseTax > ON_SURTAX_T1) surtax += 0.2 * (onBaseTax - ON_SURTAX_T1);
  if (onBaseTax > ON_SURTAX_T2) surtax += 0.36 * (onBaseTax - ON_SURTAX_T2);
  const onTax = onBaseTax + surtax + ontarioHealthPremium(gross);
  const cpp1 = CPP_RATE * Math.max(0, Math.min(gross, CPP_YMPE) - CPP_EXEMPTION);
  const cpp2 = CPP2_RATE * Math.max(0, Math.min(gross, CPP2_CEILING) - CPP_YMPE);
  const ei = EI_RATE * Math.min(gross, EI_MAX_INSURABLE);
  const totalDeductions = fedTax + onTax + cpp1 + cpp2 + ei;
  const annualNet = gross - totalDeductions;
  return { annualNet, monthlyNet: annualNet / 12, annualTax: totalDeductions };
}

// ============================================================
// Personal budget model
// This is YOUR budget: your take-home pay against your share of costs.
// Each category says how its bill is split with your partner:
//   mine   — you pay it all (amount = your amount)
//   income — shared in proportion to take-home pay (amount = the full bill)
//   even   — shared 50/50 (amount = the full bill)
// Your partner's income is only used to work out the "income" percentage.
// ============================================================

const LEFTOVER_NAME = "Leftover / savings";
const LEFTOVER_ID = "__leftover";

const GROUPS = ["Housing", "Food", "Transport", "Bills", "Lifestyle", "Other"];
const GROUP_COLORS = {
  Housing: "#7C6FF2",
  Food: "#3DD6A0",
  Transport: "#FFC145",
  Bills: "#5BC8E8",
  Lifestyle: "#FF8A3D",
  Other: "#9AA6BA",
};
const FREQS = {
  monthly: { label: "Monthly", perMonth: 1 },
  annual: { label: "Yearly", perMonth: 1 / 12 },
};
const CATEGORY_TYPES = { fixed: "Fixed bill", variable: "Varies month to month" };
const SPLITS = { mine: "Just me", income: "Shared by take-home pay", even: "Shared 50 / 50" };
const PERSON_IDS = ["a", "b"]; // a = you, b = your partner

let idCounter = 0;
const newId = (prefix = "c") =>
  `${prefix}_${Date.now().toString(36)}${(idCounter++).toString(36)}${Math.random().toString(36).slice(2, 6)}`;

// Starter categories. Everything starts at the typical downtown Toronto amount for one
// person, except rent and vehicle, which are sized from your combined take-home pay
// (30% and 10%) and split by income. `legacy` is the name used by the first version.
const TORONTO_TEMPLATE = [
  { name: "Rent", legacy: "Rent (30% cap)", group: "Housing", type: "fixed", split: "income", pctOfNet: 0.3, avgPer: 1470 },
  { name: "Groceries", group: "Food", type: "variable", split: "even", avgPer: 470 },
  { name: "Hobbies & entertainment", group: "Lifestyle", type: "variable", split: "mine", avgPer: 200 },
  { name: "Clothing & personal care", group: "Lifestyle", type: "variable", split: "mine", avgPer: 195 },
  { name: "Parking", group: "Transport", type: "fixed", split: "mine", avgPer: 150 },
  { name: "Utilities (hydro/internet)", group: "Bills", type: "fixed", split: "mine", avgPer: 160 },
  { name: "Phone", group: "Bills", type: "fixed", split: "mine", avgPer: 75 },
  { name: "Household bills", group: "Bills", type: "fixed", split: "mine", avgPer: 105 },
  { name: "Dining out", group: "Food", type: "variable", split: "mine", avgPer: 250 },
  { name: "Beers/drinks out", group: "Lifestyle", type: "variable", split: "mine", avgPer: 150 },
  { name: "Gym", group: "Lifestyle", type: "fixed", split: "mine", avgPer: 80 },
  { name: "Vehicle", legacy: "Vehicle (your half)", group: "Transport", type: "fixed", split: "income", pctOfNet: 0.1, avgPer: 686 },
];

// Take-home pay for one person: their own figure if entered, otherwise the tax estimate.
function personNet(p) {
  const est = calcNet(Math.max(0, Number(p.gross) || 0));
  const overridden = Number(p.netOverride) > 0;
  return {
    monthlyNet: overridden ? Number(p.netOverride) : est.monthlyNet,
    estimatedMonthlyNet: est.monthlyNet,
    annualTax: est.annualTax,
    overridden,
  };
}

const householdNet = (people) => people.reduce((s, p) => s + personNet(p).monthlyNet, 0);

// Your fraction of income-split bills, from two monthly take-home figures.
function shareFromNets(mine, partner) {
  const total = mine + partner;
  return total > 0 ? mine / total : 0.5;
}
const incomeShare = (people) => shareFromNets(personNet(people[0]).monthlyNet, personNet(people[1]).monthlyNet);

// The full bill per month (yearly costs spread over 12 months).
function monthlyCost(c) {
  return Math.max(0, Number(c.amount) || 0) * (FREQS[c.freq]?.perMonth ?? 1);
}
const splitFraction = (split, share) => (split === "even" ? 0.5 : split === "income" ? share : 1);
// What a category costs YOU per month.
const myShare = (c, share) => monthlyCost(c) * splitFraction(c.split, share);

// Builds the starter categories. `legacyOverrides` are the per-person slider values saved
// by the first version (keyed by its category names) — those were already "your share",
// so they're converted back to full bills where a category is shared.
function buildTemplateCategories(people, legacyOverrides = {}) {
  const share = incomeShare(people);
  const combined = householdNet(people);
  return TORONTO_TEMPLATE.map((t) => {
    let full = t.pctOfNet ? combined * t.pctOfNet : t.avgPer / splitFraction(t.split, share);
    const ov = legacyOverrides[t.legacy || t.name];
    if (typeof ov === "number" && ov >= 0) {
      const frac = splitFraction(t.split, share);
      full = frac > 0 ? ov / frac : ov;
    }
    return {
      id: newId(),
      name: t.name,
      amount: Math.round(full),
      freq: "monthly",
      type: t.type,
      split: t.split,
      group: t.group,
      avg: t.avgPer, // what a typical person pays — compared with YOUR share
    };
  });
}

// The leftover benchmark is a savings RATE (from the original $80k baseline),
// so it stays meaningful at any income.
const AVG_SAVINGS_RATE = (() => {
  const net = calcNet(80000).monthlyNet;
  const avgTotal = TORONTO_TEMPLATE.reduce((s, t) => s + t.avgPer, 0);
  return (net - avgTotal) / net;
})();

function buildBudget(household, cats, showBenchmark = true) {
  const [me, partner] = household.people;
  const nets = household.people.map(personNet);
  const monthlyNet = nets[0].monthlyNet;
  const share = shareFromNets(nets[0].monthlyNet, nets[1].monthlyNet);

  const categories = cats.map((c) => ({
    ...c,
    full: monthlyCost(c),
    fraction: splitFraction(c.split, share),
    value: myShare(c, share),
    avg: showBenchmark && typeof c.avg === "number" ? c.avg : null,
    benchmark: showBenchmark,
  }));
  const expenseTotal = categories.reduce((s, d) => s + d.value, 0);
  const avgExpenseTotal = categories.reduce((s, d) => s + (d.avg ?? 0), 0);
  const leftover = monthlyNet - expenseTotal;
  categories.push({
    id: LEFTOVER_ID,
    name: LEFTOVER_NAME,
    value: leftover,
    avg: showBenchmark ? monthlyNet * AVG_SAVINGS_RATE : null,
    benchmark: showBenchmark,
    isLeftover: true,
    group: "Savings",
  });

  // Shared bills summary: what you and your partner each put toward them.
  const shared = categories.filter((c) => !c.isLeftover && c.split !== "mine");
  const sharedTotal = shared.reduce((s, c) => s + c.full, 0);
  const myPart = shared.reduce((s, c) => s + c.value, 0);

  return {
    categories,
    monthlyNet,
    expenseTotal,
    avgExpenseTotal,
    leftover,
    annualTax: nets[0].annualTax,
    grossTotal: Number(me.gross) || 0,
    effectiveRate: me.gross > 0 ? nets[0].annualTax / me.gross : 0,
    nets,
    share,
    partnerName: partner.name,
    shared: { total: sharedTotal, mine: myPart, partner: sharedTotal - myPart, count: shared.length },
  };
}

// ============================================================
// Budget-side transactions & month maths.
// Spending is imported into the ledger (ledger.js, integer cents); Ledger.toBudgetTransactions
// turns posted personal rows into { id, date: "YYYY-MM-DD", amount ($), description, categoryId }
// for the plan-vs-actual, overview and forecast maths below. categoryId null = not in budget.
// ============================================================

const UNCATEGORIZED = "__none";
const pad2 = (n) => String(n).padStart(2, "0");

const currentMonthKey = () => todayISO().slice(0, 7);
function shiftMonth(key, delta) {
  let [y, m] = key.split("-").map(Number);
  m += delta;
  while (m < 1) { m += 12; y--; }
  while (m > 12) { m -= 12; y++; }
  return `${y}-${pad2(m)}`;
}
function monthLabel(key) {
  const [y, m] = key.split("-").map(Number);
  return new Date(y, m - 1, 1).toLocaleDateString(undefined, { month: "long", year: "numeric" });
}
const daysInMonth = (key) => {
  const [y, m] = key.split("-").map(Number);
  return new Date(y, m, 0).getDate();
};
// Fraction of the month that has passed: 1 for past months, 0 for future ones.
function monthElapsed(key) {
  const cur = currentMonthKey();
  if (key < cur) return 1;
  if (key > cur) return 0;
  return new Date().getDate() / daysInMonth(key);
}
function shortDate(iso) {
  const [y, m, d] = iso.split("-").map(Number);
  return new Date(y, m - 1, d).toLocaleDateString(undefined, { month: "short", day: "numeric" });
}

// Old (v3) expenses stored a fixed category label; map it onto the matching budget category.
const LEGACY_EXPENSE_WORDS = {
  Rent: "rent", Groceries: "groceries", Hobbies: "hobbies", Clothing: "clothing", Parking: "parking",
  Utilities: "utilities", Phone: "phone", "Dining Out": "dining", Drinks: "drinks", Gym: "gym",
  "Household bills": "household", Vehicle: "vehicle",
};
function migrateExpenses(expenses, categories) {
  return expenses
    .filter((e) => isObj(e) && typeof e.date === "string" && Number.isFinite(Number(e.amount)))
    .map((e) => {
      const word = LEGACY_EXPENSE_WORDS[e.category];
      const cat = word ? categories.find((c) => c.name.toLowerCase().includes(word)) : null;
      return { id: newId("t"), date: e.date.slice(0, 10), amount: Number(e.amount), description: "", categoryId: cat ? cat.id : null, paidBy: null };
    });
}

function normalizeTransaction(t) {
  return {
    id: typeof t.id === "string" && t.id ? t.id : newId("t"),
    date: typeof t.date === "string" && /^\d{4}-\d{2}-\d{2}$/.test(t.date) ? t.date : todayISO(),
    amount: Number.isFinite(Number(t.amount)) ? Number(t.amount) : 0,
    description: typeof t.description === "string" ? t.description : "",
    categoryId: typeof t.categoryId === "string" ? t.categoryId : null,
    paidBy: PERSON_IDS.includes(t.paidBy) ? t.paidBy : null,
  };
}

// ---- Month maths ----

// Your share of one logged purchase: purchases are logged as the full bill, and the
// category's split decides your part. Uncategorised purchases count in full.
function txShare(t, catById, share) {
  const c = catById.get(t.categoryId);
  return t.amount * (c ? splitFraction(c.split, share) : 1);
}

// Planned vs spent for one month — all in YOUR share. Monthly categories compare this
// month's spending with their monthly amount; yearly categories compare year-to-date
// spending with the yearly amount. `share` is your fraction of income-split bills.
function monthStats(transactions, categories, key, share = 0.5) {
  const catById = new Map(categories.map((c) => [c.id, c]));
  const year = key.slice(0, 4);
  const month = new Map();
  const ytd = new Map();
  let total = 0, count = 0;
  for (const t of transactions) {
    const id = catById.has(t.categoryId) ? t.categoryId : UNCATEGORIZED;
    const mine = txShare(t, catById, share);
    if (t.date.startsWith(key)) {
      month.set(id, (month.get(id) || 0) + mine);
      total += mine;
      count++;
    }
    if (t.date.slice(0, 4) === year && t.date.slice(0, 7) <= key) ytd.set(id, (ytd.get(id) || 0) + mine);
  }
  const rows = categories.map((c) => {
    const yearly = c.freq === "annual";
    const planned = myShare(c, share);
    return {
      category: c,
      yearly,
      planned: yearly ? planned * 12 : planned,
      spent: yearly ? ytd.get(c.id) || 0 : month.get(c.id) || 0,
      monthSpent: month.get(c.id) || 0,
    };
  });
  const monthlyRows = rows.filter((r) => !r.yearly);
  const plannedMonthly = monthlyRows.reduce((s, r) => s + r.planned, 0);
  const uncategorized = month.get(UNCATEGORIZED) || 0;
  // Uncategorised spending counts against the monthly plan; yearly categories don't.
  const spentMonthly = monthlyRows.reduce((s, r) => s + r.spent, 0) + uncategorized;
  return { rows, total, count, uncategorized, plannedMonthly, spentMonthly, leftMonthly: plannedMonthly - spentMonthly, elapsed: monthElapsed(key) };
}

// "over" = past its amount; "ahead" = spending faster than the month is passing.
// `elapsed` is how far through `key`'s month we are; yearly categories compare against
// how far through the year that month is.
function paceStatus(r, elapsed, key) {
  if (r.planned <= 0) return r.spent > 0 ? "over" : "ok";
  if (r.spent > r.planned + 0.5) return "over";
  const frac = r.yearly ? (Number(key.slice(5)) - 1 + elapsed) / 12 : elapsed;
  if (r.spent / r.planned > frac + 0.15 && frac < 1) return "ahead";
  return "ok";
}

// ============================================================
// Forecast — month-by-month cash flow with future events and scenarios.
// Event amounts are signed: + money in, − money out.
//   oneoff:    amount in one month (a bonus, a vacation)
//   recurring: amount every month from `month` to `endMonth` (a car payment, daycare)
//   income:    partner `person` earns `salary` per year from `month` to `endMonth`
//              (a raise; parental leave with an end month, after which pay returns)
// ============================================================

const EVENT_KINDS = {
  oneoff: "One-off",
  recurring: "Monthly change",
  income: "Income change",
};

function defaultForecast() {
  return {
    startBalance: null, // cash in chequing/savings today; null = not entered yet
    floor: null, // safety line; null = suggest 3 months of fixed bills
    horizon: 24,
    useActuals: true,
    scenarios: [{ id: "base", name: "Current plan", events: [] }],
    activeId: "base",
    compareId: null,
  };
}

function normalizeEvent(e) {
  const kind = EVENT_KINDS[e.kind] ? e.kind : "oneoff";
  const month = typeof e.month === "string" && /^\d{4}-\d{2}$/.test(e.month) ? e.month : shiftMonth(currentMonthKey(), 1);
  const endMonth = typeof e.endMonth === "string" && /^\d{4}-\d{2}$/.test(e.endMonth) && e.endMonth >= month ? e.endMonth : null;
  return {
    id: typeof e.id === "string" && e.id ? e.id : newId("e"),
    kind,
    name: typeof e.name === "string" ? e.name : "",
    month,
    endMonth: kind === "oneoff" ? null : endMonth,
    amount: Number.isFinite(Number(e.amount)) ? Number(e.amount) : 0,
    person: PERSON_IDS.includes(e.person) ? e.person : "a",
    salary: nonNeg(e.salary),
  };
}

function normalizeForecast(d) {
  const f = defaultForecast();
  if (!isObj(d)) return f;
  if (Number.isFinite(Number(d.startBalance)) && d.startBalance !== null) f.startBalance = Number(d.startBalance);
  if (Number.isFinite(Number(d.floor)) && d.floor !== null) f.floor = nonNeg(d.floor);
  if ([12, 24, 36].includes(Number(d.horizon))) f.horizon = Number(d.horizon);
  if (typeof d.useActuals === "boolean") f.useActuals = d.useActuals;
  if (Array.isArray(d.scenarios) && d.scenarios.length) {
    f.scenarios = d.scenarios.filter(isObj).map((s, i) => ({
      id: typeof s.id === "string" && s.id ? s.id : newId("s"),
      name: typeof s.name === "string" && s.name.trim() ? s.name : `Scenario ${i + 1}`,
      events: Array.isArray(s.events) ? s.events.filter(isObj).map(normalizeEvent) : [],
    }));
  }
  if (!f.scenarios.length) f.scenarios = defaultForecast().scenarios;
  const ids = f.scenarios.map((s) => s.id);
  f.activeId = ids.includes(d.activeId) ? d.activeId : ids[0];
  f.compareId = ids.includes(d.compareId) && d.compareId !== f.activeId ? d.compareId : null;
  return f;
}

const isActive = (e, key) => e.month <= key && (!e.endMonth || key <= e.endMonth);

// Average monthly spending per category over the last `n` complete months before `key`,
// but only if every one of those months has some logged spending (otherwise we'd be
// averaging in months where nothing was tracked).
function trailingAverages(transactions, key, n = 3) {
  const months = [...Array(n).keys()].map((i) => shiftMonth(key, -(i + 1)));
  const tracked = new Set(transactions.map((t) => t.date.slice(0, 7)));
  if (!months.every((m) => tracked.has(m))) return null;
  const set = new Set(months);
  const sums = new Map();
  for (const t of transactions) {
    if (!set.has(t.date.slice(0, 7)) || !t.categoryId) continue;
    sums.set(t.categoryId, (sums.get(t.categoryId) || 0) + t.amount);
  }
  const avg = new Map();
  for (const [id, s] of sums) avg.set(id, s / n);
  return avg;
}

// Runs one scenario forward from the month after `todayKey`, from YOUR point of view:
// income is your take-home; spending is your share of each bill, recalculated every
// month because a change in either income moves your share of income-split bills.
function runForecast({ household, categories, transactions, holdings, forecast: f, events, todayKey = currentMonthKey() }) {
  const avgs = f.useActuals ? trailingAverages(transactions, todayKey) : null;
  const usedAverage = [];
  // full monthly bill per category — logged averages (full bills) for categories that vary
  const bills = categories.map((c) => {
    if (avgs && c.type === "variable" && c.freq === "monthly" && avgs.has(c.id)) {
      usedAverage.push({ category: c, average: avgs.get(c.id) });
      return { c, full: avgs.get(c.id) };
    }
    return { c, full: monthlyCost(c) };
  });
  const spendingAt = (share) => bills.reduce((s, b) => s + b.full * splitFraction(b.c.split, share), 0);
  const baseShare = incomeShare(household.people);
  // Savings transfers are % of the budget's planned leftover, from whichever savings
  // stage is running that month.
  const plannedLeftover = personNet(household.people[0]).monthlyNet - categories.reduce((s, c) => s + myShare(c, baseShare), 0);
  const contribAt = (key) => LEFTOVER_OPTIONS.reduce((s, o) => s + allocAmount(holdings, o.name, plannedLeftover, key), 0);

  let balance = f.startBalance ?? 0;
  const rows = [];
  for (let i = 1; i <= f.horizon; i++) {
    const key = shiftMonth(todayKey, i);
    const notes = [];
    const nets = household.people.map((p, pi) => {
      // the latest-starting income change that covers this month wins
      const change = events
        .filter((e) => e.kind === "income" && e.person === p.id && isActive(e, key))
        .sort((a, b) => (a.month < b.month ? 1 : -1))[0];
      if (change) {
        notes.push(`${personLabel(p, pi)}: ${change.name || "income change"}`);
        return calcNet(change.salary).monthlyNet;
      }
      return personNet(p).monthlyNet;
    });
    const income = nets[0];
    const contrib = contribAt(key);
    const share = shareFromNets(nets[0], nets[1]);
    const spending = spendingAt(share);
    if (Math.abs(share - baseShare) > 0.005) notes.push(`your share of income-split bills ${Math.round(share * 100)}%`);
    let eventFlow = 0;
    for (const e of events) {
      if ((e.kind === "oneoff" && e.month === key) || (e.kind === "recurring" && isActive(e, key))) {
        eventFlow += e.amount;
        notes.push(`${e.name || EVENT_KINDS[e.kind]} ${e.amount >= 0 ? "+" : "−"}${fmt(Math.abs(e.amount))}`);
      }
    }
    const flow = income - spending - contrib + eventFlow;
    balance += flow;
    rows.push({ key, income, spending, share, contrib, eventFlow, flow, balance, notes });
  }
  const spending = spendingAt(baseShare);
  const contrib = contribAt(shiftMonth(todayKey, 1));
  const low = rows.reduce((m, r) => (r.balance < m.balance ? r : m), rows[0] || { balance: balance, key: todayKey });
  // Typical month once one-offs are excluded — used to extend the long-range projection.
  const last = rows[rows.length - 1];
  const oneoffsInLast = last ? events.filter((e) => e.kind === "oneoff" && e.month === last.key).reduce((s, e) => s + e.amount, 0) : 0;
  const steadyFlow = last ? last.flow - oneoffsInLast : 0;
  return { rows, spending, contrib, plannedLeftover, usedAverage, low, end: balance, steadyFlow };
}

// Suggested safety line: three months of your share of fixed bills.
const suggestedFloor = (categories, share = 0.5) =>
  Math.round(categories.filter((c) => c.type === "fixed").reduce((s, c) => s + myShare(c, share), 0) * 3);

// Net worth after `years`: cash (from the forecast, then its steady monthly flow) plus
// every savings account growing at its rate (scaled by bear/base/bull).
function netWorthAt(years, { cashResult, startCash, holdings, rateMult = 1 }) {
  const months = years * 12;
  const rows = cashResult.rows;
  let cash;
  if (months <= 0) cash = startCash;
  else if (months <= rows.length) cash = rows[months - 1].balance;
  else cash = cashResult.end + cashResult.steadyFlow * (months - rows.length);
  const invest = projectAccounts(holdings, cashResult.plannedLeftover, (o) => o.rate * rateMult, months).reduce((s, a) => s + a.points[months].value, 0);
  return { cash, invest, total: cash + invest };
}

// ============================================================
// Squarified treemap — every tile is a true rectangle, sized exactly
// to its share of net income, and biased toward square proportions.
// Category order is fixed, so tiles stay in roughly the same
// neighbourhood as values change.
// ============================================================

const WIDTH = 640;
const HEIGHT = 640;
const GAP = 3;

function buildTreemap(values) {
  const root = d3
    .hierarchy({ children: values.map((v, i) => ({ id: i, value: Math.max(v, 1) })) })
    .sum((d) => d.value);

  d3.treemap().tile(d3.treemapSquarify).size([WIDTH, HEIGHT]).paddingInner(GAP).round(false)(root);

  const leaves = new Array(values.length);
  root.leaves().forEach((leaf) => {
    leaves[leaf.data.id] = { x0: leaf.x0, y0: leaf.y0, x1: leaf.x1, y1: leaf.y1 };
  });
  return leaves;
}

// ============================================================
// Colors & comparison
// ============================================================

const GREEN = "#3DFFB0";
const RED = "#FF5470";
const NEUTRAL = "#8E9AAD";
const ACCENT = "#33D6FF";

// true = better than the Toronto benchmark, false = worse, null = no benchmark or within ~3%.
function isGood(d) {
  if (d.avg == null) return null;
  const delta = d.value - d.avg;
  if (Math.abs(delta) < Math.abs(d.avg) * 0.03) return null;
  if (d.isLeftover) return delta > 0;
  return delta < 0;
}
// With comparisons on: green/red/grey vs the benchmark. With them off: colour by group.
function colorFor(d) {
  if (!d.benchmark) return d.isLeftover ? (d.value >= 0 ? ACCENT : RED) : GROUP_COLORS[d.group] || NEUTRAL;
  const good = isGood(d);
  if (good === null) return NEUTRAL;
  return good ? GREEN : RED;
}

const fmt = (n) => (n < 0 ? `-$${Math.abs(Math.round(n)).toLocaleString()}` : `$${Math.round(n).toLocaleString()}`);
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
const prefersReducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

// Animates an array of numbers toward new targets whenever they change.
function useAnimatedValues(targets, duration = 550) {
  const [display, setDisplay] = useState(targets);
  const fromRef = useRef(targets);
  const startRef = useRef(null);
  const rafRef = useRef(null);

  useEffect(() => {
    if (prefersReducedMotion()) {
      setDisplay(targets);
      return;
    }
    fromRef.current = display;
    startRef.current = null;

    function tick(ts) {
      if (startRef.current === null) startRef.current = ts;
      const t = Math.min(1, (ts - startRef.current) / duration);
      const e = easeOutCubic(t);
      const next = targets.map((tv, i) => {
        const fv = fromRef.current[i] ?? tv;
        return fv + (tv - fv) * e;
      });
      setDisplay(next);
      if (t < 1) {
        rafRef.current = requestAnimationFrame(tick);
      }
    }
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(targets.map((v) => Math.round(v)))]);

  return display;
}

// Animates a single number toward a new target — used for the counting header figure.
function useAnimatedNumber(target, duration = 650) {
  const arr = useAnimatedValues([target], duration);
  return arr[0];
}

// ============================================================
// Persistent store — the whole app's saved data lives in one versioned
// localStorage entry and is written automatically on every change.
// ============================================================

const STORE_KEY = "budget-telemetry:v2";
const LEGACY_HOLDINGS_KEY = "holdings:v1"; // read once for migration, never written or deleted
// v2: single salary + per-category slider overrides. v3: two partners + editable categories.
// v4: expenses -> transactions linked to category ids, plus learned categorising rules.
// v5: forecast settings, scenarios and events.
// v6: personal budget — categories say how they're split (mine / by income / 50-50).
// v7: spending is an imported ledger (ledger.js); old manual transactions move to
//     legacyTransactions until the user downloads/removes them; learned rules dropped.
const STORE_VERSION = 7;

const DEFAULT_HOLDINGS = {
  balances: {},
  contribs: {}, // legacy fixed $/month — converted to allocPct on load
  allocPct: {}, // % of your monthly leftover that goes into each account
  targets: {},
  roomUsed: {},
  goal: 100000,
  household: false,
  snapshots: [],
  goals: [{ name: "Retirement", target: 500000, accounts: ["RRSP", "TFSA"], deadline: null }],
  incomeSources: null, // null = "one salary source matching the budget salary"
};

const freshHoldings = () => JSON.parse(JSON.stringify(DEFAULT_HOLDINGS));

// people[0] is you; people[1] is your partner (their income only sets your share of
// income-split bills).
function defaultHousehold(gross = 80000) {
  return {
    people: [
      { id: "a", name: "You", gross, netOverride: null },
      { id: "b", name: "Partner", gross, netOverride: null },
    ],
  };
}

function defaultState() {
  const household = defaultHousehold();
  return {
    version: STORE_VERSION,
    household,
    categories: buildTemplateCategories(household.people),
    settings: { showBenchmark: true },
    ledger: Ledger.emptyLedger(),
    categoryMap: {}, // imported category id -> budget category id (null = not in budget)
    legacyTransactions: [],
    forecast: defaultForecast(),
    holdings: normalizeHoldings({}),
  };
}

const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const nonNeg = (v) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : 0);

function normalizeHousehold(d) {
  const h = defaultHousehold();
  if (!isObj(d)) return h;
  if (Array.isArray(d.people)) {
    h.people = h.people.map((def, i) => {
      const p = isObj(d.people[i]) ? d.people[i] : {};
      // the previous version's placeholder names become You / Partner
      const named = typeof p.name === "string" && p.name.trim() && !/^Partner [12]$/.test(p.name.trim());
      return {
        id: def.id,
        name: named ? p.name : def.name,
        gross: typeof p.gross === "number" ? nonNeg(p.gross) : def.gross,
        netOverride: Number(p.netOverride) > 0 ? Number(p.netOverride) : null,
      };
    });
  }
  return h;
}

function normalizeCategory(c) {
  let split = SPLITS[c.split] ? c.split : null;
  let avg = typeof c.avg === "number" && c.avg >= 0 ? c.avg : null;
  if (!split && typeof c.owner === "string") {
    // v3–v5 household categories: "each"/one-partner amounts were per person -> yours;
    // "shared" amounts were the full bill -> rent/car split by income, the rest 50/50.
    split = c.owner === "shared" ? (/rent|vehicle|car\b|mortgage/i.test(c.name || "") ? "income" : "even") : "mine";
    if (avg != null) avg = avg / 2; // household benchmark -> per person
  }
  return {
    id: typeof c.id === "string" && c.id ? c.id : newId(),
    name: typeof c.name === "string" ? c.name : "Untitled",
    amount: nonNeg(c.amount),
    freq: FREQS[c.freq] ? c.freq : "monthly",
    type: CATEGORY_TYPES[c.type] ? c.type : "variable",
    split: split || "mine",
    group: GROUPS.includes(c.group) ? c.group : "Other",
    avg,
  };
}

// Accepts a holdings:v1 payload or an old holdings JSON export and returns the current holdings shape.
function normalizeHoldings(d) {
  const h = freshHoldings();
  if (!isObj(d)) d = {}; // still build stages below — returning early left them undefined and crashed the Savings tab
  for (const k of ["balances", "contribs", "targets", "roomUsed"]) if (isObj(d[k])) h[k] = d[k];
  h.allocPct = cleanPcts(d.allocPct); // legacy single plan — becomes Stage 1 if there are no stages
  h.stagesStart = typeof d.stagesStart === "string" && MONTH_KEY_RE.test(d.stagesStart) ? d.stagesStart : currentMonthKey();
  h.stages = Array.isArray(d.stages) ? d.stages.filter(isObj).map(normalizeStage) : [];
  if (!h.stages.length) h.stages = [{ id: newId("st"), name: "Stage 1", months: null, allocPct: { ...h.allocPct } }];
  if (typeof d.goal === "number") h.goal = d.goal;
  // h.household (the old "×2 for partner" toggle) stays false: balances are yours.
  if (Array.isArray(d.snapshots)) h.snapshots = d.snapshots;
  if (Array.isArray(d.goals)) h.goals = d.goals;
  else if (typeof d.goal === "number") h.goals = [{ name: "Retirement", target: d.goal, accounts: ["RRSP", "TFSA"], deadline: null }];
  if (Array.isArray(d.incomeSources)) h.incomeSources = d.incomeSources;
  else if (typeof d.grossSalary === "number") h.incomeSources = [{ name: "Salary", annual: d.grossSalary, type: "salary" }];
  return h;
}

function normalizeState(d) {
  const s = defaultState();
  if (!isObj(d)) return s;

  if (isObj(d.household)) {
    s.household = normalizeHousehold(d.household);
  } else if (typeof d.grossSalary === "number") {
    // v2 migration: the old model assumed both partners earned the slider salary.
    s.household = defaultHousehold(nonNeg(d.grossSalary));
  }

  if (Array.isArray(d.categories)) {
    s.categories = d.categories.filter(isObj).map(normalizeCategory);
  } else {
    // v2 migration: rebuild the Toronto categories for this household and carry over
    // any slider adjustments (old values were one partner's share).
    s.categories = buildTemplateCategories(s.household.people, isObj(d.overrides) ? d.overrides : {});
  }

  if (isObj(d.settings) && typeof d.settings.showBenchmark === "boolean") s.settings.showBenchmark = d.settings.showBenchmark;
  s.ledger = Ledger.normalizeLedger(d.ledger);
  if (isObj(d.categoryMap)) {
    for (const [k, v] of Object.entries(d.categoryMap)) {
      if (Ledger.CATEGORY[k] && (v === null || typeof v === "string")) s.categoryMap[k] = v;
    }
  }
  // Manual spending from v6 and earlier is kept aside, untouched, until the user removes it.
  if (Array.isArray(d.legacyTransactions)) {
    s.legacyTransactions = d.legacyTransactions.filter(isObj).map(normalizeTransaction);
  } else if (Array.isArray(d.transactions)) {
    s.legacyTransactions = d.transactions.filter(isObj).map(normalizeTransaction);
  } else if (Array.isArray(d.expenses)) {
    s.legacyTransactions = migrateExpenses(d.expenses, s.categories);
  }
  s.forecast = normalizeForecast(d.forecast);
  s.holdings = normalizeHoldings(d.holdings);
  // Older saves stored fixed $/month contributions; turn them into % of today's leftover
  // so the dollars stay the same now and then follow the budget.
  const h = s.holdings;
  if (Object.keys(h.allocPct).length === 0 && Object.values(h.contribs).some((v) => Number(v) > 0)) {
    const leftover = buildBudget(s.household, s.categories, false).leftover;
    if (leftover > 0) {
      for (const [k, v] of Object.entries(h.contribs)) {
        if (Number(v) > 0) h.allocPct[k] = Math.min(100, Math.round((Number(v) / leftover) * 1000) / 10);
      }
      if (!(isObj(d.holdings) && Array.isArray(d.holdings.stages))) h.stages[0].allocPct = { ...h.allocPct };
    }
  }
  return s;
}

// ---- Savings stages ----
// Savings plans that run back to back from `stagesStart`, each with its own % split of
// your leftover — e.g. fill the emergency fund for 12 months, then switch to investing.
// The last stage never ends.

const monthsBetween = (a, b) => {
  const [ya, ma] = a.split("-").map(Number);
  const [yb, mb] = b.split("-").map(Number);
  return (yb - ya) * 12 + (mb - ma);
};
const MONTH_KEY_RE = /^\d{4}-(0[1-9]|1[0-2])$/;

function cleanPcts(obj) {
  const out = {};
  if (isObj(obj)) for (const [k, v] of Object.entries(obj)) if (Number(v) > 0) out[k] = Math.min(100, Math.round(Number(v) * 10) / 10);
  return out;
}

function normalizeStage(s, i) {
  const months = Math.round(Number(s.months));
  return {
    id: typeof s.id === "string" && s.id ? s.id : newId("st"),
    name: typeof s.name === "string" && s.name.trim() ? s.name : `Stage ${i + 1}`,
    months: months >= 1 && months <= 600 ? months : null,
    allocPct: cleanPcts(s.allocPct),
  };
}

// Index of the stage running in month `key`.
function stageIndexAt(h, key) {
  const stages = h.stages || [];
  if (stages.length <= 1) return 0;
  let offset = monthsBetween(h.stagesStart || key, key);
  if (offset < 0) return 0;
  for (let i = 0; i < stages.length - 1; i++) {
    const m = stages[i].months || 0;
    if (offset < m) return i;
    offset -= m;
  }
  return stages.length - 1;
}

// First and last month of stage `i` (end is null for the last, ongoing stage).
function stageRange(h, i) {
  const before = h.stages.slice(0, i).reduce((s, st) => s + (st.months || 0), 0);
  const start = shiftMonth(h.stagesStart, before);
  const last = i === h.stages.length - 1;
  return { start, end: last ? null : shiftMonth(start, Math.max(1, h.stages[i].months || 1) - 1) };
}

const allocPctAt = (h, key = currentMonthKey()) => (h.stages?.[stageIndexAt(h, key)]?.allocPct) || h.allocPct || {};

// Monthly $ into one account in month `key`: that stage's % of your leftover
// (nothing if there's no leftover).
const allocAmount = (holdings, name, leftover, key = currentMonthKey()) =>
  (Math.max(0, leftover) * (allocPctAt(holdings, key)[name] ?? 0)) / 100;

// Month-by-month value of every account: grows at its monthly rate, plus whatever the
// stage running that month puts in. points[m] = { value, paid } after m months.
function projectAccounts(holdings, leftover, rateOf, months, startKey = currentMonthKey()) {
  return LEFTOVER_OPTIONS.map((o) => {
    const r = rateOf(o) / 12;
    let value = holdings.balances[o.name] ?? 0;
    let paid = value;
    const points = [{ value, paid }];
    for (let m = 1; m <= months; m++) {
      const c = allocAmount(holdings, o.name, leftover, shiftMonth(startKey, m));
      value = value * (1 + r) + c;
      paid += c;
      points.push({ value, paid });
    }
    return { opt: o, points };
  });
}

function loadState() {
  try {
    const raw = localStorage.getItem(STORE_KEY);
    if (raw) return normalizeState(JSON.parse(raw));
    const legacy = localStorage.getItem(LEGACY_HOLDINGS_KEY);
    if (legacy) return { ...defaultState(), holdings: normalizeHoldings(JSON.parse(legacy)) };
  } catch {
    /* corrupt or unavailable storage — fall through to defaults */
  }
  return defaultState();
}

function writeState(state) {
  localStorage.setItem(STORE_KEY, JSON.stringify(state));
}

// Returns [state, setState, saveStatus]. Changes are saved ~400ms after they stop,
// and flushed immediately if the app is backgrounded or closed.
function useStore() {
  const [state, setState] = useState(loadState);
  const [saveStatus, setSaveStatus] = useState("saved"); // "saved" | "pending" | "error"
  const stateRef = useRef(state);
  stateRef.current = state;
  const firstRun = useRef(true);

  useEffect(() => {
    if (firstRun.current) {
      firstRun.current = false;
      return;
    }
    setSaveStatus("pending");
    const t = setTimeout(() => {
      try {
        writeState(state);
        setSaveStatus("saved");
      } catch {
        setSaveStatus("error");
      }
    }, 400);
    return () => clearTimeout(t);
  }, [state]);

  useEffect(() => {
    const flush = () => {
      try {
        writeState(stateRef.current);
      } catch {
        /* surfaced via saveStatus on the next debounced write */
      }
    };
    const onVisibility = () => document.visibilityState === "hidden" && flush();
    document.addEventListener("visibilitychange", onVisibility);
    window.addEventListener("pagehide", flush);
    return () => {
      document.removeEventListener("visibilitychange", onVisibility);
      window.removeEventListener("pagehide", flush);
    };
  }, []);

  return [state, setState, saveStatus];
}

// A useState-style setter for one key of an object owned by a parent setter.
function keySetter(setParent, key) {
  return (v) => setParent((p) => ({ ...p, [key]: typeof v === "function" ? v(p[key]) : v }));
}

function downloadFile(filename, text, type) {
  const blob = new Blob([text], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

// Local calendar date (toISOString would give the UTC date, which is "tomorrow" on a Toronto evening).
const todayISO = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};

const TAB_KEY = "budget-telemetry:tab";
const TABS = [
  { id: "home", label: "Home", icon: "⌂" },
  { id: "budget", label: "Budget", icon: "▦" },
  { id: "spending", label: "Spending", icon: "≡" },
  { id: "forecast", label: "Forecast", icon: "∿" },
  { id: "savings", label: "Savings", icon: "↗" },
  { id: "settings", label: "Settings", icon: "⚙" },
];

function BudgetVoronoi() {
  const [store, setStore, saveStatus] = useStore();
  const { household, categories, settings, ledger, categoryMap: savedMap, legacyTransactions, forecast, holdings } = store;
  const setForecast = keySetter(setStore, "forecast");
  const setHousehold = keySetter(setStore, "household");
  const setCategories = keySetter(setStore, "categories");
  const setSettings = keySetter(setStore, "settings");
  const showBenchmark = settings.showBenchmark;
  const setLedger = keySetter(setStore, "ledger");
  const setHoldings = keySetter(setStore, "holdings");

  // Imported categories -> budget categories: saved choices, plus name-based guesses for the rest.
  const categoryMap = useMemo(() => Ledger.suggestCategoryMap(categories, savedMap), [categories, savedMap]);
  const setMapping = (taxonomyId, budgetId) => setStore((p) => ({ ...p, categoryMap: { ...categoryMap, ...p.categoryMap, [taxonomyId]: budgetId } }));
  // Posted personal spending in the shape the budget / overview / forecast maths expect.
  const budgetTx = useMemo(() => Ledger.toBudgetTransactions(ledger, categoryMap), [ledger, categoryMap]);

  const exportLegacy = () =>
    downloadFile(
      `budget-telemetry-backup_old-spending_${todayISO()}.json`,
      JSON.stringify({ app: "budget-telemetry", kind: "legacy-spending", exportedAt: new Date().toISOString(), transactions: legacyTransactions }, null, 2),
      "application/json"
    );

  // Full backup of everything (budget, spending ledger, holdings).
  const exportBackup = () =>
    downloadFile(
      `budget-telemetry-backup_${todayISO()}.json`,
      JSON.stringify({ app: "budget-telemetry", exportedAt: new Date().toISOString(), ...store }, null, 2),
      "application/json"
    );

  // Restores a full backup, or an older holdings-only export. Returns true on success.
  const importBackup = async (file) => {
    try {
      const data = JSON.parse(await file.text());
      if (isObj(data) && (data.app === "budget-telemetry" || isObj(data.holdings))) {
        setStore(normalizeState(data));
        return true;
      }
      if (isObj(data) && data.balances !== undefined && data.contribs !== undefined) {
        setHoldings(normalizeHoldings(data));
        return true;
      }
    } catch {
      /* fall through */
    }
    return false;
  };

  const budget = useMemo(() => buildBudget(household, categories, showBenchmark), [household, categories, showBenchmark]);
  const targetValues = useMemo(() => budget.categories.map((d) => d.value), [budget]);
  const animatedValues = useAnimatedValues(targetValues);
  const animatedLeftover = useAnimatedNumber(budget.leftover);

  // Highlighted category: follows the mouse on desktop, and toggles on tap so it
  // also works on touch screens.
  const [hovered, setHovered] = useState(null);
  const toggleHighlight = (name) => setHovered((h) => (h === name ? null : name));

  // Tab navigation. The tab lives in the URL hash (#budget, #savings…) so the phone's
  // back button steps between tabs; the last tab used is remembered for next launch.
  const isTab = (t) => TABS.some((x) => x.id === t);
  const [tab, setTab] = useState(() => {
    const fromHash = window.location.hash.slice(1);
    if (isTab(fromHash)) return fromHash;
    try {
      const t = localStorage.getItem(TAB_KEY);
      return isTab(t) ? t : "home";
    } catch {
      return "home";
    }
  });
  useEffect(() => {
    const onHash = () => {
      const t = window.location.hash.slice(1);
      if (isTab(t)) {
        setTab(t);
        window.scrollTo({ top: 0, behavior: "auto" });
      }
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => {
    try {
      localStorage.setItem(TAB_KEY, tab);
    } catch {
      /* not critical */
    }
  }, [tab]);
  const goTo = (t) => {
    if (t === tab) return;
    window.location.hash = t; // triggers hashchange -> setTab, and adds a history entry
  };

  // "What-if" snapshot: freeze the current numbers, then compare against whatever
  // the sliders are changed to afterward.
  const [snapshot, setSnapshot] = useState(null);
  const takeSnapshot = () =>
    setSnapshot({
      grossTotal: budget.grossTotal,
      monthlyNet: budget.monthlyNet,
      expenseTotal: budget.expenseTotal,
      leftover: budget.leftover,
    });
  const clearSnapshot = () => setSnapshot(null);

  const nodes = useMemo(() => {
    // While a category is being added/removed the animated array briefly has the old
    // length; use the real values for that frame so the layout never sees gaps.
    const synced = animatedValues.length === budget.categories.length;
    const values = budget.categories.map((d, i) => (synced ? animatedValues[i] : d.value));
    const rects = buildTreemap(values);
    return budget.categories.map((d, i) => ({
      ...d,
      value: values[i],
      key: d.id,
      gradId: `grad-${i}`,
      color: colorFor(d),
      rect: rects[i],
    }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [animatedValues, budget]);

  return (
    <div
      style={{
        minHeight: "100vh",
        width: "100%",
        position: "relative",
        overflow: "hidden",
        background: "#05070A",
        color: "#E7ECF2",
        fontFamily: "'Sora', -apple-system, sans-serif",
        boxSizing: "border-box",
      }}
      className="app-shell"
    >
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Sora:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap');
        * { box-sizing: border-box; }
        .display { font-family: 'Space Grotesk', sans-serif; }
        .mono { font-family: 'JetBrains Mono', monospace; }
        .legend-row { transition: background 0.15s ease, transform 0.15s ease; }
        .legend-row:hover, .legend-row.is-active { background: rgba(51,214,255,0.07); }
        .cell-rect { transition: filter 0.18s ease, opacity 0.18s ease; }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        .fade-up { animation: fadeUp 0.5s ease both; }
        @keyframes scanSweep { 0% { transform: translateY(-10%); opacity: 0; } 8% { opacity: 0.5; } 92% { opacity: 0.5; } 100% { transform: translateY(110vh); opacity: 0; } }
        @keyframes pulseDot { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }

        /* ---- Layout shell: top tab bar on desktop, bottom tab bar on phones ---- */
        .app-shell { padding: 0 20px 60px; }
        .tabbar {
          position: sticky; top: 0; z-index: 40;
          display: flex; gap: 4px; justify-content: center;
          margin: 0 -20px 28px; padding: 10px 20px;
          background: rgba(5,7,10,0.88); backdrop-filter: blur(8px);
          border-bottom: 1px solid rgba(51,214,255,0.18);
        }
        .tab-btn {
          display: flex; align-items: center; justify-content: center; gap: 8px;
          min-height: 44px; padding: 0 18px;
          background: transparent; border: 1px solid transparent; border-radius: 3px;
          color: #9AA6BA; font: 500 14px 'Sora', sans-serif; cursor: pointer;
        }
        .tab-btn:hover { color: #E7ECF2; background: rgba(51,214,255,0.06); }
        .tab-btn[aria-current="page"] { color: ${ACCENT}; background: rgba(51,214,255,0.1); border-color: rgba(51,214,255,0.35); }
        .tab-icon { font-size: 16px; line-height: 1; }
        .tab-btn:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible {
          outline: 2px solid ${ACCENT}; outline-offset: 2px;
        }
        @media (max-width: 720px) {
          .app-shell { padding: 20px 16px calc(96px + env(safe-area-inset-bottom)); }
          .tabbar {
            position: fixed; top: auto; bottom: 0; left: 0; right: 0; margin: 0;
            padding: 6px 6px calc(6px + env(safe-area-inset-bottom));
            border-bottom: none; border-top: 1px solid rgba(51,214,255,0.22);
            justify-content: space-around;
          }
          .tab-btn { flex: 1; flex-direction: column; gap: 3px; min-height: 54px; padding: 0 4px; font-size: 12px; }
          .tab-icon { font-size: 18px; }
        }

        .text-btn {
          display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 16px;
          font: 600 14px 'Sora', sans-serif; color: ${ACCENT};
          background: rgba(51,214,255,0.1); border: 1px solid rgba(51,214,255,0.4); border-radius: 3px; cursor: pointer;
        }
        .text-btn:hover { background: rgba(51,214,255,0.16); }
        .text-btn.danger { color: ${RED}; background: rgba(255,84,112,0.08); border-color: rgba(255,84,112,0.4); }

        /* Respect the OS "reduce motion" setting: no ambient or page animations. */
        @media (prefers-reduced-motion: reduce) {
          *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
        }

        @keyframes pageFade { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
        .page-fade { animation: pageFade 0.4s ease both; }
        .salary-slider { -webkit-appearance: none; appearance: none; width: 100%; height: 6px; border-radius: 999px; outline: none; cursor: pointer; }
        .salary-slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 22px; height: 22px; border-radius: 50%; background: #E7ECF2; border: 3px solid ${ACCENT}; box-shadow: 0 2px 8px rgba(0,0,0,0.4); cursor: pointer; margin-top: -8px; }
        .salary-slider::-moz-range-thumb { width: 22px; height: 22px; border-radius: 50%; background: #E7ECF2; border: 3px solid ${ACCENT}; box-shadow: 0 2px 8px rgba(0,0,0,0.4); cursor: pointer; }
        .salary-slider::-webkit-slider-runnable-track { height: 6px; border-radius: 999px; }
        .salary-slider::-moz-range-track { height: 6px; border-radius: 999px; }

        .cat-slider { -webkit-appearance: none; appearance: none; flex: 1; height: 8px; border-radius: 999px; outline: none; cursor: pointer; touch-action: none; }
        .cat-slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 24px; height: 24px; border-radius: 50%; background: #E7ECF2; border: 3px solid var(--thumb-color, ${ACCENT}); box-shadow: 0 1px 6px rgba(0,0,0,0.5); cursor: pointer; margin-top: -8px; }
        .cat-slider::-moz-range-thumb { width: 24px; height: 24px; border-radius: 50%; background: #E7ECF2; border: 3px solid var(--thumb-color, ${ACCENT}); box-shadow: 0 1px 6px rgba(0,0,0,0.5); cursor: pointer; }
        .cat-slider::-webkit-slider-runnable-track { height: 8px; border-radius: 999px; }
        .cat-slider::-moz-range-track { height: 8px; border-radius: 999px; }
        .reset-btn { min-width: 44px; min-height: 44px; display: flex; align-items: center; justify-content: center; font-size: 15px !important; }
        .alloc-input {
          flex: 1;
          min-width: 0;
          background: rgba(0,0,0,0.35);
          border: 1px solid rgba(51,214,255,0.3);
          border-radius: 2px;
          color: #E7ECF2;
          font-size: 13px;
          font-weight: 600;
          padding: 7px 9px;
          outline: none;
        }
        .alloc-input:focus { border-color: ${ACCENT}; box-shadow: 0 0 0 2px rgba(51,214,255,0.15); }
        .alloc-input::-webkit-outer-spin-button, .alloc-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        .alloc-input[type=number] { -moz-appearance: textfield; }
        .quick-input {
          width: 100%; min-height: 40px; padding: 6px; text-align: right;
          font-size: 14px; color: #E7ECF2;
          background: rgba(51,214,255,0.05); border: 1px solid rgba(51,214,255,0.18); border-radius: 2px;
          -moz-appearance: textfield;
        }
        .quick-input::-webkit-outer-spin-button, .quick-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        .quick-input:focus { border-color: ${ACCENT}; outline: none; box-shadow: 0 0 0 2px rgba(51,214,255,0.15); }

        /* ---- Budget editor ---- */
        .panel { position: relative; background: rgba(51,214,255,0.035); border: 1px solid rgba(51,214,255,0.16); border-radius: 3px; padding: 18px 16px; }
        .panel-title { font-size: 15px; font-weight: 600; color: #E7ECF2; margin-bottom: 12px; }
        .sub-card { background: rgba(0,0,0,0.25); border: 1px solid rgba(51,214,255,0.12); border-radius: 3px; padding: 14px; min-width: 0; }
        .name-input {
          width: 100%; margin-bottom: 10px; padding: 4px 0; background: transparent; border: none;
          border-bottom: 1px dashed rgba(51,214,255,0.3); color: #E7ECF2; font: 600 17px 'Space Grotesk', sans-serif;
        }
        .name-input:focus { outline: none; border-bottom-color: ${ACCENT}; }
        .field-label { display: block; font-size: 12.5px; color: #9AA6BA; margin: 8px 0 5px; }
        .field-input, .row-input {
          background: rgba(0,0,0,0.35); border: 1px solid rgba(51,214,255,0.25); border-radius: 2px; color: #E7ECF2;
          font-size: 14px; padding: 8px 10px; min-height: 42px; width: 100%; min-width: 0;
        }
        .row-input { width: 92px; flex-shrink: 0; text-align: right; padding: 6px 8px; min-height: 40px; }
        select.field-input { cursor: pointer; }
        .field-input:focus, .row-input:focus { outline: none; border-color: ${ACCENT}; box-shadow: 0 0 0 2px rgba(51,214,255,0.15); }
        .field-input[type=number]::-webkit-inner-spin-button, .row-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        .field-input[type=number], .row-input { -moz-appearance: textfield; }
        .link-btn { background: none; border: none; padding: 10px 0 0; color: ${ACCENT}; font-size: 13px; cursor: pointer; text-align: left; min-height: 36px; }
        .link-btn:hover { text-decoration: underline; }
        .icon-btn {
          width: 40px; height: 40px; flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center;
          background: rgba(51,214,255,0.06); border: 1px solid rgba(51,214,255,0.25); border-radius: 3px; color: ${ACCENT}; font-size: 16px; cursor: pointer;
        }
        .seg { display: inline-flex; border: 1px solid rgba(51,214,255,0.3); border-radius: 3px; overflow: hidden; }
        .seg button { min-height: 40px; padding: 0 14px; background: transparent; border: none; color: #9AA6BA; font: 500 13px 'Sora', sans-serif; cursor: pointer; }
        .seg button[aria-pressed="true"] { background: rgba(51,214,255,0.16); color: ${ACCENT}; }
        .check-row { display: inline-flex; align-items: center; gap: 8px; min-height: 40px; font-size: 13.5px; color: #E7ECF2; cursor: pointer; }
        .check-row input { width: 18px; height: 18px; accent-color: ${ACCENT}; cursor: pointer; }
        .editor { margin: 10px 0 4px 18px; padding: 12px; background: rgba(0,0,0,0.3); border: 1px solid rgba(51,214,255,0.2); border-radius: 3px; }
        .editor-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(190px, 100%), 1fr)); gap: 0 12px; }
        .text-btn:disabled { opacity: 0.35; cursor: default; }
        .stage-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: stretch; margin: 4px 0 10px; }
        .stage-chip {
          display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-height: 48px; padding: 6px 12px;
          background: rgba(0,0,0,0.25); border: 1px solid rgba(51,214,255,0.2); border-radius: 3px; color: #B9C4D6; cursor: pointer; text-align: left; font: inherit;
        }
        .stage-chip[aria-selected="true"] { border-color: ${ACCENT}; background: rgba(51,214,255,0.12); color: #E7ECF2; }
        .stage-chip-name { display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 600; }
        .stage-chip-when { font-size: 12px; color: #8E9AAD; }
        .badge.now { color: ${GREEN}; border-color: rgba(61,255,176,0.45); font-weight: 600; }
        .stage-editor { padding: 10px 12px 12px; margin-bottom: 12px; background: rgba(0,0,0,0.25); border: 1px solid rgba(51,214,255,0.15); border-radius: 3px; }
        .pct-wrap { position: relative; }
        .pct-wrap .quick-input { padding-right: 22px; }
        .pct-wrap > span { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: #8E9AAD; font-size: 13px; pointer-events: none; }
        .cat-name {
          flex: 1; min-width: 0; font-size: 14px; line-height: 1.25; overflow-wrap: anywhere;
          display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
        }
        .share-banner { margin-top: 14px; padding: 10px 12px; font-size: 13.5px; line-height: 1.55; color: #B9C4D6; background: rgba(51,214,255,0.06); border-left: 3px solid ${ACCENT}; border-radius: 2px; }
        .share-banner strong { color: ${ACCENT}; }
        .text-btn.primary { background: ${ACCENT}; color: #04121A; border-color: ${ACCENT}; }
        .text-btn.primary:hover { background: #5FE0FF; }
        .app-shell { color-scheme: dark; }

        /* ---- Spending ---- */
        .qa-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(200px, 100%), 1fr)); gap: 0 12px; }
        .bar { position: relative; height: 8px; margin: 6px 0 4px; background: rgba(51,214,255,0.12); border-radius: 999px; overflow: hidden; }
        .bar-fill { height: 100%; border-radius: 999px; transition: width 0.4s ease; }
        .pace-mark { position: absolute; top: -2px; bottom: -2px; width: 2px; margin-left: -1px; background: #E7ECF2; opacity: 0.7; }
        .progress-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr)); gap: 4px 18px; }
        .progress-row {
          display: block; width: 100%; text-align: left; padding: 8px 6px; border-radius: 3px; cursor: pointer;
          background: transparent; border: 1px solid transparent; color: inherit; font: inherit;
        }
        .progress-row:hover, .progress-row.is-active { background: rgba(51,214,255,0.07); border-color: rgba(51,214,255,0.25); }
        .month-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 0 0 14px; }
        .filter-row { display: grid; grid-template-columns: 3fr 2fr; gap: 8px; }
        @media (max-width: 640px) { .filter-row { grid-template-columns: 1fr; } }
        .tx-row { border-bottom: 1px solid rgba(51,214,255,0.08); }
        .tx-row.is-open { background: rgba(51,214,255,0.05); }
        .tx-main {
          display: flex; align-items: center; gap: 12px; width: 100%; min-height: 52px; padding: 6px 4px;
          background: none; border: none; color: inherit; text-align: left; cursor: pointer; font: inherit;
        }
        .tx-date { width: 52px; flex-shrink: 0; font-size: 12.5px; color: #8E9AAD; }
        .tx-text { flex: 1; min-width: 0; display: flex; flex-direction: column; }
        .tx-desc { font-size: 14px; color: #E7ECF2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .tx-meta { font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .tx-amt { font-size: 14px; font-weight: 600; flex-shrink: 0; }
        .toast {
          position: fixed; left: 50%; transform: translateX(-50%); bottom: 24px; z-index: 60;
          display: flex; align-items: center; gap: 14px; max-width: calc(100vw - 32px);
          padding: 12px 16px; background: #0D141C; border: 1px solid rgba(51,214,255,0.4); border-radius: 4px;
          box-shadow: 0 8px 30px rgba(0,0,0,0.6); font-size: 14px; color: #E7ECF2;
        }
        @media (max-width: 720px) { .toast { bottom: calc(84px + env(safe-area-inset-bottom)); } }
        .overview-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(340px, 100%), 1fr)); gap: 16px; align-items: start; }
        .overview-grid > form { margin-bottom: 0 !important; }

        /* ---- Forecast ---- */
        .month-detail { margin-top: 12px; min-height: 64px; font-size: 13.5px; line-height: 1.5; padding: 10px 12px; background: rgba(0,0,0,0.25); border: 1px solid rgba(51,214,255,0.12); border-radius: 3px; }
        .nw-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(150px, 45%), 1fr)); gap: 10px; }
        .nw-cell { padding: 10px 12px; background: rgba(0,0,0,0.25); border: 1px solid rgba(51,214,255,0.12); border-radius: 3px; min-width: 0; }
        @media (max-width: 400px) { .tab-btn { font-size: 11px; padding: 0 1px; } }

        /* ---- Import dialog ---- */
        .modal-backdrop {
          position: fixed; inset: 0; z-index: 80; background: rgba(2,3,5,0.8); backdrop-filter: blur(3px);
          display: flex; align-items: flex-start; justify-content: center; padding: 24px 16px; overflow-y: auto;
        }
        .modal {
          position: relative; width: 100%; max-width: 820px; background: #0A0D13;
          border: 1px solid rgba(51,214,255,0.3); border-radius: 4px; padding: 18px;
        }
        @media (max-width: 720px) { .modal-backdrop { padding: 0; } .modal { min-height: 100%; border-radius: 0; border: none; } }
        .steps { display: flex; gap: 6px; list-style: none; padding: 0; margin: 4px 0 16px; counter-reset: step; flex-wrap: wrap; }
        .steps li { counter-increment: step; font-size: 12.5px; color: #8E9AAD; padding: 4px 10px; border: 1px solid rgba(51,214,255,0.15); border-radius: 999px; }
        .steps li::before { content: counter(step) ". "; }
        .steps li[aria-current="step"] { color: ${ACCENT}; border-color: rgba(51,214,255,0.5); background: rgba(51,214,255,0.08); }
        .preview { border: 1px solid rgba(51,214,255,0.15); border-radius: 3px; }
        .preview-row { display: grid; grid-template-columns: 96px 1fr auto; gap: 10px; padding: 8px 10px; font-size: 13px; border-bottom: 1px solid rgba(51,214,255,0.08); }
        .preview-desc { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .review-list { max-height: 55vh; overflow-y: auto; border: 1px solid rgba(51,214,255,0.15); border-radius: 3px; }
        @media (max-width: 720px) { .review-list { max-height: none; } }
        .review-row { display: grid; grid-template-columns: 28px 1fr; gap: 6px; align-items: start; padding: 10px; border-bottom: 1px solid rgba(51,214,255,0.08); }
        .review-row input[type=checkbox] { width: 18px; height: 18px; margin-top: 2px; accent-color: ${ACCENT}; }
        .review-row.is-off { opacity: 0.5; }
        .review-select { width: auto; min-height: 36px; padding: 4px 8px; font-size: 13px; margin-left: auto; max-width: 100%; }
        .badge { font-size: 11.5px; padding: 2px 8px; border-radius: 999px; border: 1px solid rgba(51,214,255,0.3); color: #9AA6BA; }
        .badge.warn { color: #FFC145; border-color: rgba(255,193,69,0.5); }
        .badge.in { color: ${GREEN}; border-color: rgba(61,255,176,0.4); }

        /* ---- Spending ledger ---- */
        .spend-filters { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 0 0 14px; }
        .stat-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(170px, 45%), 1fr)); gap: 10px; margin-bottom: 18px; }
        .spend-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); gap: 18px; margin-bottom: 18px; align-items: start; }
        .spend-grid > *, .stat-row > *, .spark-grid > * { min-width: 0; }
        .swatch { display: inline-block; width: 9px; height: 9px; border-radius: 2px; margin-right: 6px; vertical-align: 0; flex-shrink: 0; }
        .chart-tip {
          position: absolute; z-index: 5; width: 220px; pointer-events: none; padding: 8px 10px; font-size: 12.5px; color: #E7ECF2;
          background: #0D141C; border: 1px solid rgba(51,214,255,0.35); border-radius: 4px; box-shadow: 0 6px 24px rgba(0,0,0,0.6);
        }
        .tip-row { display: flex; justify-content: space-between; gap: 10px; line-height: 1.6; }
        .cat-row, .spark-cell {
          display: block; width: 100%; text-align: left; background: transparent; border: 1px solid transparent; border-radius: 3px;
          padding: 7px 8px; margin: 0 0 2px; color: inherit; font: inherit; cursor: pointer;
        }
        .cat-row:hover, .cat-row.is-active, .spark-cell:hover { background: rgba(51,214,255,0.07); border-color: rgba(51,214,255,0.25); }
        .hbar { height: 8px; margin: 6px 0 4px; }
        .hbar > div { height: 100%; border-radius: 0 4px 4px 0; min-width: 2px; }
        .div-row { display: grid; grid-template-columns: minmax(90px, 1.3fr) 2fr auto; gap: 10px; align-items: center; padding: 5px 0; font-size: 13px; }
        .div-label { color: #E7ECF2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .div-track { position: relative; height: 12px; }
        .div-mid { position: absolute; left: 50%; top: -3px; bottom: -3px; width: 1px; background: rgba(154,166,186,0.6); }
        .div-bar { position: absolute; top: 0; height: 100%; min-width: 2px; }
        .div-val { color: #B9C4D6; text-align: right; white-space: nowrap; font-size: 12.5px; }
        .spark-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(150px, 45%), 1fr)); gap: 8px; }
        .spark-cell { border-color: rgba(51,214,255,0.1); padding: 10px; margin: 0; }
        .data-table { width: 100%; border-collapse: collapse; font-size: 13px; color: #B9C4D6; }
        .data-table th { font-weight: 600; font-size: 12.5px; color: #8E9AAD; padding: 6px 6px; border-bottom: 1px solid rgba(51,214,255,0.2); }
        .data-table td { padding: 7px 6px; border-bottom: 1px solid rgba(51,214,255,0.08); vertical-align: top; }
        .data-table tbody tr:hover { background: rgba(51,214,255,0.05); }
        .review-item { padding: 10px 0; border-bottom: 1px solid rgba(51,214,255,0.08); }
        .map-row { display: grid; grid-template-columns: 1fr minmax(150px, 1fr); gap: 10px; align-items: center; padding: 3px 0 3px 15px; }
        .ledger-filters { display: grid; grid-template-columns: 2fr 1.4fr 1fr; gap: 8px; }
        @media (max-width: 640px) { .ledger-filters { grid-template-columns: 1fr 1fr; } .ledger-filters > input { grid-column: 1 / -1; } }
        .detail-grid { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; font-size: 13px; color: #B9C4D6; }
        .detail-grid > span:nth-child(odd) { color: #8E9AAD; }
        .detail-grid > span { min-width: 0; overflow-wrap: anywhere; }
        details > summary { list-style-position: inside; }
        @media (max-width: 420px) {
          .row-input { width: 78px; }
          .editor { margin-left: 0; }
        }
      `}</style>

      {/* Fine instrument grid */}
      <div
        style={{
          position: "absolute",
          inset: 0,
          backgroundImage:
            "linear-gradient(rgba(51,214,255,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(51,214,255,0.05) 1px, transparent 1px)",
          backgroundSize: "36px 36px",
          pointerEvents: "none",
        }}
      />
      {/* Slow vertical scan sweep — the signature ambient touch */}
      <div
        style={{
          position: "absolute",
          left: 0,
          right: 0,
          height: 140,
          background: "linear-gradient(to bottom, transparent, rgba(51,214,255,0.05), transparent)",
          animation: "scanSweep 9s linear infinite",
          pointerEvents: "none",
        }}
      />
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 1, background: "linear-gradient(90deg, transparent, rgba(51,214,255,0.5), transparent)", pointerEvents: "none" }} />

      <nav className="tabbar" aria-label="Sections">
        {TABS.map((t) => (
          <button
            key={t.id}
            type="button"
            className="tab-btn"
            aria-current={tab === t.id ? "page" : undefined}
            onClick={() => goTo(t.id)}
          >
            <span className="tab-icon" aria-hidden="true">{t.icon}</span>
            {t.label}
          </button>
        ))}
      </nav>

      {tab === "budget" && (
      <div className="page-fade" style={{ maxWidth: 1120, margin: "0 auto", position: "relative" }}>
        <PageHeader
          eyebrow="Monthly plan"
          saveStatus={saveStatus}
          title={
            <>
              <span style={{ color: budget.leftover >= 0 ? ACCENT : RED, textShadow: `0 0 24px rgba(51,214,255,0.35)` }}>
                {fmt(animatedLeftover)}
              </span>{" "}
              {budget.leftover >= 0 ? "left over each month" : "short each month"}
            </>
          }
          subtitle={`From your ${fmt(budget.monthlyNet)}/month take-home pay, minus ${fmt(budget.expenseTotal)} — your share of planned spending.`}
        />

        <IncomePanel household={household} setHousehold={setHousehold} budget={budget} />

        <div className="fade-up" style={{ marginBottom: 20 }}>
          {!snapshot ? (
            <button
              type="button"
              onClick={takeSnapshot}
              className="text-btn"
              title="Freeze today's numbers, then change incomes or categories to compare"
            >
              Compare a what-if
            </button>
          ) : (
            <div className="panel" style={{ maxWidth: 640 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10, gap: 8 }}>
                <span style={{ fontSize: 14, color: "#B9C4D6" }}>
                  What-if comparison <span style={{ color: "#8391A6", fontSize: 13 }}>— change any number to see the difference</span>
                </span>
                <button
                  type="button"
                  onClick={clearSnapshot}
                  style={{ fontSize: 13, color: "#9AA6BA", background: "none", border: "none", cursor: "pointer", minHeight: 44, padding: "0 8px", flexShrink: 0 }}
                >
                  ✕ Clear
                </button>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto auto auto", gap: "6px 14px", fontSize: 13.5 }}>
                <span style={{ color: "#8391A6" }} />
                <span style={{ color: "#8391A6", textAlign: "right" }}>Then</span>
                <span style={{ color: "#8391A6", textAlign: "right" }}>Now</span>
                <span style={{ color: "#8391A6", textAlign: "right" }}>Δ</span>
                <CompareRow label="Your salary" then={snapshot.grossTotal} now={budget.grossTotal} />
                <CompareRow label="Take-home / month" then={snapshot.monthlyNet} now={budget.monthlyNet} />
                <CompareRow label="Your spending / month" then={snapshot.expenseTotal} now={budget.expenseTotal} invert />
                <CompareRow label="Left over / month" then={snapshot.leftover} now={budget.leftover} />
              </div>
            </div>
          )}
        </div>

        <div style={{ display: "flex", gap: 12, marginBottom: 24, flexWrap: "wrap", alignItems: "center" }} className="fade-up">
          <label className="check-row">
            <input
              type="checkbox"
              checked={showBenchmark}
              onChange={(e) => setSettings((s) => ({ ...s, showBenchmark: e.target.checked }))}
            />
            Compare with Toronto averages
          </label>
          {showBenchmark ? (
            <>
              <LegendChip color={GREEN} label="▼ Below average" />
              <LegendChip color={RED} label="▲ Above average" />
              <LegendChip color={NEUTRAL} label="About average / no comparison" />
            </>
          ) : (
            GROUPS.map((g) => <LegendChip key={g} color={GROUP_COLORS[g]} label={g} />)
          )}
        </div>

        <div style={{ display: "flex", gap: 32, flexWrap: "wrap", alignItems: "flex-start" }}>
          <div className="fade-up" style={{ position: "relative", flex: "1 1 460px", minWidth: 0, background: "rgba(51,214,255,0.02)", border: "1px solid rgba(51,214,255,0.16)", borderRadius: 3, padding: 16 }}>
            <CornerBrackets />
            <svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} style={{ width: "100%", height: "auto", display: "block" }}>
              <defs>
                {nodes.map((n) => (
                  <radialGradient key={n.gradId} id={n.gradId} cx="35%" cy="30%" r="80%">
                    <stop offset="0%" stopColor={d3.color(n.color).brighter(0.7)} />
                    <stop offset="100%" stopColor={n.color} />
                  </radialGradient>
                ))}
              </defs>

              {nodes.map((n) => {
                if (!n.rect) return null;
                const w = Math.max(0, n.rect.x1 - n.rect.x0);
                const h = Math.max(0, n.rect.y1 - n.rect.y0);
                const active = hovered === n.id;
                return (
                  <rect
                    key={n.key}
                    className="cell-rect"
                    x={n.rect.x0}
                    y={n.rect.y0}
                    width={w}
                    height={h}
                    rx={1.5}
                    fill={`url(#${n.gradId})`}
                    opacity={active ? 1 : 0.9}
                    stroke="#05070A"
                    strokeWidth={2}
                    style={{ cursor: "pointer", filter: active ? "brightness(1.12) saturate(1.1)" : "none" }}
                    onMouseEnter={() => setHovered(n.id)}
                    onMouseLeave={() => setHovered(null)}
                    onClick={() => toggleHighlight(n.id)}
                  >
                    <title>{`${n.name}: ${fmt(n.value)}/month`}</title>
                  </rect>
                );
              })}

              {nodes.map((n) => {
                if (!n.rect) return null;
                const w = n.rect.x1 - n.rect.x0;
                const h = n.rect.y1 - n.rect.y0;
                const cx = n.rect.x0 + w / 2;
                const cy = n.rect.y0 + h / 2;
                // Fit labels to the tile: try the full name, then its first word, at a
                // normal then a small size; drop the name (or everything) if nothing fits.
                // Anything hidden is still readable via the detail line below the chart.
                const fits = (text, fs, charW) => text.length * fs * charW <= w - 10;
                const value = fmt(n.value);
                const shortName = n.name.split(/[\s(/&]/)[0];
                let fontSize = Math.min(w, h) > 90 ? 15 : 13;
                let label = [n.name, shortName].find((t) => t && fits(t, fontSize, 0.6));
                if (!label && shortName && fits(shortName, 11, 0.6)) {
                  fontSize = 11;
                  label = shortName;
                }
                if (h < fontSize * 2 + 12) label = null; // no room for two lines
                const showValue = fits(value, fontSize, 0.62) && h > fontSize + 6;
                if (!showValue) return null;
                if (!label) {
                  return (
                    <text key={`label-${n.key}`} x={cx} y={cy + fontSize * 0.35} textAnchor="middle" fontSize={fontSize} fontWeight={700} className="mono" fill="#05070A" style={{ pointerEvents: "none" }}>
                      {value}
                    </text>
                  );
                }
                return (
                  <g key={`label-${n.key}`} style={{ pointerEvents: "none" }}>
                    <text x={cx} y={cy - 3} textAnchor="middle" fontSize={fontSize} fontWeight={700} fill="#05070A">
                      {label}
                    </text>
                    <text x={cx} y={cy + fontSize + 1} textAnchor="middle" fontSize={fontSize} className="mono" fill="#05070A">
                      {value}
                    </text>
                  </g>
                );
              })}
            </svg>
            <CategoryDetail
              category={budget.categories.find((c) => c.id === hovered)}
              monthlyNet={budget.monthlyNet}
            />
          </div>

          <CategoryLedger
            budget={budget}
            setCategories={setCategories}
            hovered={hovered}
            setHovered={setHovered}
            goTo={goTo}
          />
        </div>

      </div>
      )}

      {tab === "home" && (
        <OverviewPage
          transactions={budgetTx}
          hasLedger={ledger.rows.length > 0}
          categories={categories}
          share={budget.share}
          budget={budget}
          goTo={goTo}
          saveStatus={saveStatus}
        />
      )}

      {tab === "spending" && (
        <SpendingPage
          ledger={ledger}
          setLedger={setLedger}
          categoryMap={categoryMap}
          setMapping={setMapping}
          budgetTx={budgetTx}
          categories={categories}
          share={budget.share}
          saveStatus={saveStatus}
        />
      )}

      {tab === "forecast" && (
        <ForecastPage
          forecast={forecast}
          setForecast={setForecast}
          household={household}
          categories={categories}
          transactions={budgetTx}
          holdings={holdings}
          saveStatus={saveStatus}
          goTo={goTo}
        />
      )}

      {tab === "savings" && (
        <LeftoverOptionsPage
          leftoverAmount={budget.leftover}
          monthlyExpenses={budget.expenseTotal}
          grossSalary={household.people[0].gross}
          householdGross={budget.grossTotal}
          holdings={holdings}
          setHoldings={setHoldings}
          saveStatus={saveStatus}
        />
      )}

      {tab === "settings" && (
        <SettingsPage
          saveStatus={saveStatus}
          holdings={holdings}
          exportBackup={exportBackup}
          importBackup={importBackup}
          resetAll={() => setStore(defaultState())}
          resetCategories={() => setCategories(buildTemplateCategories(household.people))}
          leftover={budget.leftover}
          legacyCount={legacyTransactions.length}
          exportLegacy={exportLegacy}
          clearLegacy={() => setStore((p) => ({ ...p, legacyTransactions: [] }))}
          ledgerCount={ledger.rows.length}
          clearLedger={() => setStore((p) => ({ ...p, ledger: Ledger.emptyLedger() }))}
        />
      )}
    </div>
  );
}

// ============================================================
// Holdings model
// Rates: deposit rates reflect 2026 ongoing Canadian HISA levels; market rates
// are long-run historical averages, not forecasts. Bear/base/bull multipliers
// stress-test those assumptions rather than predicting anything.
// ============================================================

const LEFTOVER_OPTIONS = [
  {
    name: "High-Interest Savings (HISA)",
    tag: "LIQUIDITY",
    color: "#3DFFB0",
    rate: 0.03,
    assetClass: "Cash",
    room: null,
    isEmergency: true,
    rateNote: "ongoing 2026 HISA rates run ~2.75–3.5%",
    body:
      "Fully liquid, no lock-in. The natural home for a 3–6 month emergency fund before money goes anywhere else.",
  },
  {
    name: "TFSA",
    tag: "TAX-FREE GROWTH",
    color: "#33D6FF",
    rate: 0.06,
    assetClass: "Equity",
    room: { type: "fixed", lifetime: 109000, annual: 7000 },
    rateNote: "assumes a balanced portfolio held inside the account",
    body:
      "2026 room is $7,000/yr; $109,000 lifetime if eligible since 2009. Growth and withdrawals entirely tax-free.",
  },
  {
    name: "RRSP",
    tag: "TAX-DEFERRED",
    color: "#7C6FF2",
    rate: 0.06,
    assetClass: "Equity",
    room: { type: "income", pct: 0.18, cap: 33810 },
    rateNote: "assumes a balanced portfolio; withdrawals taxed later",
    body:
      "Deducted from this year's taxable income; taxed on withdrawal, ideally at a lower retirement-era rate.",
  },
  {
    name: "FHSA",
    tag: "FIRST HOME",
    color: "#FFC145",
    rate: 0.05,
    assetClass: "Balanced",
    room: { type: "fixed", lifetime: 40000, annual: 8000 },
    rateNote: "shorter horizon usually means a more conservative mix",
    body:
      "$8,000/yr, $40,000 lifetime. Deductible like an RRSP, tax-free out like a TFSA for a qualifying first home.",
  },
  {
    name: "Low-Cost Index/Tracker ETF",
    tag: "LONG-TERM GROWTH",
    color: "#FF5470",
    rate: 0.07,
    assetClass: "Equity",
    room: null,
    rateNote: "long-run global equity average, before inflation",
    body:
      "Broad-market ETFs for long-term growth. Outside a registered account, gains are taxable.",
  },
  {
    name: "Bonds / GICs",
    tag: "DEFENSIVE",
    color: "#5BC8E8",
    rate: 0.035,
    assetClass: "Fixed Income",
    room: null,
    rateNote: "2026 GIC rates run ~2.25–3.85% for 1–5yr terms",
    body:
      "Lower expected return, lower volatility. Ballast that cushions equity drawdowns and funds nearer-term goals.",
  },
  {
    name: "Crypto Assets",
    tag: "HIGH VOLATILITY",
    color: "#FF8A3D",
    rate: 0.1,
    assetClass: "Alternative",
    room: null,
    rateNote: "placeholder only — outcomes range from total loss to many multiples",
    body:
      "No CDIC/CIPF protection. Can't be held directly in a TFSA/RRSP, though Canadian-listed crypto ETFs can.",
  },
  {
    name: "Extra Debt Repayment",
    tag: "GUARANTEED RETURN",
    color: "#7E8CA3",
    rate: 0.1,
    assetClass: "Debt Payoff",
    room: null,
    rateNote: "equals the interest rate avoided; credit cards run ~20%",
    body:
      "A guaranteed return equal to the interest avoided — hard to beat before high-interest debt is cleared.",
  },
];

const HORIZONS = [1, 3, 5, 10];
const ALLOC_MAX = 100000;
const PROJECTION_YEARS = 10;

const SCENARIOS = {
  bear: { label: "BEAR", mult: 0.5, color: "#FF5470" },
  base: { label: "BASE", mult: 1, color: "#33D6FF" },
  bull: { label: "BULL", mult: 1.45, color: "#3DFFB0" },
};

const ASSET_CLASS_COLORS = {
  Equity: "#FF5470",
  "Fixed Income": "#5BC8E8",
  Cash: "#3DFFB0",
  Balanced: "#FFC145",
  Alternative: "#FF8A3D",
  "Debt Payoff": "#7E8CA3",
};
// Rough growth-vs-defensive split used for the risk gauge.
const DEFENSIVE_CLASSES = new Set(["Cash", "Fixed Income", "Debt Payoff"]);

const INFLATION = 0.021;

// Future value of a lump sum plus monthly contributions, compounded monthly.
function projectValue(balance, monthlyContrib, annualRate, years) {
  const r = annualRate / 12;
  const n = years * 12;
  if (Math.abs(r) < 1e-9) return balance + monthlyContrib * n;
  return balance * Math.pow(1 + r, n) + monthlyContrib * ((Math.pow(1 + r, n) - 1) / r);
}

function LeftoverOptionsPage({
  leftoverAmount,
  monthlyExpenses,
  grossSalary, // partner 1's salary — used for RRSP room until accounts get owners
  householdGross,
  holdings,
  setHoldings,
  saveStatus,
}) {
  // Saved data comes from the app-wide store (autosaved); view-only toggles stay local.
  const { balances, roomUsed, goal, snapshots, goals, stages, stagesStart } = holdings;
  const setBalances = keySetter(setHoldings, "balances");
  const setStages = keySetter(setHoldings, "stages");
  const setStagesStart = keySetter(setHoldings, "stagesStart");
  const activeStage = stageIndexAt(holdings, currentMonthKey());
  const [selStage, setSelStage] = useState(activeStage);
  const sel = Math.min(selStage, stages.length - 1);
  const stage = stages[sel];
  const allocPct = stage.allocPct;
  const setAllocPct = (fn) => setStages((ss) => ss.map((s, i) => (i === sel ? { ...s, allocPct: typeof fn === "function" ? fn(s.allocPct) : fn } : s)));
  const updateStage = (patch) => setStages((ss) => ss.map((s, i) => (i === sel ? { ...s, ...patch } : s)));
  const addStage = () => {
    const last = stages[stages.length - 1];
    setStages((ss) => [
      ...ss.map((s, i) => (i === ss.length - 1 && !s.months ? { ...s, months: 12 } : s)),
      { id: newId("st"), name: `Stage ${ss.length + 1}`, months: null, allocPct: { ...last.allocPct } },
    ]);
    setSelStage(stages.length);
  };
  const deleteStage = () => {
    if (stages.length < 2 || !window.confirm(`Delete "${stage.name}"?`)) return;
    setStages((ss) => ss.filter((_, i) => i !== sel));
    setSelStage(Math.max(0, sel - 1));
  };
  const setRoomUsed = keySetter(setHoldings, "roomUsed");
  const setGoal = keySetter(setHoldings, "goal");
  const setSnapshots = keySetter(setHoldings, "snapshots");
  const setGoals = keySetter(setHoldings, "goals");

  const [scenario, setScenario] = useState("base");
  const [realDollars, setRealDollars] = useState(false);
  const [expandedAccount, setExpandedAccount] = useState(null);
  const [showSnapshots, setShowSnapshots] = useState(false);
  const [showSettings, setShowSettings] = useState(false);

  const recordSnapshot = () => {
    const newSnapshot = {
      date: new Date().toISOString(),
      balances: { ...balances },
      allocPct: { ...allocPctAt(holdings) },
      leftover: leftoverAmount,
      totalBalance: LEFTOVER_OPTIONS.reduce((s, o) => s + ((balances[o.name] ?? 0) * hhMult), 0),
    };
    setSnapshots([...snapshots, newSnapshot]);
  };

  const addGoal = () => {
    setGoals([...goals, { name: `Goal ${goals.length + 1}`, target: 100000, accounts: ["RRSP"], deadline: null }]);
  };

  const updateGoal = (idx, field, value) => {
    const newGoals = [...goals];
    newGoals[idx] = { ...newGoals[idx], [field]: value };
    setGoals(newGoals);
  };

  const deleteGoal = (idx) => {
    setGoals(goals.filter((_, i) => i !== idx));
  };

  const hhMult = 1; // balances and contributions are yours (the old ×2 partner toggle is gone)
  const num = (raw, max) => Math.min(max, Math.max(0, Number(raw) || 0));
  const setBalance = (k, v) => setBalances((p) => ({ ...p, [k]: num(v, ALLOC_MAX) }));
  const setPct = (k, v) => setAllocPct((p) => ({ ...p, [k]: Math.round(num(v, 100) * 10) / 10 }));
  const setRoom = (k, v) => setRoomUsed((p) => ({ ...p, [k]: num(v, 1000000) }));

  const bal = (o) => (balances[o.name] ?? 0) * hhMult;
  // The table edits the selected stage; "monthly in" figures use the stage running now.
  const pctOf = (o) => allocPct[o.name] ?? 0;
  const stageMo = (o) => (Math.max(0, leftoverAmount) * pctOf(o)) / 100;
  const mo = (o) => allocAmount(holdings, o.name, leftoverAmount);

  const totalBalance = LEFTOVER_OPTIONS.reduce((s, o) => s + bal(o), 0);
  const totalMonthly = LEFTOVER_OPTIONS.reduce((s, o) => s + mo(o), 0);
  const stageMonthly = LEFTOVER_OPTIONS.reduce((s, o) => s + stageMo(o), 0);
  const totalPct = LEFTOVER_OPTIONS.reduce((s, o) => s + pctOf(o), 0);
  // Put whatever isn't assigned yet into one account.
  const assignRest = (name) => setPct(name, Math.max(0, 100 - (totalPct - (allocPct[name] ?? 0))));
  const contribRemaining = leftoverAmount - totalMonthly;
  const scen = SCENARIOS[scenario];
  const effRate = (o) => o.rate * scen.mult;

  // Month-by-month projection (60 years) following your savings stages.
  const proj = projectAccounts(holdings, leftoverAmount, effRate, 720);
  const projOf = (o) => proj.find((a) => a.opt.name === o.name).points;
  const valueAtMonth = (m) => proj.reduce((s, a) => s + a.points[m].value, 0);
  const paidAtMonth = (m) => proj.reduce((s, a) => s + a.points[m].paid, 0);

  const blendedRate =
    totalBalance > 0
      ? LEFTOVER_OPTIONS.reduce((s, o) => s + bal(o) * effRate(o), 0) / totalBalance
      : 0;

  const adjust = (v, years) => (realDollars ? v / Math.pow(1 + INFLATION, years) : v);

  const totalAt = (years) => adjust(valueAtMonth(years * 12), years);

  // ---- Asset class rollup (cuts across accounts) ----
  const byClass = {};
  LEFTOVER_OPTIONS.forEach((o) => {
    byClass[o.assetClass] = (byClass[o.assetClass] ?? 0) + bal(o);
  });
  const classRows = Object.entries(byClass)
    .filter(([, v]) => v > 0)
    .sort((a, b) => b[1] - a[1]);
  const defensiveTotal = LEFTOVER_OPTIONS.reduce(
    (s, o) => s + (DEFENSIVE_CLASSES.has(o.assetClass) ? bal(o) : 0),
    0
  );
  const growthPct = totalBalance > 0 ? ((totalBalance - defensiveTotal) / totalBalance) * 100 : 0;

  // ---- Emergency fund runway ----
  const emergencyBalance = LEFTOVER_OPTIONS.reduce((s, o) => s + (o.isEmergency ? bal(o) : 0), 0);
  const runwayMonths = monthlyExpenses > 0 ? emergencyBalance / monthlyExpenses : 0;

  // ---- Goal tracking ----
  const goalTarget = goal * hhMult;
  const goalPct = goalTarget > 0 ? Math.min(100, (totalBalance / goalTarget) * 100) : 0;
  const yearsToGoal = (() => {
    if (totalBalance >= goalTarget) return 0;
    for (let m = 6; m <= 720; m += 6) {
      if (valueAtMonth(m) >= goalTarget) return m / 12;
    }
    return null;
  })();

  // ---- Job-loss stress test: emergency accounts after 3 more years of their stages ----
  const emergencyIn3y = proj.filter((a) => a.opt.isEmergency).reduce((s, a) => s + a.points[36].value, 0);
  const jobLossMonths = monthlyExpenses > 0 ? emergencyIn3y / monthlyExpenses : 0;

  // ---- Stacked projection series ----
  const stackSeries = proj
    .map((a) => ({
      name: a.opt.name,
      color: a.opt.color,
      points: Array.from({ length: PROJECTION_YEARS + 1 }, (_, y) => adjust(a.points[y * 12].value, y)),
    }))
    .filter((s) => s.points[PROJECTION_YEARS] > 0);

  const stackMax = Math.max(
    1,
    ...Array.from({ length: PROJECTION_YEARS + 1 }, (_, y) =>
      stackSeries.reduce((s, ser) => s + ser.points[y], 0)
    )
  );

  return (
    <div className="page-fade" style={{ maxWidth: 1120, margin: "0 auto", position: "relative" }}>
      <PageHeader
        eyebrow="Savings & investments"
        saveStatus={saveStatus}
        title={
          <>
            Portfolio worth{" "}
            <span style={{ color: ACCENT, textShadow: `0 0 24px rgba(51,214,255,0.45)` }}>{fmt(totalBalance)}</span>
          </>
        }
        subtitle={`Enter what's in each account and what you add monthly. Your budget leaves ${fmt(leftoverAmount)}/month to put somewhere.`}
      />

      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 18 }}>
        <button
          type="button"
          onClick={recordSnapshot}
          className="text-btn"
          title="Save today's balances so you can track progress over time"
        >
          Record today's balances
        </button>
        {snapshots.length > 0 && (
          <button type="button" onClick={() => setShowSnapshots(!showSnapshots)} className="text-btn" aria-expanded={showSnapshots}>
            {showSnapshots ? "Hide" : "Show"} history ({snapshots.length})
          </button>
        )}
        <button type="button" onClick={() => setShowSettings(!showSettings)} className="text-btn" aria-expanded={showSettings}>
          {showSettings ? "Hide" : "Edit"} goals
        </button>
      </div>

      {/* ---- Two-column layout: Input grid + Visualizations ---- */}
      <div style={{ display: "flex", gap: 18, marginBottom: 18, flexWrap: "wrap" }}>
        {/* Left column: Compact input grid */}
        <div style={{ flex: "1 1 100%", minWidth: 0, overflowX: "auto" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(400px, 100%), 1fr))", gap: 14 }}>
            {/* Input Grid Card */}
            <div style={cardStyle}>
              <CornerBrackets size={10} color={ACCENT} />
              <div style={{ fontSize: 15, fontWeight: 600, color: "#E7ECF2", marginBottom: 4 }}>Your accounts</div>
              <div style={{ fontSize: 13, color: "#9AA6BA", marginBottom: 12, lineHeight: 1.4 }}>
                Enter what's in each account, then choose what <strong style={{ color: "#E7ECF2" }}>% of your leftover</strong>{" "}
                ({fmt(Math.max(0, leftoverAmount))}/mo) goes into it — the monthly amount is worked out for you and follows your
                budget. Tap an account name for projections and contribution room.
              </div>
              {leftoverAmount <= 0 && (
                <div role="alert" style={{ fontSize: 13, color: RED, marginBottom: 10 }}>
                  Your budget has no leftover right now, so nothing goes into savings. Adjust it on the Budget tab.
                </div>
              )}

              {/* ---- Savings stages ---- */}
              <div className="stage-bar" role="tablist" aria-label="Savings stages">
                {stages.map((st, i) => {
                  const r = stageRange(holdings, i);
                  return (
                    <button
                      key={st.id}
                      type="button"
                      role="tab"
                      aria-selected={i === sel}
                      className="stage-chip"
                      onClick={() => setSelStage(i)}
                    >
                      <span className="stage-chip-name">
                        {st.name}
                        {i === activeStage && <span className="badge now">Now</span>}
                      </span>
                      <span className="stage-chip-when">
                        {shortMonth(r.start)}
                        {r.end ? ` – ${shortMonth(r.end)}` : " onward"}
                      </span>
                    </button>
                  );
                })}
                <button type="button" className="text-btn" onClick={addStage} title="Add a stage that starts when the last one ends">
                  + Add next stage
                </button>
              </div>

              <div className="stage-editor">
                <div className="editor-grid">
                  <div>
                    <label className="field-label" htmlFor="stage-name">Stage name</label>
                    <input id="stage-name" type="text" className="field-input" value={stage.name} placeholder={`Stage ${sel + 1}`} onChange={(e) => updateStage({ name: e.target.value })} />
                  </div>
                  {sel === 0 && (
                    <div>
                      <label className="field-label" htmlFor="stage-start">Starts</label>
                      <input id="stage-start" type="month" className="field-input" value={stagesStart} onChange={(e) => MONTH_KEY_RE.test(e.target.value) && setStagesStart(e.target.value)} />
                    </div>
                  )}
                  {sel < stages.length - 1 ? (
                    <div>
                      <label className="field-label" htmlFor="stage-months">Lasts (months)</label>
                      <input
                        id="stage-months"
                        type="number"
                        inputMode="numeric"
                        min={1}
                        max={600}
                        className="field-input mono"
                        value={stage.months || ""}
                        onChange={(e) => updateStage({ months: Math.min(600, Math.max(1, Math.round(Number(e.target.value) || 1))) })}
                      />
                    </div>
                  ) : (
                    <div style={{ alignSelf: "end", fontSize: 13, color: "#9AA6BA", paddingBottom: 10 }}>
                      {stages.length > 1 ? "Last stage — runs until you add another." : "Runs until you add another stage."}
                    </div>
                  )}
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center", marginTop: 10 }}>
                  <span style={{ fontSize: 13, color: "#B9C4D6", flex: "1 1 200px" }}>
                    {(() => {
                      const r = stageRange(holdings, sel);
                      return `${stage.name || `Stage ${sel + 1}`}: ${monthLabel(r.start)}${r.end ? ` to ${monthLabel(r.end)}` : " onward"}. Set its percentages below.`;
                    })()}
                  </span>
                  <button type="button" className="text-btn" onClick={() => setAllocPct({})}>Clear %</button>
                  {stages.length > 1 && (
                    <button type="button" className="text-btn danger" onClick={deleteStage}>Delete stage</button>
                  )}
                </div>
              </div>

              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, tableLayout: "fixed" }}>
                <colgroup>
                  <col />
                  <col style={{ width: "25%" }} />
                  <col style={{ width: "18%" }} />
                  <col style={{ width: "19%" }} />
                </colgroup>
                <thead>
                  <tr style={{ borderBottom: "1px solid rgba(51,214,255,0.2)" }}>
                    <th style={quickTh("left")}>Account</th>
                    <th style={quickTh("right")}>Balance</th>
                    <th style={quickTh("right")} title="Share of your monthly leftover">% of leftover</th>
                    <th style={quickTh("right")}>Per month</th>
                  </tr>
                </thead>
                <tbody>
                  {LEFTOVER_OPTIONS.map((opt) => {
                    const balance = balances[opt.name] ?? 0;
                    const share = pctOf(opt);
                    const monthly = stageMo(opt);
                    const open = expandedAccount === opt.name;
                    return (
                      <tr key={opt.name} style={{ borderBottom: "1px solid rgba(51,214,255,0.08)", background: open ? "rgba(51,214,255,0.08)" : "transparent" }}>
                        <td style={{ padding: "4px 4px 4px 0" }}>
                          <button
                            type="button"
                            onClick={() => setExpandedAccount(open ? null : opt.name)}
                            aria-expanded={open}
                            style={{
                              display: "flex",
                              alignItems: "center",
                              gap: 6,
                              width: "100%",
                              minHeight: 44,
                              padding: 0,
                              background: "none",
                              border: "none",
                              color: opt.color,
                              fontWeight: 500,
                              fontSize: 13.5,
                              textAlign: "left",
                              cursor: "pointer",
                            }}
                          >
                            <span aria-hidden="true" style={{ flexShrink: 0, color: "#9AA6BA" }}>{open ? "▾" : "▸"}</span>
                            <span>{opt.name}</span>
                          </button>
                        </td>
                        <td style={{ padding: "4px" }}>
                          <input
                            type="number" inputMode="decimal" min={0} max={ALLOC_MAX} step={100} value={balance}
                            onChange={(e) => setBalance(opt.name, e.target.value)}
                            className="mono quick-input"
                            aria-label={`${opt.name} balance`}
                          />
                        </td>
                        <td style={{ padding: "4px" }}>
                          <div className="pct-wrap">
                            <input
                              type="number" inputMode="decimal" min={0} max={100} step={1}
                              value={share || ""}
                              placeholder="0"
                              onChange={(e) => setPct(opt.name, e.target.value)}
                              className="mono quick-input"
                              aria-label={`${opt.name} percent of leftover`}
                            />
                            <span aria-hidden="true">%</span>
                          </div>
                        </td>
                        <td className="mono" style={{ padding: "4px 0 4px 4px", textAlign: "right", fontSize: 13.5, color: monthly > 0 ? "#E7ECF2" : "#8E9AAD" }}>
                          {fmt(monthly)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
                <tfoot>
                  <tr style={{ borderTop: "1px solid rgba(51,214,255,0.25)" }}>
                    <td style={{ padding: "10px 4px 4px 0", fontSize: 13.5, fontWeight: 600 }}>Total</td>
                    <td />
                    <td className="mono" style={{ padding: "10px 4px 4px", textAlign: "right", fontWeight: 700, color: totalPct > 100.05 ? RED : totalPct >= 99.95 ? GREEN : "#E7ECF2" }}>
                      {Math.round(totalPct * 10) / 10}%
                    </td>
                    <td className="mono" style={{ padding: "10px 0 4px 4px", textAlign: "right", fontWeight: 700 }}>{fmt(stageMonthly)}</td>
                  </tr>
                </tfoot>
              </table>
              <div role="status" style={{ fontSize: 13, marginTop: 10, lineHeight: 1.5, color: totalPct > 100.05 ? RED : "#9AA6BA" }}>
                {totalPct > 100.05
                  ? `That's ${Math.round((totalPct - 100) * 10) / 10}% more than your leftover — lower some percentages so the total is 100% or less.`
                  : totalPct >= 99.95
                  ? "✓ All of your leftover has a home."
                  : `${Math.round((100 - totalPct) * 10) / 10}% (${fmt(Math.max(0, leftoverAmount) - stageMonthly)}/mo) isn't assigned yet — it stays in your chequing account.`}
              </div>
              {totalPct < 99.95 && leftoverAmount > 0 && (
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginTop: 8 }}>
                  <label htmlFor="assign-rest" style={{ fontSize: 13, color: "#9AA6BA" }}>Put the rest into</label>
                  <select
                    id="assign-rest"
                    className="field-input"
                    style={{ width: "auto", minHeight: 40 }}
                    value=""
                    onChange={(e) => e.target.value && assignRest(e.target.value)}
                  >
                    <option value="">Choose an account…</option>
                    {LEFTOVER_OPTIONS.map((o) => (
                      <option key={o.name} value={o.name}>{o.name}</option>
                    ))}
                  </select>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Expanded account details modal */}
        {expandedAccount && (
          <div style={{ flex: "1 1 100%", minWidth: 0 }}>
            {LEFTOVER_OPTIONS.map((opt) => {
              if (opt.name !== expandedAccount) return null;

              const balance = balances[opt.name] ?? 0;
              const share = pctOf(opt);

              let roomInfo = null;
              if (opt.room) {
                const used = roomUsed[opt.name] ?? 0;
                const limit =
                  opt.room.type === "income"
                    ? Math.min(grossSalary * opt.room.pct, opt.room.cap)
                    : opt.room.lifetime;
                const remaining = limit - used;
                roomInfo = { used, limit, remaining, annual: opt.room.annual };
              }

              return (
                <div key={opt.name} style={cardStyle}>
                  <CornerBrackets size={10} color={opt.color} />
                  <div className="mono" style={{ fontSize: 12, letterSpacing: "0.1em", color: opt.color, marginBottom: 8 }}>
                    {opt.tag} · {opt.assetClass}
                  </div>
                  <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6, color: "#E7ECF2" }}>{opt.name}</div>
                  <p style={{ margin: "0 0 14px", fontSize: 12, lineHeight: 1.5, color: "#9AA6BA" }}>{opt.body}</p>

                  <Field label="Current balance" color={opt.color}>
                    <input type="number" min={0} max={ALLOC_MAX} step={100} value={balance} onChange={(e) => setBalance(opt.name, e.target.value)} className="mono alloc-input" />
                  </Field>
                  <input
                    type="range" min={0} max={ALLOC_MAX} step={500} value={balance}
                    onChange={(e) => setBalance(opt.name, e.target.value)}
                    className="cat-slider"
                    style={{ ...sliderStyle(balance / ALLOC_MAX, opt.color), marginBottom: 12 }}
                  />

                  <label className="field-label" htmlFor={`pct-${opt.name}`}>Share of your leftover</label>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div className="pct-wrap" style={{ width: 110 }}>
                      <input
                        id={`pct-${opt.name}`}
                        type="number" inputMode="decimal" min={0} max={100} step={1}
                        value={share || ""}
                        placeholder="0"
                        onChange={(e) => setPct(opt.name, e.target.value)}
                        className="mono quick-input"
                      />
                      <span aria-hidden="true">%</span>
                    </div>
                    <span style={{ fontSize: 13.5, color: "#B9C4D6" }}>
                      = <span className="mono" style={{ color: "#E7ECF2", fontWeight: 600 }}>{fmt(stageMo(opt))}/mo</span>
                      {stages.length > 1 && <span style={{ color: "#8E9AAD" }}> in {stage.name}</span>}
                    </span>
                  </div>
                  <input
                    type="range" min={0} max={100} step={1} value={share}
                    onChange={(e) => setPct(opt.name, e.target.value)}
                    className="cat-slider"
                    style={{ ...sliderStyle(share / 100, opt.color), margin: "10px 0 14px", width: "100%" }}
                    aria-label={`${opt.name} percent of leftover slider`}
                  />

                  {/* Contribution room */}
                  {roomInfo && (
                    <div style={{ borderTop: "1px solid rgba(51,214,255,0.12)", paddingTop: 10, marginBottom: 10 }}>
                      <div className="mono" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, color: "#8E9AAD", marginBottom: 6 }}>
                        <span>ROOM USED</span>
                        <input
                          type="number" min={0} step={500} value={roomInfo.used}
                          onChange={(e) => setRoom(opt.name, e.target.value)}
                          className="mono alloc-input"
                          style={{ width: 82, flex: "0 0 auto", padding: "4px 6px", fontSize: 12 }}
                        />
                      </div>
                      <div style={{ height: 5, background: "rgba(51,214,255,0.1)", borderRadius: 1, overflow: "hidden", marginBottom: 5 }}>
                        <div style={{ height: "100%", width: `${Math.min(100, (roomInfo.used / roomInfo.limit) * 100)}%`, background: roomInfo.remaining < 0 ? RED : opt.color }} />
                      </div>
                      <div className="mono" style={{ fontSize: 12, color: roomInfo.remaining < 0 ? RED : "#7E8CA3" }}>
                        {roomInfo.remaining < 0
                          ? `⚠ over by ${fmt(Math.abs(roomInfo.remaining))} — penalties may apply`
                          : `${fmt(roomInfo.remaining)} room left of ${fmt(roomInfo.limit)}`}
                      </div>
                      <div className="mono" style={{ fontSize: 12, color: "#7A879B", marginTop: 3 }}>
                        {opt.room.type === "income" ? "18% of income, CRA capped" : `${fmt(roomInfo.annual)}/yr`}
                      </div>
                    </div>
                  )}

                  {/* Projections */}
                  <div style={{ borderTop: "1px solid rgba(51,214,255,0.12)", paddingTop: 10 }}>
                    <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 7 }}>
                      Projected @ {(effRate(opt) * 100).toFixed(1)}%/yr
                    </div>
                    {HORIZONS.map((yr) => {
                      const pt = projOf(opt)[yr * 12];
                      const fv = adjust(pt.value, yr);
                      const invested = pt.paid;
                      const gain = fv - invested;
                      return (
                        <div key={yr} className="mono" style={{ display: "flex", justifyContent: "space-between", fontSize: 12, padding: "2.5px 0" }}>
                          <span style={{ color: "#8E9AAD" }}>{yr}y</span>
                          <span>
                            <span style={{ color: "#E7ECF2", fontWeight: 600 }}>{fmt(fv)}</span>
                            {gain > 0 && <span style={{ color: opt.color, marginLeft: 6 }}>+{fmt(gain)}</span>}
                          </span>
                        </div>
                      );
                    })}
                    <div style={{ fontSize: 12, color: "#7A879B", marginTop: 7, lineHeight: 1.4 }}>{opt.rateNote}</div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* ---- Controls ---- */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginBottom: 18 }}>
        <div style={{ display: "flex", border: "1px solid rgba(51,214,255,0.2)", borderRadius: 2, overflow: "hidden" }}>
          {Object.entries(SCENARIOS).map(([k, s]) => (
            <button
              key={k}
              type="button"
              onClick={() => setScenario(k)}
              className="mono"
              style={{
                fontSize: 12,
                letterSpacing: "0.08em",
                padding: "7px 12px",
                background: scenario === k ? `${s.color}22` : "transparent",
                color: scenario === k ? s.color : "#8E9AAD",
                border: "none",
                cursor: "pointer",
              }}
            >
              {s.label}
            </button>
          ))}
        </div>
        <Toggle on={realDollars} onClick={() => setRealDollars((v) => !v)} label={`INFLATION-ADJ (${(INFLATION * 100).toFixed(1)}%)`} />
        <span className="mono" style={{ fontSize: 12, color: "#7A879B" }}>
          {realDollars ? "showing today's purchasing power" : "showing nominal dollars"}
        </span>
      </div>

      {/* ---- Settings: Goals & Income Sources ---- */}
      {showSettings && (
        <div style={{ background: "rgba(51,214,255,0.08)", border: "1px solid rgba(51,214,255,0.2)", borderRadius: 3, padding: "16px", marginBottom: 18, overflowX: "auto" }}>
          <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: ACCENT, textTransform: "uppercase", marginBottom: 14 }}>
            ⚙ Goals
          </div>

          <div style={{ marginBottom: 18 }}>
            <div className="mono" style={{ fontSize: 12, letterSpacing: "0.1em", color: "#9AA6BA", textTransform: "uppercase", marginBottom: 10 }}>
              ▸ Financial Goals ({goals.length})
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 10, marginBottom: 10 }}>
              {goals.map((g, idx) => (
                <div key={idx} style={{ background: "rgba(51,214,255,0.05)", border: "1px solid rgba(51,214,255,0.15)", borderRadius: 2, padding: 10 }}>
                  <input type="text" value={g.name} onChange={(e) => updateGoal(idx, "name", e.target.value)} placeholder="Goal name" className="mono" style={{ display: "block", width: "100%", marginBottom: 8, padding: "6px", fontSize: 12, background: "rgba(51,214,255,0.05)", border: "1px solid rgba(51,214,255,0.15)", borderRadius: 2, color: "#E7ECF2" }} />
                  <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
                    <div style={{ flex: 1 }}>
                      <label className="mono" style={{ fontSize: 12, color: "#8E9AAD" }}>Target</label>
                      <input type="number" value={g.target} onChange={(e) => updateGoal(idx, "target", Number(e.target.value) || 0)} min="0" step="10000" className="mono" style={{ display: "block", width: "100%", padding: "4px", fontSize: 12, background: "rgba(51,214,255,0.05)", border: "1px solid rgba(51,214,255,0.15)", borderRadius: 2, color: "#E7ECF2" }} />
                    </div>
                    {goals.length > 1 && (
                      <button type="button" onClick={() => deleteGoal(idx)} className="mono" style={{ alignSelf: "flex-end", padding: "4px 8px", fontSize: 12, background: "#FF5470", border: "none", borderRadius: 2, color: "#05070A", cursor: "pointer", fontWeight: 600 }}>
                        ✕
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
            <button type="button" onClick={addGoal} className="mono" style={{ ...ghostBtn, fontSize: 12, padding: "6px 12px" }}>
              + Add Goal
            </button>
          </div>
        </div>
      )}

      {/* ---- Summary strip ---- */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: "clamp(8px, 2vw, 12px)", marginBottom: 18 }}>
        <Stat label="Total holdings" value={fmt(totalBalance)} />
        <Stat label="Your income" value={fmt(householdGross)} sub="per year · set on Budget tab" />
        <Stat label="Monthly in" value={fmt(totalMonthly)} sub={`${fmt(Math.abs(contribRemaining))} ${contribRemaining >= 0 ? "not yet assigned" : "more than you have left"}`} subColor={contribRemaining >= 0 ? GREEN : RED} />
        <Stat label="Blended rate" value={`${(blendedRate * 100).toFixed(2)}%`} sub={`${scen.label.toLowerCase()}`} subColor={scen.color} />
        <Stat
          label="Emergency runway"
          value={`${runwayMonths.toFixed(1)}mo`}
          sub={runwayMonths >= 3 ? "✓ target met" : "⚠ low"}
          subColor={runwayMonths >= 3 ? GREEN : RED}
        />
        <Stat label="Growth / safe" value={`${growthPct.toFixed(0)} / ${(100 - growthPct).toFixed(0)}`} sub="% investments vs cash & bonds" />
      </div>

      {/* ---- Stacked projection chart ---- */}
      <Panel title={`▸ ${PROJECTION_YEARS}-year projection by account`}>
        {totalBalance + totalMonthly > 0 ? (
          <StackedAreaChart series={stackSeries} max={stackMax} years={PROJECTION_YEARS} />
        ) : (
          <Empty>Enter balances or monthly contributions in "Your accounts" above to see projected growth.</Empty>
        )}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, marginTop: 12 }}>
          {stackSeries.map((s) => (
            <div key={s.name} className="mono" style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#7E8CA3" }}>
              <span style={{ width: 8, height: 8, background: s.color, boxShadow: `0 0 5px ${s.color}` }} />
              {s.name}
            </div>
          ))}
        </div>
      </Panel>

      {/* ---- Goal + stress test ---- */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 14, marginBottom: 18 }}>
        <Panel title="▸ Goal progress" noMargin>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 12, color: ACCENT }}>$</span>
            <input
              type="number"
              min={0}
              step={5000}
              value={goal}
              onChange={(e) => setGoal(num(e.target.value, 100000000))}
              className="mono alloc-input"
              aria-label="Goal amount"
            />
          </div>
          <div style={{ height: 10, background: "rgba(51,214,255,0.1)", borderRadius: 1, overflow: "hidden", marginBottom: 8 }}>
            <div style={{ height: "100%", width: `${goalPct}%`, background: `linear-gradient(90deg, ${ACCENT}, ${GREEN})`, boxShadow: `0 0 12px ${ACCENT}`, transition: "width 0.4s ease" }} />
          </div>
          <div className="mono" style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "#7E8CA3" }}>
            <span>{goalPct.toFixed(1)}% there</span>
            <span style={{ color: "#E7ECF2" }}>
              {yearsToGoal === 0
                ? "goal reached"
                : yearsToGoal === null
                ? "not reachable at this rate"
                : `${yearsToGoal.toFixed(1)} yrs to go`}
            </span>
          </div>
        </Panel>

        <Panel title="▸ Job-loss stress test" noMargin>
          <p style={{ margin: "0 0 10px", fontSize: 12, lineHeight: 1.5, color: "#9AA6BA" }}>
            If income stopped, liquid savings alone would cover{" "}
            <strong style={{ color: runwayMonths >= 3 ? GREEN : RED }}>{runwayMonths.toFixed(1)} months</strong> of
            your spending at {fmt(monthlyExpenses)}/mo.
          </p>
          <p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "#9AA6BA" }}>
            After 3 more years of contributions, that rises to{" "}
            <strong style={{ color: "#E7ECF2" }}>{jobLossMonths.toFixed(1)} months</strong>.
          </p>
        </Panel>
      </div>

      {/* ---- Asset class breakdown ---- */}
      <Panel title="▸ Asset class exposure (across all accounts)">
        {classRows.length === 0 ? (
          <Empty>Add balances to see how your exposure splits by asset class.</Empty>
        ) : (
          <>
            <div style={{ display: "flex", height: 26, borderRadius: 1, overflow: "hidden", marginBottom: 14 }}>
              {classRows.map(([cls, v]) => (
                <div
                  key={cls}
                  title={`${cls}: ${fmt(v)}`}
                  style={{
                    width: `${(v / totalBalance) * 100}%`,
                    background: ASSET_CLASS_COLORS[cls],
                    boxShadow: `0 0 12px ${ASSET_CLASS_COLORS[cls]}66`,
                  }}
                />
              ))}
            </div>
            {classRows.map(([cls, v]) => (
              <div key={cls} className="mono" style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, padding: "4px 0" }}>
                <span style={{ display: "flex", alignItems: "center", gap: 8, color: "#B9C4D6" }}>
                  <span style={{ width: 8, height: 8, background: ASSET_CLASS_COLORS[cls] }} />
                  {cls}
                </span>
                <span>
                  <span style={{ color: "#8E9AAD", marginRight: 10 }}>{((v / totalBalance) * 100).toFixed(1)}%</span>
                  <span style={{ color: "#E7ECF2", fontWeight: 600 }}>{fmt(v)}</span>
                </span>
              </div>
            ))}
          </>
        )}
      </Panel>

      {/* ---- Grand totals ---- */}
      <div style={{ position: "relative", marginTop: 24, background: "rgba(51,214,255,0.05)", border: "1px solid rgba(51,214,255,0.28)", borderRadius: 3, padding: "20px 20px 22px" }}>
        <CornerBrackets size={14} />
        <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: ACCENT, textTransform: "uppercase", marginBottom: 16 }}>
          ▸ Combined portfolio · {scen.label} case{realDollars ? " · today's dollars" : ""}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 16 }}>
          <div>
            <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 6 }}>
              Today
            </div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "#E7ECF2" }}>{fmt(totalBalance)}</div>
            <div className="mono" style={{ fontSize: 12, color: "#7A879B", marginTop: 4 }}>
              +{fmt(totalMonthly)}/mo
            </div>
          </div>
          {HORIZONS.map((yr) => {
            const total = totalAt(yr);
            const invested = paidAtMonth(yr * 12);
            const gain = total - invested;
            return (
              <div key={yr}>
                <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 6 }}>
                  After {yr} year{yr > 1 ? "s" : ""}
                </div>
                <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: ACCENT, textShadow: "0 0 18px rgba(51,214,255,0.4)" }}>
                  {fmt(total)}
                </div>
                <div className="mono" style={{ fontSize: 12, color: gain > 0 ? GREEN : "#7A879B", marginTop: 4 }}>
                  {gain > 0 ? `+${fmt(gain)} growth` : "—"}
                </div>
              </div>
            );
          })}
        </div>
        <p style={{ margin: "18px 0 0", fontSize: 12, lineHeight: 1.5, color: "#8391A6" }}>
          Compounded monthly on current balances plus recurring contributions, before fees and (outside registered
          accounts) tax. Rates are illustrative assumptions, not predictions — actual returns vary widely and market
          assets can lose value. General information only, not personalized financial advice.
        </p>
      </div>

      {/* ---- Snapshot history ---- */}
      {showSnapshots && snapshots.length > 0 && (
        <div style={{ position: "relative", marginTop: 24, background: "rgba(51,214,255,0.05)", border: "1px solid rgba(51,214,255,0.28)", borderRadius: 3, padding: "clamp(12px, 3vw, 20px)" }}>
          <CornerBrackets size={14} />
          <div className="mono" style={{ fontSize: 13, letterSpacing: "0.08em", color: ACCENT, textTransform: "uppercase", marginBottom: 12 }}>
            ▸ Performance History · {snapshots.length} snapshot{snapshots.length !== 1 ? "s" : ""}
          </div>
          <div style={{ overflowX: "auto", margin: "0 -clamp(8px, 2vw, 12px)" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 320 }}>
              <thead>
                <tr style={{ borderBottom: "1px solid rgba(51,214,255,0.2)" }}>
                  <th style={{ textAlign: "left", padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", color: "#8E9AAD", fontWeight: 600 }}>Date</th>
                  <th style={{ textAlign: "right", padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", color: "#8E9AAD", fontWeight: 600 }}>Balance</th>
                  <th style={{ textAlign: "right", padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", color: "#8E9AAD", fontWeight: 600 }}>Δ</th>
                  <th style={{ textAlign: "right", padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", color: "#8E9AAD", fontWeight: 600 }}>%</th>
                </tr>
              </thead>
              <tbody>
                {snapshots.map((snap, idx) => {
                  const daysAgo = Math.floor((Date.now() - new Date(snap.date).getTime()) / (1000 * 60 * 60 * 24));
                  const diff = totalBalance - snap.totalBalance;
                  const pct = snap.totalBalance > 0 ? ((diff / snap.totalBalance) * 100).toFixed(1) : 0;
                  return (
                    <tr key={idx} style={{ borderBottom: "1px solid rgba(51,214,255,0.08)" }}>
                      <td style={{ padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", color: "#9AA6BA", whiteSpace: "nowrap" }}>
                        {new Date(snap.date).toLocaleDateString("en-US", {month:"short", day:"2-digit"})} ({daysAgo}d)
                      </td>
                      <td style={{ padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", textAlign: "right", color: "#E7ECF2" }}>{fmt(snap.totalBalance)}</td>
                      <td style={{ padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", textAlign: "right", color: diff > 0 ? GREEN : "#FF5470", whiteSpace: "nowrap" }}>
                        {diff > 0 ? "+" : ""}{fmt(Math.abs(diff))}
                      </td>
                      <td style={{ padding: "clamp(6px, 1.5vw, 8px) clamp(6px, 1vw, 12px)", textAlign: "right", color: pct > 0 ? GREEN : "#FF5470" }}>
                        {pct > 0 ? "+" : ""}{pct}%
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <div style={{ fontSize: 13, color: "#7A879B", marginTop: 8 }}>
            Track performance over time to validate your projections.
          </div>
        </div>
      )}
    </div>
  );
}

// ---- Small presentational helpers ----

const ghostBtn = {
  flexShrink: 0,
  fontSize: 12,
  letterSpacing: "0.08em",
  color: ACCENT,
  background: "rgba(51,214,255,0.08)",
  border: "1px solid rgba(51,214,255,0.3)",
  borderRadius: 2,
  padding: "8px 12px",
  cursor: "pointer",
};

const cardStyle = {
  position: "relative",
  background: "rgba(51,214,255,0.03)",
  border: "1px solid rgba(51,214,255,0.16)",
  borderRadius: 3,
  padding: "16px 16px 18px",
  display: "flex",
  flexDirection: "column",
};

const quickTh = (align) => ({ textAlign: align, padding: "6px 4px", color: "#8E9AAD", fontWeight: 600, fontSize: 12.5 });

const sliderStyle = (frac, color) => ({
  background: `linear-gradient(to right, ${color} 0%, ${color} ${frac * 100}%, rgba(51,214,255,0.14) ${frac * 100}%, rgba(51,214,255,0.14) 100%)`,
  "--thumb-color": color,
});

function Field({ label, color, children }) {
  return (
    <div style={{ marginBottom: 6 }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 5 }}>
        {label}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="mono" style={{ fontSize: 13, color }}>$</span>
        {children}
      </div>
    </div>
  );
}

function Stat({ label, value, sub, subColor }) {
  return (
    <div style={{ position: "relative", background: "rgba(51,214,255,0.035)", border: "1px solid rgba(51,214,255,0.16)", borderRadius: 3, padding: "12px 14px" }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 5 }}>
        {label}
      </div>
      <div className="mono" style={{ fontSize: 17, fontWeight: 700, color: "#E7ECF2" }}>{value}</div>
      {sub && (
        <div className="mono" style={{ fontSize: 12, color: subColor ?? "#7A879B", marginTop: 3 }}>{sub}</div>
      )}
    </div>
  );
}

function Panel({ title, children, noMargin }) {
  return (
    <div style={{ position: "relative", background: "rgba(51,214,255,0.025)", border: "1px solid rgba(51,214,255,0.16)", borderRadius: 3, padding: "16px 18px 18px", marginBottom: noMargin ? 0 : 18 }}>
      <CornerBrackets size={10} />
      <div className="mono" style={{ fontSize: 12, letterSpacing: "0.08em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 14 }}>
        {title}
      </div>
      {children}
    </div>
  );
}

function Empty({ children }) {
  return (
    <div className="mono" style={{ fontSize: 12.5, color: "#7A879B", padding: "20px 0", textAlign: "center" }}>
      {children}
    </div>
  );
}

function Toggle({ on, onClick, label }) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="mono"
      style={{
        display: "flex",
        alignItems: "center",
        gap: 8,
        fontSize: 12,
        letterSpacing: "0.06em",
        color: on ? ACCENT : "#8E9AAD",
        background: on ? "rgba(51,214,255,0.1)" : "transparent",
        border: `1px solid ${on ? "rgba(51,214,255,0.35)" : "rgba(51,214,255,0.15)"}`,
        borderRadius: 2,
        padding: "7px 12px",
        cursor: "pointer",
      }}
    >
      <span style={{ width: 7, height: 7, background: on ? ACCENT : "#7A879B", boxShadow: on ? `0 0 6px ${ACCENT}` : "none" }} />
      {label}
    </button>
  );
}

function StackedAreaChart({ series, max, years }) {
  const W = 700;
  const H = 240;
  const PADL = 54;
  const PADB = 24;
  const PADT = 8;
  const plotW = W - PADL - 8;
  const plotH = H - PADB - PADT;

  const xAt = (y) => PADL + (y / years) * plotW;
  const yAt = (v) => PADT + plotH - (v / max) * plotH;

  // Build cumulative bands
  const cum = Array.from({ length: years + 1 }, () => 0);
  const bands = series.map((s) => {
    const lower = [...cum];
    s.points.forEach((p, i) => (cum[i] += p));
    const upper = [...cum];
    return { ...s, lower, upper };
  });

  const gridVals = [0, 0.25, 0.5, 0.75, 1].map((f) => f * max);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", display: "block" }}>
      {gridVals.map((v, i) => (
        <g key={i}>
          <line x1={PADL} y1={yAt(v)} x2={W - 8} y2={yAt(v)} stroke="rgba(51,214,255,0.12)" strokeWidth={1} />
          <text x={PADL - 8} y={yAt(v) + 3.5} textAnchor="end" fontSize={12} fill="#7A879B" fontFamily="'JetBrains Mono', monospace">
            {v >= 1000 ? `${Math.round(v / 1000)}k` : Math.round(v)}
          </text>
        </g>
      ))}

      {bands.map((b) => {
        const up = b.upper.map((v, i) => `${xAt(i)},${yAt(v)}`).join(" ");
        const down = [...b.lower].reverse().map((v, i) => `${xAt(years - i)},${yAt(v)}`).join(" ");
        return (
          <polygon
            key={b.name}
            points={`${up} ${down}`}
            fill={b.color}
            fillOpacity={0.55}
            stroke={b.color}
            strokeWidth={1.25}
          />
        );
      })}

      {Array.from({ length: years + 1 }, (_, y) => y).filter((y) => y % 2 === 0).map((y) => (
        <text key={y} x={xAt(y)} y={H - 7} textAnchor="middle" fontSize={12} fill="#7A879B" fontFamily="'JetBrains Mono', monospace">
          {y}y
        </text>
      ))}
    </svg>
  );
}


function InfoSection({ title, children, last }) {
  return (
    <div style={{ marginBottom: last ? 0 : 16, paddingBottom: last ? 0 : 16, borderBottom: last ? "none" : "1px solid rgba(51,214,255,0.1)" }}>
      <div className="mono" style={{ fontSize: 12, letterSpacing: "0.1em", color: "#8E9AAD", textTransform: "uppercase", marginBottom: 6 }}>
        {title}
      </div>
      <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, color: "#B9C4D6" }}>{children}</p>
    </div>
  );
}

function CompareRow({ label, then, now, invert = false }) {
  const delta = now - then;
  const good = invert ? delta < 0 : delta > 0;
  const isFlat = Math.abs(delta) < 0.5;
  const deltaColor = isFlat ? "#8E9AAD" : good ? "#4FC98A" : "#EC5F5F";
  const arrow = isFlat ? "—" : delta > 0 ? "▲" : "▼";
  return (
    <>
      <span style={{ color: "#B9C4D6" }}>{label}</span>
      <span className="mono" style={{ color: "#8E9AAD", textAlign: "right" }}>{fmt(then)}</span>
      <span className="mono" style={{ color: "#E7ECF2", fontWeight: 600, textAlign: "right" }}>{fmt(now)}</span>
      <span className="mono" style={{ color: deltaColor, textAlign: "right" }}>
        {arrow} {fmt(Math.abs(delta))}
      </span>
    </>
  );
}

const fmtCents = (n) => {
  const s = Math.abs(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  return `${n < 0 ? "-" : ""}$${s}`;
};

const PACE_COLORS = { ok: GREEN, ahead: "#FFC145", over: RED };

function ProgressBar({ spent, planned, elapsed, status, label }) {
  const pct = planned > 0 ? Math.min(100, (spent / planned) * 100) : spent > 0 ? 100 : 0;
  const color = PACE_COLORS[status] || GREEN;
  return (
    <div className="bar" role="img" aria-label={label}>
      <div className="bar-fill" style={{ width: `${Math.max(0, pct)}%`, background: color, boxShadow: `0 0 8px ${color}88` }} />
      {elapsed > 0 && elapsed < 1 && <div className="pace-mark" style={{ left: `${elapsed * 100}%` }} title="How far through the period we are" />}
    </div>
  );
}

function MonthProgress({ stats, monthKey, onPick, activeId }) {
  const { rows, elapsed } = stats;
  const monthlyRows = rows.filter((r) => !r.yearly && (r.planned > 0 || r.spent !== 0));
  const yearlyRows = rows.filter((r) => r.yearly && (r.planned > 0 || r.spent !== 0));
  const yearFrac = (Number(monthKey.slice(5)) - 1 + elapsed) / 12;

  const renderRow = (r, frac) => {
    const status = paceStatus(r, elapsed, monthKey);
    const left = r.planned - r.spent;
    const active = activeId === r.category.id;
    return (
      <button key={r.category.id} type="button" className={`progress-row${active ? " is-active" : ""}`} onClick={() => onPick(active ? null : r.category.id)} aria-pressed={active}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
          <span style={{ fontSize: 14, color: "#E7ECF2", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {r.category.name || "Unnamed"}
          </span>
          <span className="mono" style={{ fontSize: 13, color: "#B9C4D6", flexShrink: 0 }}>
            {fmt(r.spent)} <span style={{ color: "#8E9AAD" }}>of {fmt(r.planned)}</span>
          </span>
        </div>
        <ProgressBar spent={r.spent} planned={r.planned} elapsed={frac} status={status} label={`${r.category.name}: ${fmt(r.spent)} of ${fmt(r.planned)}`} />
        <div style={{ fontSize: 12.5, color: PACE_COLORS[status] === GREEN ? "#8E9AAD" : PACE_COLORS[status], textAlign: "left" }}>
          {status === "over" ? `${fmt(-left)} over` : `${fmt(left)} left`}
          {status === "ahead" && " · spending faster than planned"}
        </div>
      </button>
    );
  };

  return (
    <div className="panel fade-up" style={{ marginBottom: 18 }}>
      <CornerBrackets />
      <div className="panel-title" style={{ marginBottom: 4 }}>Plan vs actual</div>
      <div style={{ fontSize: 12.5, color: "#8E9AAD", marginBottom: 8 }}>
        The thin line marks how far through the month we are. Tap a category to see its purchases.
      </div>
      {monthlyRows.length === 0 && yearlyRows.length === 0 && (
        <div style={{ fontSize: 13.5, color: "#9AA6BA", padding: "8px 0" }}>Add categories on the Budget tab to track against a plan.</div>
      )}
      <div className="progress-grid">
        {monthlyRows.map((r) => (
          renderRow(r, elapsed)
        ))}
      </div>
      {stats.uncategorized !== 0 && (
        <button type="button" className={`progress-row${activeId === UNCATEGORIZED ? " is-active" : ""}`} onClick={() => onPick(activeId === UNCATEGORIZED ? null : UNCATEGORIZED)} style={{ marginTop: 6 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
            <span style={{ color: "#FFC145" }}>Uncategorised</span>
            <span className="mono" style={{ color: "#B9C4D6" }}>{fmt(stats.uncategorized)}</span>
          </div>
          <div style={{ fontSize: 12.5, color: "#8E9AAD", textAlign: "left" }}>Not in your plan yet — tap to sort these into categories.</div>
        </button>
      )}
      {yearlyRows.length > 0 && (
        <>
          <div style={{ fontSize: 13, color: "#9AA6BA", margin: "14px 0 4px" }}>Yearly costs — spent so far this year</div>
          <div className="progress-grid">
            {yearlyRows.map((r) => (
              renderRow(r, yearFrac)
            ))}
          </div>
        </>
      )}
    </div>
  );
}

function UndoToast({ toast, onUndo, onClose }) {
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(onClose, 8000);
    return () => clearTimeout(t);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [toast]);
  if (!toast) return null;
  return (
    <div className="toast" role="status">
      <span>{toast.text}</span>
      {toast.undo && <button type="button" className="link-btn" style={{ padding: 0 }} onClick={onUndo}>Undo</button>}
      <button type="button" className="link-btn" style={{ padding: 0, color: "#9AA6BA" }} onClick={onClose} aria-label="Dismiss">✕</button>
    </div>
  );
}

// ---- Spending: imported expense ledger (logic lives in ledger.js as window.Ledger) ----

const categoryName = (id, categories) => categories.find((c) => c.id === id)?.name || "Uncategorised";

// Fixed categorical order (taxonomy group order) — validated for CVD separation and
// contrast on the app's dark surface. Colour follows the group, never its rank.
const SPEND_GROUP_COLORS = {
  food_drink: "#338ced",
  shopping: "#e76624",
  transport: "#00a888",
  lifestyle_leisure: "#d28e05",
  health_wellbeing: "#e24d8b",
  general_living: "#0aac23",
  business: "#9887ef",
  [Ledger.UNCAT]: "#6B7686",
};
const SPEND_GROUP_ORDER = [...Ledger.GROUPS.map((g) => g.id), Ledger.UNCAT];
const groupLabel = (id) => (Ledger.GROUP[id] ? Ledger.GROUP[id].label : "Uncategorised");
const catLabel = (id) => (id && Ledger.CATEGORY[id] ? Ledger.CATEGORY[id].label : "Uncategorised");
const groupOfCat = (id) => (id && Ledger.CATEGORY[id] ? Ledger.CATEGORY[id].group_id : Ledger.UNCAT);
const catColor = (id) => SPEND_GROUP_COLORS[groupOfCat(id)];
const fmtMinor = (c) => fmtCents(c / 100);
const fmtMinor0 = (c) => fmt(c / 100);
const EMPTY_MONTH = { total: 0, personal: 0, business: 0, unallocated: 0, byCategory: {}, byGroup: {}, count: 0 };
const INK = "#E7ECF2";
const INK2 = "#9AA6BA";
const INK3 = "#8E9AAD";
const UP_COLOR = "#e76624"; // diverging: more spending
const DOWN_COLOR = "#338ced"; // diverging: less spending

// Axis ticks: $500, $1k, $1.5k — never two ticks with the same label.
const fmtAxisDollars = (v) => (Math.abs(v) >= 1000 ? `$${+(v / 1000).toFixed(Math.abs(v) % 1000 ? 1 : 0)}k` : `$${Math.round(v)}`);

function monthList(from, to) {
  const out = [];
  if (!from || !to || from > to) return out;
  for (let m = from; m <= to && out.length < 240; m = shiftMonth(m, 1)) out.push(m);
  return out;
}

// Average of the given months' totals, counting only complete months that have data.
function fullMonthAverage(months, byMonth, partial, pick = (m) => m.total) {
  const full = months.filter((m) => !partial.has(m) && byMonth[m]);
  if (!full.length) return null;
  return full.reduce((s, m) => s + pick(byMonth[m]), 0) / full.length;
}

function DeltaText({ now, then, label }) {
  if (then === null || then === undefined) return null;
  const d = now - then;
  if (Math.abs(d) < 50) return <span style={{ color: INK3 }}>≈ {label}</span>;
  const pctTxt = then > 0 ? ` (${d > 0 ? "+" : "−"}${Math.round((Math.abs(d) / then) * 100)}%)` : "";
  return (
    <span style={{ color: "#B9C4D6" }}>
      {d > 0 ? "▲" : "▼"} {fmtMinor0(Math.abs(d))}
      {pctTxt} vs {label}
    </span>
  );
}

function PartialBadge({ show }) {
  if (!show) return null;
  return <span className="badge warn" title="Not every day of this month is covered by your imports yet">partial month</span>;
}

// ---- Monthly trend: stacked bars by group ----
function SpendTrendChart({ months, byMonth, pendingByMonth, partial, selected, onSelect }) {
  const [ref, width] = useElementWidth();
  const [hover, setHover] = useState(null);
  const W = Math.max(300, width);
  const H = 260;
  const PADL = 50, PADR = 8, PADT = 18, PADB = 40;
  const totals = months.map((m) => (byMonth[m] ? Math.max(0, byMonth[m].total) : 0) + (pendingByMonth[m] ? Math.max(0, pendingByMonth[m].total) : 0));
  const max = Math.max(1, ...totals);
  const x = d3.scaleBand().domain(months).range([PADL, W - PADR]).padding(months.length > 8 ? 0.22 : 0.34);
  const y = d3.scaleLinear().domain([0, max * 1.08]).nice(4).range([H - PADB, PADT]);
  const avg = fullMonthAverage(months, byMonth, partial);
  const present = SPEND_GROUP_ORDER.filter((g) => months.some((m) => byMonth[m] && byMonth[m].byGroup[g] > 0));
  const bw = x.bandwidth();
  const labelEvery = Math.ceil(months.length / Math.max(1, Math.floor((W - PADL) / 56)));

  const topRounded = (x0, y0, w, h, r) => {
    const rr = Math.min(r, w / 2, h);
    return `M${x0},${y0 + h}V${y0 + rr}Q${x0},${y0} ${x0 + rr},${y0}H${x0 + w - rr}Q${x0 + w},${y0} ${x0 + w},${y0 + rr}V${y0 + h}Z`;
  };

  const hm = hover && byMonth[hover] ? byMonth[hover] : null;
  const hp = hover && pendingByMonth[hover] ? pendingByMonth[hover].total : 0;
  const tipLeft = hover ? Math.min(Math.max(0, x(hover) + bw / 2 - 110), W - 220) : 0;

  return (
    <div ref={ref} style={{ position: "relative", width: "100%" }}>
      <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} style={{ display: "block", maxWidth: "100%" }} role="img" aria-label="Posted spending per month, stacked by group">
        <defs>
          <pattern id="spend-hatch" patternUnits="userSpaceOnUse" width="6" height="6" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="#05070A" strokeWidth="2" strokeOpacity="0.55" />
          </pattern>
        </defs>
        {y.ticks(4).map((v) => (
          <g key={v}>
            <line x1={PADL} x2={W - PADR} y1={y(v)} y2={y(v)} stroke="rgba(51,214,255,0.10)" />
            <text x={PADL - 8} y={y(v) + 4} textAnchor="end" fontSize={11.5} fill={INK3} fontFamily="'JetBrains Mono', monospace">
              {fmtAxisDollars(v / 100)}
            </text>
          </g>
        ))}
        {months.map((m, i) => {
          const mb = byMonth[m];
          const x0 = x(m);
          let acc = 0;
          const segs = mb ? SPEND_GROUP_ORDER.filter((g) => mb.byGroup[g] > 0) : [];
          const isSel = m === selected;
          const pend = pendingByMonth[m] ? Math.max(0, pendingByMonth[m].total) : 0;
          const postedTop = y(mb ? Math.max(0, mb.total) : 0);
          return (
            <g key={m}>
              {isSel && <rect x={x0 - bw * 0.18} y={PADT - 6} width={bw * 1.36} height={H - PADB - PADT + 6} fill="rgba(51,214,255,0.07)" rx={3} />}
              {segs.map((g, j) => {
                const v = mb.byGroup[g];
                const yTop = y(acc + v);
                const yBot = y(acc);
                acc += v;
                const h = Math.max(0, yBot - yTop - (j > 0 ? 2 : 0)); // 2px surface gap between segments
                const isTop = j === segs.length - 1;
                return isTop ? (
                  <path key={g} d={topRounded(x0, yTop, bw, h, 4)} fill={SPEND_GROUP_COLORS[g]} />
                ) : (
                  <rect key={g} x={x0} y={yTop} width={bw} height={h} fill={SPEND_GROUP_COLORS[g]} />
                );
              })}
              {partial.has(m) && mb && mb.total > 0 && <rect x={x0} y={postedTop} width={bw} height={y(0) - postedTop} fill="url(#spend-hatch)" />}
              {pend > 0 && (
                <rect x={x0 + 1} y={y((mb ? Math.max(0, mb.total) : 0) + pend)} width={bw - 2} height={Math.max(1, postedTop - y((mb ? Math.max(0, mb.total) : 0) + pend) - 2)} fill="none" stroke={INK2} strokeDasharray="3 3" rx={3} />
              )}
              {i % labelEvery === 0 && (
                <text x={x0 + bw / 2} y={H - PADB + 16} textAnchor="middle" fontSize={11.5} fill={isSel ? ACCENT : INK3} fontWeight={isSel ? 700 : 400} fontFamily="'JetBrains Mono', monospace">
                  {shortMonth(m)}
                </text>
              )}
              {partial.has(m) && i % labelEvery === 0 && (
                <text x={x0 + bw / 2} y={H - PADB + 30} textAnchor="middle" fontSize={10.5} fill="#FFC145">
                  partial
                </text>
              )}
              <rect
                x={x0 - (x.step() - bw) / 2}
                y={PADT}
                width={x.step()}
                height={H - PADB - PADT}
                fill="transparent"
                style={{ cursor: "pointer" }}
                onMouseEnter={() => setHover(m)}
                onMouseLeave={() => setHover(null)}
                onClick={() => onSelect(m)}
              >
                <title>{`${monthLabel(m)}: ${fmtMinor0(mb ? mb.total : 0)}`}</title>
              </rect>
            </g>
          );
        })}
        {avg !== null && avg > 0 && (
          <g pointerEvents="none">
            <line x1={PADL} x2={W - PADR} y1={y(avg)} y2={y(avg)} stroke={INK} strokeOpacity={0.7} strokeDasharray="5 4" strokeWidth={1.5} />
            <text x={W - PADR - 4} y={y(avg) - 6} textAnchor="end" fontSize={11.5} fill={INK} fontFamily="'JetBrains Mono', monospace">
              avg {fmtMinor0(avg)} (full months)
            </text>
          </g>
        )}
        <line x1={PADL} x2={W - PADR} y1={y(0)} y2={y(0)} stroke="rgba(51,214,255,0.3)" />
      </svg>
      {hover && (
        <div className="chart-tip" style={{ left: tipLeft, top: 0 }}>
          <div style={{ fontWeight: 600, marginBottom: 4 }}>
            {monthLabel(hover)} {partial.has(hover) && <span style={{ color: "#FFC145", fontWeight: 400 }}>· partial</span>}
          </div>
          {hm ? (
            SPEND_GROUP_ORDER.filter((g) => hm.byGroup[g]).map((g) => (
              <div key={g} className="tip-row">
                <span><span className="swatch" style={{ background: SPEND_GROUP_COLORS[g] }} />{groupLabel(g)}</span>
                <span className="mono">{fmtMinor0(hm.byGroup[g])}</span>
              </div>
            ))
          ) : (
            <div style={{ color: INK3 }}>No posted spending</div>
          )}
          <div className="tip-row" style={{ borderTop: "1px solid rgba(51,214,255,0.2)", marginTop: 4, paddingTop: 4 }}>
            <span>Posted total</span>
            <span className="mono">{fmtMinor0(hm ? hm.total : 0)}</span>
          </div>
          {hp > 0 && (
            <div className="tip-row" style={{ color: INK2 }}>
              <span>Pending (not counted)</span>
              <span className="mono">{fmtMinor0(hp)}</span>
            </div>
          )}
        </div>
      )}
      <div style={{ display: "flex", flexWrap: "wrap", gap: "6px 14px", marginTop: 8 }}>
        {present.map((g) => (
          <LegendChip key={g} color={SPEND_GROUP_COLORS[g]} label={groupLabel(g)} />
        ))}
        {months.some((m) => pendingByMonth[m]) && <span style={{ fontSize: 12, color: INK2 }}>┆ dashed = pending</span>}
        {months.some((m) => partial.has(m)) && <span style={{ fontSize: 12, color: INK2 }}>▨ hatched = partial month</span>}
      </div>
    </div>
  );
}

// ---- Category breakdown for one month (with deltas) ----
function CategoryBreakdown({ monthKey, cur, prev, avgByCat, onPick, activeCat }) {
  const rows = Object.keys(cur.byCategory)
    .map((id) => ({ id, v: cur.byCategory[id] || 0, p: prev ? prev.byCategory[id] || 0 : null, a: avgByCat ? avgByCat[id] || 0 : null }))
    .filter((r) => r.v !== 0)
    .sort((a, b) => b.v - a.v);
  // Categories you spent on last month but not this month — named in one line, not listed as $0 rows.
  const dropped = prev ? Object.keys(prev.byCategory).filter((id) => prev.byCategory[id] > 0 && !cur.byCategory[id]) : [];
  const max = Math.max(1, ...rows.map((r) => r.v));
  if (!rows.length) return <Empty>No posted spending in {monthLabel(monthKey)}.</Empty>;
  return (
    <div>
      {rows.map((r) => {
        const cat = r.id === Ledger.UNCAT ? null : r.id;
        const active = activeCat === r.id;
        return (
          <button key={r.id} type="button" className={`cat-row${active ? " is-active" : ""}`} onClick={() => onPick(active ? null : r.id)} aria-pressed={active}>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
              <span style={{ fontSize: 13.5, color: INK, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                <span className="swatch" style={{ background: catColor(cat) }} />
                {catLabel(cat)}
              </span>
              <span className="mono" style={{ fontSize: 13, color: INK, flexShrink: 0 }}>{fmtMinor0(r.v)}</span>
            </div>
            <div className="hbar">
              <div style={{ width: `${Math.max(0, (r.v / max) * 100)}%`, background: catColor(cat) }} />
            </div>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap", fontSize: 12, textAlign: "left" }}>
              {r.p !== null && <DeltaText now={r.v} then={r.p} label="last month" />}
              {r.a !== null && <DeltaText now={r.v} then={r.a} label="3-mo avg" />}
            </div>
          </button>
        );
      })}
      {dropped.length > 0 && (
        <div style={{ fontSize: 12.5, color: INK3, marginTop: 8, lineHeight: 1.5 }}>
          Nothing this month in: {dropped.map((id) => `${catLabel(id === Ledger.UNCAT ? null : id)} (${fmtMinor0(prev.byCategory[id])} last month)`).join(", ")}.
        </div>
      )}
    </div>
  );
}

// ---- Month vs month: diverging bars per category ----
function MonthCompare({ dataMonths, byMonth, partial, defaultA, defaultB }) {
  const [a, setA] = useState(defaultA);
  const [b, setB] = useState(defaultB);
  useEffect(() => {
    setA(defaultA);
    setB(defaultB);
  }, [defaultA, defaultB]);
  const A = byMonth[a] || EMPTY_MONTH;
  const B = byMonth[b] || EMPTY_MONTH;
  const ids = [...new Set([...Object.keys(A.byCategory), ...Object.keys(B.byCategory)])];
  const rows = ids.map((id) => ({ id, a: A.byCategory[id] || 0, b: B.byCategory[id] || 0 })).map((r) => ({ ...r, d: r.b - r.a })).filter((r) => r.a || r.b).sort((x, y) => Math.abs(y.d) - Math.abs(x.d));
  const max = Math.max(1, ...rows.map((r) => Math.abs(r.d)));
  const totalD = B.total - A.total;
  const opts = dataMonths.slice().reverse();
  return (
    <div>
      <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 10 }}>
        <select className="field-input" style={{ width: "auto" }} value={a || ""} onChange={(e) => setA(e.target.value)} aria-label="First month">
          {opts.map((m) => <option key={m} value={m}>{monthLabel(m)}{partial.has(m) ? " (partial)" : ""}</option>)}
        </select>
        <span style={{ color: INK2 }}>→</span>
        <select className="field-input" style={{ width: "auto" }} value={b || ""} onChange={(e) => setB(e.target.value)} aria-label="Second month">
          {opts.map((m) => <option key={m} value={m}>{monthLabel(m)}{partial.has(m) ? " (partial)" : ""}</option>)}
        </select>
      </div>
      <div style={{ fontSize: 14, color: INK, marginBottom: 4 }}>
        {fmtMinor0(A.total)} → {fmtMinor0(B.total)}{" "}
        <span className="mono" style={{ color: INK2 }}>
          ({totalD >= 0 ? "+" : "−"}{fmtMinor0(Math.abs(totalD))}{A.total > 0 ? `, ${totalD >= 0 ? "+" : "−"}${Math.round((Math.abs(totalD) / A.total) * 100)}%` : ""})
        </span>
      </div>
      {(partial.has(a) || partial.has(b)) && <div style={{ fontSize: 12.5, color: "#FFC145", marginBottom: 6 }}>One of these months is partial, so the comparison understates it.</div>}
      <div style={{ display: "flex", gap: 14, fontSize: 12, color: INK2, margin: "6px 0 8px" }}>
        <span><span className="swatch" style={{ background: DOWN_COLOR }} />spent less</span>
        <span><span className="swatch" style={{ background: UP_COLOR }} />spent more</span>
      </div>
      {rows.map((r) => {
        const cat = r.id === Ledger.UNCAT ? null : r.id;
        const w = (Math.abs(r.d) / max) * 50;
        return (
          <div key={r.id} className="div-row" title={`${catLabel(cat)}: ${fmtMinor0(r.a)} → ${fmtMinor0(r.b)}`}>
            <span className="div-label">{catLabel(cat)}</span>
            <span className="div-track">
              <span className="div-mid" />
              {r.d !== 0 && (
                <span
                  className="div-bar"
                  style={{ left: r.d > 0 ? "50%" : `${50 - w}%`, width: `${w}%`, background: r.d > 0 ? UP_COLOR : DOWN_COLOR, borderRadius: r.d > 0 ? "0 4px 4px 0" : "4px 0 0 4px" }}
                />
              )}
            </span>
            <span className="mono div-val">
              {r.d >= 0 ? "+" : "−"}{fmtMinor0(Math.abs(r.d))}
              {r.a > 0 && <span style={{ color: INK3 }}> {r.d >= 0 ? "+" : "−"}{Math.round((Math.abs(r.d) / r.a) * 100)}%</span>}
            </span>
          </div>
        );
      })}
      {!rows.length && <Empty>No posted spending in either month.</Empty>}
    </div>
  );
}

// ---- Small multiples: one sparkline per category ----
function Sparkline({ values, months, partial, color, max }) {
  const W = 160, H = 38, P = 4;
  const xs = (i) => (values.length < 2 ? W / 2 : P + (i / (values.length - 1)) * (W - 2 * P));
  const ys = (v) => H - P - (max > 0 ? (Math.max(0, v) / max) * (H - 2 * P) : 0);
  const pts = values.map((v, i) => `${xs(i)},${ys(v)}`).join(" ");
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: H, display: "block" }} aria-hidden="true">
      <line x1={P} x2={W - P} y1={H - P} y2={H - P} stroke="rgba(51,214,255,0.15)" />
      {values.length > 1 && <polyline points={pts} fill="none" stroke={color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />}
      {values.map((v, i) => (
        <circle key={months[i]} cx={xs(i)} cy={ys(v)} r={i === values.length - 1 ? 4 : 2.5} fill={partial.has(months[i]) ? "#05070A" : color} stroke={color} strokeWidth={1.5}>
          <title>{`${monthLabel(months[i])}: ${fmtMinor0(v)}${partial.has(months[i]) ? " (partial)" : ""}`}</title>
        </circle>
      ))}
    </svg>
  );
}

function CategoryTrends({ months, byMonth, partial, onPick }) {
  const ids = [...new Set(months.flatMap((m) => (byMonth[m] ? Object.keys(byMonth[m].byCategory) : [])))];
  const rows = ids
    .map((id) => {
      const values = months.map((m) => (byMonth[m] && byMonth[m].byCategory[id]) || 0);
      const total = values.reduce((s, v) => s + v, 0);
      const avg = fullMonthAverage(months, byMonth, partial, (mb) => mb.byCategory[id] || 0);
      return { id, values, total, avg };
    })
    .filter((r) => r.total !== 0)
    .sort((a, b) => b.total - a.total);
  if (!rows.length) return <Empty>No posted spending in this range.</Empty>;
  return (
    <div className="spark-grid">
      {rows.map((r) => {
        const cat = r.id === Ledger.UNCAT ? null : r.id;
        return (
          <button key={r.id} type="button" className="spark-cell" onClick={() => onPick(r.id)} title="Show these purchases">
            <div style={{ fontSize: 13, color: INK, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              <span className="swatch" style={{ background: catColor(cat) }} />
              {catLabel(cat)}
            </div>
            <Sparkline values={r.values} months={months} partial={partial} color={catColor(cat)} max={Math.max(...r.values)} />
            <div className="mono" style={{ fontSize: 12, color: INK2, display: "flex", justifyContent: "space-between" }}>
              <span>{fmtMinor0(r.total)}</span>
              <span>{r.avg !== null ? `avg ${fmtMinor0(r.avg)}/mo` : "—"}</span>
            </div>
          </button>
        );
      })}
    </div>
  );
}

function TopMerchants({ rows, onSearch }) {
  const [all, setAll] = useState(false);
  const list = Ledger.merchantTotals(rows);
  const shown = all ? list : list.slice(0, 10);
  if (!list.length) return <Empty>No posted spending in this range.</Empty>;
  return (
    <div style={{ overflowX: "auto" }}>
      <table className="data-table">
        <thead>
          <tr>
            <th style={{ textAlign: "left" }}>Merchant</th>
            <th style={{ textAlign: "right" }}>Visits</th>
            <th style={{ textAlign: "right" }}>Total</th>
            <th style={{ textAlign: "right" }}>Avg</th>
          </tr>
        </thead>
        <tbody>
          {shown.map((m) => (
            <tr key={m.merchant} onClick={() => onSearch(m.merchant)} style={{ cursor: "pointer" }} title="Show these purchases">
              <td>
                <div style={{ color: INK }}>{m.merchant}</div>
                <div style={{ fontSize: 12, color: INK3 }}>
                  <span className="swatch" style={{ background: catColor(m.category_id) }} />
                  {catLabel(m.category_id)}
                </div>
              </td>
              <td className="mono" style={{ textAlign: "right" }}>{m.count}</td>
              <td className="mono" style={{ textAlign: "right", color: INK }}>{fmtMinor0(m.total)}</td>
              <td className="mono" style={{ textAlign: "right" }}>{m.count ? fmtMinor0(m.total / m.count) : "—"}</td>
            </tr>
          ))}
        </tbody>
      </table>
      {list.length > 10 && (
        <button type="button" className="link-btn" onClick={() => setAll(!all)}>{all ? "Show top 10" : `Show all ${list.length} merchants`}</button>
      )}
    </div>
  );
}

function TaxonomySelect({ value, onChange, id, label, includeNone = true }) {
  return (
    <select id={id} className="field-input" value={value || ""} onChange={(e) => onChange(e.target.value || null)} aria-label={label}>
      {includeNone && <option value="">Uncategorised</option>}
      {Ledger.GROUPS.map((g) => (
        <optgroup key={g.id} label={g.label}>
          {g.categories.map(([cid, clabel]) => <option key={cid} value={cid}>{clabel}</option>)}
        </optgroup>
      ))}
    </select>
  );
}

function CategoryMapEditor({ categories, categoryMap, setMapping }) {
  return (
    <div>
      <p style={{ margin: "0 0 10px", fontSize: 13, lineHeight: 1.5, color: INK2 }}>
        Each imported category counts toward one Budget-tab category, so plan vs actual works. Business categories default to
        "Not in budget" so they stay separate.
      </p>
      {Ledger.GROUPS.map((g) => (
        <div key={g.id} style={{ marginBottom: 10 }}>
          <div style={{ fontSize: 12.5, color: INK3, margin: "8px 0 4px" }}>
            <span className="swatch" style={{ background: SPEND_GROUP_COLORS[g.id] }} />
            {g.label}
          </div>
          {g.categories.map(([cid, clabel]) => (
            <div key={cid} className="map-row">
              <label htmlFor={`map-${cid}`} style={{ fontSize: 13.5, color: INK }}>{clabel}</label>
              <select id={`map-${cid}`} className="field-input" value={categoryMap[cid] || ""} onChange={(e) => setMapping(cid, e.target.value || null)}>
                <option value="">Not in budget</option>
                {categories.map((c) => <option key={c.id} value={c.id}>{c.name || "Unnamed"}</option>)}
              </select>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

// ---- Review bucket ----
function ReviewPanel({ ledger, setOverride, acceptProposed, dismissProposed }) {
  const rows = ledger.rows
    .filter((r) => Ledger.isSpend(r.transaction_type))
    .map((r) => ({ raw: r, e: Ledger.effective(r) }))
    .filter(({ raw, e }) => e.review_required || raw.proposed)
    .sort((a, b) => (a.e.transaction_date < b.e.transaction_date ? 1 : -1));
  const [all, setAll] = useState(false);
  if (!rows.length) return <div style={{ fontSize: 13.5, color: INK2 }}>✓ Nothing to review.</div>;
  const shown = all ? rows : rows.slice(0, 8);
  return (
    <div>
      <p style={{ margin: "0 0 10px", fontSize: 13, color: INK2, lineHeight: 1.5 }}>
        These are counted in your totals already. Confirm or fix each category; your choice is never overwritten by a later import.
      </p>
      {shown.map(({ raw, e }) => (
        <div key={raw.uid} className="review-item">
          <div style={{ display: "flex", gap: 10, alignItems: "baseline" }}>
            <span className="mono" style={{ fontSize: 12.5, color: INK3, width: 52, flexShrink: 0 }}>{shortDate(e.transaction_date)}</span>
            <span style={{ flex: 1, minWidth: 0, fontSize: 14, color: INK, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.merchant}</span>
            <span className="mono" style={{ fontSize: 14, color: INK }}>{fmtMinor(e.amount_minor)}</span>
          </div>
          {e.notes && <div style={{ fontSize: 12.5, color: "#FFC145", margin: "4px 0 0 62px" }}>{e.notes}</div>}
          {raw.proposed && (
            <div style={{ fontSize: 12.5, color: INK2, margin: "4px 0 0 62px" }}>
              A later import suggests <b style={{ color: INK }}>{catLabel(raw.proposed.category_id)}</b>.{" "}
              <button type="button" className="link-btn" style={{ padding: 0, minHeight: 0 }} onClick={() => acceptProposed(raw.uid)}>Use it</button>{" · "}
              <button type="button" className="link-btn" style={{ padding: 0, minHeight: 0 }} onClick={() => dismissProposed(raw.uid)}>Keep mine</button>
            </div>
          )}
          <div style={{ display: "flex", gap: 8, alignItems: "center", margin: "8px 0 0 62px", flexWrap: "wrap" }}>
            <div style={{ flex: "1 1 200px" }}>
              <TaxonomySelect value={e.category_id} label={`Category for ${e.merchant}`} onChange={(v) => setOverride(raw.uid, { category_id: v, reviewed: v !== null })} />
            </div>
            {e.review_required && e.category_id && (
              <button type="button" className="text-btn" onClick={() => setOverride(raw.uid, { reviewed: true })}>✓ Looks right</button>
            )}
          </div>
        </div>
      ))}
      {rows.length > 8 && <button type="button" className="link-btn" onClick={() => setAll(!all)}>{all ? "Show fewer" : `Show all ${rows.length}`}</button>}
    </div>
  );
}

// ---- Full transaction list ----
function LedgerTable({ ledger, monthKey, months, filter, setFilter, categoryMap, categories, setOverride, clearOverride }) {
  const [openId, setOpenId] = useState(null);
  const [scope, setScope] = useState("month");
  const [sort, setSort] = useState("date");
  const [limit, setLimit] = useState(150);
  const q = filter.search.trim().toLowerCase();
  const inScope = (m) => (scope === "month" ? m === monthKey : scope === "range" ? months.includes(m) : true);
  const batchById = useMemo(() => new Map(ledger.batches.map((b) => [b.id, b])), [ledger.batches]);

  let list = ledger.rows
    .map((r) => ({ raw: r, e: Ledger.effective(r) }))
    .filter(({ e }) => {
      if (!inScope(e.transaction_date.slice(0, 7))) return false;
      const spend = Ledger.isSpend(e.transaction_type);
      if (!filter.showAll && (!spend || e.status === "pending")) return false;
      if (filter.cat && (!spend || (e.category_id || Ledger.UNCAT) !== filter.cat)) return false;
      if (filter.budgetCat) {
        if (!spend || e.expense_type === "business") return false;
        const mapped = (e.category_id && categoryMap[e.category_id]) || UNCATEGORIZED;
        if (mapped !== filter.budgetCat) return false;
      }
      if (filter.reviewOnly && !e.review_required) return false;
      if (q && !`${e.merchant} ${e.raw_description} ${catLabel(e.category_id)}`.toLowerCase().includes(q)) return false;
      return true;
    });
  const cmp = {
    date: (a, b) => (a.e.transaction_date < b.e.transaction_date ? 1 : a.e.transaction_date > b.e.transaction_date ? -1 : 0),
    amount: (a, b) => b.e.amount_minor - a.e.amount_minor,
    merchant: (a, b) => a.e.merchant.localeCompare(b.e.merchant),
  }[sort];
  list = list.sort(cmp);
  const spendTotal = list.filter(({ e }) => Ledger.isSpend(e.transaction_type) && e.status === "posted").reduce((s, { e }) => s + e.amount_minor, 0);
  const active = filter.cat || filter.budgetCat || q || filter.reviewOnly;

  return (
    <div>
      <div className="ledger-filters">
        <input type="search" className="field-input" placeholder="Search merchant or description" value={filter.search} onChange={(e) => setFilter({ search: e.target.value })} aria-label="Search" />
        <select className="field-input" value={filter.cat || ""} onChange={(e) => setFilter({ cat: e.target.value || null })} aria-label="Filter by category">
          <option value="">All categories</option>
          <option value={Ledger.UNCAT}>Uncategorised</option>
          {Ledger.GROUPS.map((g) => (
            <optgroup key={g.id} label={g.label}>
              {g.categories.map(([cid, clabel]) => <option key={cid} value={cid}>{clabel}</option>)}
            </optgroup>
          ))}
        </select>
        <select className="field-input" value={sort} onChange={(e) => setSort(e.target.value)} aria-label="Sort">
          <option value="date">Newest first</option>
          <option value="amount">Largest first</option>
          <option value="merchant">Merchant A–Z</option>
        </select>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", margin: "10px 0 6px" }}>
        <div className="seg" role="group" aria-label="Period">
          {[["month", monthLabel(monthKey)], ["range", "Chart range"], ["all", "All time"]].map(([k, lbl]) => (
            <button key={k} type="button" aria-pressed={scope === k} onClick={() => setScope(k)}>{lbl}</button>
          ))}
        </div>
        <Toggle on={filter.reviewOnly} onClick={() => setFilter({ reviewOnly: !filter.reviewOnly })} label="Needs review" />
        <Toggle on={filter.showAll} onClick={() => setFilter({ showAll: !filter.showAll })} label="Pending & payments" />
      </div>
      <div style={{ fontSize: 13, color: INK2, margin: "6px 0" }}>
        {list.length} row{list.length === 1 ? "" : "s"} · posted spending <span className="mono" style={{ color: INK }}>{fmtMinor(spendTotal)}</span>
        {filter.budgetCat && <span className="badge" style={{ marginLeft: 8 }}>Budget: {filter.budgetCat === UNCATEGORIZED ? "not in plan" : categoryName(filter.budgetCat, categories)}</span>}
        {active && (
          <button type="button" className="link-btn" style={{ padding: "0 0 0 10px", minHeight: 0 }} onClick={() => setFilter({ cat: null, budgetCat: null, search: "", reviewOnly: false })}>
            Clear filters
          </button>
        )}
      </div>
      {list.length === 0 && <Empty>Nothing matches.</Empty>}
      {list.slice(0, limit).map(({ raw, e }) => {
        const open = openId === raw.uid;
        const spend = Ledger.isSpend(e.transaction_type);
        const acct = ledger.accounts[e.account_id];
        return (
          <div key={raw.uid} className={`tx-row${open ? " is-open" : ""}`} style={{ opacity: e.status === "pending" ? 0.7 : 1 }}>
            <button type="button" className="tx-main" onClick={() => setOpenId(open ? null : raw.uid)} aria-expanded={open}>
              <span className="tx-date mono">{shortDate(e.transaction_date)}</span>
              <span className="tx-text">
                <span className="tx-desc">{e.merchant}</span>
                <span className="tx-meta" style={{ color: INK3 }}>
                  {spend ? (
                    <>
                      <span className="swatch" style={{ background: catColor(e.category_id) }} />
                      {catLabel(e.category_id)}
                      {e.expense_type === "business" && " · business"}
                    </>
                  ) : (
                    <>{Ledger.TX_TYPE_LABEL[e.transaction_type]} · not spending</>
                  )}
                  {e.status === "pending" && " · pending"}
                  {e.review_required && <span style={{ color: "#FFC145" }}> · review</span>}
                  {raw.override && raw.override.category_id !== undefined && " · edited"}
                </span>
              </span>
              <span className="tx-amt mono" style={{ color: e.amount_minor < 0 ? GREEN : INK }}>{fmtMinor(e.amount_minor)}</span>
            </button>
            {open && (
              <div className="editor">
                <div className="detail-grid">
                  <span>Description</span><span className="mono">{e.raw_description}</span>
                  <span>Account</span><span>{acct ? acct.label : e.account_id}</span>
                  <span>Date</span>
                  <span>
                    {e.transaction_date}
                    {e.posting_date && ` (posted ${e.posting_date})`}
                    {e.date_basis !== "transaction_date" && <span style={{ color: INK3 }}> · {e.date_basis === "posting_date_fallback" ? "posting date used" : "statement date"}</span>}
                  </span>
                  <span>Status</span><span>{e.status}</span>
                  {spend && (<><span>Confidence</span><span>{e.classification_confidence}</span></>)}
                  {e.notes && (<><span>Notes</span><span style={{ color: "#FFC145" }}>{e.notes}</span></>)}
                  <span>Source</span>
                  <span>
                    {raw.sourceRefs.map((s, i) => {
                      const b = batchById.get(s.batchId);
                      const src = b && b.sources.find((x) => x.id === s.source_id);
                      return (
                        <div key={i}>
                          {src ? src.label : s.source_id} · row {s.row}{s.page ? `, page ${s.page}` : ""}
                          {b && <span style={{ color: INK3 }}> · {b.fileName || b.export_id}</span>}
                        </div>
                      );
                    })}
                  </span>
                </div>
                {spend && (
                  <div style={{ marginTop: 10 }}>
                    <label className="field-label" htmlFor={`cat-${raw.uid}`}>Category</label>
                    <TaxonomySelect id={`cat-${raw.uid}`} value={e.category_id} label="Category" onChange={(v) => setOverride(raw.uid, { category_id: v, reviewed: v !== null })} />
                    {raw.override && raw.override.category_id !== undefined && (
                      <button type="button" className="link-btn" onClick={() => clearOverride(raw.uid)}>
                        Reset to imported ({catLabel(raw.category_id)})
                      </button>
                    )}
                    {raw.proposed && <div style={{ fontSize: 12.5, color: INK2, marginTop: 6 }}>Latest import suggested: {catLabel(raw.proposed.category_id)}</div>}
                  </div>
                )}
                {raw.history.length > 0 && (
                  <div style={{ marginTop: 10, fontSize: 12.5, color: INK2 }}>
                    <div style={{ color: INK3, marginBottom: 2 }}>Changes from later imports</div>
                    {raw.history.map((h, i) => (
                      <div key={i} className="mono">
                        {h.at.slice(0, 10)} · {h.field}: {String(h.field === "amount_minor" ? fmtMinor(h.from) : h.from)} → {String(h.field === "amount_minor" ? fmtMinor(h.to) : h.to)}
                      </div>
                    ))}
                  </div>
                )}
                <button type="button" className="text-btn" style={{ marginTop: 12 }} onClick={() => setOpenId(null)}>Done</button>
              </div>
            )}
          </div>
        );
      })}
      {list.length > limit && <button type="button" className="link-btn" onClick={() => setLimit(limit + 150)}>Show more ({list.length - limit} left)</button>}
    </div>
  );
}

// ---- Import dialog: pick JSON -> validate -> preview -> commit atomically ----
function LedgerImportModal({ ledger, onApply, onClose }) {
  const [step, setStep] = useState("file");
  const [fileName, setFileName] = useState("");
  const [data, setData] = useState(null);
  const [check, setCheck] = useState(null);
  const [plan, setPlan] = useState(null);
  const [unlink, setUnlink] = useState(() => new Set());

  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const pick = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json,application/json";
    input.onchange = async (ev) => {
      const file = ev.target.files?.[0];
      if (!file) return;
      setFileName(file.name);
      setStep("checking");
      let parsed;
      try {
        parsed = JSON.parse(await file.text());
      } catch {
        setCheck({ ok: false, errors: ["This file isn't valid JSON."], warnings: [] });
        setStep("errors");
        return;
      }
      try {
        const v = await Ledger.validateExport(parsed);
        setCheck(v);
        if (!v.ok) {
          setStep("errors");
          return;
        }
        setData(parsed);
        setPlan(Ledger.planImport(ledger, parsed));
        setUnlink(new Set());
        setStep("preview");
      } catch (err) {
        setCheck({ ok: false, errors: [`Couldn't check this file: ${err && err.message ? err.message : err}`], warnings: [] });
        setStep("errors");
      }
    };
    input.click();
  };

  const rowById = useMemo(() => new Map(ledger.rows.map((r) => [r.uid, r])), [ledger]);
  const links = plan ? plan.items.filter((i) => i.kind === "pendingLink") : [];
  const changed = plan ? plan.items.filter((i) => i.kind === "changed") : [];
  const refused = plan ? plan.items.filter((i) => i.kind === "downgradeRefused") : [];
  const nothing = plan && plan.counts.new + plan.counts.changed + plan.counts.pendingLink === 0;
  const s = plan ? plan.summary : null;

  const commit = () => {
    const res = Ledger.applyImport(ledger, data, plan, { unlink, fileName });
    onApply(res, data);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" role="dialog" aria-modal="true" aria-label="Import spending" onClick={(e) => e.stopPropagation()}>
        <CornerBrackets />
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
          <div className="panel-title" style={{ margin: 0, flex: 1 }}>Import spending</div>
          <button type="button" className="icon-btn" onClick={onClose} aria-label="Close">✕</button>
        </div>
        <ol className="steps">
          <li aria-current={step === "file" || step === "checking" ? "step" : undefined}>Choose file</li>
          <li aria-current={step === "errors" ? "step" : undefined}>Check</li>
          <li aria-current={step === "preview" ? "step" : undefined}>Review & import</li>
        </ol>

        {(step === "file" || step === "checking") && (
          <div>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: "#B9C4D6", marginTop: 0 }}>
              Choose the <b>.json</b> export your import chat produced (schema v{Ledger.SCHEMA_VERSION}). It's checked line by line:
              structure, categories, every transaction ID, and the totals must add up exactly. Nothing is saved until you confirm, and
              nothing leaves this device.
            </p>
            <button type="button" className="text-btn primary" onClick={pick} disabled={step === "checking"}>
              {step === "checking" ? "Checking…" : "Choose JSON file"}
            </button>
          </div>
        )}

        {step === "errors" && check && (
          <div>
            <p style={{ color: RED, fontSize: 14, marginTop: 0 }}>✕ {fileName || "This file"} can't be imported. Nothing was changed.</p>
            <div className="review-list" style={{ padding: 10, fontSize: 13, lineHeight: 1.5 }}>
              {check.errors.map((e, i) => (
                <div key={i} style={{ marginBottom: 6, color: "#E7B4BE" }}>• {e}</div>
              ))}
            </div>
            <p style={{ fontSize: 13, color: INK2 }}>Ask the import chat to fix these and regenerate the file (IDs and totals must be computed with code, not typed).</p>
            <button type="button" className="text-btn" onClick={pick}>Choose another file</button>
          </div>
        )}

        {step === "preview" && plan && (
          <div>
            <div style={{ fontSize: 13.5, color: "#B9C4D6", lineHeight: 1.6 }}>
              <b style={{ color: INK }}>{fileName}</b> · {data.export_id}
              <br />
              {data.period.start} → {data.period.end} · {data.accounts.map((a) => a.label).join(", ")}
            </div>
            {plan.priorBatch && (
              <p style={{ fontSize: 13, color: "#FFC145" }}>
                An export with this ID was imported on {plan.priorBatch.importedAt.slice(0, 10)}. Rows already in your record are skipped.
              </p>
            )}
            <div className="nw-grid" style={{ margin: "12px 0" }}>
              {[
                ["New rows", plan.counts.new],
                ["Already imported", plan.counts.unchanged],
                ["Updated", plan.counts.changed],
                ["Pending → posted", plan.counts.pendingLink],
              ].map(([k, v]) => (
                <div key={k} className="nw-cell">
                  <div style={{ fontSize: 12, color: INK3 }}>{k}</div>
                  <div className="mono" style={{ fontSize: 18, color: INK }}>{v}</div>
                </div>
              ))}
            </div>
            <div className="detail-grid" style={{ fontSize: 13 }}>
              <span>Posted spending in file</span><span className="mono">{fmtMinor(s.posted_net_expense_minor)} (personal {fmtMinor(s.posted_personal_minor)}, business {fmtMinor(s.posted_business_minor)}{s.posted_unallocated_minor ? `, unallocated ${fmtMinor(s.posted_unallocated_minor)}` : ""})</span>
              <span>Pending (not counted)</span><span className="mono">{fmtMinor(s.pending_net_expense_minor)}</span>
              <span>Payments & other non-spending</span><span className="mono">{fmtMinor(s.non_spending_net_minor)}</span>
              <span>Flagged for review</span><span className="mono">{s.review_count}</span>
            </div>

            {links.length > 0 && (
              <div style={{ marginTop: 14 }}>
                <div style={{ fontSize: 13, color: INK, marginBottom: 6 }}>These look like earlier pending charges that have now posted. Untick any that aren't the same purchase.</div>
                <div className="review-list">
                  {links.map((it) => {
                    const old = rowById.get(it.existingUid);
                    const off = unlink.has(it.index);
                    return (
                      <label key={it.index} className={`review-row${off ? " is-off" : ""}`}>
                        <input
                          type="checkbox"
                          checked={!off}
                          onChange={() => setUnlink((u) => {
                            const n = new Set(u);
                            if (n.has(it.index)) n.delete(it.index);
                            else n.add(it.index);
                            return n;
                          })}
                        />
                        <span style={{ fontSize: 13 }}>
                          {old.merchant} {fmtMinor(old.amount_minor)} on {old.transaction_date} (pending)
                          <br />→ {it.incoming.merchant} {fmtMinor(it.incoming.amount_minor)} on {it.incoming.transaction_date} (posted)
                        </span>
                      </label>
                    );
                  })}
                </div>
              </div>
            )}

            {changed.length > 0 && (
              <details style={{ marginTop: 12, fontSize: 13, color: "#B9C4D6" }}>
                <summary style={{ cursor: "pointer" }}>{changed.length} existing row{changed.length === 1 ? "" : "s"} will be updated{plan.counts.conflicts ? ` (${plan.counts.conflicts} keep your category)` : ""}</summary>
                {changed.slice(0, 40).map((it) => (
                  <div key={it.index} style={{ margin: "6px 0" }}>
                    {it.incoming.merchant} {it.incoming.transaction_date}:{" "}
                    {it.changes.map((c) => `${c.field} ${c.field === "amount_minor" ? fmtMinor(c.from) : c.from} → ${c.field === "amount_minor" ? fmtMinor(c.to) : c.to}`).join("; ") || "review flag"}
                    {it.conflict && " · your category kept; suggestion saved"}
                  </div>
                ))}
              </details>
            )}
            {refused.length > 0 && (
              <p style={{ fontSize: 13, color: "#FFC145" }}>
                {refused.length} row{refused.length === 1 ? " is" : "s are"} already posted here but pending in this file — kept as posted.
              </p>
            )}
            {data.reconciliation.coverage_notes.length > 0 && (
              <details style={{ marginTop: 12, fontSize: 13, color: "#B9C4D6" }}>
                <summary style={{ cursor: "pointer" }}>Coverage notes from the export</summary>
                <ul style={{ margin: "6px 0", paddingLeft: 18 }}>
                  {data.reconciliation.coverage_notes.map((n, i) => <li key={i}>{n}</li>)}
                  {data.sources.map((src) => <li key={src.id}>{src.label}: {src.first_date || "?"} → {src.last_date || "?"}. {src.coverage_notes}</li>)}
                </ul>
              </details>
            )}
            <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
              {nothing ? (
                <button type="button" className="text-btn primary" onClick={onClose}>Nothing new — close</button>
              ) : (
                <button type="button" className="text-btn primary" onClick={commit}>
                  Import {plan.counts.new + unlink.size} new{plan.counts.changed + plan.counts.pendingLink - unlink.size > 0 ? ` · update ${plan.counts.changed + plan.counts.pendingLink - unlink.size}` : ""}
                </button>
              )}
              <button type="button" className="text-btn" onClick={onClose}>Cancel</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ---- Spending over time: running total for a month/period, vs a comparison period ----
const OT_MAIN = "#338ced";
const OT_COMPARE = "#e76624";
const OT_LENGTHS = [[1, "1 mo"], [3, "3 mo"], [6, "6 mo"], [12, "12 mo"]];

const periodName = (end, len) => (len === 1 ? monthLabel(end) : `${shortMonth(Ledger.addMonths(end, -(len - 1)))} – ${shortMonth(end)}`);
const niceDate = (iso) => new Date(`${iso}T12:00:00`).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" });

// One period's running total, plus the index range we actually have data for
// (days before the first import or after the last one aren't drawn).
function buildPeriod(rows, end, len, cov, today) {
  const b = Ledger.periodBounds(end, len);
  const s = Ledger.dailySeries(rows, b.start, b.end);
  const first = cov ? (cov.start > b.start ? cov.start : b.start) : null;
  let last = cov ? (cov.end < b.end ? cov.end : b.end) : null;
  if (last && today < last) last = today;
  const vs = first ? s.dates.indexOf(first) : -1;
  const ve = last ? s.dates.indexOf(last) : -1;
  return { ...s, end, len, start: b.start, vs, ve, ok: vs >= 0 && ve >= vs };
}

function SpendOverTime({ rows, ledger, monthKey, dataMonths }) {
  const [len, setLen] = useState(1);
  const [end, setEnd] = useState(monthKey);
  const [mode, setMode] = useState("prev"); // prev | year | custom | none
  const [customEnd, setCustomEnd] = useState(null);
  const [hoverI, setHoverI] = useState(null);
  const [ref, width] = useElementWidth();
  useEffect(() => setEnd(monthKey), [monthKey]);

  const today = todayISO();
  const cov = useMemo(() => Ledger.coverage(ledger), [ledger]);
  const main = useMemo(() => buildPeriod(rows, end, len, cov, today), [rows, end, len, cov, today]);
  const cmpEnd = mode === "prev" ? Ledger.addMonths(end, -len) : mode === "year" ? Ledger.addMonths(end, -12) : mode === "custom" ? customEnd || Ledger.addMonths(end, -len) : null;
  const cmp = useMemo(() => (cmpEnd ? buildPeriod(rows, cmpEnd, len, cov, today) : null), [rows, cmpEnd, len, cov, today]);
  const monthOpts = dataMonths.slice().reverse();

  const W = Math.max(300, width);
  const H = 280;
  const PADL = 54, PADR = W < 520 ? 12 : 120, PADT = 14, PADB = 30;
  const N = Math.max(main.dates.length, cmp ? cmp.dates.length : 0);
  const x = d3.scaleLinear().domain([0, Math.max(1, N - 1)]).range([PADL, W - PADR]);
  const visMax = (p) => (p && p.ok ? Math.max(0, ...p.cumulative.slice(p.vs, p.ve + 1)) : 0);
  const y = d3.scaleLinear().domain([0, Math.max(100, visMax(main), visMax(cmp)) * 1.06]).nice(4).range([H - PADB, PADT]);
  const pathFor = (p) => {
    if (!p || !p.ok) return null;
    let d = "";
    for (let i = p.vs; i <= p.ve; i++) d += `${i === p.vs ? "M" : "L"}${x(i).toFixed(1)},${y(p.cumulative[i]).toFixed(1)}`;
    return d;
  };

  // X ticks: days of the month for 1-month views; month starts for longer periods.
  const ticks = [];
  if (len === 1) {
    for (const d of [1, 8, 15, 22, 29]) if (d - 1 < N) ticks.push({ i: d - 1, label: String(d) });
  } else {
    const step = len >= 12 ? (W < 520 ? 3 : 2) : len >= 6 && W < 520 ? 2 : 1;
    let monthIndex = 0;
    main.dates.forEach((iso, i) => {
      if (!iso.endsWith("-01")) return;
      if (monthIndex % step === 0) ticks.push({ i, label: shortMonth(iso.slice(0, 7)) });
      monthIndex++;
    });
  }

  // Comparing at the same point: the compare total on the same day of the period as main's last day.
  const at = main.ok ? main.ve : -1;
  const mainNow = main.ok ? main.cumulative[at] : 0;
  const cmpSame = cmp && cmp.ok && at >= cmp.vs ? cmp.cumulative[Math.min(at, cmp.ve)] : null;
  const cmpFull = cmp && cmp.ok ? cmp.cumulative[cmp.ve] : null;
  const diff = cmpSame !== null ? mainNow - cmpSame : null;
  const mainComplete = main.ok && main.ve === main.dates.length - 1 && main.vs === 0;

  // End-of-line labels, nudged apart if they'd overlap.
  const endLabels = [];
  if (PADR > 60) {
    if (main.ok) endLabels.push({ key: "m", x: x(main.ve), y: y(main.cumulative[main.ve]), color: OT_MAIN, text: fmtMinor0(main.cumulative[main.ve]), sub: periodName(main.end, len) });
    if (cmp && cmp.ok) endLabels.push({ key: "c", x: x(cmp.ve), y: y(cmp.cumulative[cmp.ve]), color: OT_COMPARE, text: fmtMinor0(cmp.cumulative[cmp.ve]), sub: periodName(cmp.end, len) });
    if (endLabels.length === 2 && Math.abs(endLabels[0].y - endLabels[1].y) < 30) {
      const [hi, lo] = endLabels[0].y <= endLabels[1].y ? [endLabels[0], endLabels[1]] : [endLabels[1], endLabels[0]];
      const mid = (hi.y + lo.y) / 2;
      hi.y = mid - 15;
      lo.y = mid + 15;
    }
  }

  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const mx = ((e.clientX - rect.left) / rect.width) * W;
    setHoverI(Math.max(0, Math.min(N - 1, Math.round(x.invert(mx)))));
  };
  const hv = (p) => (p && p.ok && hoverI !== null && hoverI >= p.vs && hoverI <= Math.min(p.ve, p.dates.length - 1) ? p.cumulative[hoverI] : null);
  const hMain = hv(main);
  const hCmp = hv(cmp);
  const tipLeft = hoverI !== null ? Math.min(Math.max(0, x(hoverI) + 12), W - 232) : 0;

  return (
    <div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center", marginBottom: 8 }}>
        <div className="seg" role="group" aria-label="Period length">
          {OT_LENGTHS.map(([v, lbl]) => (
            <button key={v} type="button" aria-pressed={len === v} onClick={() => setLen(v)}>{lbl}</button>
          ))}
        </div>
        <label style={{ fontSize: 13, color: INK2, display: "flex", alignItems: "center", gap: 6 }}>
          <span className="swatch" style={{ background: OT_MAIN }} />
          {len === 1 ? "Month" : "Ending"}
          <select className="field-input" style={{ width: "auto" }} value={end} onChange={(e) => setEnd(e.target.value)}>
            {!monthOpts.includes(end) && <option value={end}>{monthLabel(end)}</option>}
            {monthOpts.map((m) => <option key={m} value={m}>{monthLabel(m)}</option>)}
          </select>
        </label>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center", marginBottom: 10 }}>
        <label style={{ fontSize: 13, color: INK2, display: "flex", alignItems: "center", gap: 6 }}>
          <span className="swatch" style={{ background: OT_COMPARE, opacity: 0.6 }} />
          Compare with
          <select className="field-input" style={{ width: "auto" }} value={mode} onChange={(e) => setMode(e.target.value)}>
            <option value="prev">Previous {len === 1 ? "month" : `${len} months`}</option>
            <option value="year">Same {len === 1 ? "month" : "period"} last year</option>
            <option value="custom">Choose {len === 1 ? "a month" : "a period"}…</option>
            <option value="none">No comparison</option>
          </select>
        </label>
        {mode === "custom" && (
          <select className="field-input" style={{ width: "auto" }} value={customEnd || cmpEnd} onChange={(e) => setCustomEnd(e.target.value)} aria-label={len === 1 ? "Comparison month" : "Comparison period ending"}>
            {!monthOpts.includes(customEnd || cmpEnd) && <option value={customEnd || cmpEnd}>{periodName(customEnd || cmpEnd, len)}</option>}
            {monthOpts.map((m) => <option key={m} value={m}>{periodName(m, len)}</option>)}
          </select>
        )}
      </div>

      <div style={{ fontSize: 14, color: INK, marginBottom: 6, lineHeight: 1.5 }}>
        {main.ok ? (
          <>
            <b>{periodName(main.end, len)}</b>: <span className="mono">{fmtMinor0(mainNow)}</span>
            {!mainComplete && (
              <span style={{ color: "#FFC145" }}>
                {" "}(imports cover {main.vs > 0 ? `from ${niceDate(main.dates[main.vs])}` : ""}
                {main.vs > 0 && main.ve < main.dates.length - 1 ? " " : ""}
                {main.ve < main.dates.length - 1 ? `to ${niceDate(main.dates[main.ve])}` : ""})
              </span>
            )}
            {cmp && cmp.ok && cmpSame !== null && (
              <>
                {" · "}
                <span style={{ color: INK2 }}>{periodName(cmp.end, len)}</span> at the same point <span className="mono">{fmtMinor0(cmpSame)}</span>
                <span className="mono" style={{ color: "#B9C4D6" }}>
                  {" "}({diff >= 0 ? "▲ +" : "▼ −"}{fmtMinor0(Math.abs(diff))}{cmpSame > 0 ? `, ${diff >= 0 ? "+" : "−"}${Math.round((Math.abs(diff) / cmpSame) * 100)}%` : ""})
                </span>
                {cmpFull !== cmpSame && <span style={{ color: INK3 }}>, {fmtMinor0(cmpFull)} by the end</span>}
              </>
            )}
            {cmp && !cmp.ok && <span style={{ color: INK3 }}> · no imported data for {periodName(cmp.end, len)}</span>}
          </>
        ) : (
          <span style={{ color: INK3 }}>No imported data covers {periodName(end, len)}.</span>
        )}
      </div>

      <div ref={ref} style={{ position: "relative", width: "100%" }}>
        <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} style={{ display: "block", maxWidth: "100%", touchAction: "pan-y" }} role="img" aria-label={`Running total of spending, ${periodName(end, len)}${cmp ? ` compared with ${periodName(cmp.end, len)}` : ""}`}>
          {y.ticks(4).map((v) => (
            <g key={v}>
              <line x1={PADL} x2={W - PADR} y1={y(v)} y2={y(v)} stroke="rgba(51,214,255,0.10)" />
              <text x={PADL - 8} y={y(v) + 4} textAnchor="end" fontSize={11.5} fill={INK3} fontFamily="'JetBrains Mono', monospace">{fmtAxisDollars(v / 100)}</text>
            </g>
          ))}
          {ticks.map((t) => (
            <text key={t.i} x={x(t.i)} y={H - PADB + 18} textAnchor="middle" fontSize={11.5} fill={INK3} fontFamily="'JetBrains Mono', monospace">{t.label}</text>
          ))}
          <line x1={PADL} x2={W - PADR} y1={y(0)} y2={y(0)} stroke="rgba(51,214,255,0.3)" />
          {cmp && pathFor(cmp) && <path d={pathFor(cmp)} fill="none" stroke={OT_COMPARE} strokeOpacity={0.55} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />}
          {pathFor(main) && <path d={pathFor(main)} fill="none" stroke={OT_MAIN} strokeWidth={2.5} strokeLinejoin="round" strokeLinecap="round" />}
          {cmp && cmp.ok && <circle cx={x(cmp.ve)} cy={y(cmp.cumulative[cmp.ve])} r={4} fill={OT_COMPARE} fillOpacity={0.55} stroke="#05070A" strokeWidth={2} />}
          {main.ok && <circle cx={x(main.ve)} cy={y(main.cumulative[main.ve])} r={4.5} fill={OT_MAIN} stroke="#05070A" strokeWidth={2} />}
          {endLabels.map((l) => (
            <g key={l.key}>
              <text x={l.x + 10} y={l.y - 1} fontSize={12.5} fill={INK} fontFamily="'JetBrains Mono', monospace">{l.text}</text>
              <text x={l.x + 10} y={l.y + 13} fontSize={11} fill={INK3}>{l.sub}</text>
            </g>
          ))}
          {hoverI !== null && (
            <g pointerEvents="none">
              <line x1={x(hoverI)} x2={x(hoverI)} y1={PADT} y2={H - PADB} stroke={INK2} strokeOpacity={0.5} />
              {hCmp !== null && <circle cx={x(hoverI)} cy={y(hCmp)} r={4} fill={OT_COMPARE} fillOpacity={0.7} stroke="#05070A" strokeWidth={2} />}
              {hMain !== null && <circle cx={x(hoverI)} cy={y(hMain)} r={4.5} fill={OT_MAIN} stroke="#05070A" strokeWidth={2} />}
            </g>
          )}
          <rect x={PADL} y={PADT} width={Math.max(0, W - PADR - PADL)} height={H - PADB - PADT} fill="transparent" onPointerMove={onMove} onPointerDown={onMove} onPointerLeave={() => setHoverI(null)} />
        </svg>
        {hoverI !== null && (hMain !== null || hCmp !== null) && (
          <div className="chart-tip" style={{ left: tipLeft, top: PADT, width: 220 }}>
            <div style={{ color: INK3, marginBottom: 4 }}>Day {hoverI + 1} of the {len === 1 ? "month" : "period"}</div>
            <div className="tip-row">
              <span><span className="swatch" style={{ background: OT_MAIN }} />{main.dates[hoverI] ? niceDate(main.dates[hoverI]) : "—"}</span>
              <span className="mono">{hMain !== null ? fmtMinor0(hMain) : "no data"}</span>
            </div>
            {cmp && (
              <div className="tip-row">
                <span><span className="swatch" style={{ background: OT_COMPARE, opacity: 0.6 }} />{cmp.dates[hoverI] ? niceDate(cmp.dates[hoverI]) : "—"}</span>
                <span className="mono">{hCmp !== null ? fmtMinor0(hCmp) : "no data"}</span>
              </div>
            )}
            {hMain !== null && hCmp !== null && (
              <div className="tip-row" style={{ borderTop: "1px solid rgba(51,214,255,0.2)", marginTop: 4, paddingTop: 4 }}>
                <span>Difference</span>
                <span className="mono">{hMain - hCmp >= 0 ? "+" : "−"}{fmtMinor0(Math.abs(hMain - hCmp))}</span>
              </div>
            )}
            {main.dates[hoverI] && (main.daily[hoverI] || 0) !== 0 && hMain !== null && (
              <div style={{ color: INK3, fontSize: 12, marginTop: 4 }}>Spent that day: {fmtMinor0(main.daily[hoverI])}</div>
            )}
          </div>
        )}
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: "6px 16px", marginTop: 8, fontSize: 12.5, color: INK2 }}>
        <span><span className="swatch" style={{ background: OT_MAIN }} />{periodName(end, len)}</span>
        {cmp && <span><span className="swatch" style={{ background: OT_COMPARE, opacity: 0.6 }} />{periodName(cmp.end, len)} (comparison)</span>}
        <span style={{ color: INK3 }}>Running total of posted spending; lines stop where your imports stop.</span>
      </div>
    </div>
  );
}

function SpendingIntro({ onImport }) {
  return (
    <div className="panel fade-up" style={{ marginBottom: 18 }}>
      <CornerBrackets />
      <div className="panel-title">Build your spending record</div>
      <ol style={{ margin: "0 0 14px", paddingLeft: 20, fontSize: 14, lineHeight: 1.7, color: "#B9C4D6" }}>
        <li>Give your statements to your import chat (it uses the files in <span className="mono">import-spec/</span>).</li>
        <li>Download the <span className="mono">.json</span> export it produces. Keep it out of this project folder, or in <span className="mono">private/</span>.</li>
        <li>Import it here. Every month, repeat — overlaps and re-imports are handled automatically.</li>
      </ol>
      <button type="button" className="text-btn primary" onClick={onImport}>⬆ Import JSON</button>
      <p style={{ margin: "12px 0 0", fontSize: 12.5, color: INK3 }}>Imported data stays in this browser only. It is never uploaded or sent anywhere.</p>
    </div>
  );
}

function SpendingPage({ ledger, setLedger, categories, categoryMap, setMapping, budgetTx, share, saveStatus }) {
  const today = todayISO();
  const spendMonths = useMemo(
    () => [...new Set(ledger.rows.filter((r) => Ledger.isSpend(r.transaction_type)).map((r) => r.transaction_date.slice(0, 7)))].sort(),
    [ledger]
  );
  // Open on the newest month with posted spending (a month with only pending charges would read $0).
  const latestPosted = useMemo(() => {
    let m = null;
    for (const r of ledger.rows) if (Ledger.isSpend(r.transaction_type) && r.status === "posted" && (!m || r.transaction_date > m)) m = r.transaction_date;
    return m ? m.slice(0, 7) : null;
  }, [ledger]);
  const latest = latestPosted || spendMonths[spendMonths.length - 1] || currentMonthKey();
  const [monthKey, setMonthKey] = useState(latest);
  const [range, setRange] = useState(6);
  const [expenseType, setExpenseType] = useState("all");
  const [account, setAccount] = useState("all");
  const [filter, setFilterState] = useState({ cat: null, budgetCat: null, search: "", reviewOnly: false, showAll: false });
  const setFilter = (patch) => setFilterState((f) => ({ ...f, ...patch }));
  const [importing, setImporting] = useState(false);
  const [toast, setToast] = useState(null);
  const listRef = useRef(null);

  const partial = useMemo(() => Ledger.partialMonths(ledger, today), [ledger, today]);
  const accountIds = Object.keys(ledger.accounts);
  const posted = useMemo(
    () => Ledger.spendRows(ledger, { status: "posted", accounts: account === "all" ? null : new Set([account]), expenseType }),
    [ledger, account, expenseType]
  );
  const pendingRows = useMemo(
    () => Ledger.spendRows(ledger, { status: "pending", accounts: account === "all" ? null : new Set([account]), expenseType }),
    [ledger, account, expenseType]
  );
  const byMonth = useMemo(() => Ledger.monthBreakdown(posted), [posted]);
  const pendingByMonth = useMemo(() => Ledger.monthBreakdown(pendingRows), [pendingRows]);
  const first = spendMonths[0] || monthKey;
  // Chart range ends at the selected month and never starts before the first imported month.
  const months = useMemo(() => {
    const start = range === 0 ? first : shiftMonth(monthKey, -(range - 1));
    const from = start < first ? first : start;
    return monthList(from <= monthKey ? from : monthKey, monthKey);
  }, [range, first, monthKey]);
  const rangeRows = useMemo(() => posted.filter((r) => months.includes(r.transaction_date.slice(0, 7))), [posted, months]);
  const reviewCount = useMemo(() => ledger.rows.filter((r) => Ledger.isSpend(r.transaction_type) && (Ledger.effective(r).review_required || r.proposed)).length, [ledger]);

  const cur = byMonth[monthKey] || EMPTY_MONTH;
  const prevKey = shiftMonth(monthKey, -1);
  const prev = byMonth[prevKey] || null;
  const prior3 = [1, 2, 3].map((i) => shiftMonth(monthKey, -i));
  const avg3 = fullMonthAverage(prior3, byMonth, partial);
  const avgByCat = useMemo(() => {
    const full = prior3.filter((m) => !partial.has(m) && byMonth[m]);
    if (!full.length) return null;
    const o = {};
    for (const m of full) for (const [c, v] of Object.entries(byMonth[m].byCategory)) o[c] = (o[c] || 0) + v / full.length;
    return o;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [byMonth, partial, monthKey]);
  const pendingNow = pendingByMonth[monthKey] ? pendingByMonth[monthKey].total : 0;
  const budgetStats = useMemo(() => monthStats(budgetTx, categories, monthKey, share), [budgetTx, categories, monthKey, share]);

  const updateRow = (uid, fn) => setLedger((l) => ({ ...l, rows: l.rows.map((r) => (r.uid === uid ? fn(r) : r)) }));
  const setOverride = (uid, patch) => updateRow(uid, (r) => ({ ...r, override: { ...(r.override || {}), ...patch, at: new Date().toISOString() } }));
  const clearOverride = (uid) => updateRow(uid, (r) => ({ ...r, override: null }));
  const acceptProposed = (uid) => updateRow(uid, (r) => ({ ...r, override: { ...(r.override || {}), category_id: r.proposed.category_id, reviewed: true, at: new Date().toISOString() }, proposed: null }));
  const dismissProposed = (uid) => updateRow(uid, (r) => ({ ...r, proposed: null }));

  const showInList = (patch) => {
    setFilter({ cat: null, budgetCat: null, search: "", reviewOnly: false, ...patch });
    setTimeout(() => listRef.current && listRef.current.scrollIntoView({ behavior: "smooth", block: "start" }), 50);
  };

  const onApply = (res, data) => {
    const before = ledger;
    setLedger(res.ledger);
    setImporting(false);
    const ms = data.transactions.filter((t) => Ledger.isSpend(t.transaction_type) && t.status === "posted").map((t) => t.transaction_date.slice(0, 7)).sort();
    if (ms.length) setMonthKey(ms[ms.length - 1]);
    const c = res.counts;
    const parts = [`${c.new} new`, c.changed && `${c.changed} updated`, c.linked && `${c.linked} pending→posted`, c.unchanged && `${c.unchanged} already had`].filter(Boolean);
    setToast({ text: `Imported: ${parts.join(", ")}.`, undo: () => setLedger(before) });
  };

  const hasData = ledger.rows.length > 0;
  const isPartial = partial.has(monthKey);

  return (
    <div className="page-fade" style={{ maxWidth: 1120, margin: "0 auto", position: "relative" }}>
      <PageHeader
        eyebrow="Spending"
        saveStatus={saveStatus}
        title={
          hasData ? (
            <>
              <span style={{ color: ACCENT }}>{fmt(cur.total / 100)}</span> spent in {monthLabel(monthKey)}
            </>
          ) : (
            "Your spending record"
          )
        }
        subtitle={
          hasData
            ? `Posted purchases minus refunds${expenseType !== "all" ? ` (${expenseType} only)` : ""}: personal ${fmtMinor0(cur.personal)}, business ${fmtMinor0(cur.business)}${cur.unallocated ? `, unallocated ${fmtMinor0(cur.unallocated)}` : ""}. Card payments aren't spending and pending charges aren't counted until they post.`
            : "Import the monthly JSON export from your import chat to see every month, category and merchant."
        }
      />

      {!hasData && <SpendingIntro onImport={() => setImporting(true)} />}

      {hasData && (
        <>
          <div className="month-bar fade-up">
            <button type="button" className="icon-btn" onClick={() => setMonthKey((k) => shiftMonth(k, -1))} aria-label="Previous month">‹</button>
            <span style={{ fontSize: 16, fontWeight: 600, minWidth: 150, textAlign: "center" }}>{monthLabel(monthKey)}</span>
            <button type="button" className="icon-btn" onClick={() => setMonthKey((k) => shiftMonth(k, 1))} aria-label="Next month">›</button>
            {monthKey !== latest && <button type="button" className="link-btn" style={{ padding: 0 }} onClick={() => setMonthKey(latest)}>Latest</button>}
            <PartialBadge show={isPartial} />
            <button type="button" className="text-btn primary" onClick={() => setImporting(true)} style={{ marginLeft: "auto" }}>⬆ Import JSON</button>
          </div>

          <div className="spend-filters fade-up">
            <div className="seg" role="group" aria-label="Chart range">
              {[[3, "3 mo"], [6, "6 mo"], [12, "12 mo"], [0, "All"]].map(([v, lbl]) => (
                <button key={v} type="button" aria-pressed={range === v} onClick={() => setRange(v)}>{lbl}</button>
              ))}
            </div>
            <div className="seg" role="group" aria-label="Personal or business">
              {[["all", "All"], ["personal", "Personal"], ["business", "Business"]].map(([v, lbl]) => (
                <button key={v} type="button" aria-pressed={expenseType === v} onClick={() => setExpenseType(v)}>{lbl}</button>
              ))}
            </div>
            {accountIds.length > 1 && (
              <select className="field-input" style={{ width: "auto" }} value={account} onChange={(e) => setAccount(e.target.value)} aria-label="Account">
                <option value="all">All accounts</option>
                {accountIds.map((id) => <option key={id} value={id}>{ledger.accounts[id].label || id}</option>)}
              </select>
            )}
          </div>

          <div className="stat-row fade-up">
            <Stat label="Posted this month" value={fmtMinor0(cur.total)} sub={`${cur.count} purchase${cur.count === 1 ? "" : "s"}${isPartial ? " · partial" : ""}`} subColor={isPartial ? "#FFC145" : undefined} />
            <Stat label="vs last month" value={prev ? `${cur.total >= prev.total ? "+" : "−"}${fmtMinor0(Math.abs(cur.total - prev.total))}` : "—"} sub={prev ? `${monthLabel(prevKey)}: ${fmtMinor0(prev.total)}${partial.has(prevKey) ? " (partial)" : ""}` : "no data"} />
            <Stat label="vs 3-month avg" value={avg3 !== null ? `${cur.total >= avg3 ? "+" : "−"}${fmtMinor0(Math.abs(cur.total - avg3))}` : "—"} sub={avg3 !== null ? `avg ${fmtMinor0(avg3)} (full months)` : "needs a full prior month"} />
            <Stat label="Pending" value={fmtMinor0(pendingNow)} sub="not counted yet" />
            <Stat label="Needs review" value={String(reviewCount)} sub={reviewCount ? "see below" : "all clear"} subColor={reviewCount ? "#FFC145" : undefined} />
          </div>

          <div className="panel fade-up" style={{ marginBottom: 18 }}>
            <CornerBrackets />
            <div className="panel-title">Monthly spending</div>
            <div style={{ fontSize: 12.5, color: INK3, marginBottom: 8 }}>Tap a month to select it. The dashed line averages complete months only.</div>
            <SpendTrendChart months={months} byMonth={byMonth} pendingByMonth={pendingByMonth} partial={partial} selected={monthKey} onSelect={setMonthKey} />
          </div>

          <div className="panel fade-up" style={{ marginBottom: 18 }}>
            <CornerBrackets />
            <div className="panel-title">Spending over time</div>
            <SpendOverTime rows={posted} ledger={ledger} monthKey={monthKey} dataMonths={spendMonths} />
          </div>

          <div className="spend-grid">
            <div className="panel fade-up">
              <CornerBrackets />
              <div className="panel-title">Where it went in {monthLabel(monthKey)}</div>
              <CategoryBreakdown monthKey={monthKey} cur={cur} prev={prev} avgByCat={avgByCat} activeCat={filter.cat} onPick={(id) => (id ? showInList({ cat: id }) : setFilter({ cat: null }))} />
            </div>
            <div className="panel fade-up">
              <CornerBrackets />
              <div className="panel-title">Compare months</div>
              <MonthCompare dataMonths={spendMonths} byMonth={byMonth} partial={partial} defaultA={spendMonths.includes(prevKey) ? prevKey : spendMonths[0]} defaultB={monthKey} />
            </div>
          </div>

          <div className="panel fade-up" style={{ marginBottom: 18 }}>
            <CornerBrackets />
            <div className="panel-title">Category trends · {monthLabel(months[0])} – {monthLabel(monthKey)}</div>
            <div style={{ fontSize: 12.5, color: INK3, marginBottom: 10 }}>Hollow points are partial months. Tap a category to list its purchases.</div>
            <CategoryTrends months={months} byMonth={byMonth} partial={partial} onPick={(id) => showInList({ cat: id })} />
          </div>

          <div className="spend-grid">
            <div className="panel fade-up">
              <CornerBrackets />
              <div className="panel-title">Top merchants · chart range</div>
              <TopMerchants rows={rangeRows} onSearch={(m) => showInList({ search: m })} />
            </div>
            <div className="panel fade-up">
              <CornerBrackets />
              <div className="panel-title">Needs review ({reviewCount})</div>
              <ReviewPanel ledger={ledger} setOverride={setOverride} acceptProposed={acceptProposed} dismissProposed={dismissProposed} />
            </div>
          </div>

          <MonthProgress stats={budgetStats} monthKey={monthKey} onPick={(id) => (id ? showInList({ budgetCat: id }) : setFilter({ budgetCat: null }))} activeId={filter.budgetCat} />
          <details className="panel fade-up" style={{ marginBottom: 18 }}>
            <summary style={{ cursor: "pointer", fontSize: 15, fontWeight: 600, color: INK }}>Link imported categories to your budget</summary>
            <div style={{ marginTop: 12 }}>
              <CategoryMapEditor categories={categories} categoryMap={categoryMap} setMapping={setMapping} />
            </div>
          </details>

          <div className="panel fade-up" ref={listRef} style={{ marginBottom: 18, scrollMarginTop: 16 }}>
            <CornerBrackets />
            <div className="panel-title">Transactions</div>
            <LedgerTable
              ledger={ledger}
              monthKey={monthKey}
              months={months}
              filter={filter}
              setFilter={setFilter}
              categoryMap={categoryMap}
              categories={categories}
              setOverride={setOverride}
              clearOverride={clearOverride}
            />
          </div>

          <details className="panel fade-up" style={{ marginBottom: 18 }}>
            <summary style={{ cursor: "pointer", fontSize: 15, fontWeight: 600, color: INK }}>Import history ({ledger.batches.length})</summary>
            <div style={{ marginTop: 10 }}>
              {[...ledger.batches].reverse().map((b) => (
                <div key={b.id} style={{ padding: "8px 0", borderBottom: "1px solid rgba(51,214,255,0.08)", fontSize: 13, color: "#B9C4D6" }}>
                  <span className="mono" style={{ color: INK3 }}>{b.importedAt.slice(0, 10)}</span> · {b.fileName || b.export_id} · {b.period.start} → {b.period.end}
                  <div style={{ color: INK3, fontSize: 12.5 }}>
                    {b.counts.new} new · {b.counts.changed} updated · {b.counts.linked} pending→posted · {b.counts.unchanged} already had
                  </div>
                </div>
              ))}
            </div>
          </details>
        </>
      )}

      {importing && <LedgerImportModal ledger={ledger} onApply={onApply} onClose={() => setImporting(false)} />}
      <UndoToast
        toast={toast}
        onUndo={() => {
          toast.undo();
          setToast(null);
        }}
        onClose={() => setToast(null)}
      />
    </div>
  );
}

// ---- Home: this month at a glance ----

function OverviewPage({ transactions, hasLedger, categories, share, budget, goTo, saveStatus }) {
  const key = currentMonthKey();
  const stats = useMemo(() => monthStats(transactions, categories, key, share), [transactions, categories, key, share]);
  const daysLeft = daysInMonth(key) - new Date().getDate() + 1; // including today
  const perDay = stats.leftMonthly > 0 ? stats.leftMonthly / daysLeft : 0;
  const attention = stats.rows
    .map((r) => ({ ...r, status: paceStatus(r, stats.elapsed, key) }))
    .filter((r) => r.status !== "ok")
    .sort((a, b) => (a.status === b.status ? b.spent / (b.planned || 1) - a.spent / (a.planned || 1) : a.status === "over" ? -1 : 1))
    .slice(0, 5);
  const recent = [...transactions].sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0)).slice(0, 5);

  return (
    <div className="page-fade" style={{ maxWidth: 1120, margin: "0 auto", position: "relative" }}>
      <PageHeader
        eyebrow={monthLabel(key)}
        saveStatus={saveStatus}
        title={
          stats.plannedMonthly > 0 ? (
            <>
              <span style={{ color: stats.leftMonthly >= 0 ? ACCENT : RED }}>{fmt(Math.abs(stats.leftMonthly))}</span>{" "}
              {stats.leftMonthly >= 0 ? "left to spend this month" : "over plan this month"}
            </>
          ) : (
            "Welcome"
          )
        }
        subtitle={
          stats.plannedMonthly > 0
            ? `Spent ${fmt(stats.spentMonthly)} of ${fmt(stats.plannedMonthly)} planned · ${daysLeft} day${daysLeft === 1 ? "" : "s"} left including today${
                perDay > 0 ? ` · about ${fmt(perDay)}/day` : ""
              }`
            : "Start on the Budget tab: enter your incomes and what you spend each month."
        }
      />

      {stats.plannedMonthly > 0 && (
        <div className="fade-up" style={{ marginBottom: 18 }}>
          <ProgressBar
            spent={stats.spentMonthly}
            planned={stats.plannedMonthly}
            elapsed={stats.elapsed}
            status={stats.spentMonthly > stats.plannedMonthly ? "over" : stats.spentMonthly / stats.plannedMonthly > stats.elapsed + 0.1 ? "ahead" : "ok"}
            label={`Spent ${fmt(stats.spentMonthly)} of ${fmt(stats.plannedMonthly)}`}
          />
        </div>
      )}

      <div className="overview-grid">
        <div className="panel fade-up">
          <CornerBrackets />
          <div className="panel-title">Needs attention</div>
          {attention.length === 0 ? (
            <div style={{ fontSize: 13.5, color: "#9AA6BA" }}>
              {stats.count === 0 ? "No posted purchases imported for this month yet." : "✓ Every category is on track."}
            </div>
          ) : (
            attention.map((r) => (
              <div key={r.category.id} style={{ marginBottom: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
                  <span>{r.category.name}</span>
                  <span className="mono" style={{ color: PACE_COLORS[r.status] }}>
                    {r.status === "over" ? `${fmt(r.spent - r.planned)} over` : `${Math.round((r.spent / r.planned) * 100)}% used`}
                  </span>
                </div>
                <ProgressBar spent={r.spent} planned={r.planned} elapsed={r.yearly ? 0 : stats.elapsed} status={r.status} label={r.category.name} />
              </div>
            ))
          )}
          {stats.uncategorized > 0 && (
            <div style={{ fontSize: 13, color: "#FFC145", marginTop: 6 }}>{fmt(stats.uncategorized)} uncategorised — sort it on the Spending tab.</div>
          )}
        </div>

        <div className="panel fade-up">
          <CornerBrackets />
          <div className="panel-title">Recent purchases</div>
          {recent.length === 0 && (
            <div style={{ fontSize: 13.5, color: "#9AA6BA" }}>
              {hasLedger ? "No posted personal purchases yet." : "Nothing yet — import your monthly JSON export on the Spending tab."}
            </div>
          )}
          {recent.map((t) => (
            <div key={t.id} style={{ display: "flex", gap: 10, alignItems: "baseline", padding: "6px 0", borderBottom: "1px solid rgba(51,214,255,0.08)" }}>
              <span className="mono" style={{ fontSize: 12.5, color: "#8E9AAD", width: 52, flexShrink: 0 }}>{shortDate(t.date)}</span>
              <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                {t.description || categoryName(t.categoryId, categories)}
              </span>
              <span className="mono" style={{ fontSize: 13.5 }}>{fmtCents(t.amount)}</span>
            </div>
          ))}
          <button type="button" className="link-btn" onClick={() => goTo("spending")}>See all spending →</button>
        </div>

        <div className="panel fade-up">
          <CornerBrackets />
          <div className="panel-title">Your plan</div>
          <div style={{ fontSize: 14, color: "#B9C4D6", lineHeight: 1.7 }}>
            Your take-home <span className="mono" style={{ float: "right", color: "#E7ECF2" }}>{fmt(budget.monthlyNet)}/mo</span>
            <br />
            Your planned spending <span className="mono" style={{ float: "right", color: "#E7ECF2" }}>{fmt(budget.expenseTotal)}/mo</span>
            <br />
            Left for savings{" "}
            <span className="mono" style={{ float: "right", color: budget.leftover >= 0 ? GREEN : RED }}>{fmt(budget.leftover)}/mo</span>
          </div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 12 }}>
            <button type="button" className="text-btn" onClick={() => goTo("budget")}>Edit budget</button>
            <button type="button" className="text-btn" onClick={() => goTo("savings")}>Plan savings →</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Forecast tab ----

const shortMonth = (key) => {
  const [y, m] = key.split("-").map(Number);
  return new Date(y, m - 1, 1).toLocaleDateString(undefined, { month: "short", year: "2-digit" });
};
const fmtK = (v) => (Math.abs(v) >= 1000 ? `${v < 0 ? "-" : ""}$${Math.round(Math.abs(v) / 1000)}k` : fmt(v));

// Width of an element in CSS pixels, kept up to date — lets charts draw at their real
// size so text stays readable instead of being scaled down on phones.
function useElementWidth(fallback = 700) {
  const ref = useRef(null);
  const [width, setWidth] = useState(fallback);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const measure = () => setWidth(Math.round(el.getBoundingClientRect().width) || fallback);
    measure();
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", measure);
      return () => window.removeEventListener("resize", measure);
    }
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return [ref, width];
}

function CashChart(props) {
  const [ref, width] = useElementWidth();
  return (
    <div ref={ref} style={{ width: "100%" }}>
      <CashChartSvg {...props} W={Math.max(280, width)} />
    </div>
  );
}

function CashChartSvg({ result, compare, floor, selected, onSelect, compareName, W }) {
  const H = W < 500 ? 220 : 260, PL = 52, PR = 10, PT = 12, PB = 28;
  const rows = result.rows;
  const n = rows.length;
  if (!n) return null;
  const vals = [...rows.map((r) => r.balance), ...(compare ? compare.rows.map((r) => r.balance) : []), floor || 0, 0];
  let lo = Math.min(...vals), hi = Math.max(...vals);
  if (hi - lo < 1) hi = lo + 1;
  const padv = (hi - lo) * 0.08;
  lo -= padv;
  hi += padv;
  const x = (i) => PL + (n === 1 ? (W - PL - PR) / 2 : (i / (n - 1)) * (W - PL - PR));
  const y = (v) => PT + (1 - (v - lo) / (hi - lo)) * (H - PT - PB);
  const line = (rs) => rs.map((r, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(r.balance).toFixed(1)}`).join(" ");
  const ticks = d3.ticks(lo, hi, 4);
  // roughly one month label per 70px so they never collide
  const labelEvery = Math.max(1, Math.ceil(n / Math.max(2, Math.floor((W - PL - PR) / 70))));
  const step = n > 1 ? (W - PL - PR) / (n - 1) : W;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} style={{ width: "100%", height: "auto", display: "block", touchAction: "pan-y" }} role="img" aria-label="Projected cash balance by month">
      {ticks.map((t) => (
        <g key={t}>
          <line x1={PL} x2={W - PR} y1={y(t)} y2={y(t)} stroke={t === 0 ? "rgba(231,236,242,0.35)" : "rgba(51,214,255,0.1)"} />
          <text x={PL - 8} y={y(t) + 4} textAnchor="end" fontSize={12} fill="#8E9AAD" className="mono">{fmtK(t)}</text>
        </g>
      ))}
      {floor > 0 && (
        <g>
          <line x1={PL} x2={W - PR} y1={y(floor)} y2={y(floor)} stroke={RED} strokeDasharray="6 5" strokeWidth={1.5} opacity={0.8} />
          <text x={W - PR} y={y(floor) - 6} textAnchor="end" fontSize={12} fill={RED}>safety line</text>
        </g>
      )}
      {compare && <path d={line(compare.rows)} fill="none" stroke="#FFC145" strokeWidth={2} strokeDasharray="5 4" />}
      <path d={`${line(rows)} L${x(n - 1)},${y(lo)} L${x(0)},${y(lo)} Z`} fill="rgba(51,214,255,0.08)" />
      <path d={line(rows)} fill="none" stroke={ACCENT} strokeWidth={2.5} style={{ filter: `drop-shadow(0 0 4px ${ACCENT})` }} />
      {rows.map((r, i) => (
        <circle key={r.key} cx={x(i)} cy={y(r.balance)} r={selected === i ? 6 : 3} fill={r.balance < (floor || 0) ? RED : ACCENT} stroke="#05070A" strokeWidth={1.5} />
      ))}
      {rows.map((r, i) =>
        i % labelEvery === 0 || i === n - 1 ? (
          <text key={`l${r.key}`} x={x(i)} y={H - 8} textAnchor={i === n - 1 ? "end" : i === 0 ? "start" : "middle"} fontSize={12} fill="#8E9AAD">{shortMonth(r.key)}</text>
        ) : null
      )}
      {selected != null && <line x1={x(selected)} x2={x(selected)} y1={PT} y2={H - PB} stroke="rgba(231,236,242,0.4)" />}
      {/* invisible hit areas so a tap or hover anywhere in a month's column selects it */}
      {rows.map((r, i) => (
        <rect
          key={`h${r.key}`}
          x={x(i) - step / 2}
          y={PT}
          width={step}
          height={H - PT - PB}
          fill="transparent"
          style={{ cursor: "pointer" }}
          onMouseEnter={() => onSelect(i)}
          onClick={() => onSelect(i)}
        >
          <title>{`${monthLabel(r.key)}: ${fmt(r.balance)}${compare ? ` (${compareName}: ${fmt(compare.rows[i]?.balance ?? 0)})` : ""}`}</title>
        </rect>
      ))}
    </svg>
  );
}

function EventEditor({ ev, people, update, onDelete, onDone }) {
  const dirOut = ev.amount < 0 || (ev.amount === 0 && ev.kind !== "income");
  const setAmount = (abs, out) => update({ amount: out ? -Math.abs(abs) : Math.abs(abs) });
  return (
    <div className="editor" style={{ marginLeft: 0 }}>
      <div className="editor-grid">
        <div>
          <label className="field-label" htmlFor={`evk-${ev.id}`}>Kind</label>
          <select id={`evk-${ev.id}`} className="field-input" value={ev.kind} onChange={(e) => update({ kind: e.target.value, endMonth: e.target.value === "oneoff" ? null : ev.endMonth })}>
            <option value="oneoff">One-off (happens once)</option>
            <option value="recurring">Monthly change (e.g. a new payment)</option>
            <option value="income">Income change (raise, leave…)</option>
          </select>
        </div>
        <div>
          <label className="field-label" htmlFor={`evn-${ev.id}`}>Name</label>
          <input id={`evn-${ev.id}`} type="text" className="field-input" value={ev.name} placeholder="e.g. Car payment" onChange={(e) => update({ name: e.target.value })} />
        </div>
        <div>
          <label className="field-label" htmlFor={`evm-${ev.id}`}>{ev.kind === "oneoff" ? "Month" : "Starts"}</label>
          <input id={`evm-${ev.id}`} type="month" className="field-input" value={ev.month} onChange={(e) => e.target.value && update({ month: e.target.value })} />
        </div>
        {ev.kind !== "oneoff" && (
          <div>
            <label className="field-label" htmlFor={`eve-${ev.id}`}>Ends (optional)</label>
            <input id={`eve-${ev.id}`} type="month" className="field-input" value={ev.endMonth || ""} min={ev.month} onChange={(e) => update({ endMonth: e.target.value || null })} />
          </div>
        )}
        {ev.kind === "income" ? (
          <>
            <div>
              <label className="field-label" htmlFor={`evp-${ev.id}`}>Who</label>
              <select id={`evp-${ev.id}`} className="field-input" value={ev.person} onChange={(e) => update({ person: e.target.value })}>
                {people.map((p, i) => (
                  <option key={p.id} value={p.id}>{personLabel(p, i)}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="field-label" htmlFor={`evs-${ev.id}`}>New salary per year (before tax)</label>
              <MoneyInput id={`evs-${ev.id}`} value={ev.salary} step={1000} onChange={(v) => update({ salary: v })} label="New salary" />
            </div>
          </>
        ) : (
          <>
            <div>
              <label className="field-label" htmlFor={`evd-${ev.id}`}>Money</label>
              <select id={`evd-${ev.id}`} className="field-input" value={dirOut ? "out" : "in"} onChange={(e) => setAmount(ev.amount, e.target.value === "out")}>
                <option value="out">Goes out (a cost)</option>
                <option value="in">Comes in (income, savings)</option>
              </select>
            </div>
            <div>
              <label className="field-label" htmlFor={`eva-${ev.id}`}>{ev.kind === "recurring" ? "Amount per month" : "Amount"}</label>
              <MoneyInput id={`eva-${ev.id}`} value={Math.abs(ev.amount)} step={50} onChange={(v) => setAmount(v, dirOut)} label="Amount" />
            </div>
          </>
        )}
      </div>
      {ev.kind === "income" && (
        <div style={{ fontSize: 12.5, color: "#8E9AAD", marginTop: 8 }}>
          Take-home on {fmt(ev.salary)}: about {fmt(calcNet(ev.salary).monthlyNet)}/mo. {ev.endMonth ? "Pay goes back to normal after the end month." : "Lasts for the rest of the forecast."}
        </div>
      )}
      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <button type="button" className="text-btn" onClick={onDone}>Done</button>
        <button type="button" className="text-btn danger" onClick={onDelete} style={{ marginLeft: "auto" }}>Delete</button>
      </div>
    </div>
  );
}

// Short summary for the event list (the start month is already shown beside it).
function describeEvent(e, people) {
  if (e.kind === "oneoff") return e.amount >= 0 ? "money in" : "money out";
  const when = e.endMonth ? `until ${shortMonth(e.endMonth)}` : "ongoing";
  if (e.kind === "income") {
    const i = people.findIndex((p) => p.id === e.person);
    return `${i >= 0 ? personLabel(people[i], i) : "Partner"} earns ${fmt(e.salary)}/yr · ${when}`;
  }
  return `${e.amount >= 0 ? "+" : "−"}${fmt(Math.abs(e.amount))}${e.kind === "recurring" ? "/mo" : ""} · ${when}`;
}

function ForecastPage({ forecast: f, setForecast, household, categories, transactions, holdings, saveStatus, goTo }) {
  const [selected, setSelected] = useState(null);
  const [openEvent, setOpenEvent] = useState(null);
  const [rateCase, setRateCase] = useState("base");
  const [real, setReal] = useState(false);
  const scenario = f.scenarios.find((s) => s.id === f.activeId) || f.scenarios[0];
  const compareScenario = f.scenarios.find((s) => s.id === f.compareId) || null;
  const floor = f.floor ?? suggestedFloor(categories, incomeShare(household.people));
  const inputs = { household, categories, transactions, holdings, forecast: f };
  const result = useMemo(() => runForecast({ ...inputs, events: scenario.events }), [household, categories, transactions, holdings, f, scenario]);
  const compare = useMemo(() => (compareScenario ? runForecast({ ...inputs, events: compareScenario.events }) : null), [household, categories, transactions, holdings, f, compareScenario]);

  const set = (patch) => setForecast((x) => ({ ...x, ...patch }));
  const setScenario = (id, patch) => setForecast((x) => ({ ...x, scenarios: x.scenarios.map((s) => (s.id === id ? { ...s, ...patch } : s)) }));
  const setEvents = (fn) => setScenario(scenario.id, { events: fn(scenario.events) });
  const addEvent = () => {
    const ev = normalizeEvent({ kind: "oneoff", name: "", month: shiftMonth(currentMonthKey(), 2), amount: -1000, person: "a", salary: household.people[0].gross });
    setEvents((es) => [...es, ev]);
    setOpenEvent(ev.id);
  };
  const copyScenario = () => {
    const copy = { id: newId("s"), name: `${scenario.name} (copy)`, events: scenario.events.map((e) => ({ ...e, id: newId("e") })) };
    setForecast((x) => ({ ...x, scenarios: [...x.scenarios, copy], compareId: x.activeId, activeId: copy.id }));
  };
  const deleteScenario = () => {
    if (f.scenarios.length < 2) return;
    if (!window.confirm(`Delete the scenario "${scenario.name}" and its events?`)) return;
    setForecast((x) => {
      const rest = x.scenarios.filter((s) => s.id !== scenario.id);
      return { ...x, scenarios: rest, activeId: rest[0].id, compareId: x.compareId === scenario.id || x.compareId === rest[0].id ? null : x.compareId };
    });
  };

  const low = result.low;
  const belowFloor = result.rows.filter((r) => r.balance < floor);
  const sel = selected != null ? result.rows[selected] : null;
  const noStart = f.startBalance == null;
  const mult = SCENARIOS[rateCase].mult;
  const startCash = f.startBalance ?? 0;
  const deflate = (v, years) => (real ? v / Math.pow(1 + INFLATION, years) : v);

  return (
    <div className="page-fade" style={{ maxWidth: 1120, margin: "0 auto", position: "relative" }}>
      <PageHeader
        eyebrow={`Forecast · ${scenario.name}`}
        saveStatus={saveStatus}
        title={
          low.balance < 0 ? (
            <>
              Cash runs out: <span style={{ color: RED }}>{fmt(low.balance)}</span> by {monthLabel(low.key)}
            </>
          ) : (
            <>
              <span style={{ color: ACCENT }}>{fmt(result.end)}</span> in cash by {monthLabel(shiftMonth(currentMonthKey(), f.horizon))}
            </>
          )
        }
        subtitle={
          belowFloor.length
            ? `Dips below your ${fmt(floor)} safety line in ${belowFloor.length} month${belowFloor.length === 1 ? "" : "s"} — lowest ${fmt(low.balance)} in ${monthLabel(low.key)}.`
            : `Stays above your ${fmt(floor)} safety line the whole time. Lowest point: ${fmt(low.balance)} in ${monthLabel(low.key)}.`
        }
      />

      <div className="panel fade-up" style={{ marginBottom: 16 }}>
        <CornerBrackets />
        <div className="panel-title">Starting point</div>
        <div className="editor-grid">
          <div>
            <label className="field-label" htmlFor="fc-start">Cash in chequing & everyday savings today</label>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span className="mono" style={{ color: ACCENT }}>$</span>
              <MoneyInput id="fc-start" value={f.startBalance ?? 0} step={100} onChange={(v) => set({ startBalance: v })} label="Cash today" />
            </div>
            {noStart && <div style={{ fontSize: 12.5, color: "#FFC145", marginTop: 4 }}>Enter this so the forecast starts from your real balance.</div>}
          </div>
          <div>
            <label className="field-label" htmlFor="fc-floor">Safety line (don't go below)</label>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span className="mono" style={{ color: ACCENT }}>$</span>
              <MoneyInput id="fc-floor" value={floor} step={500} onChange={(v) => set({ floor: v })} label="Safety line" />
            </div>
            {f.floor == null && <div style={{ fontSize: 12.5, color: "#8E9AAD", marginTop: 4 }}>Suggested: 3 months of fixed bills.</div>}
          </div>
          <div>
            <label className="field-label" htmlFor="fc-h">Look ahead</label>
            <select id="fc-h" className="field-input" value={f.horizon} onChange={(e) => set({ horizon: Number(e.target.value) })}>
              <option value={12}>12 months</option>
              <option value={24}>2 years</option>
              <option value={36}>3 years</option>
            </select>
          </div>
        </div>
        <label className="check-row" style={{ marginTop: 8 }}>
          <input type="checkbox" checked={f.useActuals} onChange={(e) => set({ useActuals: e.target.checked })} />
          Use our recent spending for categories that vary
        </label>
        <div style={{ fontSize: 12.5, color: "#8E9AAD", lineHeight: 1.5 }}>
          Each month: {fmt(result.rows[0]?.income ?? 0)} take-home − {fmt(result.spending)} spending − {fmt(result.contrib)} into savings accounts
          {result.usedAverage.length > 0
            ? ` (${result.usedAverage.length} categor${result.usedAverage.length === 1 ? "y uses" : "ies use"} your 3-month average)`
            : f.useActuals
            ? " (log 3 full months of spending to use real averages)"
            : ""}
          .{" "}
          <button type="button" className="link-btn" style={{ padding: 0, minHeight: 0 }} onClick={() => goTo("savings")}>Savings contributions →</button>
        </div>
      </div>

      <div className="panel fade-up" style={{ marginBottom: 16 }}>
        <CornerBrackets />
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "flex-end", marginBottom: 10 }}>
          <div style={{ flex: "1 1 180px" }}>
            <label className="field-label" htmlFor="fc-sc">Scenario</label>
            <select id="fc-sc" className="field-input" value={scenario.id} onChange={(e) => set({ activeId: e.target.value, compareId: f.compareId === e.target.value ? null : f.compareId })}>
              {f.scenarios.map((s) => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </div>
          <div style={{ flex: "1 1 180px" }}>
            <label className="field-label" htmlFor="fc-cmp">Compare with</label>
            <select id="fc-cmp" className="field-input" value={f.compareId || ""} onChange={(e) => set({ compareId: e.target.value || null })}>
              <option value="">Nothing</option>
              {f.scenarios.filter((s) => s.id !== scenario.id).map((s) => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </div>
          <button type="button" className="text-btn" onClick={copyScenario} title="Copy this scenario so you can try changes without losing it">Copy as new what-if</button>
        </div>

        <CashChart result={result} compare={compare} floor={floor} selected={selected} onSelect={setSelected} compareName={compareScenario?.name} />
        <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 6 }}>
          <LegendChip color={ACCENT} label={scenario.name} />
          {compareScenario && <LegendChip color="#FFC145" label={`${compareScenario.name} (dashed)`} />}
          <LegendChip color={RED} label="Safety line" />
        </div>

        <div className="month-detail" aria-live="polite">
          {sel ? (
            <>
              <strong>{monthLabel(sel.key)}</strong>: end with <span className="mono" style={{ color: sel.balance < floor ? RED : "#E7ECF2" }}>{fmt(sel.balance)}</span>
              {compare && <> (vs <span className="mono" style={{ color: "#FFC145" }}>{fmt(compare.rows[selected].balance)}</span>)</>}
              <div style={{ color: "#9AA6BA", marginTop: 4 }}>
                +{fmt(sel.income)} take-home − {fmt(sel.spending)} spending − {fmt(sel.contrib)} savings
                {sel.eventFlow !== 0 && ` ${sel.eventFlow > 0 ? "+" : "−"} ${fmt(Math.abs(sel.eventFlow))} events`} ={" "}
                <span style={{ color: sel.flow >= 0 ? GREEN : RED }}>{sel.flow >= 0 ? "+" : ""}{fmt(sel.flow)}</span>
              </div>
              {sel.notes.length > 0 && <div style={{ color: "#8E9AAD", marginTop: 2 }}>{sel.notes.join(" · ")}</div>}
            </>
          ) : (
            <span style={{ color: "#8E9AAD" }}>Tap or hover a month on the chart for its details.</span>
          )}
        </div>
      </div>

      <div className="panel fade-up" style={{ marginBottom: 16 }}>
        <CornerBrackets />
        <div className="panel-title" style={{ marginBottom: 4 }}>What's coming up</div>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 10, flexWrap: "wrap", marginBottom: 8 }}>
          <div style={{ flex: "1 1 200px" }}>
            <label className="field-label" htmlFor="fc-name">Scenario name</label>
            <input id="fc-name" type="text" className="field-input" value={scenario.name} onChange={(e) => setScenario(scenario.id, { name: e.target.value })} />
          </div>
          {f.scenarios.length > 1 && (
            <button type="button" className="text-btn danger" onClick={deleteScenario}>Delete scenario</button>
          )}
        </div>
        <div style={{ fontSize: 12.5, color: "#8E9AAD", marginBottom: 8 }}>
          Raises, a new car payment, a vacation, parental leave — anything that changes your cash on top of the normal monthly budget.
        </div>
        {scenario.events.length === 0 && <div style={{ fontSize: 13.5, color: "#9AA6BA", padding: "6px 0" }}>No events yet.</div>}
        {[...scenario.events]
          .sort((a, b) => (a.month < b.month ? -1 : a.month > b.month ? 1 : 0))
          .map((e) => {
            const open = openEvent === e.id;
            return (
              <div key={e.id} className={`tx-row${open ? " is-open" : ""}`}>
                <button type="button" className="tx-main" onClick={() => setOpenEvent(open ? null : e.id)} aria-expanded={open}>
                  <span className="tx-date mono" style={{ width: 64 }}>{shortMonth(e.month)}</span>
                  <span className="tx-text">
                    <span className="tx-desc">{e.name || EVENT_KINDS[e.kind]}</span>
                    <span className="tx-meta" style={{ color: "#8E9AAD" }}>{EVENT_KINDS[e.kind]} · {describeEvent(e, household.people)}</span>
                  </span>
                  <span className="tx-amt mono" style={{ color: e.kind === "income" ? ACCENT : e.amount >= 0 ? GREEN : "#E7ECF2" }}>
                    {e.kind === "income" ? fmtK(e.salary) : `${e.amount >= 0 ? "+" : "−"}${fmt(Math.abs(e.amount))}`}
                  </span>
                </button>
                {open && (
                  <EventEditor
                    ev={e}
                    people={household.people}
                    update={(patch) => setEvents((es) => es.map((x) => (x.id === e.id ? normalizeEvent({ ...x, ...patch }) : x)))}
                    onDelete={() => { setEvents((es) => es.filter((x) => x.id !== e.id)); setOpenEvent(null); }}
                    onDone={() => setOpenEvent(null)}
                  />
                )}
              </div>
            );
          })}
        <div style={{ marginTop: 10 }}>
          <button type="button" className="text-btn" onClick={addEvent}>+ Add event</button>
        </div>
      </div>

      <div className="panel fade-up">
        <CornerBrackets />
        <div className="panel-title" style={{ marginBottom: 4 }}>Net worth over the long run</div>
        <div style={{ fontSize: 12.5, color: "#8E9AAD", marginBottom: 10, lineHeight: 1.5 }}>
          Cash from this forecast plus your savings accounts (Savings tab) growing at their assumed rates. Illustrative only — returns vary and aren't guaranteed.
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginBottom: 12 }}>
          <div className="seg" role="group" aria-label="Market returns">
            {Object.entries(SCENARIOS).map(([k, s]) => (
              <button key={k} type="button" aria-pressed={rateCase === k} onClick={() => setRateCase(k)}>
                {k === "bear" ? "Weak" : k === "base" ? "Typical" : "Strong"} returns
              </button>
            ))}
          </div>
          <label className="check-row">
            <input type="checkbox" checked={real} onChange={(e) => setReal(e.target.checked)} />
            In today's dollars
          </label>
        </div>
        <div className="nw-grid">
          {[0, 1, 5, 10, 20, 30].map((yrs) => {
            const v = netWorthAt(yrs, { cashResult: result, startCash, holdings, rateMult: mult });
            return (
              <div key={yrs} className="nw-cell">
                <div style={{ fontSize: 12.5, color: "#8E9AAD" }}>{yrs === 0 ? "Today" : `In ${yrs} year${yrs === 1 ? "" : "s"}`}</div>
                <div className="mono" style={{ fontSize: 19, fontWeight: 700, color: v.total >= 0 ? (yrs ? ACCENT : "#E7ECF2") : RED }}>{fmtK(deflate(v.total, yrs))}</div>
                <div style={{ fontSize: 12, color: "#8E9AAD" }}>
                  {fmtK(deflate(v.cash, yrs))} cash · {fmtK(deflate(v.invest, yrs))} invested
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ fontSize: 12, color: "#8E9AAD", marginTop: 10, lineHeight: 1.5 }}>
          After the {f.horizon}-month forecast, cash keeps changing by your typical month ({result.steadyFlow >= 0 ? "+" : ""}{fmt(result.steadyFlow)}) and earns no interest. Not financial advice.
        </div>
      </div>
    </div>
  );
}

// ---- Page chrome shared by every tab ----

function SaveBadge({ status }) {
  const text = status === "error" ? "Not saved — storage full or blocked" : status === "pending" ? "Saving…" : "Saved on this device";
  const color = status === "error" ? RED : status === "pending" ? "#9AA6BA" : GREEN;
  return (
    <span role="status" style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color }}>
      <span aria-hidden="true" style={{ width: 7, height: 7, borderRadius: "50%", background: color, boxShadow: `0 0 6px ${color}` }} />
      {text}
    </span>
  );
}

function PageHeader({ eyebrow, title, subtitle, saveStatus }) {
  return (
    <div className="fade-up" style={{ marginBottom: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 10 }}>
        <span className="mono" style={{ fontSize: 12.5, letterSpacing: "0.1em", color: "#8E9AAD", textTransform: "uppercase" }}>
          {eyebrow}
        </span>
        {saveStatus && <SaveBadge status={saveStatus} />}
      </div>
      <h1 className="display" style={{ fontSize: "clamp(26px, 4vw, 42px)", fontWeight: 600, margin: 0, lineHeight: 1.1, letterSpacing: "-0.01em" }}>
        {title}
      </h1>
      <div
        aria-hidden="true"
        style={{
          height: 3,
          width: "100%",
          maxWidth: 560,
          marginTop: 12,
          background: `linear-gradient(90deg, ${ACCENT}, rgba(51,214,255,0.05))`,
          boxShadow: `0 0 14px 2px rgba(51,214,255,0.6), 0 0 38px 6px rgba(51,214,255,0.25)`,
        }}
      />
      {subtitle && <p style={{ margin: "12px 0 0", fontSize: 14.5, lineHeight: 1.5, color: "#B9C4D6", maxWidth: 680 }}>{subtitle}</p>}
    </div>
  );
}

// ---- Budget tab: income, categories, details ----

const personLabel = (p, i) => (p.name && p.name.trim()) || (i === 0 ? "You" : "Partner");
const pct = (f) => `${Math.round(f * 100)}%`;

// "Just me" / "Shared by take-home pay (you 58%)" / "Shared 50 / 50"
function splitLabel(split, share, short = false) {
  if (split === "income") return short ? `Split by income · you ${pct(share)}` : `Shared by take-home pay (you pay ${pct(share)})`;
  if (split === "even") return short ? "Split 50 / 50" : "Shared 50 / 50";
  return short ? "Just you" : "Just me";
}

// Number input that lets the field be emptied while typing (shows blank for 0).
function MoneyInput({ value, onChange, label, step = 1, className = "field-input mono", ...rest }) {
  return (
    <input
      type="number"
      inputMode="decimal"
      min={0}
      step={step}
      value={value ? Math.round(value * 100) / 100 : ""}
      placeholder="0"
      onChange={(e) => onChange(e.target.value === "" ? 0 : Math.max(0, Number(e.target.value) || 0))}
      aria-label={label}
      className={className}
      {...rest}
    />
  );
}

function TakeHomeOverride({ person, net, setPerson, who }) {
  return net.overridden ? (
    <div style={{ marginTop: 10 }}>
      <label className="field-label" htmlFor={`net-${person.id}`}>Actual take-home per month (from a payslip)</label>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="mono" style={{ color: ACCENT }}>$</span>
        <MoneyInput id={`net-${person.id}`} value={person.netOverride} step={50} onChange={(v) => setPerson({ netOverride: v > 0 ? v : null })} label={`${who} actual monthly take-home`} />
      </div>
      <button type="button" className="link-btn" onClick={() => setPerson({ netOverride: null })}>Use the tax estimate instead</button>
    </div>
  ) : (
    <button type="button" className="link-btn" onClick={() => setPerson({ netOverride: Math.round(net.estimatedMonthlyNet) })}>
      Know the exact take-home pay? Enter it
    </button>
  );
}

function IncomePanel({ household, setHousehold, budget }) {
  const setPerson = (id) => (patch) =>
    setHousehold((h) => ({ ...h, people: h.people.map((p) => (p.id === id ? { ...p, ...patch } : p)) }));
  const [me, partner] = household.people;
  const [myNet, partnerNet] = budget.nets;
  const sliderMax = Math.max(250000, me.gross);
  const fill = Math.min(100, (me.gross / sliderMax) * 100);
  const partnerName = personLabel(partner, 1);

  return (
    <div className="fade-up panel" style={{ marginBottom: 16 }}>
      <CornerBrackets />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(280px, 100%), 1fr))", gap: 14 }}>
        <div className="sub-card">
          <div className="panel-title" style={{ marginBottom: 4 }}>Your income</div>
          <label className="field-label" htmlFor="gross-a">Your salary per year, before tax</label>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="mono" style={{ color: ACCENT }}>$</span>
            <MoneyInput id="gross-a" value={me.gross} step={1000} onChange={(v) => setPerson("a")({ gross: v })} label="Your gross salary" />
          </div>
          <input
            type="range"
            min={0}
            max={sliderMax}
            step={500}
            value={me.gross}
            onChange={(e) => setPerson("a")({ gross: Number(e.target.value) })}
            className="salary-slider"
            style={{ marginTop: 12, background: `linear-gradient(to right, ${ACCENT} 0%, ${ACCENT} ${fill}%, rgba(51,214,255,0.18) ${fill}%, rgba(51,214,255,0.18) 100%)` }}
            aria-label="Your gross salary slider"
          />
          <div style={{ marginTop: 14, fontSize: 13.5, color: "#B9C4D6" }}>
            Take-home: <span className="mono" style={{ color: "#E7ECF2", fontWeight: 700, fontSize: 16 }}>{fmt(myNet.monthlyNet)}/mo</span>
            <div style={{ fontSize: 12.5, color: "#8E9AAD", marginTop: 3 }}>
              {myNet.overridden
                ? `Your figure (the tax estimate is ${fmt(myNet.estimatedMonthlyNet)}/mo)`
                : me.gross > 0
                ? `Estimated after ${((myNet.annualTax / me.gross) * 100).toFixed(1)}% Ontario tax, CPP & EI`
                : "No income entered"}
            </div>
          </div>
          <TakeHomeOverride person={me} net={myNet} setPerson={setPerson("a")} who="Your" />
        </div>

        <div className="sub-card">
          <div className="panel-title" style={{ marginBottom: 4 }}>Your partner</div>
          <div style={{ fontSize: 12.5, color: "#8E9AAD", lineHeight: 1.45, marginBottom: 4 }}>
            Only used to work out your share of bills you split by income (rent and the car).
          </div>
          <div className="editor-grid">
            <div>
              <label className="field-label" htmlFor="name-b">Name</label>
              <input id="name-b" type="text" className="field-input" value={partner.name} placeholder="Partner" onChange={(e) => setPerson("b")({ name: e.target.value })} />
            </div>
            <div>
              <label className="field-label" htmlFor="gross-b">Their salary per year</label>
              <MoneyInput id="gross-b" value={partner.gross} step={1000} onChange={(v) => setPerson("b")({ gross: v })} label="Partner gross salary" />
            </div>
          </div>
          <div style={{ marginTop: 10, fontSize: 13, color: "#9AA6BA" }}>
            {partnerName}'s take-home: <span className="mono" style={{ color: "#E7ECF2" }}>{fmt(partnerNet.monthlyNet)}/mo</span>
            {partnerNet.overridden ? " (their figure)" : " (estimated)"}
          </div>
          <TakeHomeOverride person={partner} net={partnerNet} setPerson={setPerson("b")} who={partnerName} />
        </div>
      </div>

      <div className="share-banner">
        You earn <strong>{pct(budget.share)}</strong> of your combined take-home, so you pay{" "}
        <strong>{pct(budget.share)}</strong> of bills split by income.
        {budget.shared.count > 0 && (
          <>
            {" "}
            Of <span className="mono">{fmt(budget.shared.total)}/mo</span> in shared bills, your part is{" "}
            <span className="mono" style={{ color: ACCENT }}>{fmt(budget.shared.mine)}</span> and {partnerName}'s is{" "}
            <span className="mono">{fmt(budget.shared.partner)}</span>.
          </>
        )}
      </div>
    </div>
  );
}

function CategoryLedger({ budget, setCategories, hovered, setHovered, goTo }) {
  const [editingId, setEditingId] = useState(null);
  const update = (id, patch) => setCategories((cs) => cs.map((c) => (c.id === id ? { ...c, ...patch } : c)));
  const remove = (id) => {
    const c = budget.categories.find((x) => x.id === id);
    if (!window.confirm(`Delete "${c?.name || "this category"}"?`)) return;
    setCategories((cs) => cs.filter((x) => x.id !== id));
    setEditingId(null);
  };
  const move = (id, dir) =>
    setCategories((cs) => {
      const i = cs.findIndex((c) => c.id === id);
      const j = i + dir;
      if (i < 0 || j < 0 || j >= cs.length) return cs;
      const next = [...cs];
      [next[i], next[j]] = [next[j], next[i]];
      return next;
    });
  const add = () => {
    const c = { id: newId(), name: "", amount: 0, freq: "monthly", type: "variable", split: "mine", group: "Other", avg: null };
    setCategories((cs) => [...cs, c]);
    setEditingId(c.id);
  };

  const rows = budget.categories.filter((d) => !d.isLeftover);
  const leftover = budget.categories.find((d) => d.isLeftover);
  const net = budget.monthlyNet;

  return (
    <div className="fade-up panel" style={{ flex: "1 1 340px", minWidth: 0 }}>
      <CornerBrackets />
      <div className="panel-title" style={{ marginBottom: 4 }}>Your monthly spending plan</div>
      <div style={{ fontSize: 12.5, color: "#8E9AAD", marginBottom: 10, lineHeight: 1.45 }}>
        For shared bills, type the <strong style={{ color: "#B9C4D6" }}>whole bill</strong> — your share is worked out for you. Tap ✎ to
        rename, change how it's split, make it yearly, or delete.
      </div>

      {rows.length === 0 && (
        <div style={{ fontSize: 13.5, color: "#9AA6BA", padding: "14px 4px" }}>No categories yet — add your first one below.</div>
      )}

      {rows.map((d, idx) => {
        const swatch = colorFor(d);
        const good = isGood(d);
        const delta = d.avg != null ? d.value - d.avg : 0;
        const editing = editingId === d.id;
        const perUnit = d.freq === "annual" ? "/yr" : "/mo";
        const shared = d.split !== "mine";
        return (
          <div
            key={d.id}
            className={`legend-row${hovered === d.id || editing ? " is-active" : ""}`}
            onMouseEnter={() => setHovered(d.id)}
            onMouseLeave={() => setHovered(null)}
            style={{ padding: "8px 6px", borderRadius: 3 }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span aria-hidden="true" style={{ width: 10, height: 10, borderRadius: 1, background: swatch, boxShadow: `0 0 5px ${swatch}66`, flexShrink: 0 }} />
              <span className="cat-name" title={d.name}>
                {d.name || <span style={{ color: "#8E9AAD", fontStyle: "italic" }}>Unnamed</span>}
              </span>
              <span className="mono" style={{ color: "#8E9AAD", fontSize: 13 }}>$</span>
              <MoneyInput
                value={d.amount}
                step={d.freq === "annual" ? 50 : 5}
                onChange={(v) => update(d.id, { amount: v })}
                label={`${d.name || "Category"} ${shared ? "total bill" : "amount"} ${d.freq === "annual" ? "per year" : "per month"}`}
                className="row-input mono"
              />
              <span style={{ fontSize: 12, color: "#8E9AAD", width: 26 }}>{perUnit}</span>
              <button
                type="button"
                className="icon-btn"
                onClick={() => setEditingId(editing ? null : d.id)}
                aria-expanded={editing}
                aria-label={`${editing ? "Close" : "Edit"} ${d.name || "category"}`}
                title={editing ? "Done" : "Edit"}
              >
                {editing ? "✓" : "✎"}
              </button>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: "2px 10px", paddingLeft: 18, marginTop: 3, fontSize: 12.5, color: "#8E9AAD" }}>
              {shared ? (
                <span>
                  {d.split === "even" ? "Split 50 / 50" : `Split by income`} → your share{" "}
                  <span className="mono" style={{ color: "#E7ECF2" }}>{fmt(d.value)}/mo</span> ({pct(d.fraction)})
                </span>
              ) : (
                d.freq === "annual" && <span>= <span className="mono" style={{ color: "#B9C4D6" }}>{fmt(d.value)}/mo</span></span>
              )}
              {net > 0 && <span>{((d.value / net) * 100).toFixed(1)}% of your take-home</span>}
              {d.avg != null && Math.round(delta) !== 0 && (
                <span style={{ color: good === null ? NEUTRAL : good ? GREEN : RED }} title={`Typical downtown Toronto amount for one person: ${fmt(d.avg)}/mo`}>
                  {delta > 0 ? "▲" : "▼"} {fmt(Math.abs(delta))} vs avg
                </span>
              )}
            </div>
            {editing && (
              <CategoryEditor
                category={d}
                share={budget.share}
                update={(patch) => update(d.id, patch)}
                onDelete={() => remove(d.id)}
                onMove={(dir) => move(d.id, dir)}
                isFirst={idx === 0}
                isLast={idx === rows.length - 1}
                onDone={() => setEditingId(null)}
              />
            )}
          </div>
        );
      })}

      <div style={{ padding: "10px 6px 4px" }}>
        <button type="button" className="text-btn" onClick={add}>+ Add category</button>
      </div>

      {leftover && (
        <div
          className={`legend-row${hovered === leftover.id ? " is-active" : ""}`}
          onMouseEnter={() => setHovered(leftover.id)}
          onMouseLeave={() => setHovered(null)}
          style={{ padding: "10px 6px", borderRadius: 3, marginTop: 6, borderTop: "1px solid rgba(51,214,255,0.18)" }}
        >
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
            <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14, fontWeight: 600 }}>
              <span aria-hidden="true" style={{ width: 10, height: 10, borderRadius: 1, background: colorFor(leftover), flexShrink: 0 }} />
              {LEFTOVER_NAME}
            </span>
            <span className="mono" style={{ fontSize: 15, fontWeight: 700, color: leftover.value >= 0 ? "#E7ECF2" : RED }}>{fmt(leftover.value)}/mo</span>
          </div>
          {leftover.avg != null && (
            <div style={{ paddingLeft: 18, marginTop: 3, fontSize: 12.5, color: "#8E9AAD" }}>
              A typical Toronto renter on your income saves about {fmt(leftover.avg)}/mo
            </div>
          )}
          <div style={{ paddingLeft: 18, marginTop: 8 }}>
            <button type="button" className="text-btn" onClick={() => goTo("savings")}>Plan where it goes →</button>
          </div>
        </div>
      )}

      <div style={{ display: "flex", justifyContent: "space-between", padding: "12px 6px 2px", marginTop: 6, borderTop: "1px solid rgba(51,214,255,0.18)", fontSize: 14 }}>
        <span>Your spending</span>
        <span className="mono">{fmt(budget.expenseTotal)}/mo</span>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", padding: "2px 6px", fontSize: 14, fontWeight: 700 }}>
        <span>Your take-home pay</span>
        <span className="mono">{fmt(budget.monthlyNet)}/mo</span>
      </div>
    </div>
  );
}

function CategoryEditor({ category: c, share, update, onDelete, onMove, isFirst, isLast, onDone }) {
  const frac = splitFraction(c.split, share);
  const sliderMax = Math.max(500, c.amount * 2, c.avg && frac > 0 ? (c.avg / frac) * 2 : 0);
  const fill = Math.min(100, (c.amount / sliderMax) * 100);
  const nameRef = useRef(null);
  useEffect(() => {
    if (!c.name && nameRef.current) nameRef.current.focus();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    <div className="editor">
      <label className="field-label" htmlFor={`name-${c.id}`}>Name</label>
      <input
        id={`name-${c.id}`}
        ref={nameRef}
        type="text"
        value={c.name}
        placeholder="e.g. Car insurance"
        onChange={(e) => update({ name: e.target.value })}
        className="field-input"
      />

      <div className="editor-grid">
        <div>
          <label className="field-label" htmlFor={`split-${c.id}`}>How it's split</label>
          <select id={`split-${c.id}`} className="field-input" value={c.split} onChange={(e) => update({ split: e.target.value })}>
            {Object.keys(SPLITS).map((k) => (
              <option key={k} value={k}>{splitLabel(k, share)}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="field-label" htmlFor={`freq-${c.id}`}>How often</label>
          <select id={`freq-${c.id}`} className="field-input" value={c.freq} onChange={(e) => update({ freq: e.target.value })}>
            <option value="monthly">Every month</option>
            <option value="annual">Once a year (spread over 12 months)</option>
          </select>
        </div>
        <div>
          <label className="field-label" htmlFor={`type-${c.id}`}>Kind of cost</label>
          <select id={`type-${c.id}`} className="field-input" value={c.type} onChange={(e) => update({ type: e.target.value })}>
            {Object.entries(CATEGORY_TYPES).map(([k, v]) => (
              <option key={k} value={k}>{v}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="field-label" htmlFor={`group-${c.id}`}>Group</label>
          <select id={`group-${c.id}`} className="field-input" value={c.group} onChange={(e) => update({ group: e.target.value })}>
            {GROUPS.map((g) => (
              <option key={g} value={g}>{g}</option>
            ))}
          </select>
        </div>
      </div>

      <label className="field-label" style={{ marginTop: 12 }}>
        Quick adjust ({c.split === "mine" ? "your amount" : "whole bill"}, {c.freq === "annual" ? "per year" : "per month"})
      </label>
      <input
        type="range"
        min={0}
        max={sliderMax}
        step={sliderMax > 5000 ? 50 : 5}
        value={c.amount}
        onChange={(e) => update({ amount: Number(e.target.value) })}
        className="cat-slider"
        style={{ width: "100%", ...sliderStyle(fill / 100, ACCENT) }}
        aria-label={`${c.name || "Category"} amount slider`}
      />

      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
        <button type="button" className="text-btn" onClick={onDone}>Done</button>
        <button type="button" className="text-btn" onClick={() => onMove(-1)} disabled={isFirst} aria-label="Move up">↑</button>
        <button type="button" className="text-btn" onClick={() => onMove(1)} disabled={isLast} aria-label="Move down">↓</button>
        <button type="button" className="text-btn danger" onClick={onDelete} style={{ marginLeft: "auto" }}>Delete</button>
      </div>
    </div>
  );
}

// Detail line under the treemap for the tapped/hovered tile, so small tiles and
// truncated labels are still readable (and it works without a mouse).
function CategoryDetail({ category, monthlyNet }) {
  if (!category) {
    return (
      <div style={{ marginTop: 12, fontSize: 13, color: "#8E9AAD", minHeight: 40 }}>
        Tap or hover a tile to see its details.
      </div>
    );
  }
  const delta = category.avg != null ? category.value - category.avg : null;
  const good = isGood(category);
  const color = good === null ? "#B9C4D6" : good ? GREEN : RED;
  return (
    <div style={{ marginTop: 12, fontSize: 13.5, lineHeight: 1.5, minHeight: 40 }}>
      <strong style={{ color: "#E7ECF2" }}>{category.name || "Unnamed"}</strong>{" "}
      <span className="mono" style={{ color: "#E7ECF2" }}>{fmt(category.value)}/mo</span>
      {!category.isLeftover && category.split !== "mine" && (
        <span style={{ color: "#8E9AAD" }}> · your {pct(category.fraction)} of {fmt(category.full)}</span>
      )}
      {monthlyNet > 0 && <span style={{ color: "#8E9AAD" }}> · {((category.value / monthlyNet) * 100).toFixed(1)}% of your take-home</span>}
      {delta != null && (
        <span style={{ color }}>
          {" · "}
          {Math.round(delta) === 0
            ? "about the Toronto average"
            : `${fmt(Math.abs(delta))} ${delta > 0 ? "more" : "less"} than a typical Torontonian`}
        </span>
      )}
    </div>
  );
}

function exportHoldingsCSV(holdings, leftover) {
  const rows = [["Account", "Balance", "% of leftover", "Monthly contribution", "Room used"]];
  LEFTOVER_OPTIONS.forEach((opt) => {
    rows.push([
      opt.name,
      holdings.balances[opt.name] ?? 0,
      allocPctAt(holdings)[opt.name] ?? 0, // the stage running now
      Math.round(allocAmount(holdings, opt.name, leftover) * 100) / 100,
      holdings.roomUsed[opt.name] ?? 0,
    ]);
  });
  const csv = rows.map((r) => r.map((v) => `"${v}"`).join(",")).join("\n");
  downloadFile(`holdings_${todayISO()}.csv`, csv, "text/csv");
}

function SettingsPage({ saveStatus, holdings, leftover, exportBackup, importBackup, resetAll, resetCategories, legacyCount, exportLegacy, clearLegacy, ledgerCount, clearLedger }) {
  const [message, setMessage] = useState(null); // { ok: boolean, text: string }

  const pickBackupFile = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = ".json,application/json";
    input.onchange = async (e) => {
      const file = e.target.files?.[0];
      if (!file) return;
      if (!window.confirm("Restoring a backup replaces everything currently in the app. Continue?")) return;
      const ok = await importBackup(file);
      setMessage(ok ? { ok: true, text: `Restored from ${file.name}.` } : { ok: false, text: "That file isn't a Budget Telemetry backup." });
    };
    input.click();
  };

  const confirmTemplate = () => {
    if (!window.confirm("Replace all your budget categories with the Toronto starter set? Your incomes, spending log and savings are kept.")) return;
    resetCategories();
    setMessage({ ok: true, text: "Categories replaced with the Toronto starter set." });
  };

  const confirmReset = () => {
    if (!window.confirm("Erase all budget, spending and savings data on this device? Download a backup first if you might want it back.")) return;
    resetAll();
    setMessage({ ok: true, text: "All data cleared." });
  };

  return (
    <div className="page-fade" style={{ maxWidth: 760, margin: "0 auto", position: "relative" }}>
      <PageHeader
        eyebrow="Settings"
        saveStatus={saveStatus}
        title="Your data"
        subtitle="Everything is stored only in this browser on this device and saves automatically. Clearing your browser's site data erases it, so download a backup now and then."
      />

      <Panel title="Backup & restore">
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
          <button type="button" className="text-btn" onClick={exportBackup}>⬇ Download full backup</button>
          <button type="button" className="text-btn" onClick={pickBackupFile}>⬆ Restore from backup…</button>
          <button type="button" className="text-btn" onClick={() => exportHoldingsCSV(holdings, leftover)}>Export savings as CSV</button>
        </div>
        <p style={{ margin: "12px 0 0", fontSize: 13, lineHeight: 1.5, color: "#9AA6BA" }}>
          A backup is one .json file with your budget, spending and savings. Older holdings-only exports can be restored too.
          To move to another phone, download a backup here and restore it there.
        </p>
        {message && (
          <p role="status" style={{ margin: "12px 0 0", fontSize: 13.5, color: message.ok ? GREEN : RED }}>
            {message.ok ? "✓ " : "✕ "}
            {message.text}
          </p>
        )}
      </Panel>

      <Panel title="Spending data">
        <p style={{ margin: "0 0 12px", fontSize: 13, lineHeight: 1.5, color: "#9AA6BA" }}>
          {ledgerCount} imported row{ledgerCount === 1 ? "" : "s"}, stored only in this browser. Imports, exports and backups contain your
          private financial data: keep them out of the project folder (or in its git-ignored <span className="mono">private/</span> folder) and
          never commit them.
        </p>
        {ledgerCount > 0 && (
          <button
            type="button"
            className="text-btn danger"
            onClick={() => {
              if (!window.confirm("Remove every imported spending row from this device? Your budget and savings are kept. Download a backup first if you might want it back.")) return;
              clearLedger();
              setMessage({ ok: true, text: "Imported spending removed." });
            }}
          >
            Erase imported spending
          </button>
        )}
        {legacyCount > 0 && (
          <div style={{ marginTop: 16 }}>
            <p style={{ margin: "0 0 10px", fontSize: 13, lineHeight: 1.5, color: "#FFC145" }}>
              {legacyCount} purchase{legacyCount === 1 ? "" : "s"} from the old manual spending log are kept aside. They no longer count anywhere.
            </p>
            <button
              type="button"
              className="text-btn"
              onClick={() => {
                exportLegacy();
                if (window.confirm("Downloaded. Remove the old spending log from this device now?")) {
                  clearLegacy();
                  setMessage({ ok: true, text: "Old spending log downloaded and removed." });
                }
              }}
            >
              ⬇ Download & remove old spending log
            </button>
          </div>
        )}
      </Panel>

      <Panel title="How the numbers work">
        <HowItWorks />
      </Panel>

      <Panel title="Start over">
        <p style={{ margin: "0 0 12px", fontSize: 13, lineHeight: 1.5, color: "#9AA6BA" }}>
          Reload the Toronto starter categories (rent and vehicle sized to your current take-home pay), keeping
          everything else.
        </p>
        <button type="button" className="text-btn" onClick={confirmTemplate}>Use Toronto starter categories</button>
        <p style={{ margin: "18px 0 12px", fontSize: 13, lineHeight: 1.5, color: "#9AA6BA" }}>
          Or clear every saved number on this device and return the app to its defaults.
        </p>
        <button type="button" className="text-btn danger" onClick={confirmReset}>Erase all data</button>
      </Panel>
    </div>
  );
}

function HowItWorks() {
  return (
    <>
      <InfoSection title="Whose budget">
        This is your personal budget: your take-home pay against your share of costs. Your partner's income is only used
        to work out what share of income-split bills is yours.
      </InfoSection>
      <InfoSection title="Income">
        Take-home pay is estimated from salary using 2026 CRA federal brackets, Ontario brackets/surtax/health premium,
        CPP (incl. CPP2) and EI. If you know the real figure from a payslip, enter it instead — it replaces the estimate.
      </InfoSection>
      <InfoSection title="Splitting bills">
        Each category is either <strong style={{ color: "#E7ECF2" }}>just yours</strong>, <strong style={{ color: "#E7ECF2" }}>shared by take-home
        pay</strong> (if you earn 58% of the two incomes, you pay 58%), or <strong style={{ color: "#E7ECF2" }}>shared 50/50</strong>. For shared
        bills you enter — and log — the whole bill; the app works out your part. The starter set splits rent and the car by
        income, groceries 50/50, and everything else is yours. Yearly costs are spread over 12 months.
      </InfoSection>
      <InfoSection title="Spending record">
        Spending comes from the JSON exports your import chat makes from your statements. Each import is checked (every
        ID is recomputed and the totals must add up to the cent) and previewed before anything is saved; re-importing the
        same file adds nothing. Totals count posted purchases minus refunds — pending charges, card payments and transfers
        are never counted as spending. Personal and business stay separate, and only personal spending counts against your
        budget. Months not fully covered by your imports are marked partial and left out of averages.
      </InfoSection>
      <InfoSection title="Starting amounts & colours">
        Categories start at what a typical person renting in downtown Toronto spends, except rent and the car, which start
        at 30% and 10% of your combined take-home. With comparisons on, <span style={{ color: GREEN }}>green ▼</span> means
        your share is below that typical amount and <span style={{ color: RED }}>red ▲</span> above — reversed for{" "}
        <strong style={{ color: "#E7ECF2" }}>leftover/savings</strong>. Grey means within about 3% or no comparison.
      </InfoSection>
      <InfoSection title="The tile chart" last>
        Each tile's area is its exact share of your take-home pay.
      </InfoSection>
    </>
  );
}

function CornerBrackets({ size = 12, color = ACCENT }) {
  const base = { position: "absolute", width: size, height: size, pointerEvents: "none" };
  return (
    <>
      <span style={{ ...base, top: -1, left: -1, borderTop: `2px solid ${color}`, borderLeft: `2px solid ${color}` }} />
      <span style={{ ...base, top: -1, right: -1, borderTop: `2px solid ${color}`, borderRight: `2px solid ${color}` }} />
      <span style={{ ...base, bottom: -1, left: -1, borderBottom: `2px solid ${color}`, borderLeft: `2px solid ${color}` }} />
      <span style={{ ...base, bottom: -1, right: -1, borderBottom: `2px solid ${color}`, borderRight: `2px solid ${color}` }} />
    </>
  );
}

function LegendChip({ color, label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, color: "#B9C4D6" }}>
      <span style={{ width: 10, height: 10, background: color, boxShadow: `0 0 5px ${color}`, flexShrink: 0 }} />
      <span>{label}</span>
    </div>
  );
}


const rootEl = document.getElementById("root");
ReactDOM.createRoot(rootEl).render(<BudgetVoronoi />);
const boot = document.getElementById("boot");
if (boot) boot.remove();
