/* ============================================================
   Core PCP Calculator screen
   ============================================================ */
const { useMemo: useMemoP } = React;

function PCPCalculator({ inputs, setInputs }) {
  const set = (k, v) => setInputs((s) => ({ ...s, [k]: v }));
  const setFee = (k, v) => setInputs((s) => ({ ...s, fees: { ...s.fees, [k]: v } }));
  const r = useMemoP(() => PCPEngine.calculatePCP(inputs), [inputs]);

  const donut = [
    { k: "Amount financed", v: r.amountFinanced, label: fmt.gbp(r.amountFinanced) },
    { k: "Deposit + part-ex", v: r.totalDeposit, label: fmt.gbp(r.totalDeposit) },
    { k: "Interest & fees", v: r.costOfCredit, label: fmt.gbp(r.costOfCredit) },
  ];

  return (
    <div className="grid-12">
      {/* ---- Inputs ---- */}
      <div className="stack">
        <Card title="Vehicle & deposit" icon="pcp">
          <MoneyInput label="Vehicle cash price" value={inputs.cashPrice} onChange={(v) => set("cashPrice", v)}
            tip="The on-the-road price of the car you're financing." step={250} />
          <div className="grid-2" style={{ gap: 12 }}>
            <MoneyInput label="Cash deposit" value={inputs.deposit} onChange={(v) => set("deposit", v)} step={100} />
            <MoneyInput label="Part exchange" value={inputs.partExchange} onChange={(v) => set("partExchange", v)}
              tip="Value of any vehicle you're trading in." step={100} />
          </div>
          <MoneyInput label="Dealer deposit contribution" value={inputs.dealerContribution}
            onChange={(v) => set("dealerContribution", v)} tip="Money the dealer or manufacturer puts towards your deposit." step={50} />
          <div style={{ marginTop: 4 }}>
            <Pill kind={r.depositPct >= 10 ? "pos" : "warn"}>
              {fmt.pct(r.depositPct)} total deposit
            </Pill>
          </div>
        </Card>

        <Card title="Finance terms" icon="settle">
          <Slider label="APR (representative)" value={inputs.apr} onChange={(v) => set("apr", v)}
            min={0} max={29.9} step={0.1} display={(v) => v.toFixed(1) + "%"}
            tip="Annual Percentage Rate — the cost of borrowing including interest and fees." />
          <div className="field">
            <label className="field-label">
              Rate basis
              <InfoTip text="How the APR is applied each month. Effective APR — (1+APR)^(1/12)−1 — is the FCA-correct definition. Nominal (APR÷12) matches many dealer and aggregator tools like Autotrader, giving a slightly higher payment." />
            </label>
            <Segmented
              options={[{ value: "effective", label: "Effective APR" }, { value: "nominal", label: "Nominal (APR÷12)" }]}
              value={inputs.rateBasis || "effective"} onChange={(v) => set("rateBasis", v)} />
            <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 6, lineHeight: 1.45 }}>
              {(inputs.rateBasis || "effective") === "nominal"
                ? "Aggregator-style — matches many dealer & comparison sites."
                : "FCA-correct true annual rate. Lower monthly than nominal."}
            </div>
          </div>
          <Slider label="Term" value={inputs.termMonths} onChange={(v) => set("termMonths", v)}
            min={12} max={60} step={6} display={(v) => v + " months"} />
          <div className="field">
            <div className="slider-row">
              <label className="field-label" style={{ marginBottom: 0 }}>
                GMFV / balloon payment
                <InfoTip text="Guaranteed Minimum Future Value — the optional final payment to own the car. Type the exact figure from your quote, or drag to explore." />
              </label>
              <span className="slider-val">{fmt.pct(inputs.cashPrice ? (inputs.balloon / inputs.cashPrice) * 100 : 0)} of price</span>
            </div>
            <div className="input-wrap" style={{ marginBottom: 9 }}>
              <span className="input-prefix">£</span>
              <input className="text-input" type="number" inputMode="decimal" min={0} step={250}
                value={inputs.balloon}
                onChange={(e) => set("balloon", e.target.value === "" ? 0 : Math.max(0, Math.min(inputs.cashPrice, parseFloat(e.target.value))))} />
            </div>
            <input className="rng" type="range" min={0} max={Math.max(250, Math.round(inputs.cashPrice * 0.75))} step={250}
              value={Math.min(inputs.balloon, Math.round(inputs.cashPrice * 0.75))}
              onChange={(e) => set("balloon", parseFloat(e.target.value))} />
          </div>
          <Slider label="Annual mileage" value={inputs.annualMileage} onChange={(v) => set("annualMileage", v)}
            min={5000} max={30000} step={1000} display={(v) => fmt.num(v) + " mi"}
            tip="Higher mileage lowers the GMFV and can raise payments." />
        </Card>

        <Card title="Fees" icon="dealer" sub="Common PCP charges — check your agreement.">
          <div className="grid-2" style={{ gap: 12 }}>
            <MoneyInput label="Acceptance fee" value={inputs.fees.acceptance} onChange={(v) => setFee("acceptance", v)} step={10} />
            <MoneyInput label="Documentation fee" value={inputs.fees.documentation} onChange={(v) => setFee("documentation", v)} step={10} />
          </div>
          <MoneyInput label="Option to purchase fee" value={inputs.fees.optionToPurchase} onChange={(v) => setFee("optionToPurchase", v)}
            tip="Paid with the final balloon payment if you keep the car." step={10} />
        </Card>
      </div>

      {/* ---- Results ---- */}
      <div className="stack" style={{ position: "sticky", top: 86 }}>
        <div className="hero-result">
          <div className="hr-label">ESTIMATED MONTHLY PAYMENT</div>
          <div className="hr-value">{fmt.gbp(r.monthly)}<small>/mo</small></div>
          <div className="hr-foot">{inputs.termMonths} monthly payments · then {fmt.gbpAuto(r.finalPayment)} balloon to own</div>
        </div>

        <div className="stat-grid">
          <Stat label="Amount financed" value={fmt.gbp(r.amountFinanced)} />
          <Stat label="Balloon (GMFV)" value={fmt.gbpAuto(r.balloon)} tip="Optional final payment to keep the car." />
          <Stat label="Total interest" value={fmt.gbp(r.interest)} />
          <Stat label="Cost of credit" value={fmt.gbp(r.costOfCredit)} tip="Total interest plus all fees." accent />
        </div>

        <Card title="Where your money goes" icon="equity">
          <DonutBreakdown data={donut} centerValue={fmt.gbp(r.totalPayable)} centerLabel="total payable" />
        </Card>

        <Card title="Finance summary" icon="compare">
          <BrkRow k="Vehicle cash price" v={fmt.gbp(inputs.cashPrice)} />
          <BrkRow k="Less deposit & part-exchange" v={"– " + fmt.gbp(r.totalDeposit)} />
          <BrkRow k="Amount of credit" v={fmt.gbp(r.amountFinanced)} />
          <BrkRow k={`${inputs.termMonths} monthly payments`} v={fmt.gbp(r.monthly)} />
          <BrkRow k="Total of monthly payments" v={fmt.gbp(r.totalInstalments)} />
          <BrkRow k="Optional final payment" v={fmt.gbpAuto(r.finalPayment)} tip="Balloon + option-to-purchase fee." />
          <BrkRow k="Fixed fees" v={fmt.gbp(r.feeTotal)} />
          <BrkRow k="Total amount payable" v={fmt.gbp(r.totalPayable)} total />
        </Card>

        <Disclaimer>
          Representative example only. Figures are estimates and not a finance quotation or financial advice.
          Actual APR, GMFV and payments depend on your circumstances and the lender's terms. PCP finance is subject to
          status and affordability checks. <b>UK PCP Calculator Pro is not a lender or credit broker.</b>
        </Disclaimer>
      </div>
    </div>
  );
}
window.PCPCalculator = PCPCalculator;
