/* ===================================================================
   TOOL EV - merged employee calculator (EV-led, single tax band)
   The EV picker + tax band lead the page. Home solar / battery / charger
   are optional add-ons underneath; they reuse the SAME tax band (there is
   no second selector). A combined total appears only once an add-on is
   bundled. EV cost is the headline; add-ons are secondary.

   Compliance-safe: "indicative net cost", never "save/savings". Tax band
   genuinely moves the EV figure; for home-energy items it is tax-neutral
   (relief and BIK cancel — no HMRC exemption), explained via a toast.
   =================================================================== */
const { useState: useStateEV, useMemo: useMemoEV } = React;

const POPULAR_EV = ['tesla-model-3', 'tesla-model-y', 'byd-atto-2', 'kia-ev3', 'hyundai-ioniq-5', 'polestar-2'];

function ToolEV() {
  const [evId, setEvId] = useStateEV('tesla-model-3');
  const [band, setBand] = useStateEV('higher');
  const [term, setTerm] = useStateEV(36);
  const [products, setProducts] = useStateEV({ charger: false, solar: false, battery: false });
  const [unlocked, setUnlocked] = useStateEV(false);
  const [share, setShare] = useStateEV(false);
  const [toast, setToast] = useStateEV(false);
  const [toastSeen, setToastSeen] = useStateEV(false);
  const ref = useMemoEV(() => PX.shortRef(), []);

  const ev = useMemoEV(() => PX.EVS.find(e => e.id === evId) || PX.EVS[0], [evId]);
  const evR = useMemoEV(() => PX.calcEV(ev, band, term), [ev, band, term]);
  const energyR = useMemoEV(() => PX.calcEmployee(products, band, term), [products, band, term]);
  const popular = POPULAR_EV.map(id => PX.EVS.find(e => e.id === id)).filter(Boolean);
  const name = ev.make + ' ' + ev.model;
  const anyEnergy = !!energyR;
  const energyNet = anyEnergy ? energyR.net : 0;
  const total = evR.net + energyNet;

  const toggle = (k) => {
    setProducts(p => {
      const next = { ...p, [k]: !p[k] };
      // first time an energy item is switched on, explain tax-neutrality
      if (!p[k] && !toastSeen) { setToast(true); setToastSeen(true); }
      return next;
    });
  };

  return (
    <div>
      <ToolHead eyebrow="Covase EV salary sacrifice"
        title="What does an EV really cost through salary sacrifice?"
        sub="Pick a car and your tax band for an indicative net monthly cost after income tax, NI and the 2026/27 company-car (BIK) tax. Add home solar, battery or a charger to bundle them into the same salary sacrifice." />

      <div className="grid2">
        {/* INPUTS */}
        <div className="card card-pad">
          <div className="card-title"><span className="n">1</span>Choose your EV</div>
          <div className="field">
            <div className="flabel"><b>Popular choices</b><span className="hint">Tap to pick</span></div>
            <div className="prodgrid">
              {popular.map(e => {
                const on = ev.id === e.id;
                return (
                  <button key={e.id} className={'prodchip' + (on ? ' on' : '')} onClick={() => setEvId(e.id)} style={{ minHeight: 92 }}>
                    <span className="chk">{UIICON.check}</span>
                    <div style={{ marginTop: 'auto' }}>
                      <div className="pname" style={{ fontSize: 13 }}>{e.make}</div>
                      <div className="pname" style={{ fontSize: 14, marginTop: 1 }}>{e.model}</div>
                      <div className="pcost">{PX.gbp(e.lease)}/mo</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
          <div className="field">
            <div className="flabel"><b>More models</b><span className="hint">{PX.EVS.length} curated EVs</span></div>
            <select className="sel" value={evId} onChange={e => setEvId(e.target.value)}>
              {PX.EVS.map(e => (
                <option key={e.id} value={e.id}>{e.make} {e.model} — {e.variant} · {PX.gbp(e.p11d)}</option>
              ))}
            </select>
          </div>

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

          {/* SINGLE tax band — drives both the EV and any home-energy add-on */}
          <div className="field">
            <div className="flabel">
              <b>Your tax band
                <Tooltip>
                  <b>Your tax band sets your EV relief.</b> The higher your rate, the more income tax and NI you save on the car.
                  {' '}It does <b>not</b> change the cost of home solar, battery or a charger — those have no HMRC tax exemption,
                  so their relief and Benefit-in-Kind cancel out at every band. Their benefit is £0 upfront, spread cost from gross pay, and the employer NI freed up.
                </Tooltip>
              </b>
              <span className="hint">Sets your EV relief rate</span>
            </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 className="field">
            <div className="flabel"><b>Contract term</b></div>
            <Seg value={term} onChange={setTerm} options={[
              { value: 24, label: '24 mo' }, { value: 36, label: '36 mo' }, { value: 48, label: '48 mo' },
            ]} />
          </div>

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

          {/* Optional home-energy add-ons — secondary to the car */}
          <div className="field">
            <div className="flabel">
              <b>Add home energy <span style={{ color: 'var(--faint)', fontWeight: 500 }}>· optional</span></b>
              <span className="hint">Same salary sacrifice</span>
            </div>
            <div className="prodgrid">
              <ProductChip kind="solar" on={products.solar} onToggle={() => toggle('solar')} />
              <ProductChip kind="battery" on={products.battery} onToggle={() => toggle('battery')} />
              <ProductChip kind="charger" on={products.charger} onToggle={() => toggle('charger')} />
            </div>
            <p className="note" style={{ marginTop: 12 }}>Home solar, battery and chargers have no HMRC salary-sacrifice tax exemption, so your tax band doesn't change their cost — the benefit is <b>£0 upfront</b>, spread cost from gross pay, and the employer NI freed up.</p>
          </div>
        </div>

        {/* RESULT */}
        <div className="sticky">
          <div className="hero fade-in">
            {/* EV is always the headline */}
            <div className="hero-kick">{UIICON.spark} {name} · {ev.variant}</div>
            <div className="hero-num">{PX.gbp(evR.net)}<span className="per">/mo</span></div>
            <div className="hero-cap">A <b>{name}</b> costs you about <b>{PX.gbp(evR.net)}/mo</b> through salary sacrifice —
              from a {PX.gbp(evR.gross)}/mo gross rental, after {Math.round(evR.band.rate * 100)}% tax and {Math.round(evR.band.nic * 100)}% NI relief, including BIK.</div>
            <div className="pill-row" style={{ marginTop: 16 }}>
              <span className="pill tag-bik">BIK {evR.bikYear} · {Math.round(evR.bikRate * 100)}%</span>
              <span className="pill">{ev.range} mi range</span>
              <span className="pill">P11D {PX.gbp(ev.p11d)}</span>
            </div>

            {/* rising BIK schedule (HMRC, confirmed to 2029/30) */}
            <div className="bik-sched">
              <span className="bsl">Company-car (BIK) rate rises each year:</span>
              {evR.bikSchedule.map(s => (
                <span key={s.year} className={'bsp' + (s.year === evR.bikYear ? ' on' : '')}>
                  {s.year} · {Math.round(s.rate * 100)}%
                </span>
              ))}
            </div>

            {/* comparison vs personal PCP */}
            <div className="metrics" style={{ marginTop: 18 }}>
              <div className="metric"><div className="ml">Salary sacrifice</div><div className="mv g">{PX.gbp(evR.net)}</div></div>
              <div className="metric"><div className="ml">Personal PCP</div><div className="mv dim">{PX.gbp(evR.pcp)}</div></div>
              <div className="metric"><div className="ml">Net difference / mo</div><div className="mv">{PX.gbp(evR.savingVsPcpM)}</div></div>
            </div>

            {/* bundled home-energy add-on — secondary, appears only when added */}
            {anyEnergy && (
              <div className="addon-strip fade-in">
                <div className="addon-head">
                  <span>Plus home energy</span>
                  <span className="addon-tot">+{PX.gbp2(energyR.net)}/mo</span>
                </div>
                {energyR.lines.map(l => (
                  <div className="addon-row" key={l.key}><span>{l.name}</span><span className="pt-num">+{PX.gbp2(l.monthly)}/mo</span></div>
                ))}
                <div className="addon-note">Tax-band neutral — no HMRC exemption on home energy. £0 upfront, employer NI freed up {PX.gbp2(energyR.employerNic)}/mo.</div>
              </div>
            )}

            {/* combined total — only shown once an add-on is bundled */}
            {anyEnergy && (
              <div className="total-strip fade-in">
                <span className="tsl">Your total indicative monthly cost</span>
                <span className="tsv">{PX.gbp(total)}<span className="per">/mo</span></span>
              </div>
            )}

            <div style={{ marginTop: 18 }}>
              <EmailGate unlocked={unlocked} onUnlock={() => setUnlocked(true)}
                headline="Unlock your full breakdown"
                blurb="Enter your email to see every line — tax, NI and BIK relief on the car, your home-energy bundle, and whether your employer can offer Covase salary sacrifice."
                lead={() => ({
                  _subject: 'Covase EV salary sacrifice — new lead',
                  tool: 'EV salary sacrifice' + (anyEnergy ? ' + home energy' : ''),
                  vehicle: name + ' — ' + ev.variant,
                  'tax band': evR.band.label,
                  term: term + ' months',
                  'EV indicative net / mo': PX.gbp2(evR.net),
                  'home energy': anyEnergy ? energyR.lines.map(l => l.name).join(', ') : 'none',
                  'home energy / mo': anyEnergy ? PX.gbp2(energyR.net) : '£0.00',
                  'total indicative / mo': PX.gbp2(total),
                  ref: ref,
                })}>
                <div className="bd">
                  <div className="bd-sub">Electric car</div>
                  <div className="bd-row"><span className="l">Gross monthly rental</span><span className="v">{PX.gbp2(evR.gross)}</span></div>
                  <div className="bd-row"><span className="l">Income tax relief ({Math.round(evR.band.rate * 100)}%)</span><span className="v pos">−{PX.gbp2(evR.taxSaving)}</span></div>
                  <div className="bd-row"><span className="l">NI relief ({Math.round(evR.band.nic * 100)}%)</span><span className="v pos">−{PX.gbp2(evR.nicSaving)}</span></div>
                  <div className="bd-row"><span className="l">Company-car tax (BIK)<small>{Math.round(evR.bikRate * 100)}% of {PX.gbp(ev.p11d)} P11D ({evR.bikYear}), income tax at {Math.round(evR.band.rate * 100)}%</small></span><span className="v neg">+{PX.gbp2(evR.bikTax)}</span></div>
                  <div className="bd-row"><span className="l">BIK NI on benefit ({Math.round(evR.band.nic * 100)}%)</span><span className="v neg">+{PX.gbp2(evR.bikNi)}</span></div>
                  <div className="bd-row tot"><span className="l">EV indicative net monthly cost</span><span className="v">{PX.gbp2(evR.net)}</span></div>
                  <div className="bd-row"><span className="l">vs personal PCP ({PX.gbp(evR.pcp)}/mo)<small>indicative consumer PCP: ratebook rental + VAT</small></span><span className="v pos">{PX.gbp(evR.savingVsPcpM)}/mo lower</span></div>

                  {anyEnergy && (
                    <>
                      <div className="bd-sub">Home energy</div>
                      {energyR.lines.map(l => (
                        <div className="bd-row" key={l.key}><span className="l">{l.name} (financed)</span><span className="v">{PX.gbp2(l.monthly)}</span></div>
                      ))}
                      <div className="bd-row"><span className="l">Income tax + NI relief ({Math.round((energyR.band.rate + energyR.band.nic) * 100)}%)</span><span className="v pos">−{PX.gbp2(energyR.taxSaving + energyR.nicSaving)}</span></div>
                      <div className="bd-row"><span className="l">Benefit-in-kind tax + NI<small>no HMRC exemption — offsets the relief, so tax-band neutral</small></span><span className="v neg">+{PX.gbp2(energyR.bikTax + energyR.bikNi)}</span></div>
                      <div className="bd-row tot"><span className="l">Home-energy monthly cost</span><span className="v">{PX.gbp2(energyR.net)}</span></div>
                      <div className="bd-row"><span className="l">Employer NI freed up (15%)<small>the business's saving — may be passed back</small></span><span className="v pos">{PX.gbp2(energyR.employerNic)}/mo</span></div>
                    </>
                  )}

                  <div className="bd-row tot grand"><span className="l">Total indicative monthly cost</span><span className="v">{PX.gbp2(total)}</span></div>
                </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>
            <Caveat />
            <TrustStrip />
          </div>
          <ShareModal open={share} onClose={() => setShare(false)} refCode={ref}
            big={PX.gbp(total)} bigEm="/mo"
            sub={anyEnergy
              ? `A ${name} + ${energyR.lines.map(l => l.name).join(' + ')} for an indicative ${PX.gbp(total)}/mo through Covase salary sacrifice.`
              : `A ${name} for an indicative ${PX.gbp(evR.net)}/mo through Covase EV salary sacrifice.`} />
        </div>
      </div>

      <Toast open={toast} onClose={() => setToast(false)}>
        <b>Heads-up:</b> your tax band changes the <b>car</b> cost, but home solar, battery and chargers are <b>tax-band neutral</b> — there's no HMRC tax break on them. The benefit is £0 upfront, spread cost from gross pay, and the employer NI freed up.
      </Toast>
    </div>
  );
}

window.ToolEV = ToolEV;
