/* ═══════════════════════════════════════════════════════════════════
   PERX — company-car-tax (BIK) calculator · suite tab "c"
   EV-first; petrol / diesel / plug-in hybrid via CO2. Indicative
   figure → email gate → Class 1A NI waterfall + multi-year schedule.
   Mounted by app.jsx (no self-mount); reuses shared.jsx + data.js (PX)
   + bik.js (BIK engine + DVLA proxy lookup).
   ═══════════════════════════════════════════════════════════════════ */
const { useState: useStateK, useMemo: useMemoK } = React;

function MoneyInput({ value, onChange }) {
  // Text + inputMode=numeric so we can show a thousands separator (39,990) —
  // a type=number input can't render commas. Parse digits back to a number.
  const display = value > 0 ? value.toLocaleString('en-GB') : '';
  return (
    <div className="inp-money">
      <span className="cur">£</span>
      <input className="inp" type="text" inputMode="numeric" value={display}
        placeholder="0"
        onChange={e => onChange(Math.max(0, +e.target.value.replace(/[^0-9]/g, '') || 0))} />
    </div>
  );
}

/* UK number-plate styled input (blue GB band + yellow field) */
function PlateField({ value, onChange, onEnter }) {
  return (
    <div style={{ display: 'flex', alignItems: 'stretch', borderRadius: 10, overflow: 'hidden', border: '2px solid #11110a', height: 54, boxShadow: '0 4px 14px rgba(0,0,0,.4)', flex: 1, minWidth: 0 }}>
      <div style={{ background: '#0a3aa8', color: '#fff', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: 30, fontWeight: 800, fontSize: 11, lineHeight: 1.1 }}>
        <span style={{ fontSize: 10 }}>★</span><span>GB</span>
      </div>
      <input value={value} onChange={e => onChange(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') onEnter(); }}
        placeholder="YOUR REG" maxLength={9}
        style={{ flex: 1, minWidth: 0, border: 0, outline: 0, background: '#FFD400', color: '#11110a', fontFamily: 'var(--mono)', fontWeight: 800, fontSize: 23, letterSpacing: '.06em', textAlign: 'center', textTransform: 'uppercase' }} />
    </div>
  );
}

/* reg lookup — calls the DVLA VES proxy (via BIK.lookupReg) and lifts the result */
function RegLookup({ onApply }) {
  const [plate, setPlate] = useStateK('');
  const [busy, setBusy] = useStateK(false);
  const [err, setErr] = useStateK('');
  const run = async (p) => {
    const val = (p != null ? p : plate);
    if (!val || !val.trim() || busy) return;
    setBusy(true); setErr('');
    const res = await BIK.lookupReg(val);
    setBusy(false);
    if (res.found) onApply(BIK.dvlaToInputs(res.data), res.plate);
    else setErr('No DVLA record for “' + val.toUpperCase().trim() + '”. Enter the details manually below.');
  };
  const ex = [['CA03 ABC', 'Porsche ’03'], ['LV23 EVX', 'Tesla EV'], ['BD68 XKD', 'BMW diesel'], ['P123 OLD', 'missing CO₂']];
  return (
    <div className="field">
      <div className="flabel"><b>Look up your reg</b><span className="hint">via DVLA</span></div>
      <div style={{ display: 'flex', gap: 10 }}>
        <PlateField value={plate} onChange={setPlate} onEnter={() => run()} />
        <button className="cta" style={{ width: 'auto', padding: '0 22px' }} onClick={() => run()} disabled={busy}>
          {busy ? <span className="spin"></span> : 'Look up'}
        </button>
      </div>
      {err && <div style={{ marginTop: 10, fontSize: 12.5, color: 'var(--orange)', fontWeight: 500 }}>{err}</div>}
      <div className="pill-row" style={{ marginTop: 12 }}>
        {ex.map(([p, l]) => (
          <button key={p} className="pill" style={{ cursor: 'pointer' }} onClick={() => { setPlate(p); run(p); }}>
            <span className="pt-num" style={{ fontSize: 11 }}>{p}</span><span style={{ opacity: .6 }}>{l}</span>
          </button>
        ))}
      </div>
      <div className="note" style={{ marginTop: 10 }}>DVLA returns fuel, CO₂, engine &amp; age — <b style={{ color: 'var(--text)' }}>not P11D</b>, so you’ll still add the list price.</div>
    </div>
  );
}

/* employer Class 1A NI waterfall: P11D → ×% → benefit → ×15% → NI */
function NiWaterfall({ p11d, pct, benefit, class1a }) {
  const step = (label, val, sub, accent) => (
    <div style={{ flex: 1, minWidth: 0, background: accent ? 'rgba(167,235,82,.10)' : 'var(--field)', border: `1px solid ${accent ? 'rgba(167,235,82,.3)' : 'var(--line)'}`, borderRadius: 'var(--r-sm)', padding: '14px 12px' }}>
      <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 500 }}>{label}</div>
      <div className="pt-num" style={{ fontSize: 'clamp(13px,3.4vw,18px)', lineHeight: 1.15, letterSpacing: '-.02em', color: accent ? 'var(--green)' : 'var(--ink)', fontWeight: 600, marginTop: 5, whiteSpace: 'nowrap' }}>{val}</div>
      <div style={{ fontSize: 11, color: 'var(--faint)', marginTop: 3 }}>{sub}</div>
    </div>
  );
  const op = () => (
    <div style={{ display: 'grid', placeItems: 'center', color: 'var(--muted)', fontFamily: 'var(--mono)', fontSize: 18, padding: '0 2px', flex: '0 0 auto' }}>→</div>
  );
  return (
    <div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
      {step('P11D value', PX.gbp(p11d), 'list price + extras')}
      {op()}
      {step(`Appropriate %`, pct + '%', 'this tax year')}
      {op()}
      {step('Taxable benefit', PX.gbp(benefit), '= P11D × %', false)}
      {op()}
      {step('Class 1A NI', PX.gbp(class1a), '= benefit × 15%', true)}
    </div>
  );
}

function ScheduleTable({ rows }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 'var(--r-sm)', overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr .7fr 1fr 1fr 1.1fr', background: 'rgba(255,255,255,.04)', borderBottom: '1px solid var(--line)' }}>
        {['Tax year', 'Rate', 'Taxable benefit', 'Your tax /mo', 'Employer NI /yr'].map((h, i) => (
          <div key={i} style={{ padding: '11px 12px', fontSize: 11.5, fontWeight: 700, letterSpacing: '.03em', textTransform: 'uppercase', color: 'var(--muted)', textAlign: i ? 'right' : 'left' }}>{h}</div>
        ))}
      </div>
      {rows.map((r, i) => {
        const cur = r.year === 2026;
        return (
          <div key={r.year} style={{ display: 'grid', gridTemplateColumns: '1.1fr .7fr 1fr 1fr 1.1fr', alignItems: 'center', minHeight: 48, background: cur ? 'rgba(167,235,82,.08)' : (i % 2 ? 'rgba(255,255,255,.015)' : 'transparent'), borderBottom: i < rows.length - 1 ? '1px solid var(--line-soft)' : 'none' }}>
            <div style={{ padding: '10px 12px', fontWeight: 600, color: cur ? 'var(--green)' : 'var(--text)', display: 'flex', alignItems: 'center', gap: 8 }}>{r.label}{cur && <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--green-ink)', background: 'var(--green)', padding: '2px 6px', borderRadius: 5, lineHeight: 1.4 }}>NOW</span>}</div>
            <div className="pt-num" style={{ padding: '10px 12px', textAlign: 'right', color: 'var(--text)' }}>{r.pct}%</div>
            <div className="pt-num" style={{ padding: '10px 12px', textAlign: 'right', color: 'var(--text)' }}>{PX.gbp(r.benefit)}</div>
            <div className="pt-num" style={{ padding: '10px 12px', textAlign: 'right', color: cur ? 'var(--green)' : 'var(--text)', fontWeight: 600 }}>{PX.gbp2(r.empTaxMo)}</div>
            <div className="pt-num" style={{ padding: '10px 12px', textAlign: 'right', color: 'var(--muted)' }}>{PX.gbp(r.class1a)}</div>
          </div>
        );
      })}
    </div>
  );
}

function ToolBIK() {
  const [carId, setCarId] = useStateK('tesla-m3');
  const [fuel, setFuel] = useStateK('electric');
  const [p11d, setP11d] = useStateK(39990);
  const [co2, setCo2] = useStateK(0);
  const [erange, setErange] = useStateK(40);
  const [rde2, setRde2] = useStateK(true);
  const [band, setBand] = useStateK('higher');
  const [unlocked, setUnlocked] = useStateK(false);
  const [share, setShare] = useStateK(false);
  const [vehicle, setVehicle] = useStateK(null);     // DVLA-looked-up provenance
  const [co2Missing, setCo2Missing] = useStateK(false);
  const [p11dPending, setP11dPending] = useStateK(false);  // reg looked up, awaiting list price (VES never supplies P11D)
  const ref = useMemoK(() => PX.shortRef(), []);

  const pickCar = (c) => {
    setCarId(c.id); setVehicle(null); setCo2Missing(false); setP11dPending(false);
    setFuel(c.fuel); setP11d(c.p11d); setCo2(c.co2 || 0);
    if (c.erange) setErange(c.erange);
  };
  const applyLookup = (inp, plate) => {
    setCarId('');
    setVehicle(Object.assign({}, inp.vehicle, { plate: plate, flags: inp.flags }));
    setFuel(inp.fuel);
    setCo2(inp.co2 != null ? inp.co2 : 0);
    setCo2Missing(!!inp.flags.co2Missing);
    if (inp.fuel === 'diesel') setRde2(!!inp.rde2);
    // VES never supplies P11D — clear the carried-over value so the headline
    // isn't computed from a prior car's list price. Prompt for the real one.
    setP11d(0);
    setP11dPending(true);
  };
  const opts = useMemoK(() => ({ fuel, p11d, co2, erange, dieselSurcharge: fuel === 'diesel' && !rde2 }), [fuel, p11d, co2, erange, rde2]);
  const r = useMemoK(() => BIK.calcBik(opts, band, 2026), [opts, band]);
  const sched = useMemoK(() => BIK.schedule(opts, band), [opts, band]);
  const car = BIK.CARS.find(c => c.id === carId);
  // VES returns make only (no model/trim) — avoid "PORSCHE undefined".
  const carName = vehicle
    ? [vehicle.make, vehicle.model].filter(Boolean).join(' ')
    : (car ? car.make + ' ' + car.model : 'Your car');
  const isEV = fuel === 'electric';

  return (
    <div>
      <ToolHead eyebrow="Company-car tax calculator"
        title="What’s the Benefit-in-Kind on your car?"
        sub="Pick a car or enter its figures. See the company-car (BIK) tax you’d pay this year — and how electric compares — with the 2026/27 rate shown in full." />

      <div className="grid2">
        {/* INPUTS */}
        <div className="card card-pad">
          <div className="card-title"><span className="n">1</span>Your car</div>

          <RegLookup onApply={applyLookup} />

          {vehicle && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'rgba(167,235,82,.08)', border: '1px solid rgba(167,235,82,.28)', borderRadius: 'var(--r-sm)', marginBottom: 20 }}>
              <span className="pt-num" style={{ fontSize: 11, fontWeight: 700, color: 'var(--green-ink)', background: 'var(--green)', padding: '4px 8px', borderRadius: 6 }}>{vehicle.plate}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ink)' }}>{[vehicle.make, vehicle.model].filter(Boolean).join(' ')}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)' }}>{vehicle.year}{vehicle.engine ? ' · ' + vehicle.engine + 'cc' : ''} · from DVLA{vehicle.flags && vehicle.flags.preWltp ? ' · NEDC CO₂ basis' : ''}</div>
              </div>
            </div>
          )}

          <div className="divider"></div>

          <div className="field">
            <div className="flabel"><b>{vehicle ? 'Or pick another' : 'Quick pick'}</b><span className="hint">Across fuel types</span></div>
            <div className="prodgrid" style={{ gridTemplateColumns: 'repeat(3,1fr)' }}>
              {BIK.CARS.slice(0, 6).map(c => {
                const on = carId === c.id;
                return (
                  <button key={c.id} className={'prodchip' + (on ? ' on' : '')} onClick={() => pickCar(c)} style={{ minHeight: 86 }}>
                    <span className="chk">{UIICON.check}</span>
                    <div style={{ marginTop: 'auto' }}>
                      <div className="pname" style={{ fontSize: 13 }}>{c.make}</div>
                      <div className="pcost">{c.model}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="divider"></div>

          <div className="field">
            <div className="flabel"><b>Fuel type</b></div>
            <Seg value={fuel} onChange={v => { setFuel(v); if (v === 'electric') setCo2(0); else if (co2 === 0) setCo2(v === 'phev' ? 32 : 120); }}
              options={BIK.FUELS.map(f => ({ value: f.key, label: f.label }))} />
          </div>

          <div className="field">
            <div className="flabel"><b>P11D value</b><span className="hint">{vehicle ? 'DVLA can’t supply this' : 'List price incl. options & VAT'}</span></div>
            <MoneyInput value={p11d} onChange={v => { setP11d(v); if (v > 0) setP11dPending(false); }} />
            {vehicle && <div className="note" style={{ marginTop: 8, color: 'var(--green)' }}>Add the manufacturer list price (incl. options &amp; VAT) — the one field DVLA doesn’t hold.</div>}
          </div>

          {!isEV && (
            <div className="field">
              <div className="flabel"><b>CO₂ emissions</b><span className="val">{co2} g/km</span></div>
              <input className="inp" type="number" min="0" max="400" step="1" value={co2} onChange={e => { setCo2(Math.max(0, +e.target.value || 0)); setCo2Missing(false); }} />
              {co2Missing && <div className="note" style={{ marginTop: 8, color: 'var(--orange)' }}>DVLA didn’t return CO₂ for this vehicle (common on older cars). Check your V5C log book and enter it.</div>}
            </div>
          )}

          {fuel === 'phev' && (
            <div className="field">
              <div className="flabel"><b>Electric-only range</b><span className="val">{erange} miles</span></div>
              <Seg value={erange} onChange={setErange} options={[
                { value: 20, label: '<30' }, { value: 35, label: '30–39' }, { value: 55, label: '40–69' }, { value: 90, label: '70–129' }, { value: 130, label: '130+' },
              ]} />
            </div>
          )}

          {fuel === 'diesel' && (
            <div className="field">
              <div className="flabel"><b>RDE2 compliant?</b><span className="hint">Most cars from Sept 2020</span></div>
              <Seg value={rde2 ? 'y' : 'n'} onChange={v => setRde2(v === 'y')} options={[
                { value: 'y', label: 'Yes', sub: 'no surcharge' }, { value: 'n', label: 'No', sub: '+4% BIK' },
              ]} />
            </div>
          )}

          <div className="divider"></div>
          <div className="field">
            <div className="flabel"><b>Your tax band</b></div>
            <Seg value={band} onChange={setBand} options={[
              { value: 'basic', label: 'Basic', sub: '20%' },
              { value: 'higher', label: 'Higher', sub: '40%' },
              { value: 'additional', label: 'Additional', sub: '45%' },
            ]} />
          </div>
        </div>

        {/* RESULT */}
        <div className="sticky">
          <div className="hero fade-in">
            <div className="hero-kick">{UIICON.spark} {carName} · company-car tax</div>
            {(p11dPending || p11d <= 0) ? (
              <div style={{ padding: '18px 0 6px' }}>
                <div className="hero-num" style={{ color: 'var(--faint)' }}>£—<span className="per">/mo</span></div>
                <div className="hero-cap">Add the <b>P11D list price</b> on the left to see this car’s Benefit-in-Kind — DVLA holds the fuel, CO₂ and age, but never the list price.</div>
              </div>
            ) : co2Missing ? (
              <div style={{ padding: '18px 0 6px' }}>
                <div className="hero-num" style={{ color: 'var(--faint)' }}>£—<span className="per">/mo</span></div>
                <div className="hero-cap">Add the <b>CO₂ figure</b> on the left to see this car’s Benefit-in-Kind — DVLA didn’t hold it for this older vehicle.</div>
              </div>
            ) : (<React.Fragment>
            <div className="hero-num">{PX.gbp(r.empTaxMo)}<span className="per">/mo</span></div>
            <div className="hero-cap">What you’d pay in <b>Benefit-in-Kind tax</b> this year on a {PX.gbp(p11d)} {isEV ? 'electric ' : ''}car, at the {Math.round(r.band.rate * 100)}% tax band.</div>
            <div className="pill-row" style={{ marginTop: 16 }}>
              <span className="pill tag-bik">BIK 2026/27 · {r.pct}%</span>
              <span className="pill">{isEV ? 'Zero emission' : co2 + ' g/km'}</span>
              <span className="pill">{PX.gbp(r.benefit)} taxable / yr</span>
            </div>

            <div className="metrics" style={{ marginTop: 18 }}>
              <div className="metric"><div className="ml">Your tax / yr</div><div className="mv g">{PX.gbp(r.empTaxYr)}</div></div>
              <div className="metric"><div className="ml">Appropriate %</div><div className="mv">{r.pct}%</div></div>
              <div className="metric"><div className="ml">Employer NI / yr</div><div className="mv dim">{PX.gbp(r.class1a)}</div></div>
            </div>

            <div style={{ marginTop: 18 }}>
              <EmailGate unlocked={unlocked}
                onUnlock={() => {
                  setUnlocked(true);
                  PX.track('generate_lead', { event_category: 'conversion', source: 'bik_calculator', value_gbp: Math.round(r.empTaxYr), tax_band: r.band.label });
                }}
                headline="Unlock the full BIK breakdown"
                blurb="Enter your email to see the employer Class 1A NI waterfall and how the rate rises to 2029/30 — and check if you’re eligible for Covase EV salary sacrifice."
                lead={() => ({
                  _subject: 'Covase company-car tax (BIK) — new lead',
                  tool: 'BIK / company-car tax calculator',
                  vehicle: carName,
                  fuel: fuel,
                  'P11D value': PX.gbp(p11d),
                  'CO2': isEV ? 'zero-emission' : co2 + ' g/km',
                  'appropriate %': r.pct + '%',
                  'tax band': r.band.label,
                  'indicative BIK tax / mo': PX.gbp2(r.empTaxMo),
                  'taxable benefit / yr': PX.gbp(r.benefit),
                  'employer Class 1A NI / yr': PX.gbp(r.class1a),
                  ref: ref,
                })}>
                <div className="bd">
                  <div className="bd-row"><span className="l">P11D value</span><span className="v">{PX.gbp(p11d)}</span></div>
                  <div className="bd-row"><span className="l">Appropriate percentage<small>{isEV ? 'zero-emission, 2026/27' : co2 + ' g/km' + (fuel === 'diesel' && !rde2 ? ' · non-RDE2 +4%' : '')}</small></span><span className="v">{r.pct}%</span></div>
                  <div className="bd-row"><span className="l">Taxable benefit / yr</span><span className="v">{PX.gbp(r.benefit)}</span></div>
                  <div className="bd-row"><span className="l">Your tax band</span><span className="v">{Math.round(r.band.rate * 100)}%</span></div>
                  <div className="bd-row tot"><span className="l">Company-car tax / yr</span><span className="v">{PX.gbp(r.empTaxYr)}</span></div>
                  <div className="bd-row"><span className="l">Same, per month</span><span className="v pos">{PX.gbp2(r.empTaxMo)}</span></div>
                </div>

                <div style={{ marginTop: 22 }}>
                  <div className="card-title" style={{ marginBottom: 14 }}><span className="n" style={{ background: 'rgba(167,235,82,.18)', color: 'var(--green)' }}>£</span>Employer Class 1A NI</div>
                  <NiWaterfall p11d={p11d} pct={r.pct} benefit={r.benefit} class1a={r.class1a} />
                </div>

                <div style={{ marginTop: 22 }}>
                  <div className="card-title" style={{ marginBottom: 14 }}><span className="n">↗</span>How the rate rises</div>
                  <ScheduleTable rows={sched} />
                </div>

                <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
                  <a className="cta" href="https://apply.covase.co.uk" target="_blank" rel="noreferrer" style={{ textDecoration: 'none' }}>{UIICON.spark} See if you’re eligible</a>
                  <button className="cta ghost" onClick={() => setShare(true)} style={{ width: 'auto', padding: '15px 18px' }}>{UIICON.share}</button>
                </div>
              </EmailGate>
            </div>
            </React.Fragment>)}
            <Caveat />
            <TrustStrip />
          </div>
          <ShareModal open={share} onClose={() => setShare(false)}
            big={PX.gbp(r.empTaxMo)} bigEm="/mo"
            shareText={`${carName} — about ${PX.gbp(r.empTaxMo)}/mo in company-car tax at ${r.pct}% BIK (2026/27). Indicative, via Covase.`}
            sub={`${carName} — about ${PX.gbp(r.empTaxMo)}/mo in company-car tax at ${r.pct}% BIK (2026/27).`} />
        </div>
      </div>
    </div>
  );
}
