/* global React, ReactDOM */
const { useState, useEffect, useMemo, useRef } = React;
const { QUESTIONS, STAGES, ACTIONS, stageForTotal, targetedActionIndex } = window.AITS_DATA;

// ---------- API helpers ----------
async function apiSubmitContact(contact) {
  try {
    const r = await fetch("/api/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ contact }),
    });
    if (!r.ok) return null;
    const data = await r.json();
    return data && typeof data.id === "string" ? data.id : null;
  } catch (err) {
    console.warn("contact submit failed", err);
    return null;
  }
}

async function apiSubmitResult(id, scores, total, stageName) {
  if (!id) return false;
  try {
    const r = await fetch("/api/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, scores, total, stage: stageName }),
    });
    return r.ok;
  } catch (err) {
    console.warn("result submit failed", err);
    return false;
  }
}

// ---------- Email gate ----------
function EmailGate({ onSubmit, onCancel }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [company, setCompany] = useState("");
  const [consent, setConsent] = useState(true);
  const [touched, setTouched] = useState({});
  const emailRef = useRef(null);

  useEffect(() => {
    const t = setTimeout(() => emailRef.current && emailRef.current.focus(), 80);
    const onKey = (e) => { if (e.key === "Escape") onCancel && onCancel(); };
    window.addEventListener("keydown", onKey);
    return () => { clearTimeout(t); window.removeEventListener("keydown", onKey); };
  }, [onCancel]);

  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  const nameOk = name.trim().length >= 2;
  const canSubmit = emailOk && nameOk && consent;

  const submit = (e) => {
    e && e.preventDefault();
    setTouched({ name: true, email: true });
    if (!canSubmit) return;
    onSubmit({ name: name.trim(), email: email.trim(), company: company.trim(), consent, ts: Date.now() });
  };

  return (
    <div className="gate-overlay" role="dialog" aria-modal="true" aria-labelledby="gate-title">
      <div className="gate-card anim-fade-up">
        <div className="gate-left">
          <div className="eyebrow"><span className="tick"></span><span>Before you begin</span></div>
          <h2 id="gate-title" className="gate-title">Tell us where to send your <em>report</em>.</h2>
          <p className="gate-lead">
            We'll email a copy of your results — your stage, full score breakdown, and your three priority actions — so you can share it with your team after the webinar.
          </p>
          <ul className="gate-bullets">
            <li><span className="dot"></span>Your scores stay yours. We don't sell or share them.</li>
            <li><span className="dot"></span>One follow-up email with your report. No drip sequence.</li>
            <li><span className="dot"></span>Unsubscribe anytime — link in every email.</li>
          </ul>
        </div>

        <form className="gate-form" onSubmit={submit} noValidate>
          <label className="gate-field">
            <span className="gate-label">Full name <em>*</em></span>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={() => setTouched(t => ({...t, name: true}))}
              placeholder="Alex Morgan"
              autoComplete="name"
              className={touched.name && !nameOk ? "invalid" : ""}
            />
            {touched.name && !nameOk && <span className="gate-err">Please enter your name.</span>}
          </label>

          <label className="gate-field">
            <span className="gate-label">Work email <em>*</em></span>
            <input
              ref={emailRef}
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onBlur={() => setTouched(t => ({...t, email: true}))}
              placeholder="alex@company.com"
              autoComplete="email"
              inputMode="email"
              className={touched.email && !emailOk ? "invalid" : ""}
            />
            {touched.email && !emailOk && <span className="gate-err">Enter a valid work email.</span>}
          </label>

          <label className="gate-field">
            <span className="gate-label">Company <span className="gate-opt">(optional)</span></span>
            <input
              type="text"
              value={company}
              onChange={(e) => setCompany(e.target.value)}
              placeholder="Acme Co."
              autoComplete="organization"
            />
          </label>

          <label className="gate-consent">
            <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
            <span>I agree to receive my assessment report by email. DivergeIT will use my contact info per its <a href="https://www.divergeit.com" target="_blank" rel="noopener noreferrer">privacy policy</a>.</span>
          </label>

          <div className="gate-actions">
            <button type="submit" className="btn btn-primary" disabled={!canSubmit}>
              Begin assessment <span className="arrow">→</span>
            </button>
            <button type="button" className="gate-back" onClick={onCancel}>Cancel</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ---------- Header ----------
function AppHeader({ phase, qIndex, total, onRestart }) {
  let crumbText = "Introduction";
  let progress = 0;
  if (phase === "intro") { crumbText = "Introduction"; progress = 0; }
  else if (phase === "question") { crumbText = `Question ${String(qIndex + 1).padStart(2,"0")} of 05`; progress = ((qIndex) / 5) * 100 + 5; }
  else if (phase === "result") { crumbText = "Your Result"; progress = 100; }

  return (
    <>
      <header className="app-header">
        <div className="brand">
          <a href="https://www.divergeit.com" target="_blank" rel="noopener noreferrer" aria-label="DivergeIT">
            <img src="assets/divergeit-logo.webp" alt="DivergeIT" />
          </a>
        </div>
        <div className="crumbs">
          <span>AI Threat Spectrum</span>
          <span className="dot"></span>
          <span>Webinar Series</span>
          <span className="dot"></span>
          <span>{crumbText}</span>
        </div>
        <div className="progress-meta">
          {phase === "result" ? (
            <button className="btn btn-ghost" style={{padding:"8px 14px", fontSize:12}} onClick={onRestart}>↺ Restart</button>
          ) : phase === "question" ? (
            <span>{`0${qIndex + 1}`}<span style={{color:"var(--di-mute-2)"}}> / 05</span></span>
          ) : (
            <span>5 Questions · ~3 min</span>
          )}
        </div>
      </header>
      <div className="progress-rail">
        <div className="progress-fill" style={{ width: `${progress}%` }}></div>
      </div>
    </>
  );
}

// ---------- Intro ----------
function IntroScreen({ onStart }) {
  return (
    <section className="screen anim-fade-up">
      <div className="intro-grid">
        <div className="intro-left">
          <div className="eyebrow"><span className="tick"></span><span>AI Threat Spectrum · Self-assessment</span></div>
          <h1 className="display">Where are you<br/>on the <em>AI Threat<br/>Spectrum</em>?</h1>
          <p className="lead" style={{marginTop: 28}}>
            Five questions. Score yourself honestly. Find your stage — At&nbsp;Risk, Exposed, Aware, or Governed — and walk away with three actions to take next.
          </p>
          <div className="intro-meta">
            <span className="item"><span className="num">5</span>Questions</span>
            <span className="item"><span className="num">~3</span>Minutes</span>
            <span className="item"><span className="num">3</span>Actions</span>
            <span className="item"><span className="num">1</span>Honest baseline</span>
          </div>
          <div className="intro-actions">
            <button className="btn btn-primary" onClick={onStart}>
              Begin assessment
              <span className="arrow">→</span>
            </button>
            <span className="hint">Press <strong style={{color:"var(--di-ink)"}}>Enter</strong> to start</span>
          </div>
        </div>

        <aside className="spectrum-card">
          <div>
            <div className="label-row">
              <span>◀ Greater threat</span>
              <span>More governed ▶</span>
            </div>
            <div className="spectrum-bar">
              <div className="seg s1"></div>
              <div className="seg s2"></div>
              <div className="seg s3"></div>
              <div className="seg s4"></div>
            </div>
            <div className="spectrum-stages">
              <div className="stage">At Risk<span className="range">5–7</span></div>
              <div className="stage">Exposed<span className="range">8–10</span></div>
              <div className="stage">Aware<span className="range">11–13</span></div>
              <div className="stage">Governed<span className="range">14–15</span></div>
            </div>
          </div>

          <div className="big-stat">
            <div className="num">49<em>%</em></div>
            <div className="desc">of workers admit to using AI tools without their employer's approval. Your people are already on the spectrum — the question is whether you know where.</div>
            <div className="src">Source · BlackFog / Sapio Research · Nov 2025</div>
          </div>
        </aside>
      </div>
    </section>
  );
}

// ---------- Question ----------
function QuestionScreen({ qIndex, scores, setScore, onNext, onBack }) {
  const q = QUESTIONS[qIndex];
  const selected = scores[qIndex];
  const canNext = selected != null;

  return (
    <section className="screen" key={qIndex}>
      <div className="q-grid">
        <div className="q-left anim-fade-up">
          <div className="q-counter">
            <span>Question {String(qIndex + 1).padStart(2,"0")} of 05</span>
            <span className="pip-row">
              {QUESTIONS.map((_, i) => (
                <span key={i} className={`pip ${i < qIndex ? "done" : i === qIndex ? "current" : ""}`}></span>
              ))}
            </span>
          </div>
          <h2 className="q-title">{q.title}</h2>
          <div className="q-meaning">
            <h3 className="section">What this means</h3>
            <p className="body">{q.meaning}</p>
          </div>
          <div className="q-actions">
            <button className="btn btn-ghost" onClick={onBack} disabled={qIndex === 0}>
              <span style={{transform:"rotate(180deg)", display:"inline-block"}}>→</span> Back
            </button>
            <button className="btn btn-primary" onClick={onNext} disabled={!canNext}>
              {qIndex === 4 ? "See my result" : "Next question"}
              <span className="arrow">→</span>
            </button>
          </div>
        </div>

        <div className="q-right anim-fade-up stagger-1">
          <h3 className="section">Rate yourself</h3>
          {q.options.map((opt, i) => (
            <div
              key={opt.score}
              className={`score-card ${selected === opt.score ? `selected s-${opt.score}` : ""} anim-fade-up stagger-${i + 2}`}
              onClick={() => setScore(qIndex, opt.score)}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setScore(qIndex, opt.score); }}}
            >
              <span className="badge">{opt.score}</span>
              <div>
                <span className="label">{opt.label}</span>
                <div className="desc">{opt.text}</div>
              </div>
              <span className="key">{opt.score}</span>
            </div>
          ))}
          <div style={{marginTop: 8, fontFamily:"var(--mono)", fontSize:11, letterSpacing:"0.16em", textTransform:"uppercase", color:"var(--di-mute)"}}>
            Tip · press <strong style={{color:"var(--di-ink)"}}>1</strong> · <strong style={{color:"var(--di-ink)"}}>2</strong> · <strong style={{color:"var(--di-ink)"}}>3</strong> to score
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Result ----------
function ResultScreen({ scores, onRestart, contact }) {
  const total = scores.reduce((a, b) => a + (b || 0), 0);
  const stage = stageForTotal(total);
  const targetedIdx = targetedActionIndex(scores);

  // Position marker on spectrum (5..15 → 0..100%)
  const markerPct = ((total - 5) / (15 - 5)) * 100;

  // Animate marker from 0
  const [animatedPct, setAnimatedPct] = useState(0);
  useEffect(() => {
    const t = setTimeout(() => setAnimatedPct(markerPct), 140);
    return () => clearTimeout(t);
  }, [markerPct]);

  const lowestScore = Math.min(...scores);

  return (
    <section className="screen result-screen">
      <div className="eyebrow anim-fade-up"><span className="tick"></span><span>Your Result · {new Date().toLocaleDateString(undefined,{month:"short", day:"numeric", year:"numeric"})}{contact ? ` · ${contact.name}` : ""}</span></div>

      <div className="result-hero">
        <div className="result-score-card anim-fade-up stagger-1">
          <div>
            <div className="stage-eyebrow">You are at the</div>
            <h1 className={`stage-name ${stage.key}`}>{stage.name}</h1>
            <div className="stage-eyebrow" style={{marginTop:6}}>stage</div>
            <p className="stage-tagline">{stage.tagline}</p>
          </div>
          <div className="score-display">
            <span className="total">{total}</span>
            <span className="of">/ 15<br/>total score</span>
          </div>
        </div>

        <div className="result-spectrum anim-fade-up stagger-2">
          <h3 className="section">Threat spectrum · your position</h3>
          <div className="spectrum-viz">
            <div className="bar">
              <div className="seg atrisk"></div>
              <div className="seg exposed"></div>
              <div className="seg aware"></div>
              <div className="seg governed"></div>
            </div>
            <div className="marker" style={{ left: `${animatedPct}%` }}>
              <span className="pin"></span>
              <span className="you">YOU · {total}</span>
            </div>
          </div>
          <div className="spectrum-labels">
            {STAGES.map(s => (
              <div key={s.key} className={`stage ${s.key === stage.key ? "you" : ""}`}>
                <span className="name">{s.name}</span>
                <span className="range">{s.range[0]}–{s.range[1]}</span>
                <span className="gloss">{s.gloss}</span>
              </div>
            ))}
          </div>

          <div className="score-breakdown" style={{marginTop: 28}}>
            <h3 className="section">Your scores</h3>
            {QUESTIONS.map((q, i) => (
              <div key={q.id} className={`score-row s-${scores[i]}`}>
                <span className="num">0{i + 1}</span>
                <span className="q">{q.short}</span>
                <span className="pts">{scores[i]}<em>/3</em></span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="actions-section">
        <div className="actions-header">
          <div>
            <h3 className="section anim-fade-up">Top 3 Actions</h3>
            <h2 className="anim-fade-up stagger-1">Mitigate the risk.<br/>Capture the value.</h2>
          </div>
          <p className="body anim-fade-up stagger-2" style={{maxWidth:"36ch", margin:0}}>
            Your lowest score was <strong style={{color:"var(--di-red)"}}>{lowestScore}/3</strong>. The action highlighted below is tied to where the threat actually lives for you — start there.
          </p>
        </div>
        <div className="actions-grid">
          {ACTIONS.map((a, i) => (
            <div key={a.n} className={`action-card ${i === targetedIdx ? "targeted" : ""} anim-fade-up stagger-${i + 1}`}>
              {i === targetedIdx && (
                <div className="targeted-flag"><span className="dot"></span>Start here</div>
              )}
              <div className="num">{a.n}</div>
              <h4>{a.title}</h4>
              <div className="block">
                <span className="label">Mitigates</span>
                <p className="copy">{a.mitigates}</p>
              </div>
              <div className="block">
                <span className="label">Unlocks</span>
                <p className="copy">{a.unlocks}</p>
              </div>
              <div className="first-move">
                <span className="label">First move</span>
                <p className="copy">{a.firstMove}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="result-cta anim-fade-up">
        <div className="text">
          <span className="eyebrow"><span className="tick"></span><span>Next step{contact ? ` · We'll email a copy to ${contact.email}` : ""}</span></span>
          <h3>Want help getting to Governed?</h3>
          <p>DivergeIT runs the same assessment as a paid engagement — with named owners, milestones, and quarterly re-scoring.</p>
        </div>
        <div className="actions">
          <button className="btn btn-ghost" onClick={() => window.dispatchEvent(new CustomEvent("aits:print-preview"))}>
            <span style={{fontSize:14}}>⎙</span> Print this assessment
          </button>
          <button className="btn btn-ghost" onClick={onRestart}>↺ Re-take</button>
          <a className="btn btn-primary" href="https://meetings.hubspot.com/roshi/roshi-calendar-website-group?embed=true&parentHubspotUtk=bd1b1387cf60efa1bc06cda113a0f45d&parentPageUrl=https%3A%2F%2Fdivergeit.com%2Fcontact-us%2F&uuid=170b5af0-7344-4be2-b475-8080dbfbaebf" target="_blank" rel="noopener noreferrer">Book a 30-min consultation <span className="arrow">→</span></a>
        </div>
      </div>
    </section>
  );
}

// ---------- App root ----------
function App() {
  const [phase, setPhase] = useState("intro"); // intro | gate | question | result
  const [qIndex, setQIndex] = useState(0);
  const [scores, setScores] = useState([null, null, null, null, null]);
  const [contact, setContact] = useState(() => {
    try { const v = localStorage.getItem("aits.contact"); return v ? JSON.parse(v) : null; } catch (e) { return null; }
  });
  const [submissionId, setSubmissionId] = useState(null);
  const resultPostedRef = useRef(false);

  const setScore = (i, s) => {
    setScores(prev => { const next = [...prev]; next[i] = s; return next; });
  };

  // Stash scores + contact on window so the print-preview handler can read them.
  useEffect(() => { window.__AITS_SCORES = scores; }, [scores]);
  useEffect(() => { window.__AITS_CONTACT = contact; }, [contact]);

  const startQuestions = (c) => {
    setPhase("question");
    setQIndex(0);
    setScores([null, null, null, null, null]);
    resultPostedRef.current = false;
    setSubmissionId(null);
    apiSubmitContact(c).then((id) => { if (id) setSubmissionId(id); });
  };
  const beginFlow = () => {
    if (contact) startQuestions(contact);
    else setPhase("gate");
  };
  const submitContact = (c) => {
    setContact(c);
    try { localStorage.setItem("aits.contact", JSON.stringify(c)); } catch (e) {}
    startQuestions(c);
  };
  const start = beginFlow;
  const next = () => {
    if (qIndex < 4) setQIndex(qIndex + 1);
    else setPhase("result");
  };
  const back = () => {
    if (qIndex > 0) setQIndex(qIndex - 1);
    else setPhase("intro");
  };
  const restart = () => {
    setScores([null,null,null,null,null]);
    setQIndex(0);
    setPhase("intro");
    setSubmissionId(null);
    resultPostedRef.current = false;
  };

  // POST final result once we land on the result screen.
  useEffect(() => {
    if (phase !== "result") return;
    if (resultPostedRef.current) return;
    if (!submissionId) return;
    if (scores.some((s) => s == null)) return;
    resultPostedRef.current = true;
    const total = scores.reduce((a, b) => a + (b || 0), 0);
    const stageObj = stageForTotal(total);
    apiSubmitResult(submissionId, scores, total, stageObj && stageObj.name);
  }, [phase, submissionId, scores]);

  // Keyboard handlers
  useEffect(() => {
    const onKey = (e) => {
      if (e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA")) return;
      if (phase === "intro" && e.key === "Enter") { e.preventDefault(); beginFlow(); }
      else if (phase === "question") {
        if (e.key === "1" || e.key === "2" || e.key === "3") {
          setScore(qIndex, parseInt(e.key, 10));
        } else if (e.key === "ArrowRight" || e.key === "Enter") {
          if (scores[qIndex] != null) { e.preventDefault(); next(); }
        } else if (e.key === "ArrowLeft" || e.key === "Backspace") {
          back();
        }
      } else if (phase === "result" && e.key === "r") {
        restart();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [phase, qIndex, scores, contact]);

  return (
    <div className="app-stage">
      <AppHeader phase={phase === "gate" ? "intro" : phase} qIndex={qIndex} total={5} onRestart={restart} />
      <main className="app-main">
        {(phase === "intro" || phase === "gate") && <IntroScreen onStart={beginFlow} />}
        {phase === "question" && (
          <QuestionScreen
            qIndex={qIndex}
            scores={scores}
            setScore={setScore}
            onNext={next}
            onBack={back}
          />
        )}
        {phase === "result" && <ResultScreen scores={scores} onRestart={restart} contact={contact} />}
      </main>

      {phase === "gate" && (
        <EmailGate onSubmit={submitContact} onCancel={() => setPhase("intro")} />
      )}

      {phase === "question" && (
        <div className="kbd-hint">
          <span><span className="key">1</span><span className="key">2</span><span className="key">3</span> Score</span>
          <span><span className="key">←</span><span className="key">→</span> Navigate</span>
          <span><span className="key">Enter</span> Continue</span>
        </div>
      )}
    </div>
  );
}

window.App = App;
