// InvoiceReady ReadinessCheck — main React app
const { useState, useMemo, useEffect, useRef } = React;

// ── derive the active question sequence from current state ─────
function buildSequence(state) {
  const seq = [];
  for (const q of window.IR_QUESTIONS) {
    if (!q.show || q.show(state)) seq.push(q);
  }
  return seq;
}

// running total at any step (using whatever's been answered so far)
function runningSubtotal(state) {
  try { return window.IR_SCORE(state).annual; }
  catch { return 0; }
}

// format £ with thousands separators
const gbp = (n) => "£" + (n || 0).toLocaleString("en-GB", { maximumFractionDigits: 0 });
const gbpShort = (n) => {
  if (!n && n !== 0) return "—";
  if (n >= 1000) return "£" + (n / 1000).toFixed(n >= 10000 ? 0 : 1) + "k";
  return "£" + Math.round(n);
};

// ────────────────────────────────────────────────────────── INTRO
function IntroScreen({ onStart }) {
  return (
    <div className="screen intro">
      <div className="intro-grid">
        <div className="intro-left">
          <div className="eyebrow">ReadinessCheck · Diagnostic · 4–6 min</div>
          <h1 className="display-h">
            What is e-invoicing<br/>
            <i>actually</i> worth<br/>
            to your business?
          </h1>
          <p className="lede">
            Seven questions, grounded in the Global Exchange Network Association (GENA) Academy methodology and a verified Total Economic Impact model. Receive a personalised three-year economic case at the end — including NPV, payback, and your top three benefit streams.
          </p>
          <div className="intro-meta">
            <div><span className="mono-lbl">Methodology</span><span>GENA · EESPA · Peppol</span></div>
            <div><span className="mono-lbl">Discount rate</span><span>7.5%</span></div>
            <div><span className="mono-lbl">Risk-adjusted</span><span>80% / 70%</span></div>
            <div><span className="mono-lbl">Mandate</span><span>UK B2B · 2029</span></div>
          </div>
          <button className="btn primary big" onClick={onStart}>
            Begin ReadinessCheck <span className="ar">→</span>
          </button>
          <div className="intro-note mono-lbl">No login. No data leaves your browser.</div>
        </div>
        <div className="intro-right">
          <svg className="ast" viewBox="0 0 100 100" aria-hidden="true">
            <g fill="#B85C45">
              <path d="M50 4 L54 44 L94 50 L54 56 L50 96 L46 56 L6 50 L46 44 Z"/>
              <path d="M50 4 L54 44 L94 50 L54 56 L50 96 L46 56 L6 50 L46 44 Z" transform="rotate(45 50 50)"/>
              <path d="M50 4 L54 44 L94 50 L54 56 L50 96 L46 56 L6 50 L46 44 Z" transform="rotate(22.5 50 50)" opacity=".75"/>
            </g>
          </svg>
          <div className="tag">What you'll learn</div>
          <ul className="learn">
            <li><b>£</b> Your annual risk-adjusted benefit across 8 streams</li>
            <li><b>£</b> Three-year NPV at a 7.5% discount rate</li>
            <li><b>£</b> Payback period and ROI</li>
            <li><b>£</b> Cash freed by a 4-day DSO improvement</li>
            <li><b>£</b> The three streams worth most to you specifically</li>
            <li><b>£</b> Which InvoiceReady product fits your profile</li>
          </ul>
          <div className="pull-light">
            53% of e-invoicing benefit comes from <i>receiving</i>, not sending — most diagnostic tools only measure one side.
            <cite>GENA Academy / Italy SDI mandate data</cite>
          </div>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────── QUESTION CARD
function QuestionCard({ q, state, value, onChoose, onBack, onNext, idx, total, runningTotal }) {
  return (
    <div className="screen qscreen">
      <Rail q={q} idx={idx} total={total} state={state} running={runningTotal} />
      <div className="qmain">
        <div className="qhead">
          <div className="qmeta">
            <span className="pill out-terra">{q.id}</span>
            <span className="mono-lbl">{q.gena}</span>
            <span className="dot" />
            <span className="mono-lbl">{q.stream}</span>
          </div>
          <h2 className="qtitle">{q.prompt}</h2>
          {q.sub && <p className="qsub">{q.sub}</p>}
        </div>

        <div className="opts">
          {q.options.map((o, i) => {
            const active = value === o.key;
            return (
              <button
                key={o.key}
                className={"opt " + (active ? "active" : "")}
                onClick={() => onChoose(q.id, o.key)}
              >
                <span className="opt-key">{String.fromCharCode(65 + i)}</span>
                <span className="opt-body">
                  <span className="opt-label">{o.label}</span>
                  {o.hint && <span className="opt-hint">{o.hint}</span>}
                </span>
                <span className="opt-right">
                  {o.saving !== undefined && <span className="opt-saving">{gbp(o.saving)}<small>/yr</small></span>}
                  {o.mid !== undefined && o.saving === undefined && <span className="opt-mid mono-lbl">midpoint {o.mid.toLocaleString()}</span>}
                  {o.fte !== undefined && <span className="opt-mid mono-lbl">{o.fte} FTE</span>}
                  {o.mult !== undefined && o.saving === undefined && <span className="opt-mult mono-lbl">×{o.mult.toFixed(2)}</span>}
                  {o.base !== undefined && o.fte === undefined && <span className="opt-saving">{gbp(o.base)}<small>/yr</small></span>}
                  {o.add !== undefined && <span className="opt-saving">+{gbp(o.add)}<small>/yr</small></span>}
                  {o.cost !== undefined && <span className="opt-mid mono-lbl">£{o.cost.toFixed(2)}/inv</span>}
                  {o.dso !== undefined && <span className="opt-saving">{gbp(o.dso)}<small> cash</small></span>}
                  {o.salary !== undefined && <span className="opt-mid mono-lbl">{gbp(o.salary)}</span>}
                </span>
              </button>
            );
          })}
        </div>

        <div className="qfoot">
          <button className="btn ghost" onClick={onBack} disabled={idx === 0}>← Back</button>
          <div className="qfoot-mid">
            <span className="mono-lbl">Question {idx + 1} of ~{total}</span>
            <div className="progress"><div className="bar" style={{ width: `${((idx) / total) * 100}%` }} /></div>
          </div>
          <button className="btn primary" onClick={onNext} disabled={!value}>
            Continue <span className="ar">→</span>
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────── LEFT RAIL
function Rail({ q, idx, total, state, running }) {
  return (
    <aside className="rail">
      <div className="rail-top">
        <div className="brand">
          <svg viewBox="0 0 100 100" width="22" height="22" aria-hidden="true">
            <g fill="#B85C45">
              <path d="M50 4 L54 44 L94 50 L54 56 L50 96 L46 56 L6 50 L46 44 Z"/>
            </g>
          </svg>
          <span>InvoiceReady · ReadinessCheck</span>
        </div>
      </div>

      <div className="rail-prog">
        <div className="mono-lbl rail-step">Step {String(idx + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}</div>
        <div className="rail-bar"><div style={{ width: `${((idx + 1) / total) * 100}%` }} /></div>
      </div>

      <div className="rail-running">
        <div className="mono-lbl">Running annual benefit</div>
        <div className="rail-amount">{gbp(running)}<small>/yr</small></div>
        <div className="rail-hint">Risk-adjusted · updates as you answer</div>
      </div>

      <div className="rail-section">
        <div className="mono-lbl">This question drives</div>
        <div className="rail-stream">{q.stream}</div>
        <div className="rail-gena mono-lbl">↳ {q.gena}</div>
      </div>

      <div className="rail-foot">
        <div className="mono-lbl">Mandate countdown</div>
        <div className="rail-count"><MandateCounter /></div>
      </div>
    </aside>
  );
}

function MandateCounter() {
  const target = new Date("2029-01-01T00:00:00Z");
  const now = new Date("2026-05-10T00:00:00Z");
  const months = Math.round((target - now) / (1000 * 60 * 60 * 24 * 30.44));
  return <span><b>{months}</b> months to UK B2B mandate</span>;
}

// ─────────────────────────────────────────────────── RESULTS
function Results({ state, onRestart }) {
  const r = useMemo(() => window.IR_SCORE(state), [state]);
  const flag = (f) => r.flags.includes(f);
  return (
    <div className="screen results">
      <div className="r-header">
        <div className="r-header-l">
          <div className="eyebrow">ReadinessCheck · Results</div>
          <h1 className="display-h">
            Your 3-year case for<br/><i>e-invoicing.</i>
          </h1>
          <p className="lede">
            Based on your answers: {r.totalInv.toLocaleString()} invoices/year · {state.Q3 && window.getOpt("Q3", state.Q3).fte} finance FTE · {state.Q6 && window.getOpt("Q6", state.Q6).label.split(" — ")[0]} on-time rate · {state.Q7 && window.getOpt("Q7", state.Q7).label.split(" (")[0].toLowerCase()} customer base.
          </p>
        </div>
        <div className="r-header-r">
          <button className="btn ghost" onClick={onRestart}>↺ Re-take</button>
          <button className="btn primary" onClick={() => window.print()}>Download PDF</button>
        </div>
      </div>

      <div className="r-grid">
        {/* HERO numbers */}
        <div className="r-card hero dark">
          <div className="hero-row">
            <Big lbl="Annual benefit" v={gbp(r.annual)} sub="Risk-adjusted · 8 streams" />
            <Big lbl="3-year NPV" v={gbp(r.npv)} sub="At 7.5% discount rate" terra />
            <Big lbl="Payback" v={r.payback ? `${r.payback}` : "—"} suffix="months" sub="From go-live" />
            <Big lbl="ROI · 3yr" v={r.roi ? `${r.roi}×` : "—"} sub={`On £${window.IR_CONSTANTS.IR_3YR_PRICE} total cost`} />
          </div>
          <div className="hero-foot">
            <div className="hero-foot-l">
              <span className="mono-lbl">InvoiceReady 3-year cost</span>
              <span className="hf-num">{gbp(window.IR_CONSTANTS.IR_3YR_PRICE)}</span>
            </div>
            <div className="hero-foot-arrow">→</div>
            <div className="hero-foot-r">
              <span className="mono-lbl">You keep</span>
              <span className="hf-num terra">{r.youKeep}%</span>
              <span className="hf-sub">of the value · {r.captureShare}% accrues to IR</span>
            </div>
          </div>
        </div>

        {/* TOP 3 streams */}
        <div className="r-card">
          <div className="card-head">
            <span className="num">01</span>
            <h3>Your top three benefit streams</h3>
          </div>
          <div className="top3">
            {r.top3.map((s, i) => (
              <div className="top3-row" key={s.id}>
                <span className="top3-rank">{i + 1}</span>
                <div className="top3-body">
                  <div className="top3-name">{s.name}</div>
                  <div className="top3-bar"><div style={{ width: `${Math.min(100, s.pct * 2.4)}%` }} /></div>
                </div>
                <div className="top3-val">{gbp(s.val)}<small>/yr</small><span className="top3-pct">{s.pct}%</span></div>
              </div>
            ))}
          </div>
        </div>

        {/* WORKING CAPITAL */}
        <div className="r-card sand">
          <div className="card-head">
            <span className="num">02</span>
            <h3>Working capital impact</h3>
            <span className="mono-lbl muted">Balance-sheet effect · not in NPV</span>
          </div>
          <p className="prose">
            A 4-day improvement in Days Sales Outstanding frees
            <span className="huge"> {gbp(r.dso)} </span>
            of cash currently tied up in unpaid receivables — immediately available for reinvestment or to reduce your credit facility.
          </p>
        </div>

        {/* FULL BREAKDOWN */}
        <div className="r-card wide">
          <div className="card-head">
            <span className="num">03</span>
            <h3>Stream-by-stream breakdown</h3>
          </div>
          <table className="breakdown">
            <thead>
              <tr><th>Benefit stream</th><th className="num-col">Your saving / yr</th><th className="pct-col">% of total</th><th className="bar-col"></th></tr>
            </thead>
            <tbody>
              {r.streamMeta.map(s => (
                <tr key={s.id}>
                  <td>{s.name}</td>
                  <td className="num-col">{gbp(s.val)}</td>
                  <td className="pct-col">{s.pct}%</td>
                  <td className="bar-col"><div className="tbar"><div style={{ width: `${Math.min(100, s.pct * 2.4)}%` }} /></div></td>
                </tr>
              ))}
              <tr className="total">
                <td><b>Total annual benefit</b></td>
                <td className="num-col"><b>{gbp(r.annual)}</b></td>
                <td className="pct-col"><b>100%</b></td>
                <td></td>
              </tr>
            </tbody>
          </table>
        </div>

        {/* RECOMMENDATION */}
        <div className="r-card dark wide rec">
          <div className="card-head">
            <span className="num invert">04</span>
            <h3>Recommended next step</h3>
            <span className="pill terra">{r.rec.tier}</span>
          </div>
          <div className="rec-body">
            <h4>{r.rec.title}</h4>
            <p className="prose">{r.rec.body}</p>
            {flag("B2C") && <p className="prose flag">↳ <b>B2C flag:</b> The 2029 mandate applies to B2B VAT invoices. Your B2C volumes are excluded, but structured invoicing for B2B customers still applies.</p>}
            {flag("CASHFLOW") && <p className="prose flag">↳ <b>Cash-flow flag:</b> Below-50% on-time payment is critical. Stream 2 (late-payment reduction) is the priority intervention.</p>}
            {flag("ERRORS") && <p className="prose flag">↳ <b>Errors flag:</b> Regular invoice disputes elevate Streams 4 & 5 — VAT compliance and fraud are material savings for you.</p>}
            {flag("ENTERPRISE") && <p className="prose flag">↳ <b>Enterprise flag:</b> Revenue over £10M — book a consultation for a tailored multi-entity TransitionPlan.</p>}
            <div className="rec-ctas">
              <button className="btn primary big">Book a 20-min ReadinessCheck call <span className="ar">→</span></button>
              <button className="btn ghost-light">Email me the full PDF</button>
            </div>
          </div>
        </div>

        {/* MANDATE COUNTDOWN */}
        <div className="r-card terra wide">
          <div className="md-grid">
            <div>
              <div className="mono-lbl" style={{color:"rgba(255,255,255,.8)"}}>Mandate countdown</div>
              <div className="md-num"><MandateCounter /></div>
            </div>
            <p className="prose">
              At your current invoice volume, transitioning in the final 6 months would mean processing <b>{Math.round(r.totalInv * 0.5).toLocaleString()}</b> invoices under emergency conditions. Early movers capture the economic benefit; late movers just achieve compliance.
            </p>
          </div>
        </div>
      </div>

      <footer className="r-foot">
        <div className="l">InvoiceReady Ltd · ReadinessCheck v1 · May 2026</div>
        <div className="r">GENA Academy · EESPA · Peppol · HMRC · Avalara/Cebr · APQC</div>
      </footer>
    </div>
  );
}

function Big({ lbl, v, suffix, sub, terra }) {
  return (
    <div className="big">
      <div className="mono-lbl">{lbl}</div>
      <div className={"big-v " + (terra ? "terra" : "")}>{v}{suffix && <small> {suffix}</small>}</div>
      <div className="big-sub">{sub}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────── APP ROOT
function App() {
  const [state, setState] = useState({});
  const [phase, setPhase] = useState("intro"); // intro | qs | done
  const [idx, setIdx] = useState(0);

  const sequence = useMemo(() => buildSequence(state), [state]);
  const total = sequence.length;
  const current = sequence[idx];
  const running = useMemo(() => runningSubtotal(state), [state]);

  function choose(qid, key) {
    setState(s => {
      const next = { ...s, [qid]: key };
      // Clear stale answers that now fail their show()
      for (const q of window.IR_QUESTIONS) {
        if (q.show && !q.show(next) && next[q.id]) delete next[q.id];
      }
      return next;
    });
  }

  function next() {
    if (idx + 1 >= sequence.length) {
      setPhase("done");
    } else {
      setIdx(idx + 1);
    }
  }
  function back() {
    if (idx > 0) setIdx(idx - 1);
    else setPhase("intro");
  }
  function start() {
    setPhase("qs");
    setIdx(0);
  }
  function restart() {
    setState({});
    setIdx(0);
    setPhase("intro");
  }

  if (phase === "intro") return <IntroScreen onStart={start} />;
  if (phase === "done")  return <Results state={state} onRestart={restart} />;
  if (!current) { setPhase("done"); return null; }
  return (
    <QuestionCard
      q={current}
      state={state}
      value={state[current.id]}
      onChoose={choose}
      onBack={back}
      onNext={next}
      idx={idx}
      total={total}
      runningTotal={running}
    />
  );
}

// ────────────────────────────────────────────────────── PASSWORD GATE
const AUTH_KEY = 'ir_auth';
const AUTH_VAL = 'check';

function PasswordGate({ children }) {
  const [authed, setAuthed]   = useState(() => sessionStorage.getItem(AUTH_KEY) === '1');
  const [value,  setValue]    = useState('');
  const [error,  setError]    = useState(false);
  const [shake,  setShake]    = useState(false);

  function attempt(e) {
    e.preventDefault();
    if (value === AUTH_VAL) {
      sessionStorage.setItem(AUTH_KEY, '1');
      setAuthed(true);
    } else {
      setError(true);
      setShake(true);
      setValue('');
      setTimeout(() => setShake(false), 500);
    }
  }

  if (authed) return children;

  return (
    <div style={{
      minHeight: '100dvh',
      background: 'var(--charcoal)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontFamily: 'var(--sans)',
    }}>
      <form
        onSubmit={attempt}
        style={{
          display: 'flex',
          flexDirection: 'column',
          gap: '1.25rem',
          width: '100%',
          maxWidth: '360px',
          padding: '2.5rem',
          background: '#221E1B',
          borderRadius: '12px',
          animation: shake ? 'gate-shake 0.45s ease' : 'none',
        }}
      >
        <div style={{ color: 'var(--terra)', fontFamily: 'var(--mono)', fontSize: '11px', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          InvoiceReady · ReadinessCheck
        </div>
        <div style={{ color: 'var(--cream)', fontSize: '1.35rem', fontFamily: 'var(--serif)', lineHeight: 1.3 }}>
          Enter access password
        </div>
        <input
          type="password"
          value={value}
          onChange={e => { setValue(e.target.value); setError(false); }}
          placeholder="Password"
          autoFocus
          style={{
            background: 'var(--charcoal)',
            border: `1.5px solid ${error ? 'var(--terra)' : '#3D3530'}`,
            borderRadius: '6px',
            color: 'var(--cream)',
            fontFamily: 'var(--mono)',
            fontSize: '14px',
            padding: '0.75rem 1rem',
            outline: 'none',
            transition: 'border-color 0.2s',
          }}
        />
        {error && (
          <div style={{ color: 'var(--terra)', fontFamily: 'var(--mono)', fontSize: '12px', marginTop: '-0.5rem' }}>
            Incorrect password
          </div>
        )}
        <button
          type="submit"
          style={{
            background: 'var(--terra)',
            color: '#fff',
            border: 'none',
            borderRadius: '6px',
            fontFamily: 'var(--sans)',
            fontSize: '14px',
            fontWeight: 600,
            padding: '0.75rem 1rem',
            cursor: 'pointer',
          }}
        >
          Continue →
        </button>
      </form>
      <style>{`
        @keyframes gate-shake {
          0%,100% { transform: translateX(0); }
          20%      { transform: translateX(-8px); }
          40%      { transform: translateX(8px); }
          60%      { transform: translateX(-5px); }
          80%      { transform: translateX(5px); }
        }
      `}</style>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(
  <PasswordGate><App /></PasswordGate>
);
