// Quiz.jsx — Multi-step quiz, result reveal, email gate, progressive profiling.
// Flow:
//   0..7 : 8 questions
//   8    : reveal + email gate (Layer 2: result gate)
//   9    : enrichment (Layer 3: city / sports / what you want)
//   10   : final celebration with next actions

function TgQuiz({ onClose, onComplete, onSeeEvent, onSeeMerch, setView, city: initialCity }) {
  const [step, setStep] = React.useState(0); // -1 intro, 0..7 q, 8 reveal+gate, 9 enrichment, 10 done
  const [intro, setIntro] = React.useState(true);
  const [answers, setAnswers] = React.useState({}); // q index -> answer index
  const [pending, setPending] = React.useState(null); // index of just-picked answer (animating)
  const [profile, setProfile] = React.useState({
    name: "", email: "", whatsapp: "", city: initialCity || "mumbai",
    sports: [], interests: [], source: "", notifs: { ws: true, email: true },
  });
  const [confetti, setConfetti] = React.useState(false);

  const total = window.TG_QUIZ.length;

  function pick(qIdx, aIdx) {
    if (pending != null) return;
    setAnswers(prev => ({ ...prev, [qIdx]: aIdx }));
    setPending(aIdx);
    setTimeout(() => {
      setPending(null);
      if (qIdx < total - 1) {
        setStep(qIdx + 1);
      } else {
        setStep(total); // advance to reveal
        setConfetti(true);
        setTimeout(() => setConfetti(false), 2600);
      }
    }, 320);
  }

  function prev() {
    if (step > 0) setStep(step - 1);
  }

  function computeResult() {
    const scores = {};
    window.TG_ARCHETYPES.forEach(k => scores[k] = 0);
    window.TG_QUIZ.forEach((q, i) => {
      const a = answers[i];
      if (a == null) return;
      const w = q.answers[a].w || {};
      Object.keys(w).forEach(k => { scores[k] = (scores[k] || 0) + w[k]; });
    });
    let best = window.TG_ARCHETYPES[0], bestScore = -1;
    window.TG_ARCHETYPES.forEach(k => {
      if (scores[k] > bestScore) { bestScore = scores[k]; best = k; }
    });
    return best;
  }

  const result = step >= total ? window.TG_RESULTS[computeResult()] : null;

  if (intro) {
    return (
      <div className="tg-quiz">
        <QuizTop step={0} total={total} onClose={onClose} />
        <div className="tg-quiz__progress"><div className="tg-quiz__progress-fill" style={{ width: "0%" }}></div></div>
        <div className="tg-quiz__stage">
          <div className="tg-quiz__card" style={{ maxWidth: 760 }}>
            <div className="tg-quiz__qnum">A highly scientific test</div>
            <h2 className="tg-quiz__q" style={{ fontSize: "clamp(48px, 7vw, 96px)" }}>
              Which <span className="script">Team Girl</span><br/>are you?
            </h2>
            <p className="tg-quiz__qsub" style={{ marginTop: 18, fontSize: 18 }}>
              Eight questions. Ninety seconds. One result, one badge, and a personalised first night.
              No spam. No long form. We'll save your spot on the way out.
            </p>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 32 }}>
              <button className="btn btn--pri btn--lg" onClick={() => setIntro(false)}>
                Start <span className="arr">→</span>
              </button>
              <button className="btn btn--ghost" onClick={onClose}>Maybe later</button>
            </div>
            <div style={{ marginTop: 36, display: "flex", gap: 18, flexWrap: "wrap", color: "var(--tg-muted)", fontSize: 12, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase" }}>
              <span>✦ 8 questions</span>
              <span>✦ 6 result types</span>
              <span>✦ Shareable badge</span>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // QUESTION STEPS
  if (step < total) {
    const q = window.TG_QUIZ[step];
    const selected = answers[step];
    const progress = ((step + (selected != null ? 1 : 0)) / total) * 100;

    return (
      <div className="tg-quiz">
        <QuizTop step={step} total={total} onClose={onClose} />
        <div className="tg-quiz__progress">
          <div className="tg-quiz__progress-fill" style={{ width: progress + "%" }}></div>
        </div>

        <div className="tg-quiz__stage">
          <div className="tg-quiz__card" key={step}>
            <div className="tg-quiz__qnum">Q{step + 1} of {total} ✦</div>
            <h2 className="tg-quiz__q">{q.q}</h2>
            <p className="tg-quiz__qsub">{q.sub}</p>

            <div className="tg-quiz__answers">
              {q.answers.map((a, i) => (
                <button key={i}
                  className={"tg-quiz__answer " + (pending === i || selected === i ? "is-selected" : "")}
                  disabled={pending != null}
                  onClick={() => pick(step, i)}>
                  <span className="tg-quiz__answer-letter">{String.fromCharCode(65 + i)}</span>
                  <span className="tg-quiz__answer-text">
                    {a.t}
                    <span className="s">{a.s}</span>
                  </span>
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="tg-quiz__nav">
          <button className="btn btn--ghost" onClick={step === 0 ? () => setIntro(true) : prev}>
            ← Back
          </button>
          <span className="tg-quiz__hint">{step === total - 1 ? "Tap an answer · see your result" : "Tap an answer to continue"}</span>
        </div>
      </div>
    );
  }

  // RESULT (step === total = 8)
  if (step === total) {
    return (
      <React.Fragment>
        {confetti && <Confetti />}
        <ResultReveal
          result={result}
          profile={profile}
          setProfile={setProfile}
          onGateDone={() => setStep(total + 1)}
          onClose={onClose}
        />
      </React.Fragment>
    );
  }

  // ENRICHMENT (step === 9)
  if (step === total + 1) {
    return (
      <Enrichment
        result={result}
        profile={profile}
        setProfile={setProfile}
        onDone={() => { setStep(total + 2); onComplete && onComplete(result.id, profile); }}
        onSkip={() => { setStep(total + 2); onComplete && onComplete(result.id, profile); }}
      />
    );
  }

  // FINAL CELEBRATION (step === 10)
  return (
    <FinalCelebration
      result={result}
      profile={profile}
      onSeeEvent={onSeeEvent}
      onSeeMerch={onSeeMerch}
      onClose={onClose}
    />
  );
}


function QuizTop({ step, total, onClose }) {
  return (
    <div className="tg-quiz__top">
      <div className="tg-quiz__brand">
        <img src="assets/logos/primary.png" alt="" />
        <div className="tg-quiz__step">✦ Highly scientific quiz</div>
      </div>
      <button className="tg-quiz__exit" onClick={onClose}>✕ Exit</button>
    </div>
  );
}

function Confetti() {
  const pieces = Array.from({ length: 80 }).map((_, i) => ({
    left: Math.random() * 100 + "%",
    delay: Math.random() * 600 + "ms",
    color: ["var(--tg-magenta)", "var(--tg-orange)", "var(--tg-peach)", "var(--tg-lilac)", "var(--tg-cream)"][i % 5],
    rot: Math.random() * 360,
  }));
  return (
    <div className="tg-confetti">
      {pieces.map((p, i) => (
        <span key={i} style={{
          left: p.left, animationDelay: p.delay,
          background: p.color, transform: `rotate(${p.rot}deg)`,
          borderRadius: i % 2 === 0 ? 2 : 999,
        }}></span>
      ))}
    </div>
  );
}

function ResultReveal({ result, profile, setProfile, onGateDone, onClose }) {
  const [step, setStep] = React.useState("reveal"); // reveal | gate

  return (
    <div className="tg-result" style={{ backgroundImage: `url(${result.bg})` }}>
      <QuizTop step={8} total={8} onClose={onClose} />
      <div style={{ height: 24 }}></div>

      <div className="tg-result__inner">
        <div>
          <span className="tg-result__eyebrow">✦ Your result is in</span>
          <h1 className="tg-result__type">{result.name}</h1>
          <span className="tg-result__sub">{result.tagline}</span>
          <p className="tg-result__desc">{result.desc}</p>

          {step === "reveal" && (
            <div className="tg-result__actions">
              <button className="btn btn--cream" style={{ background: "var(--tg-cream)", color: "var(--tg-ink)" }} onClick={() => setStep("gate")}>
                Save my result <span className="arr">→</span>
              </button>
              <button className="btn btn--invert" onClick={() => { navigator.clipboard && navigator.clipboard.writeText(`I'm a ${result.name} on Team Girl. Find your type at teamgirl.club`); alert("Copied — paste anywhere."); }}>
                Share to story
              </button>
            </div>
          )}

          {step === "gate" && (
            <div className="tg-gate" style={{ marginTop: 18 }}>
              <h3>Save your <span style={{ fontFamily: "var(--font-script)", color: "var(--tg-magenta)", fontWeight: 400, textTransform: "none" }}>badge</span>.</h3>
              <p>Drop your name + email and we'll save your result, send your badge, and show you your city's next session.</p>
              <div className="tg-gate__field">
                <label>First name</label>
                <input value={profile.name} onChange={e => setProfile({ ...profile, name: e.target.value })} placeholder="Anu" required />
              </div>
              <div className="tg-gate__field">
                <label>Email</label>
                <input type="email" value={profile.email} onChange={e => setProfile({ ...profile, email: e.target.value })} placeholder="you@somewhere.com" required />
              </div>
              <div className="tg-gate__field">
                <label>WhatsApp (optional — but recommended)</label>
                <input value={profile.whatsapp} onChange={e => setProfile({ ...profile, whatsapp: e.target.value })} placeholder="+91 98XX XX XX XX" />
              </div>
              <div style={{ display: "flex", gap: 10, marginTop: 14 }}>
                <button className="btn btn--ghost" onClick={() => setStep("reveal")}>← Back</button>
                <button className="btn btn--pri" onClick={() => profile.name && profile.email && onGateDone()} style={{ flex: 1, justifyContent: "center" }}>
                  Save & continue <span className="arr">→</span>
                </button>
              </div>
              <div style={{ fontSize: 11, color: "var(--tg-muted)", marginTop: 12, lineHeight: 1.5 }}>
                ✦ We'll save your result, send your badge, and add you to the Locker Room newsletter. One unsubscribe link. No spam, ever.
              </div>
            </div>
          )}
        </div>

        <ResultBadge result={result} profile={profile} />
      </div>
    </div>
  );
}

function ResultBadge({ result, profile }) {
  const useInk = result.id === "playmaker" || result.id === "loyal";
  const inkColor = useInk ? "var(--tg-ink)" : "var(--tg-cream)";
  const num = String(Object.keys(window.TG_RESULTS).indexOf(result.id) + 1).padStart(2, "0");
  return (
    <div className="tg-result__badge-wrap">
      <div className="tg-result__badge" style={{ background: result.badgeColor, color: inkColor, borderColor: useInk ? "var(--tg-ink)" : "rgba(17,17,17,0.85)" }}>
        <div className="tg-result__badge-top">
          <span className="mark">★ Team Girl · 2026 · {num}/06</span>
          <span className="spark">✦</span>
        </div>
        <div className="tg-result__badge-bottom">
          <div className="name">{result.name.replace("The ", "")}</div>
          <div className="tag" style={{ color: inkColor }}>{result.script}</div>
        </div>
        <div className="tg-result__badge-traits">
          {result.traits.map(t => (
            <span key={t} className="t" style={{ borderColor: inkColor, color: inkColor }}>{t}</span>
          ))}
        </div>
        {profile.name && (
          <div className="tg-result__badge-issued">Issued to · {profile.name}</div>
        )}
      </div>
    </div>
  );
}

function Enrichment({ result, profile, setProfile, onDone, onSkip }) {
  const interests = ["Watch parties", "Play dates", "Athlete dinners", "Pop-ups", "Merch drops", "Just lurk"];
  const sources = ["Instagram", "TikTok", "A friend", "Newsletter", "Walked past one", "Other"];

  function toggle(field, value) {
    setProfile(p => {
      const arr = new Set(p[field]);
      if (arr.has(value)) arr.delete(value); else arr.add(value);
      return { ...p, [field]: Array.from(arr) };
    });
  }

  return (
    <div className="tg-quiz">
      <QuizTop step={9} total={9} onClose={onSkip} />
      <div className="tg-quiz__progress"><div className="tg-quiz__progress-fill" style={{ width: "92%" }}></div></div>

      <div className="tg-quiz__stage">
        <div className="tg-quiz__card" style={{ maxWidth: 880 }}>
          <div className="tg-quiz__qnum">★ Welcome, {profile.name || result.name}. One last thing.</div>
          <h2 className="tg-quiz__q" style={{ fontSize: "clamp(36px, 5vw, 64px)" }}>
            Let's tune your <span className="script">feed</span>.
          </h2>
          <p className="tg-quiz__qsub">Quick — tap the ones that apply. We use these to pick which events, drops, and stories you see first. Skip anything you don't feel like answering.</p>

          <div style={{ display: "grid", gap: 24, marginTop: 32 }}>
            <div>
              <label style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--tg-muted)", display: "block", marginBottom: 10 }}>City</label>
              <div className="tg-prefs">
                {window.TG_CITIES.map(c => (
                  <button key={c.id} className={profile.city === c.id ? "is-selected" : ""} onClick={() => setProfile({ ...profile, city: c.id })}>
                    <span className="emoji" style={{ width: 14, height: 14, borderRadius: 999, background: c.color, display: "inline-block" }}></span>
                    {c.name}
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--tg-muted)", display: "block", marginBottom: 10 }}>Sports you care about · pick any</label>
              <div className="tg-prefs">
                {window.TG_SPORTS.map(s => (
                  <button key={s} className={profile.sports.includes(s) ? "is-selected" : ""} onClick={() => toggle("sports", s)}>{s}</button>
                ))}
              </div>
            </div>

            <div>
              <label style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--tg-muted)", display: "block", marginBottom: 10 }}>What you're here for · pick any</label>
              <div className="tg-prefs">
                {interests.map(s => (
                  <button key={s} className={profile.interests.includes(s) ? "is-selected" : ""} onClick={() => toggle("interests", s)}>{s}</button>
                ))}
              </div>
            </div>

            <div>
              <label style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--tg-muted)", display: "block", marginBottom: 10 }}>Where did you hear about us?</label>
              <div className="tg-prefs">
                {sources.map(s => (
                  <button key={s} className={profile.source === s ? "is-selected" : ""} onClick={() => setProfile({ ...profile, source: s })}>{s}</button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="tg-quiz__nav">
        <button className="btn btn--ghost" onClick={onSkip}>Skip for now</button>
        <button className="btn btn--pri" onClick={onDone}>Save preferences <span className="arr">→</span></button>
      </div>
    </div>
  );
}

function FinalCelebration({ result, profile, onSeeEvent, onSeeMerch, onClose }) {
  const cityObj = window.TG_CITIES.find(c => c.id === profile.city) || window.TG_CITIES[0];
  const suggestEvent = window.TG_EVENTS.find(e => e.id === result.suggestEvent) || window.TG_EVENTS[0];
  const cityEvent = window.TG_EVENTS.find(e => e.city === profile.city) || window.TG_EVENTS[0];

  return (
    <div className="tg-result" style={{ backgroundImage: `url(${result.bg})`, minHeight: "auto" }}>
      <QuizTop step={10} total={10} onClose={onClose} />
      <div className="tg-result__inner" style={{ paddingTop: 40, paddingBottom: 40 }}>
        <div>
          <span className="tg-result__eyebrow">✦ You're in</span>
          <h1 className="tg-result__type">Welcome,<br/><span style={{ color: "var(--tg-cream)" }}>{profile.name || "girl"}</span>.</h1>
          <p className="tg-result__desc">
            We've saved your <strong>{result.name}</strong> badge, added you to The Locker Room, and pinned the next session in {cityObj.name}. Here's what we'd do first.
          </p>
        </div>
        <ResultBadge result={result} profile={profile} />
      </div>

      <div className="tg-result__next">
        <div className="tg-result__next-inner">
          <div className="tg-result__pick">
            <span className="eyebrow"><span className="spark">✦</span> Pick #1 · Your next session</span>
            <h4 style={{ margin: "10px 0 4px" }}>{cityEvent.title}</h4>
            <p style={{ fontFamily: "var(--font-serif)", fontSize: 14, lineHeight: 1.5, color: "var(--tg-ink-soft)", margin: "0 0 14px" }}>
              {cityEvent.subtitle} · {cityEvent.day} {cityEvent.month}, {cityEvent.time} · {cityEvent.venue}, {cityObj.name}.
            </p>
            <button className="btn btn--ink" onClick={() => onSeeEvent(cityEvent)}>Save me a spot <span className="arr">→</span></button>
          </div>

          <div className="tg-result__pick" style={{ background: result.badgeColor, color: "var(--tg-cream)" }}>
            <span className="eyebrow eyebrow--light"><span className="spark">✦</span> Pick #2 · Picked for the {result.name.replace("The ", "")}</span>
            <h4 style={{ margin: "10px 0 4px" }}>{result.suggestMerch.title}</h4>
            <p style={{ fontFamily: "var(--font-serif)", fontSize: 14, lineHeight: 1.5, opacity: 0.88, margin: "0 0 14px" }}>
              {result.suggestMerch.note} · {result.suggestMerch.price}.
            </p>
            <button className="btn btn--cream" onClick={onSeeMerch} style={{ background: "var(--tg-cream)", color: "var(--tg-ink)" }}>See the edit <span className="arr">→</span></button>
          </div>
        </div>

        <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 28, flexWrap: "wrap" }}>
          <button className="btn btn--ghost" onClick={onClose}>← Back to the site</button>
          <button className="btn btn--ink" onClick={() => { navigator.clipboard && navigator.clipboard.writeText(`I'm a ${result.name} on Team Girl 🧡 Find your type at teamgirl.club`); alert("Result copied — paste it into your story."); }}>
            Share to story
          </button>
        </div>
      </div>
    </div>
  );
}

window.TgQuiz = TgQuiz;
