/* ============================================================
   App shell — sidebar nav, topbar, theme + device toggle, routing
   ============================================================ */
const { useState: useStateA, useEffect: useEffectA } = React;

const NAV = [
  { group: "Calculate", items: [
    { id: "pcp", label: "PCP Calculator", icon: "pcp" },
    { id: "balloon", label: "Balloon Optimiser", icon: "balloon", tag: "Live" },
    { id: "settlement", label: "Settlement", icon: "settle" },
    { id: "equity", label: "Equity", icon: "equity" },
  ]},
  { group: "Compare & plan", items: [
    { id: "compare", label: "PCP vs Loan vs Cash", icon: "scale" },
    { id: "ownership", label: "True Ownership Cost", icon: "owner" },
  ]},
];
const TITLES = {
  pcp: ["See what the deal really costs.", "Work out monthly payments, the optional final payment and the true cost of a Personal Contract Purchase deal."],
  balloon: ["Balloon Payment Optimiser", "See how the GMFV / balloon changes your monthly payment and total interest — drag to find your sweet spot."],
  settlement: ["Settlement Calculator", "Estimate what you'd need to pay to clear your finance early, and how much interest you'd save."],
  equity: ["Equity Calculator", "Compare your car's value against the settlement figure to see your equity position."],
  compare: ["PCP vs Personal Loan vs Cash", "Compare monthly cost, total interest and ownership outcome across three ways to fund the same car."],
  ownership: ["True Ownership Cost", "Go beyond finance — fuel, insurance, tax, servicing and depreciation to find your real monthly cost."],
};

function Placeholder({ id }) {
  return (
    <div className="card card-pad" style={{ textAlign: "center", padding: "60px 24px", color: "var(--ink-3)" }}>
      <Icon name="balloon" style={{ width: 40, height: 40, margin: "0 auto 12px", color: "var(--accent)" }} />
      <h3 style={{ marginBottom: 6 }}>{id} — coming up next</h3>
      <p style={{ maxWidth: 360, margin: "0 auto", fontSize: 14 }}>This screen is being built in the next pass.</p>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "skin": "aurora",
  "accent": ["oklch(0.60 0.114 224)", "oklch(0.50 0.125 244)"],
  "font": "Schibsted Grotesk",
  "density": "regular",
  "corners": "rounded"
}/*EDITMODE-END*/;

const DENSITY = { compact: [0.82, "14px"], regular: [1, "15px"], comfy: [1.16, "15.5px"] };
const CORNERS = {
  sharp:   ["6px", "8px", "10px", "14px"],
  rounded: ["8px", "12px", "18px", "26px"],
  soft:    ["12px", "18px", "24px", "34px"],
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useStateA(() => location.hash.replace("#", "") || "pcp");
  const theme = "dark";
  const [inputs, setInputs] = useStateA({
    cashPrice: 32000, deposit: 3000, partExchange: 2000, dealerContribution: 500,
    apr: 9.9, termMonths: 48, balloon: 13000, annualMileage: 10000, rateBasis: "effective",
    fees: { acceptance: 0, documentation: 0, optionToPurchase: 0 },
  });

  useEffectA(() => { document.documentElement.setAttribute("data-theme", theme); document.querySelector("global-nav")?.setAttribute("theme", theme); }, [theme]);
  useEffectA(() => { location.hash = route; }, [route]);
  useEffectA(() => {
    const root = document.documentElement, S = root.style;
    const acc = Array.isArray(t.accent) ? t.accent : [t.accent, t.accent];
    const isAurora = (t.skin || "default") === "aurora";
    if (isAurora) { S.removeProperty("--accent"); S.removeProperty("--accent-strong"); }
    else { S.setProperty("--accent", acc[0]); S.setProperty("--accent-strong", acc[1] || acc[0]); }
    const fontFamily = isAurora ? "Geist" : t.font;
    S.setProperty("--font-display", `"${fontFamily}", system-ui, sans-serif`);
    S.setProperty("--font-body", `"${fontFamily}", system-ui, sans-serif`);
    const [pad, fs] = DENSITY[t.density] || DENSITY.regular;
    S.setProperty("--pad", pad); document.body.style.fontSize = fs;
    const c = CORNERS[t.corners] || CORNERS.rounded;
    S.setProperty("--r-sm", c[0]); S.setProperty("--r-md", c[1]); S.setProperty("--r-lg", c[2]); S.setProperty("--r-xl", c[3]);
    // skin: aurora glass overrides tokens via CSS attribute selector
    if ((t.skin || "default") === "aurora") root.setAttribute("data-skin", "aurora");
    else root.removeAttribute("data-skin");
  }, [t]);

  const screen = (() => {
    const p = { inputs, setInputs };
    switch (route) {
      case "pcp": return <PCPCalculator {...p} />;
      case "balloon": return window.BalloonOptimiser ? <BalloonOptimiser {...p} /> : <Placeholder id="Balloon Optimiser" />;
      case "settlement": return window.SettlementTool ? <SettlementTool {...p} /> : <Placeholder id="Settlement" />;
      case "equity": return window.EquityTool ? <EquityTool {...p} /> : <Placeholder id="Equity" />;
      case "compare": return window.CompareTool ? <CompareTool {...p} /> : <Placeholder id="Compare" />;
      case "ownership": return window.OwnershipTool ? <OwnershipTool {...p} /> : <Placeholder id="Ownership" />;
      default: return <PCPCalculator {...p} />;
    }
  })();

  const [title, sub] = TITLES[route] || TITLES.pcp;
  const railSummary = PCPEngine.calculatePCP(inputs);

  function exportReport() {
    const i = inputs, g = (n) => fmt.gbp(n);
    const pcp = PCPEngine.calculatePCP(i);
    const hp = PCPEngine.calculateHP(i);
    const loan = PCPEngine.calculateLoan(i);
    const cash = PCPEngine.calculateCash(i);
    const opts = [["PCP", pcp], ["Hire Purchase", hp], ["Personal loan", loan]];
    const best = opts.slice().sort((a, b) => a[1].totalPayable - b[1].totalPayable)[0];
    window.PremiumReport.generate({
      tool: "PCP Calculator",
      accent: "#4f86d6",
      scenario: `${g(i.cashPrice)} car · ${i.termMonths}-month term · ${i.apr}% APR · ${g(i.balloon)} balloon (GMFV)`,
      verdict: {
        line: `This PCP is ${g(pcp.monthly)}/mo, with ${g(pcp.costOfCredit)} of interest and fees over the term.`,
        reasoning: `Across the ways to fund this car, ${best[0]} has the lowest total payable at ${g(best[1].totalPayable)}. PCP keeps the monthly low by deferring ${g(pcp.balloon)} to an optional final payment — you only own the car outright if you pay it.`,
      },
      metrics: [
        { label: "Monthly payment", value: g(pcp.monthly), accent: "#4f86d6" },
        { label: "Balloon (GMFV)", value: g(pcp.balloon) },
        { label: "Amount financed", value: g(pcp.amountFinanced) },
        { label: "Total interest", value: g(pcp.interest) },
        { label: "Cost of credit", value: g(pcp.costOfCredit) },
        { label: "Total payable", value: g(pcp.totalPayable) },
      ],
      chartSVG: window.PremiumReport.captureSVG(".content svg"),
      tables: [{
        title: "PCP vs Hire Purchase vs Personal loan vs Cash",
        headers: ["Option", "Monthly", "Total payable", "Cost of credit", "Owns at end"],
        rows: [
          ["PCP", g(pcp.monthly), g(pcp.totalPayable), g(pcp.costOfCredit), "Only if balloon paid"],
          ["Hire Purchase", g(hp.monthly), g(hp.totalPayable), g(hp.costOfCredit), "Yes"],
          ["Personal loan", g(loan.monthly), g(loan.totalPayable), g(loan.costOfCredit), "Yes"],
          ["Cash", g(0), g(cash.totalPayable), g(0), "Yes"],
        ],
        highlightRow: ["PCP", "Hire Purchase", "Personal loan"].indexOf(best[0]),
      }],
      notes: [
        "PCP keeps monthly payments low by deferring a large balloon (GMFV) to the end — but you only own the car if you pay it or refinance.",
        "Hire Purchase costs more per month, but you own the car outright at the end with nothing left to pay.",
        "Always compare the total cost of credit, not just the monthly payment — a low monthly often hides a large balloon.",
      ],
    });
  }

  const sidebar = (
    <aside className="sidebar">
      <nav className="rail-nav">
        {NAV.map((g) => (
          <div key={g.group} className="nav-group">
            <div className="nav-group-label">{g.group}</div>
            {g.items.map((it) => (
              <button key={it.id} className={"nav-item" + (route === it.id ? " active" : "")} onClick={() => setRoute(it.id)}>
                <span className="ni-dot" />
                <span className="ni-label">{it.label}</span>
                {it.tag && <span className="ni-tag">{it.tag}</span>}
              </button>
            ))}
          </div>
        ))}
      </nav>
      <div className="rail-foot">
        <div className="rail-foot-label">Current scenario</div>
        <div className="rail-foot-row"><span>Vehicle</span><b className="tnum">{fmt.gbp(inputs.cashPrice)}</b></div>
        <div className="rail-foot-row"><span>Term · APR</span><b className="tnum">{inputs.termMonths}mo · {inputs.apr}%</b></div>
        <div className="rail-foot-row hero"><span>Monthly</span><b className="tnum">{fmt.gbp(railSummary.monthly)}</b></div>
        <div className="rail-foot-note">Estimate only · not advice</div>
      </div>
    </aside>
  );

  const body = (
    <div className="main">
      <div className="content">
        <div className="page-head" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap" }}>
          <div><h1>{title}</h1><p><span style={{ color: "#f5f3ff8c" }}>{sub}</span></p></div>
          <button onClick={exportReport} style={{
            flex: "0 0 auto", display: "inline-flex", alignItems: "center", gap: 7, whiteSpace: "nowrap",
            fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer",
            padding: "10px 16px", borderRadius: "var(--r-md, 12px)", border: "1px solid transparent",
            color: "#04161f", background: "linear-gradient(135deg, oklch(.72 .13 220), oklch(.66 .14 250))",
            boxShadow: "0 8px 24px -12px oklch(.6 .14 240)",
          }}>↓ PDF report</button>
        </div>
        {screen}
      </div>
    </div>
  );

  const tweaksPanel = (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Skin" />
      <TweakRadio label="Visual style" value={t.skin} onChange={(v) => setTweak("skin", v)}
        options={["default", "aurora"]} />
      <TweakSection label="Brand colour" />
      <TweakColor label="Accent" value={t.accent} onChange={(v) => setTweak("accent", v)}
        options={[
          ["oklch(0.60 0.114 224)", "oklch(0.50 0.125 244)"],
          ["oklch(0.58 0.13 268)", "oklch(0.48 0.14 280)"],
          ["oklch(0.60 0.12 160)", "oklch(0.50 0.13 165)"],
          ["oklch(0.60 0.16 300)", "oklch(0.50 0.16 305)"],
          ["oklch(0.52 0.04 250)", "oklch(0.40 0.04 255)"],
        ]} />
      <TweakSection label="Typography" />
      <TweakRadio label="Typeface" value={t.font} onChange={(v) => setTweak("font", v)}
        options={["Schibsted Grotesk", "Space Grotesk", "DM Sans"]} />
      <TweakSection label="Layout" />
      <TweakRadio label="Density" value={t.density} onChange={(v) => setTweak("density", v)}
        options={["compact", "regular", "comfy"]} />
      <TweakRadio label="Corners" value={t.corners} onChange={(v) => setTweak("corners", v)}
        options={["sharp", "rounded", "soft"]} />
    </TweaksPanel>
  );

  return <div className="app">{sidebar}{body}{tweaksPanel}</div>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
