/* ===================================================================
   PERX TOOLS - shared React components + UI icons
   Exposed on window for the per-tool babel scripts.
   =================================================================== */
const { useState, useRef, useEffect } = React;
const PX = window.PX;
const ICON = window.ICON;       // product icons (svg strings)
const ctaArrow = window.ctaArrow;

/* -- inline UI icons ---------------------------------------------- */
const I = {
  lock: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>,
  check: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>,
  x: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>,
  monitor: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>,
  phone: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="6" y="2" width="12" height="20" rx="3"/><path d="M11 18h2"/></svg>,
  share: <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7"/><path d="M12 3v13M8 7l4-4 4 4"/></svg>,
  clock: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  shield: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l7 3v5c0 5-3.5 8-7 10-3.5-2-7-5-7-10V6z"/><path d="M9 12l2 2 4-4"/></svg>,
  spark: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2L4.5 13.5H11l-1 8.5L18.5 10.5H12z"/></svg>,
  zero: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="8"/><path d="M7 7l10 10" strokeLinecap="round"/></svg>,
};
const CH = {
  wa: <svg width="22" height="22" viewBox="0 0 24 24" fill="#25D366"><path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.82 11.82 0 0 1 8.413 3.488 11.82 11.82 0 0 1 3.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 0 0 1.516 5.26l-.999 3.648 3.972-1.042zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.247-.694.247-1.289.173-1.413z"/></svg>,
  li: <svg width="20" height="20" viewBox="0 0 24 24" fill="#0A66C2"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 0 1-2.063-2.065 2.064 2.064 0 1 1 2.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>,
  rd: <svg width="22" height="22" viewBox="0 0 24 24" fill="#FF4500"><circle cx="12" cy="12" r="12" fill="#FF4500"/><circle cx="8.5" cy="12" r="1.4" fill="#fff"/><circle cx="15.5" cy="12" r="1.4" fill="#fff"/><path d="M8.5 15.2c.9.7 2.1 1 3.5 1s2.6-.3 3.5-1" stroke="#fff" stroke-width="1.1" fill="none" stroke-linecap="round"/></svg>,
  cp: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#A7EB52" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>,
};

/* -- brand wordmark ----------------------------------------------- */
function Wordmark({ sub = 'by Covase' }) {
  return (
    <div className="wm">
      <div className="wm-mk">P</div>
      <div className="wm-tx"><span className="wm-nm">Perx</span><span className="wm-sub">{sub}</span></div>
    </div>
  );
}

/* -- product icon (from icons.js svg string) ---------------------- */
function Prod({ kind, w, tone = 'light' }) {
  const map = { charger: 'charger', solar: 'solar', battery: 'battery', ev: 'car' };
  const html = ICON[map[kind]] ? ICON[map[kind]]({ w: w || 54, tone }) : '';
  return <span className="ico" dangerouslySetInnerHTML={{ __html: html }} />;
}

/* -- tool header -------------------------------------------------- */
function ToolHead({ eyebrow, title, sub }) {
  return (
    <div className="tool-head">
      <div className="eyebrow"><span className="pdot"></span>{eyebrow}</div>
      <h1 className="tool-h1">{title}</h1>
      {sub && <p className="tool-sub">{sub}</p>}
    </div>
  );
}

/* -- segmented control -------------------------------------------- */
function Seg({ value, onChange, options, green }) {
  return (
    <div className={'seg' + (green ? ' green' : '')}>
      {options.map(o => (
        <button key={o.value} className={value === o.value ? 'on' : ''} onClick={() => onChange(o.value)}>
          {o.label}{o.sub && <small>{o.sub}</small>}
        </button>
      ))}
    </div>
  );
}

/* -- product multi-select chip ------------------------------------ */
const EV_META = { name: 'Electric car', cost: null, sub: 'Salary-sacrifice EV' };
function ProductChip({ kind, on, onToggle }) {
  const a = PX.ADDON[kind] || EV_META;
  return (
    <button className={'prodchip' + (on ? ' on' : '')} onClick={onToggle}>
      <span className="chk">{I.check}</span>
      <Prod kind={kind} w={kind === 'solar' ? 56 : kind === 'ev' ? 70 : 30} tone="light" />
      <div>
        <div className="pname">{a.name}</div>
        <div className="pcost">{a.cost != null ? PX.gbp(a.cost) : 'In scheme'}</div>
      </div>
    </button>
  );
}

/* -- trust strip -------------------------------------------------- */
function TrustStrip() {
  return (
    <div className="trust">
      <div className="ti"><span className="badge">BVRLA #2181</span></div>
      <div className="sep"></div>
      <div className="ti">{I.shield}<span>Built by <b>Covase</b> since 2003</span></div>
      <div className="sep"></div>
      <div className="ti"><span>Powered by <b>Heva</b></span></div>
    </div>
  );
}

/* -- email gate ---------------------------------------------------
   Submits the email + a snapshot of the result to the shared
   /api/submit endpoint (PX.submitLead) before unlocking. The unlock
   still fires on a network error so a flaky send never traps the
   user behind the blur — the lead attempt is logged server-side. */
function EmailGate({ children, unlocked, onUnlock, headline, blurb, lead }) {
  const [email, setEmail] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const valid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email);
  const submit = (e) => {
    e.preventDefault();
    if (!valid || busy) return;
    setBusy(true);
    setErr('');
    const fields = Object.assign(
      { _subject: 'Perx Calculator — new lead', email: email },
      typeof lead === 'function' ? lead() : (lead || {})
    );
    PX.submitLead(fields)
      .then((r) => { if (!r.ok) setErr(''); })
      .catch(() => {})
      .then(() => { setBusy(false); onUnlock(email); });
  };
  if (unlocked) return <div className="fade-in">{children}</div>;
  return (
    <div className="gate-wrap">
      <div className="gate-blur" aria-hidden="true">{children}</div>
      <div className="gate-over">
        <div className="gate-lock">{I.lock}</div>
        <h4>{headline || 'Unlock your full breakdown'}</h4>
        <p>{blurb || 'See every line of the figure — tax, NI and BIK relief, for illustration. No signup, just your email.'}</p>
        <form className="gate-form" onSubmit={submit}>
          <input className="inp" type="email" placeholder="you@company.co.uk" value={email}
            onChange={e => setEmail(e.target.value)} />
          <button className="cta" type="submit" disabled={!valid || busy}>
            {busy ? <span className="spin"></span> : <>Unlock {ctaArrow && <span dangerouslySetInnerHTML={{ __html: ctaArrow(18, '#0a1c03') }} />}</>}
          </button>
        </form>
        {err && <div className="gate-err">{err}</div>}
        <div className="gate-fine">We'll email your breakdown. No spam — unsubscribe anytime.</div>
      </div>
    </div>
  );
}

/* -- share modal -------------------------------------------------- */
function ShareModal({ open, onClose, big, bigEm, sub, refCode }) {
  const [copied, setCopied] = useState(false);
  if (!open) return null;
  const url = 'perx.covase.co.uk/r/' + (refCode || 'AB12CD');
  const copy = () => { setCopied(true); setTimeout(() => setCopied(false), 1600); };
  return (
    <div className="modal-bk" onClick={onClose}>
      <div className="share" onClick={e => e.stopPropagation()}>
        <div className="share-card">
          <button className="modal-x" onClick={onClose}>{I.x}</button>
          <span className="glow"></span>
          <div style={{ marginBottom: 18 }}><Wordmark /></div>
          <div className="share-eyebrow">My Perx benefit</div>
          <div className="share-big">{big} <em>{bigEm}</em></div>
          <p className="share-sub">{sub}</p>
          <div className="share-url">
            <span className="u">{url}</span>
            <button onClick={copy}>{copied ? 'Copied ✓' : 'Copy'}</button>
          </div>
          <div className="share-foot">
            <div className="chans">
              <button className="chan wa" title="WhatsApp">{CH.wa}</button>
              <button className="chan li" title="LinkedIn">{CH.li}</button>
              <button className="chan rd" title="Reddit">{CH.rd}</button>
              <button className="chan cp" title="Copy link" onClick={copy}>{CH.cp}</button>
            </div>
            <Prod kind="ev" w={62} tone="green" />
          </div>
        </div>
        <div className="share-note">A unique link — anyone who opens it sees your figure and can run their own.</div>
      </div>
    </div>
  );
}

/* -- phone frame -------------------------------------------------- */
function PhoneFrame({ children }) {
  return (
    <div className="phone">
      <div className="phone-notch"></div>
      <div className="phone-screen">
        <div className="statusbar">
          <span className="pt-num">9:41</span>
          <span className="icons">
            <svg width="17" height="11" viewBox="0 0 17 11" fill="#fff"><rect x="0" y="6" width="3" height="5" rx="1"/><rect x="4.5" y="4" width="3" height="7" rx="1"/><rect x="9" y="2" width="3" height="9" rx="1"/><rect x="13.5" y="0" width="3" height="11" rx="1" opacity=".4"/></svg>
            <svg width="22" height="11" viewBox="0 0 24 12" fill="none"><rect x="1" y="1" width="20" height="10" rx="3" stroke="#fff" strokeOpacity=".5"/><rect x="2.5" y="2.5" width="14" height="7" rx="1.5" fill="#A7EB52"/><rect x="22" y="4" width="2" height="4" rx="1" fill="#fff" fillOpacity=".5"/></svg>
          </span>
        </div>
        <div className="mscreen">{children}</div>
      </div>
    </div>
  );
}

/* -- compliance caveat -------------------------------------------- */
function Caveat({ light }) {
  return <p className={'caveat' + (light ? ' light' : '')}>{PX.CAVEAT}</p>;
}

/* expose */
Object.assign(window, {
  Wordmark, Prod, ToolHead, Seg, ProductChip, TrustStrip, EmailGate, ShareModal, PhoneFrame, Caveat,
  UIICON: I, CHICON: CH
});
