/* ===================================================================
   TOOL A - Perx Benefit Calculator (home energy salary sacrifice)
   Employee mode + Employer mode. Compliance-safe: "benefit" / "net cost",
   never "save/savings". Indicative figure -> email gate -> lead.
   =================================================================== */
const { useState: useStateA, useMemo: useMemoA } = React;

function EmployeeMode() {
  const [products, setProducts] = useStateA({ charger: true, solar: true, battery: false });
  const [band, setBand] = useStateA('basic');
  const [term, setTerm] = useStateA(36);
  const [unlocked, setUnlocked] = useStateA(false);
  const [share, setShare] = useStateA(false);
  const ref = useMemoA(() => PX.shortRef(), []);

  const r = useMemoA(() => PX.calcEmployee(products, band, term), [products, band, term]);
  const any = products.charger || products.solar || products.battery;
  const toggle = k => setProducts(p => ({ ...p, [k]: !p[k] }));

  return (
    <div className="grid2">
      {/* INPUTS */}
      <div className="card card-pad">
        <div className="card-title"><span className="n">1</span>Build your home-energy bundle</div>
        <div className="field">
          <div className="flabel"><b>Choose your kit</b><span className="hint">Multi-select</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>
        </div>
        <div className="divider"></div>
        <div className="field">
          <div className="flabel"><b>Your tax band</b><span className="hint">Sets your 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>Term</b><span className="val">{term} months</span></div>
          <Seg value={term} onChange={setTerm} options={[
            { value: 24, label: '24 mo' }, { value: 36, label: '36 mo' },
            { value: 48, label: '48 mo' }, { value: 60, label: '60 mo' },
          ]} />
        </div>
        <p className="note">Equipment is financed over the term at 5%/yr and deducted from gross pay — <b>no upfront cost</b>.
          Home solar, battery and chargers have no HMRC salary-sacrifice tax exemption, so the income-tax/NI relief is offset by Benefit-in-Kind: the employee benefit is the spread, gross-pay cost and the employer's freed-up NI (which can be passed back), not an income-tax saving. See the breakdown.</p>
      </div>

      {/* RESULT */}
      <div className="sticky">
        {!any && (
          <div className="hero" style={{ minHeight: 260, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div className="hero-kick">{UIICON.spark} Pick at least one product</div>
            <div className="hero-num" style={{ color: 'var(--faint)' }}>£–<span className="per">/mo</span></div>
            <div className="hero-cap">Select your kit on the left to see an indicative monthly cost, spread over the term with no upfront outlay.</div>
          </div>
        )}
        {any && r && (
          <div className="hero fade-in">
            <div className="hero-kick">{UIICON.spark} Indicative monthly cost</div>
            <div className="hero-num">{PX.gbp(r.net)}<span className="per">/mo</span></div>
            <div className="hero-cap">Your <b>{r.lines.map(l => l.name).join(' + ')}</b> for
              {' '}<b>{PX.gbp(r.net)}/mo</b> from gross pay — spread over {r.term} months, <b>no upfront cost</b>.</div>
            <div className="metrics">
              <div className="metric"><div className="ml">Upfront cost</div><div className="mv g">£0</div></div>
              <div className="metric"><div className="ml">Spread over</div><div className="mv">{r.term} mo</div></div>
              <div className="metric"><div className="ml">Employer NI freed up</div><div className="mv g">{PX.gbp2(r.employerNic)}<span style={{ fontSize: 11, color: 'var(--muted)' }}>/mo</span></div></div>
            </div>

            <div style={{ marginTop: 18 }}>
              <EmailGate unlocked={unlocked} onUnlock={() => setUnlocked(true)}
                headline="Check if your employer offers Perx"
                blurb="Enter your email to unlock the full line-by-line breakdown and see if your workplace can offer Perx."
                lead={() => ({
                  _subject: 'Perx Benefit Calculator (employee) — new lead',
                  tool: 'Benefit Calculator — employee',
                  bundle: r.lines.map(l => l.name).join(' + '),
                  'tax band': r.band.label,
                  term: term + ' months',
                  'indicative monthly cost (gross pay)': PX.gbp2(r.net),
                  'gross monthly sacrifice': PX.gbp2(r.gross),
                  'employer NI freed up / mo': PX.gbp2(r.employerNic),
                  ref: ref,
                })}>
                <div className="bd">
                  <div className="bd-row"><span className="l">Equipment monthly (financed)</span><span className="v">{PX.gbp2(r.base)}</span></div>
                  {r.lines.map(l => (
                    <div className="bd-row" key={l.key}><span className="l" style={{ paddingLeft: 14 }}>· {l.name}</span><span className="v">{PX.gbp2(l.monthly)}</span></div>
                  ))}
                  <div className="bd-row"><span className="l">Gross monthly sacrifice</span><span className="v">{PX.gbp2(r.gross)}</span></div>
                  <div className="bd-row"><span className="l">Income tax + NI relief ({Math.round((r.band.rate + r.band.nic) * 100)}%)</span><span className="v pos">−{PX.gbp2(r.taxSaving + r.nicSaving)}</span></div>
                  <div className="bd-row"><span className="l">Benefit-in-kind tax + NI<small>home solar / battery / charger have no HMRC tax exemption, so BIK offsets the relief</small></span><span className="v neg">+{PX.gbp2(r.bikTax + r.bikNi)}</span></div>
                  <div className="bd-row tot"><span className="l">Indicative monthly cost from gross pay</span><span className="v">{PX.gbp2(r.net)}</span></div>
                  <div className="bd-row"><span className="l">Employer NI freed up by the sacrifice (15%)<small>the business's saving — may be passed back, by arrangement</small></span><span className="v pos">{PX.gbp2(r.employerNic)}/mo</span></div>
                </div>
                <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
                  <button className="cta" onClick={() => setShare(true)}>{UIICON.share} Share my figure</button>
                  <a className="cta ghost" href="https://apply.covase.co.uk" target="_blank" rel="noreferrer" style={{ width: 'auto', padding: '15px 20px', textDecoration: 'none' }}>Register interest</a>
                </div>
              </EmailGate>
            </div>
            <Caveat />
            <TrustStrip />
          </div>
        )}
        <ShareModal open={share} onClose={() => setShare(false)} refCode={ref}
          big={PX.gbp(r ? r.net : 0)} bigEm="/mo"
          sub={`My ${r ? r.lines.map(l => l.name).join(' + ') : 'home-energy'} bundle through Perx salary sacrifice — indicative net cost.`} />
      </div>
    </div>
  );
}

function EmployerMode() {
  const [headcount, setHeadcount] = useStateA(120);
  const [part, setPart] = useStateA(0.3);
  const [mix, setMix] = useStateA({ ev: true, charger: true, solar: true, battery: true });
  const [unlocked, setUnlocked] = useStateA(false);
  const [share, setShare] = useStateA(false);
  const ref = useMemoA(() => PX.shortRef(), []);

  const r = useMemoA(() => PX.calcEmployer(headcount, part, mix), [headcount, part, mix]);
  const toggle = k => setMix(m => ({ ...m, [k]: !m[k] }));
  const hcPct = Math.min(100, (headcount / 500) * 100);

  return (
    <div className="grid2">
      <div className="card card-pad">
        <div className="card-title"><span className="n">1</span>Your workforce</div>
        <div className="field">
          <div className="flabel"><b>Headcount</b><span className="val">{headcount} staff</span></div>
          <input type="range" min="5" max="500" step="5" value={headcount}
            style={{ '--p': hcPct + '%' }} onChange={e => setHeadcount(+e.target.value)} />
          <div className="ticks"><span>5</span><span>250</span><span>500</span></div>
        </div>
        <div className="field">
          <div className="flabel"><b>Expected participation</b><span className="val">{Math.round(part * 100)}%</span></div>
          <input type="range" min="0.05" max="0.6" step="0.05" value={part}
            style={{ '--p': ((part - 0.05) / 0.55 * 100) + '%' }} onChange={e => setPart(+e.target.value)} />
          <div className="ticks"><span>5%</span><span>30%</span><span>60%</span></div>
        </div>
        <div className="divider"></div>
        <div className="field">
          <div className="flabel"><b>Product mix offered</b><span className="hint">What staff can sacrifice</span></div>
          <div className="prodgrid" style={{ gridTemplateColumns: 'repeat(2,1fr)' }}>
            <ProductChip kind="ev" on={mix.ev} onToggle={() => toggle('ev')} />
            <ProductChip kind="charger" on={mix.charger} onToggle={() => toggle('charger')} />
            <ProductChip kind="solar" on={mix.solar} onToggle={() => toggle('solar')} />
            <ProductChip kind="battery" on={mix.battery} onToggle={() => toggle('battery')} />
          </div>
        </div>
        <p className="note">Employer Class 1 NI (15%, from April 2025) doesn't apply to pay an employee sacrifices into the scheme. Figures are indicative and assume a representative bundle per participant.</p>
      </div>

      <div className="sticky">
        <div className="hero fade-in">
          <div className="hero-kick">{UIICON.spark} Indicative employer NI benefit / year</div>
          <div className="hero-num">{PX.gbp(r.totalNic)}<span className="per">/yr</span></div>
          <div className="hero-cap">From <b>{r.participants} participating employees</b> — roughly
            {' '}<b>{PX.gbp(r.perEmployeeNic)}</b> each in reduced employer NI, at no scheme cost to the business.</div>
          <div className="metrics">
            <div className="metric"><div className="ml">Participants</div><div className="mv">{r.participants}</div></div>
            <div className="metric"><div className="ml">Per employee / yr</div><div className="mv g">{PX.gbp(r.perEmployeeNic)}</div></div>
            <div className="metric"><div className="ml">Go-live</div><div className="mv dim">~2 wks</div></div>
          </div>
          <div className="pill-row" style={{ marginTop: 16 }}>
            <span className="pill"><span className="pd" style={{ background: 'var(--green)' }}></span>£0 employer cost</span>
            <span className="pill">{UIICON.clock} Install ~2 weeks</span>
            <span className="pill">{UIICON.shield} We run BIK, HMRC &amp; payroll</span>
          </div>

          <div style={{ marginTop: 18 }}>
            <EmailGate unlocked={unlocked} onUnlock={() => setUnlocked(true)}
              headline="Get a costed one-page plan"
              blurb="Enter your work email to unlock the figures and book a 15-minute call to walk through a plan for your business."
              lead={() => ({
                _subject: 'Perx Benefit Calculator (employer) — new lead',
                tool: 'Benefit Calculator — employer',
                headcount: headcount,
                participation: Math.round(part * 100) + '%',
                participants: r.participants,
                'product mix': ['ev', 'charger', 'solar', 'battery'].filter(k => mix[k]).join(', '),
                'indicative employer NI benefit / yr': PX.gbp(r.totalNic),
                ref: ref,
              })}>
              <div className="bd">
                <div className="bd-row"><span className="l">Participating employees</span><span className="v">{r.participants}</span></div>
                <div className="bd-row"><span className="l">Avg sacrifice / participant / yr</span><span className="v">{PX.gbp(r.perYear)}</span></div>
                <div className="bd-row"><span className="l">Total sacrifice across scheme / yr</span><span className="v">{PX.gbp(r.totalSacrifice)}</span></div>
                <div className="bd-row"><span className="l">Employer NI rate</span><span className="v">15%</span></div>
                <div className="bd-row tot"><span className="l">Indicative employer NI benefit / yr</span><span className="v">{PX.gbp(r.totalNic)}</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.clock} Book a 15-min call</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(r.totalNic)} bigEm="/yr"
          sub={`Indicative employer NI benefit for ${r.participants} participating employees through Perx.`} />
      </div>
    </div>
  );
}

function ToolA() {
  const [mode, setMode] = useStateA('employee');
  return (
    <div>
      <ToolHead eyebrow="Perx Benefit Calculator"
        title={mode === 'employee' ? 'What would my home-energy bundle cost?' : 'What would my business gain from Perx?'}
        sub={mode === 'employee'
          ? 'Salary-sacrifice solar, home battery and an EV charger — deducted from gross pay, no upfront cost. See an indicative monthly cost.'
          : 'Offer the Perx bundle to your team at no cost to the business. See an indicative reduction in employer National Insurance.'} />
      <div className={'mode-toggle ' + (mode === 'employer' ? 'r' : '')} style={{ maxWidth: 460 }}>
        <span className="knob"></span>
        <button className={mode === 'employee' ? 'on' : ''} onClick={() => setMode('employee')}>What would I pay?</button>
        <button className={mode === 'employer' ? 'on' : ''} onClick={() => setMode('employer')}>What would my business gain?</button>
      </div>
      {mode === 'employee' ? <EmployeeMode /> : <EmployerMode />}
    </div>
  );
}

window.ToolA = ToolA;
