/* ============================================================
   Tool screens (2): PCP vs Loan vs Cash, True Ownership Cost
   ============================================================ */
const { useState: useStateM2, useMemo: useMemoM2 } = React;

/* ---------- PCP vs Personal Loan vs Cash ---------- */
function CompareTool({ inputs }) {
  const [loanApr, setLoanApr] = useStateM2(8.9);
  const pcp = useMemoM2(() => PCPEngine.calculatePCP(inputs), [inputs]);
  const loan = useMemoM2(() => PCPEngine.calculateLoan({ ...inputs, apr: loanApr }), [inputs, loanApr]);
  const cash = useMemoM2(() => PCPEngine.calculateCash(inputs), [inputs]);

  const monthlyBars = [
    { label: "PCP", value: pcp.monthly, color: "var(--accent-strong)", sublabel: "+ balloon" },
    { label: "Bank loan", value: loan.monthly, color: "var(--accent)", sublabel: "own at end" },
    { label: "Cash", value: 0, color: "var(--pos)", sublabel: "paid upfront" },
  ];
  const costBars = [
    { label: "PCP", value: pcp.costOfCredit, color: "var(--accent-strong)" },
    { label: "Bank loan", value: loan.costOfCredit, color: "var(--accent)" },
    { label: "Cash", value: 0, color: "var(--pos)" },
  ];
  const rows = [
    { k: "Monthly payment", pcp: fmt.gbp(pcp.monthly), loan: fmt.gbp(loan.monthly), cash: "—" },
    { k: "Final balloon", pcp: fmt.gbp(pcp.balloon), loan: "—", cash: "—" },
    { k: "Interest & fees", pcp: fmt.gbp(pcp.costOfCredit), loan: fmt.gbp(loan.costOfCredit), cash: fmt.gbp(0) },
    { k: "Total to own car", pcp: fmt.gbp(pcp.totalPayable), loan: fmt.gbp((inputs.deposit + inputs.partExchange) + loan.totalInstalments), cash: fmt.gbp(inputs.cashPrice) },
    { k: "Own at the end?", pcp: "Optional", loan: "Yes", cash: "Yes" },
    { k: "Flexibility", pcp: "High", loan: "Medium", cash: "Low" },
  ];
  const saveVsPcp = pcp.costOfCredit - loan.costOfCredit;

  return (
    <div className="stack">
      <div className="grid-2">
        <Card title="Monthly cost" icon="scale" sub="What leaves your account each month.">
          <CompareBars items={monthlyBars} fmt={(v) => v ? fmt.gbp(v) : "£0"} />
        </Card>
        <Card title="Total interest & fees" icon="warn" sub="The price of borrowing, by method.">
          <CompareBars items={costBars} fmt={(v) => v ? fmt.gbp(v) : "£0"} />
        </Card>
      </div>

      <Card title="Side-by-side" icon="compare" action={
        <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--ink-2)" }}>
          Loan APR
          <input className="text-input no-prefix tnum" style={{ width: 78, padding: "6px 8px", fontSize: 13 }} type="number" step={0.1} value={loanApr} onChange={(e) => setLoanApr(parseFloat(e.target.value) || 0)} />
        </div>
      }>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13.5 }}>
            <thead>
              <tr style={{ textAlign: "left", color: "var(--ink-3)" }}>
                <th style={{ padding: "8px 10px", fontWeight: 600 }}></th>
                <th style={{ padding: "8px 10px", fontWeight: 700, color: "var(--accent-strong)" }}>PCP</th>
                <th style={{ padding: "8px 10px", fontWeight: 700 }}>Bank loan</th>
                <th style={{ padding: "8px 10px", fontWeight: 700 }}>Cash</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={i} style={{ borderTop: "1px solid var(--border)" }}>
                  <td style={{ padding: "11px 10px", color: "var(--ink-2)", fontWeight: 500 }}>{r.k}</td>
                  <td style={{ padding: "11px 10px", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{r.pcp}</td>
                  <td style={{ padding: "11px 10px", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{r.loan}</td>
                  <td style={{ padding: "11px 10px", fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{r.cash}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <div className="grid-2">
        <Card title="The trade-off" icon="info">
          <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.6 }}>
            {saveVsPcp > 0
              ? <>A bank loan at {loanApr}% would cost about <b style={{ color: "var(--pos)" }}>{fmt.gbp(Math.abs(saveVsPcp))} less</b> in interest than this PCP, and you'd own the car outright — but your monthly payment is higher and there's no low-commitment hand-back option.</>
              : <>This PCP is competitive on cost of credit versus a {loanApr}% loan, and keeps your monthly payment lower thanks to the deferred balloon. The trade-off is you don't own the car unless you pay the {fmt.gbp(pcp.balloon)} balloon.</>}
          </div>
        </Card>
        <Card title="Paying cash?" icon="spark">
          <div style={{ fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.6 }}>
            Cash avoids <b style={{ color: "var(--pos)" }}>{fmt.gbp(pcp.costOfCredit)}</b> of PCP interest and fees, but ties up {fmt.gbp(inputs.cashPrice)} of capital. Compare against what that money could earn elsewhere before deciding.
          </div>
        </Card>
      </div>
      <Disclaimer>Comparisons assume the same vehicle price and term. Loan and PCP APRs are illustrative — your actual rate depends on status. Not financial advice.</Disclaimer>
    </div>
  );
}

/* ---------- True Ownership Cost ---------- */
function OwnershipTool({ inputs }) {
  const financeMonthly = useMemoM2(() => PCPEngine.calculatePCP(inputs).monthly, [inputs]);
  const [o, setO] = useStateM2({
    fuelType: "petrol", mpg: 45, pencePerLitre: 148, milesPerKwh: 3.8, pencePerKwh: 28,
    insuranceAnnual: 720, roadTaxAnnual: 190, servicingAnnual: 300, maintenanceAnnual: 250, tyresAnnual: 180,
    depreciationAnnual: 0,
  });
  const set = (k, v) => setO((s) => ({ ...s, [k]: v }));
  const isEv = o.fuelType === "ev";

  const res = useMemoM2(() => PCPEngine.calculateOwnership({
    ...o, financeMonthly, annualMileage: inputs.annualMileage, fuelType: isEv ? "ev" : "petrol",
  }), [o, financeMonthly, inputs.annualMileage, isEv]);

  const donut = res.parts.map((p) => ({ k: p.k, v: p.v, label: fmt.gbp(p.v) }));

  return (
    <div className="grid-12">
      <div className="stack">
        <Card title="Power & energy" icon={isEv ? "bolt" : "fuel"}>
          <Segmented options={[{ value: "petrol", label: "Petrol/Diesel", icon: "fuel" }, { value: "ev", label: "Electric", icon: "bolt" }]}
            value={o.fuelType} onChange={(v) => set("fuelType", v)} />
          <div style={{ marginTop: 14 }}>
            {isEv ? (
              <div className="grid-2" style={{ gap: 12 }}>
                <MoneyInput label="Efficiency (mi/kWh)" value={o.milesPerKwh} onChange={(v) => set("milesPerKwh", v)} prefix="" suffix="mi" step={0.1} />
                <MoneyInput label="Electricity (p/kWh)" value={o.pencePerKwh} onChange={(v) => set("pencePerKwh", v)} prefix="" suffix="p" step={1} />
              </div>
            ) : (
              <div className="grid-2" style={{ gap: 12 }}>
                <MoneyInput label="Economy (mpg)" value={o.mpg} onChange={(v) => set("mpg", v)} prefix="" suffix="mpg" step={1} />
                <MoneyInput label="Fuel (p/litre)" value={o.pencePerLitre} onChange={(v) => set("pencePerLitre", v)} prefix="" suffix="p" step={1} />
              </div>
            )}
          </div>
          <div style={{ marginTop: 6, fontSize: 12, color: "var(--ink-3)" }}>
            Based on {fmt.num(inputs.annualMileage)} miles/yr · {fmt.gbp(res.energyAnnual)}/yr {isEv ? "electricity" : "fuel"}
          </div>
        </Card>
        <Card title="Running costs (per year)" icon="owner">
          <div className="grid-2" style={{ gap: 12 }}>
            <MoneyInput label="Insurance" value={o.insuranceAnnual} onChange={(v) => set("insuranceAnnual", v)} step={20} />
            <MoneyInput label="Road tax (VED)" value={o.roadTaxAnnual} onChange={(v) => set("roadTaxAnnual", v)} step={10} />
            <MoneyInput label="Servicing" value={o.servicingAnnual} onChange={(v) => set("servicingAnnual", v)} step={20} />
            <MoneyInput label="Maintenance" value={o.maintenanceAnnual} onChange={(v) => set("maintenanceAnnual", v)} step={20} />
            <MoneyInput label="Tyres" value={o.tyresAnnual} onChange={(v) => set("tyresAnnual", v)} step={20} />
            <MoneyInput label="Extra depreciation" value={o.depreciationAnnual} onChange={(v) => set("depreciationAnnual", v)}
              tip="On PCP, most depreciation sits inside your payments. Add extra here only if buying outright." step={100} />
          </div>
        </Card>
      </div>

      <div className="stack" style={{ position: "sticky", top: 86 }}>
        <div className="hero-result">
          <div className="hr-label">TRUE COST OF OWNERSHIP</div>
          <div className="hr-value">{fmt.gbp(res.totalMonthly)}<small>/mo</small></div>
          <div className="hr-foot">{fmt.gbp(res.totalAnnual)} per year · {fmt.gbp(res.fiveYear)} over 5 years</div>
        </div>
        <Card title="Where it goes" icon="equity" sub="Finance is usually the biggest slice — but not the only one.">
          <DonutBreakdown data={donut} centerValue={fmt.gbp(res.totalMonthly)} centerLabel="per month" />
        </Card>
        <div className="stat-grid">
          <Stat label="Finance" value={fmt.gbp(financeMonthly)} sub="/mo (from PCP)" />
          <Stat label={isEv ? "Electricity" : "Fuel"} value={fmt.gbp(res.energyAnnual / 12)} sub="/mo" />
          <Stat label="Everything else" value={fmt.gbp(res.runningAnnual / 12)} sub="/mo" />
        </div>
        <Disclaimer>Energy, insurance and servicing costs vary widely by car, driver and region. Depreciation on PCP is largely captured by your monthly payment and balloon. Estimates only.</Disclaimer>
      </div>
    </div>
  );
}

window.CompareTool = CompareTool;
window.OwnershipTool = OwnershipTool;
