/* ============================================================
   quiz.jsx — "Where you might fit" — 8 Qs, multidimensional
   scoring, % fit per agency. Result modes: bars / map / cards.
   ============================================================ */

function computeFit(answers) {
  const raw = { moj: 0, dia: 0, police: 0 };
  answers.forEach((ai, qi) => {
    if (ai == null) return;
    const w = window.QUIZ[qi].a[ai].w;
    for (const k in w) raw[k] += w[k];
  });
  const total = raw.moj + raw.dia + raw.police || 1;
  // soften toward a spread so no agency reads as "the winner"
  const pct = {};
  window.AGENCY_ORDER.forEach(k => { pct[k] = Math.round((raw[k] / total) * 100); });
  // fix rounding drift to 100
  const drift = 100 - (pct.moj + pct.dia + pct.police);
  const top = window.AGENCY_ORDER.slice().sort((a, b) => pct[b] - pct[a])[0];
  pct[top] += drift;
  return pct;
}

function ResultBars({ ranked }) {
  return (
    <div>
      {ranked.map(([k, pct], i) => <FitBar key={k} k={k} pct={pct} rank={"0" + (i + 1)} />)}
    </div>
  );
}

function ResultCards({ ranked }) {
  return (
    <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(210px,1fr))" }}>
      {ranked.map(([k, pct], i) => {
        const a = window.AGENCIES[k];
        return (
          <div key={k} className="wbox dbl" style={{ padding: "20px 20px", borderColor: a.color, borderWidth: i === 0 ? 3.5 : 2.5 }}>
            <div className="row between center">
              <span className="pill" style={{ borderColor: a.color, fontSize: 12 }}>{a.role}</span>
              {i === 0 && <Anno>strongest match</Anno>}
            </div>
            <div className="disp" style={{ fontSize: 64, lineHeight: .9, marginTop: 10, color: a.color }}>{pct}%</div>
            <strong style={{ fontSize: 18, display: "block", marginTop: 4 }}>{a.name}</strong>
            <p style={{ fontSize: 15, marginTop: 8 }}>{a.blurb}</p>
          </div>
        );
      })}
    </div>
  );
}

function ResultMap({ ranked }) {
  // bubble "map" — each agency a circle sized by fit, on a sketched field
  const pos = { moj: { x: 50, y: 18 }, dia: { x: 22, y: 78 }, police: { x: 78, y: 78 } };
  return (
    <div className="wbox fill" style={{ position: "relative", height: 420, padding: 0, overflow: "hidden" }}>
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        <polygon points="50,18 22,78 78,78" fill="none" stroke="var(--line)" strokeWidth="0.4" strokeDasharray="2 2" opacity="0.5" />
      </svg>
      {ranked.map(([k, pct]) => {
        const a = window.AGENCIES[k];
        const size = 70 + pct * 1.7;
        return (
          <div key={k} style={{ position: "absolute", left: pos[k].x + "%", top: pos[k].y + "%", transform: "translate(-50%,-50%)", width: size, height: size }}>
            <div style={{ width: "100%", height: "100%", borderRadius: "50%", border: "3px solid " + a.color, background: "color-mix(in srgb, " + a.color + " 22%, var(--paper-2))", display: "grid", placeItems: "center", textAlign: "center", transition: "all .6s cubic-bezier(.2,.8,.2,1)" }}>
              <div>
                <div className="disp" style={{ fontSize: 30, lineHeight: .9 }}>{pct}%</div>
                <div style={{ fontSize: 12, fontWeight: 700 }}>{a.short}</div>
              </div>
            </div>
          </div>
        );
      })}
      <div className="muted" style={{ position: "absolute", bottom: 12, left: 0, right: 0, textAlign: "center", fontSize: 14 }}>your shape across the system — bigger = stronger pull</div>
    </div>
  );
}

function ScreenQuiz({ t, go }) {
  const [stage, setStage] = React.useState("intro"); // intro | q | done
  const [qi, setQi] = React.useState(0);
  const [answers, setAnswers] = React.useState(Array(window.QUIZ.length).fill(null));

  const pick = (ai) => {
    const next = answers.slice(); next[qi] = ai; setAnswers(next);
    setTimeout(() => {
      if (qi < window.QUIZ.length - 1) setQi(qi + 1);
      else setStage("done");
    }, 230);
  };
  const restart = () => { setAnswers(Array(window.QUIZ.length).fill(null)); setQi(0); setStage("intro"); };

  if (stage === "intro") {
    return (
      <div className="screen-enter" style={{ maxWidth: 720, margin: "0 auto", textAlign: "center", padding: "30px 0" }}>
        <div className="kicker" style={{ marginBottom: 14 }}>04 · Where you might fit</div>
        <h2 className="disp" style={{ fontSize: "clamp(40px,7vw,76px)" }}>It starts to become <span className="mark">about you.</span></h2>
        <p style={{ fontSize: 20, marginTop: 18 }}>Eight quick questions — about how you think and what drives you, not your CV. No wrong answers, no rejection. You'll see how you fit across all three agencies.</p>
        <div className="row wrapw" style={{ gap: 14, marginTop: 28, justifyContent: "center" }}>
          <button className="wbtn accent big" onClick={() => setStage("q")}>Start the quiz  →</button>
          <span className="anno" style={{ alignSelf: "center" }}>8 questions · ~2 min</span>
        </div>
      </div>
    );
  }

  if (stage === "done") {
    const pct = computeFit(answers);
    const ranked = window.AGENCY_ORDER.map(k => [k, pct[k]]).sort((a, b) => b[1] - a[1]);
    const mode = t.quizResult || "bars";
    return (
      <div className="screen-enter" style={{ maxWidth: 820, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 26 }}>
          <div className="kicker" style={{ marginBottom: 10 }}>your result</div>
          <h2 className="disp" style={{ fontSize: "clamp(36px,6vw,60px)" }}>You'd fit right in.</h2>
          <p style={{ fontSize: 18, marginTop: 10, maxWidth: 560, marginInline: "auto" }}>You lean toward <strong>{window.AGENCIES[ranked[0][0]].name}</strong> — but you've got a real pull across the whole system. That's exactly the point.</p>
        </div>

        {mode === "cards" ? <ResultCards ranked={ranked} />
          : mode === "map" ? <ResultMap ranked={ranked} />
          : <ResultBars ranked={ranked} />}

        <div className="row wrapw center between" style={{ marginTop: 32, gap: 14 }}>
          <button className="wbtn" onClick={restart}>↻ Retake</button>
          <button className="wbtn accent big" onClick={() => go("next")}>See real roles that fit  →</button>
        </div>
      </div>
    );
  }

  // question stage
  const Q = window.QUIZ[qi];
  const progress = ((qi) / window.QUIZ.length) * 100;
  return (
    <div className="screen-enter" style={{ maxWidth: 760, margin: "0 auto" }}>
      <div className="row between center" style={{ marginBottom: 8 }}>
        <span className="kicker">Question {qi + 1} of {window.QUIZ.length}</span>
        {qi > 0 && <button className="wbtn sm ghost" onClick={() => setQi(qi - 1)}>← back</button>}
      </div>
      <div style={{ height: 12, border: "2.5px solid var(--line)", borderRadius: 999, background: "var(--paper)", overflow: "hidden", marginBottom: 24 }}>
        <div style={{ width: progress + "%", height: "100%", background: "var(--accent)", transition: "width .35s cubic-bezier(.2,.8,.2,1)" }} />
      </div>

      <h2 className="disp" style={{ fontSize: "clamp(28px,4vw,40px)", lineHeight: 1.16, marginBottom: 38 }}>{Q.q}</h2>

      <div className="col" style={{ gap: 12 }}>
        {Q.a.map((opt, ai) => (
          <button key={ai} onClick={() => pick(ai)}
            className={"wbox" + (answers[qi] === ai ? " " : "")}
            style={{ padding: "16px 18px", textAlign: "left", cursor: "pointer", display: "flex", gap: 14, alignItems: "flex-start",
              background: answers[qi] === ai ? "var(--accent-soft)" : "var(--paper-2)" }}>
            <span className="disp" style={{ fontSize: 26, color: "var(--ink-3)", lineHeight: 1 }}>{String.fromCharCode(65 + ai)}</span>
            <span>
              <span style={{ fontSize: 18, fontWeight: 700 }}>{opt.t}</span>
              {opt.sub && <span className="muted" style={{ display: "block", fontSize: 14, marginTop: 3 }}>{opt.sub}</span>}
            </span>
          </button>
        ))}
      </div>
      <p className="muted" style={{ textAlign: "center", fontSize: 14, marginTop: 20 }}>pick the one that feels most like you</p>
    </div>
  );
}

Object.assign(window, { ScreenQuiz, computeFit });
