/* Kybercel — Assessment flow (React). Loads after quiz-data.js. */
const { useState, useEffect, useRef } = React;
const Q = window.KYB_QUIZ;
const STORE = 'kyb_quiz_v1';
const KEYS = 'ABCDEF';

/* ---- tiny icons ---- */
function Diamond(p) {
  return (<svg className={p.className} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0Z" />
  </svg>);
}
function Check(p) {
  return (<svg className={p.className} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M20 6 9 17l-5-5" /></svg>);
}

/* ---- persistence ---- */
function load() {
  try { return JSON.parse(localStorage.getItem(STORE)) || null; } catch (e) { return null; }
}
function save(s) {
  try { localStorage.setItem(STORE, JSON.stringify(s)); } catch (e) {}
}

/* ============================================================ TOP BAR */
function TopBar(props) {
  const total = Q.questions.length;
  const pct = props.screen === 'quiz'
    ? Math.round((props.idx) / total * 100)
    : (props.screen === 'compile' ? 100 : 100);
  const canReset = props.screen === 'quiz' && props.idx > 0;
  return (
    <div className="qz-top">
      <div className="qz-top-inner">
        <a className="brand" href="home.html" aria-label="Kybercel home">
          <Diamond className="mark" /><span className="name">Kybercel</span>
        </a>
        <div className="qz-progress"><i style={{ width: pct + '%' }}></i></div>
        {props.screen === 'quiz'
          ? <span className="qz-count">{String(props.idx + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</span>
          : <span className="qz-count">{props.screen === 'report' ? 'REPORT' : 'COMPLETE'}</span>}
        {canReset && (
          <button className="qz-reset" onClick={props.restart} title="Reset quiz">↺ Reset</button>
        )}
        <a className="qz-exit" href="home.html">Exit</a>
      </div>
    </div>
  );
}

/* ============================================================ QUESTION */
function QuestionScreen(props) {
  const q = Q.questions[props.idx];
  const ans = props.answers[q.id];
  const isMulti = q.multi;
  const selectedVs = isMulti && ans ? ans.vs : [];

  function pickSingle(opt) {
    props.setAnswer(q.id, { label: opt.label, score: opt.score, v: opt.v || opt.label });
    props.advance(220);
  }
  function toggleMulti(opt) {
    const key = opt.v || opt.label;
    const cur = ans ? { labels: ans.labels.slice(), vs: ans.vs.slice() } : { labels: [], vs: [] };
    const i = cur.vs.indexOf(key);
    if (i >= 0) { cur.vs.splice(i, 1); cur.labels.splice(i, 1); }
    else { cur.vs.push(key); cur.labels.push(opt.label); }
    props.setAnswer(q.id, cur);
  }
  const answered = isMulti ? (selectedVs.length > 0) : !!ans;

  return (
    <div className="qz-card" key={q.id}>
      <div className="qz-phase">{q.phase}</div>
      <h1 className="qz-q">{q.q}</h1>
      {q.sub ? <div className="qz-sub">{q.sub}</div> : null}
      <div className="qz-options">
        {q.options.map(function (opt, i) {
          const key = opt.v || opt.label;
          const sel = isMulti ? selectedVs.indexOf(key) >= 0 : (ans && (ans.v === (opt.v || opt.label)) && ans.label === opt.label);
          return (
            <button key={i} className={'qz-opt' + (sel ? ' sel' : '')}
              onClick={function () { isMulti ? toggleMulti(opt) : pickSingle(opt); }}>
              <span className="qz-key">{KEYS[i]}</span>
              <span className="qz-lbl">{opt.label}</span>
              <Check className="qz-check" />
            </button>
          );
        })}
      </div>
      <div className="qz-nav">
        <button className="qz-back" onClick={props.back} disabled={props.idx === 0}>← Back</button>
        {isMulti
          ? <button className="btn btn-primary" disabled={!answered}
              onClick={function () { props.advance(0); }} style={answered ? null : { opacity: 0.4, pointerEvents: 'none' }}>
              Continue <span className="arrow">→</span></button>
          : <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.74rem', color: 'var(--ink-faint)' }}>
              {answered ? '' : 'Select one'}</span>}
      </div>
    </div>
  );
}

/* ============================================================ COMPILE */
function CompileScreen(props) {
  const lines = [
    'ingesting responses · 15 / 15',
    'compiling readiness codex …',
    'scoring §STD standards coverage',
    'scoring §ENF enforcement readiness',
    'scoring §AUD auditability',
    'rendering governance report ▸'
  ];
  const [shown, setShown] = useState(0);
  const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  useEffect(function () {
    if (reduce) { props.done(); return; }
    let n = 0;
    const iv = setInterval(function () {
      n += 1; setShown(n);
      if (n >= lines.length) { clearInterval(iv); setTimeout(props.done, 650); }
    }, 360);
    return function () { clearInterval(iv); };
  }, []);
  return (
    <div className="qz-compile">
      <div className="codex" id="codex">
        <div className="codex-bar">
          <span className="dot"></span><span className="dot"></span><span className="dot"></span>
          <span className="path">readiness.kybercel / <b>compile</b></span>
          <span className="live">running</span>
        </div>
        <div className="codex-body">
          {lines.map(function (l, i) {
            return (<div key={i} className={'cmp-line' + (i < shown ? ' show' : '')}>
              <span className="ok">{i < shown - 0 ? '✓' : '›'}</span><span className="t">{l}</span></div>);
          })}
        </div>
      </div>
      <div className="cmp-caption">Building your AI Governance Readiness Report…</div>
    </div>
  );
}

/* ============================================================ REPORT */
function barColor(s) {
  if (s < 40) return 'var(--warn)';
  if (s < 70) return 'oklch(0.78 0.16 50)';
  return 'var(--acc)';
}
function ReportScreen(props) {
  const a = props.answers;
  const res = Q.score(a);
  const tier = Q.tier(res.overall);
  const gaps = Q.gaps(a);
  const rec = Q.recommendation(a);
  const [grown, setGrown] = useState(false);
  useEffect(function () { const t = setTimeout(function () { setGrown(true); }, 120); return function () { clearTimeout(t); }; }, []);

  const dims = ['standards', 'enforcement', 'audit'];
  const footprint = a.footprint && a.footprint.labels && a.footprint.labels.length
    ? a.footprint.labels.join(', ') : 'Not in production yet';

  function field(k, v) {
    return (<div className="sm-row"><span className="k">{k}</span><span className="v">{v || '—'}</span></div>);
  }

  return (
    <div className="rp">
      <div className="rp-head">
        <div className="rp-head-top">
          <div>
            <div className="rp-eyebrow">AI Governance Readiness Report</div>
            <div className="rp-title">Where your AI can drift today</div>
            <span className={'rp-tier tier-' + tier.key}>{tier.label}</span>
          </div>
          <div className="rp-score">
            <div className={'num tier-' + tier.key}>{res.overall}<span className="den">/100</span></div>
          </div>
        </div>
        <div className="rp-blurb">{tier.blurb}</div>
      </div>

      <div className="rp-section-label">Readiness by dimension</div>
      <div className="rp-dims">
        {dims.map(function (d) {
          const s = res.dim[d];
          return (<div className="rp-dim" key={d}>
            <div className="rp-dim-top">
              <span className="rp-dim-name">{Q.DIM_LABEL[d]}</span>
              <span className="rp-dim-val">{s}/100</span>
            </div>
            <div className="rp-bar"><i style={{ width: (grown ? s : 0) + '%', background: barColor(s) }}></i></div>
            <div className="rp-dim-diag">{Q.dimDiagnosis(d, s)}</div>
          </div>);
        })}
      </div>

      <div className="rp-section-label">{gaps.length ? 'Your most urgent gaps' : 'No critical gaps flagged'}</div>
      <div className="rp-gaps">
        {gaps.length
          ? gaps.slice(0, 5).map(function (g, i) {
              return (<div className="rp-gap" key={i}><span className="x">✗</span><span>{g}</span></div>);
            })
          : <div className="rp-gap clean"><span className="x">✓</span><span>Your controls held across every answer. The opportunity now is proof and scale.</span></div>}
      </div>

      <div className="rp-section-label">Recommended path</div>
      <div className="rp-rec">
        <div className="lbl">For your priority</div>
        <h3>{rec.title}</h3>
        <p>{rec.body}</p>
      </div>

      <div className="rp-section-label">Your handoff summary</div>
      <div className="rp-summary">
        <div className="sm-h"><span>context.kybercel / sales-handoff</span><span className="live">warm</span></div>
        {field('Role', a.role && a.role.label)}
        {field('Company size', a.size && a.size.label)}
        {field('AI maturity', a.maturity && a.maturity.label)}
        {field('AI footprint', footprint)}
        {field('90-day priority', a.priority && a.priority.label)}
        {field('Readiness', tier.label + ' · ' + res.overall + '/100')}
      </div>

      <div className="rp-cta">
        <button className="btn btn-primary btn-lg" onClick={props.capture}>
          Get the full report &amp; book a handoff <span className="arrow">→</span></button>
        <button className="btn btn-ghost btn-lg" onClick={function() { document.getElementById('waitlist-modal') && document.getElementById('waitlist-modal').showModal ? document.getElementById('waitlist-modal').showModal() : alert('Please fill out the form above first.'); }}>Join the waitlist</button>
      </div>
      <div className="rp-foot">
        <span>Free · no sales call required to see this</span>
        <button className="rp-restart" onClick={props.restart}>Start over</button>
      </div>
    </div>
  );
}

/* ============================================================ CAPTURE */
function CaptureScreen(props) {
  const [f, setF] = useState({ name: '', email: '', company: '' });
  const ok = f.email.indexOf('@') > 0 && f.name.trim() && f.company.trim();
  function up(k) { return function (e) { setF(Object.assign({}, f, { [k]: e.target.value })); }; }
  function submit(e) { e.preventDefault(); if (ok) props.done(f); }
  return (
    <div className="qz-form-wrap">
      <div className="rp-eyebrow" style={{ color: 'var(--acc)' }}>Final step</div>
      <h2>Send me the full report.</h2>
      <p className="lede">We’ll email your complete AI Governance Readiness Report and route a contextual handoff to our team — no generic demo, just your specific gaps.</p>
      <form className="qz-form" onSubmit={submit}>
        <div className="qz-field"><label>Name</label><input value={f.name} onChange={up('name')} placeholder="Jordan Rivera" /></div>
        <div className="qz-field"><label>Work email</label><input type="email" value={f.email} onChange={up('email')} placeholder="jordan@company.com" /></div>
        <div className="qz-field"><label>Company</label><input value={f.company} onChange={up('company')} placeholder="Company, Inc." /></div>
        <button className="btn btn-primary btn-lg" type="submit" style={ok ? null : { opacity: 0.45, pointerEvents: 'none' }}>
          Send my report <span className="arrow">→</span></button>
        <p className="qz-consent">By submitting you agree to be contacted about Kybercel. We don’t share your data. [placeholder copy]</p>
      </form>
      <div className="qz-skip"><button onClick={function () { props.done(null); }}>Skip — just show me the summary</button></div>
    </div>
  );
}

/* ============================================================ DONE */
function DoneScreen(props) {
  const named = props.lead && props.lead.name ? props.lead.name.split(' ')[0] : null;
  return (
    <div className="qz-done">
      <div className="seal"><Check className="" /></div>
      <h2>{named ? named + ', your report is on its way.' : 'Your readiness report is ready.'}</h2>
      <p>{props.lead
        ? 'Check your inbox for the full AI Governance Readiness Report. Our team will reach out with context on your specific gaps — not a cold demo.'
        : 'Here\u2019s what happens when you\u2019re ready to close the gaps we found.'}</p>
      <div className="next">
        <div className="nx"><span className="n">01</span><span>We map your highest-risk standards into a portable codex.</span></div>
        <div className="nx"><span className="n">02</span><span>We stand up an enforcement layer in front of one workflow.</span></div>
        <div className="nx"><span className="n">03</span><span>Every agent action is gated and audit-logged from day one.</span></div>
      </div>
      <div className="qz-done-actions">
        <a className="btn btn-ghost btn-lg home-link" href="home.html">Back to Kybercel <span className="arrow">→</span></a>
        <button className="btn btn-ghost btn-lg" onClick={props.restart}>Retake assessment</button>
      </div>
    </div>
  );
}

/* ============================================================ APP */
function QuizApp() {
  const saved = load();
  const [screen, setScreen] = useState(saved ? saved.screen : 'quiz');
  const [idx, setIdx] = useState(saved ? saved.idx : 0);
  const [answers, setAnswers] = useState(saved ? saved.answers : {});
  const [lead, setLead] = useState(saved ? saved.lead || null : null);
  const advanceTimer = useRef(null);

  useEffect(function () { save({ screen: screen, idx: idx, answers: answers, lead: lead }); }, [screen, idx, answers, lead]);
  useEffect(function () { window.scrollTo(0, 0); }, [idx, screen]);

  function setAnswer(id, val) { setAnswers(function (p) { return Object.assign({}, p, { [id]: val }); }); }
  function advance(delay) {
    clearTimeout(advanceTimer.current);
    advanceTimer.current = setTimeout(function () {
      if (idx >= Q.questions.length - 1) setScreen('compile');
      else setIdx(idx + 1);
    }, delay || 0);
  }
  function back() {
    if (idx > 0) setIdx(idx - 1);
  }
  function restart() {
    clearTimeout(advanceTimer.current);
    setAnswers({}); setLead(null); setIdx(0); setScreen('quiz');
    try { localStorage.removeItem(STORE); } catch (e) {}
  }

  let body;
  if (screen === 'quiz') body = <QuestionScreen idx={idx} answers={answers} setAnswer={setAnswer} advance={advance} back={back} />;
  else if (screen === 'compile') body = <CompileScreen done={function () { setScreen('report'); }} />;
  else if (screen === 'report') body = <ReportScreen answers={answers} capture={function () { setScreen('capture'); }} restart={restart} />;
  else if (screen === 'capture') body = <CaptureScreen done={function (f) { setLead(f); setScreen('done'); }} />;
  else body = <DoneScreen lead={lead} restart={restart} />;

  return (
    <div className="quiz-root">
      <TopBar screen={screen} idx={idx} restart={restart} />
      <div className="qz-stage">{body}</div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('quiz-app')).render(<QuizApp />);
