/* ============================================================
   Tool screens: Balloon Optimiser, Settlement, Equity,
   Compare (PCP/Loan/Cash), True Ownership Cost
   ============================================================ */
const { useState: useStateM, useMemo: useMemoM } = React;

/* ---------- Balloon / GMFV Optimiser ---------- */
function BalloonOptimiser({ inputs, setInputs }) {
  const pctNow = inputs.cashPrice ? Math.round((inputs.balloon / inputs.cashPrice) * 100) : 0;
  const [goal, setGoal] = useStateM("monthly");
  const setBalloonPct = (p) => setInputs((s) => ({ ...s, balloon: Math.round(s.cashPrice * (p / 100) / 50) * 50 }));

  const sweep = useMemoM(() => PCPEngine.balloonSweep(inputs, [10, 20, 30, 40, 50, 60, 70]), [inputs]);
  const cur = useMemoM(() => PCPEngine.calculatePCP(inputs), [inputs]);
  const series = [{ points: sweep.map(s => ({ x: s.pct, y: s.monthly })), color: "var(--accent-strong)", fill: true }];
  const intSeries = [{ points: sweep.map(s => ({ x: s.pct, y: s.interest })), color: "var(--warn)", fill: true }];

  const lowest = sweep.reduce((a, b) => b.monthly < a.monthly ? b : a);
  const cheapest = sweep.reduce((a, b) => b.totalPayable < a.totalPayable ? b : a);
  const rec = goal === "monthly"
    ? { t: "Lowest monthly payment", b: `A larger ~${lowest.pct}% balloon pushes your monthly down to about ${fmt.gbp(lowest.monthly)}, but you'll owe ${fmt.gbp(lowest.balloon)} at the end and pay more interest overall.` }
    : goal === "total"
    ? { t: "Lowest total cost", b: `A smaller ~${cheapest.pct}% balloon means higher monthlies (${fmt.gbp(cheapest.monthly)}) but the least interest — best if you intend to keep the car.` }
    : { t: "Own the car outright", b: `Set the balloon as low as you can afford. You repay more of the car each month, leaving a smaller final payment to clear and keep it.` };

  return (
    <div className="grid-12">
      <div className="stack">
        <Card title="Tune the balloon" icon="balloon" sub="GMFV as a share of the cash price.">
          <Slider label="Balloon / GMFV" value={pctNow} onChange={setBalloonPct} min={10} max={70} step={1}
            display={(v) => v + "% · " + fmt.gbp(inputs.cashPrice * v / 100)} />
          <div className="row-wrap" style={{ marginTop: 4 }}>
            {[20, 30, 40, 50, 60, 70].map((p) => (
              <button key={p} className={"btn " + (Math.abs(pctNow - p) < 1 ? "btn-primary" : "btn-ghost")}
                style={{ padding: "7px 13px" }} onClick={() => setBalloonPct(p)}>{p}%</button>
            ))}
          </div>
          <div style={{ height: 1, background: "var(--border)", margin: "16px 0" }} />
          <Slider label="APR" value={inputs.apr} onChange={(v) => setInputs(s => ({ ...s, apr: v }))} min={0} max={29.9} step={0.1} display={(v) => v.toFixed(1) + "%"} />
          <Slider label="Term" value={inputs.termMonths} onChange={(v) => setInputs(s => ({ ...s, termMonths: v }))} min={12} max={60} step={6} display={(v) => v + " mo"} />
        </Card>

        <Card title="What's your priority?" icon="info">
          <Segmented options={[{ value: "monthly", label: "Low monthly" }, { value: "total", label: "Low total cost" }, { value: "own", label: "Own it" }]} value={goal} onChange={setGoal} />
          <div style={{ marginTop: 14, padding: "14px 16px", background: "var(--accent-soft)", borderRadius: "var(--r-md)" }}>
            <div style={{ fontWeight: 700, color: "var(--accent-strong)", fontSize: 14, marginBottom: 4 }}>{rec.t}</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5 }}>{rec.b}</div>
          </div>
        </Card>
      </div>

      <div className="stack" style={{ position: "sticky", top: 86 }}>
        <div className="stat-grid">
          <Stat label="Monthly payment" value={fmt.gbp(cur.monthly)} accent sub={pctNow + "% balloon"} />
          <Stat label="Final balloon" value={fmt.gbp(cur.balloon)} />
          <Stat label="Total interest" value={fmt.gbp(cur.interest)} />
          <Stat label="Total payable" value={fmt.gbp(cur.totalPayable)} />
        </div>
        <Card title="Monthly payment vs balloon size" icon="balloon" sub="Bigger balloon → lower monthly, more interest.">
          <LineChart series={series} yFmt={(v) => "£" + Math.round(v)} marker={{ x: pctNow, y: cur.monthly }}
            xLabels={[10, 30, 50, 70].map(x => ({ x, label: x + "%" }))} />
        </Card>
        <Card title="Total interest vs balloon size" icon="warn">
          <LineChart series={intSeries} height={170} yFmt={(v) => "£" + Math.round(v / 100) / 10 + "k"} marker={{ x: pctNow, y: cur.interest }}
            xLabels={[10, 30, 50, 70].map(x => ({ x, label: x + "%" }))} />
        </Card>
        <Disclaimer>The GMFV is set by the lender based on age, mileage and forecast resale value — you can't usually choose it freely. This optimiser shows the trade-offs to discuss with your dealer.</Disclaimer>
      </div>
    </div>
  );
}

/* ---------- Settlement ---------- */
function SettlementTool({ inputs }) {
  const term = inputs.termMonths;
  const [m, setM] = useStateM(Math.round(term / 2));
  const s = useMemoM(() => PCPEngine.calculateSettlement(inputs, m), [inputs, m]);
  const curve = useMemoM(() => PCPEngine.settlementCurve(inputs), [inputs]);
  const series = [{ points: curve.map(p => ({ x: p.month, y: p.value })), color: "var(--accent-strong)", fill: true }];

  return (
    <div className="grid-12">
      <div className="stack">
        <Card title="When would you settle?" icon="clock" sub={`Based on your current PCP: ${fmt.gbp(inputs.cashPrice)} car, ${inputs.apr}% APR, ${term} months.`}>
          <Slider label="Months into agreement" value={m} onChange={setM} min={0} max={term} step={1} display={(v) => v + " / " + term + " mo"} />
          <div className="stat-grid" style={{ marginTop: 14 }}>
            <Stat label="Paid so far" value={fmt.gbp(s.paidToDate)} sub={`incl. ${fmt.gbp(PCPEngine.calculatePCP(inputs).totalDeposit)} deposit`} />
            <Stat label="Interest you'd save" value={fmt.gbp(s.interestSaved)} sub="vs running full term" />
          </div>
        </Card>
        <Disclaimer>A real settlement figure comes from your lender and may include a short interest period and a small admin charge. Early settlement rebates are governed by the Consumer Credit Act 1974. This is an estimate only.</Disclaimer>
      </div>
      <div className="stack" style={{ position: "sticky", top: 86 }}>
        <div className="hero-result">
          <div className="hr-label">ESTIMATED SETTLEMENT AT MONTH {m}</div>
          <div className="hr-value">{fmt.gbp(s.settlement)}</div>
          <div className="hr-foot">To clear the agreement and own the car today</div>
        </div>
        <Card title="Settlement over the agreement" icon="settle" sub="What you'd pay to clear, month by month.">
          <LineChart series={series} yFmt={(v) => "£" + Math.round(v / 1000) + "k"} marker={{ x: m, y: s.settlement }}
            xLabels={[0, Math.round(term / 3), Math.round(2 * term / 3), term].map(x => ({ x, label: "m" + x }))} />
        </Card>
        <Card title="If you settled now" icon="compare">
          <BrkRow k="Settlement figure" v={fmt.gbp(s.settlement)} />
          <BrkRow k="Remaining payments avoided" v={fmt.gbp(s.remainingPayments)} tip="Future monthlies plus the balloon you would no longer pay." />
          <BrkRow k="Estimated interest saved" v={fmt.gbp(s.interestSaved)} total />
        </Card>
      </div>
    </div>
  );
}

/* ---------- Equity ---------- */
function EquityTool({ inputs }) {
  const term = inputs.termMonths;
  const [m, setM] = useStateM(Math.round(term / 2));
  const [marketValue, setMarketValue] = useStateM(Math.round(inputs.cashPrice * 0.62 / 250) * 250);
  const settle = useMemoM(() => PCPEngine.calculateSettlement(inputs, m).settlement, [inputs, m]);
  const eq = useMemoM(() => PCPEngine.calculateEquity({ marketValue, settlement: settle }), [marketValue, settle]);
  const positive = eq.equity >= 0;

  return (
    <div className="grid-12">
      <div className="stack">
        <Card title="Your car & finance" icon="equity">
          <MoneyInput label="Current market value" value={marketValue} onChange={setMarketValue}
            tip="What your car is worth today — check a valuation tool or dealer offer." step={250} />
          <Slider label="Months into agreement" value={m} onChange={setM} min={0} max={term} step={1} display={(v) => v + " / " + term + " mo"} />
          <div className="field" style={{ marginTop: 4 }}>
            <div className="field-label">Estimated settlement <InfoTip text="Pulled from your PCP settlement estimate at the selected month." /></div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 600, color: "var(--ink)" }}>{fmt.gbp(settle)}</div>
          </div>
        </Card>
        <Card title="What this means" icon="info">
          <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.55 }}>
            {positive ? (
              <>You hold <b style={{ color: "var(--pos)" }}>{fmt.gbp(eq.equity)}</b> of positive equity. You could put this towards a new deposit, change car early, or settle and sell privately.</>
            ) : (
              <>You're in <b style={{ color: "var(--neg)" }}>{fmt.gbp(-eq.equity)}</b> of negative equity — the car is worth less than you owe. Wait for the balance to fall, or budget to cover the gap before changing.</>
            )}
          </div>
        </Card>
      </div>
      <div className="stack" style={{ position: "sticky", top: 86 }}>
        <div className="hero-result" style={positive ? null : { background: "linear-gradient(150deg, var(--neg), oklch(0.5 0.15 25))" }}>
          <div className="hr-label">{positive ? "POSITIVE EQUITY" : "NEGATIVE EQUITY"}</div>
          <div className="hr-value">{positive ? "" : "–"}{fmt.gbp(Math.abs(eq.equity))}</div>
          <div className="hr-foot">Value {fmt.gbp(marketValue)} − settlement {fmt.gbp(settle)}</div>
        </div>
        <Card title="Value vs what you owe" icon="equity">
          <EquityBar marketValue={marketValue} settlement={settle} />
        </Card>
        <div className="stat-grid">
          <Stat label="Loan-to-value" value={fmt.pct(eq.ltv)} sub={eq.ltv > 100 ? "owe more than it's worth" : "owe less than it's worth"} />
          <Stat label="Usable for next deposit" value={fmt.gbp(Math.max(0, eq.equity))} accent />
        </div>
      </div>
    </div>
  );
}

window.BalloonOptimiser = BalloonOptimiser;
window.SettlementTool = SettlementTool;
window.EquityTool = EquityTool;
