/* Veridyne Learning Portal — Knowledge checks: quiz engine, scoring, review */

function QuizLanding() {
  const store = useStore();
  const quizzes = [window.OKTA_QUIZ, window.AUTH0_QUIZ];
  return (
    <div className="anim-fade-up">
      <div className="page-head">
        <h1>Knowledge Checks</h1>
        <p>25 scenario-based questions per product. Passing score is 80% — your best score is saved, and you can retry any time.</p>
      </div>
      <div className="card-grid">
        {quizzes.map((qz) => {
          const s = store.scores[qz.id];
          const badge = s ? scoreBadge(s.best) : null;
          return (
            <div key={qz.id} className="glass-card" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <ProductBadge product={qz.id} />
                <span className="badge">{qz.questions.length} questions</span>
                <span className="badge">Pass: {qz.passing}%</span>
              </div>
              <h3 style={{ fontSize: "1.1em" }}>{qz.title}</h3>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <ProgressRing value={s ? s.best : 0} size={56} stroke={5}
                  color={s && s.best >= 80 ? "var(--ok)" : "var(--warn)"} label={s ? s.best + "%" : "—"} />
                <div style={{ fontSize: "0.85em", color: "var(--bone-70)" }}>
                  {s ? <>Best score <strong style={{ color: "var(--bone)" }}>{s.best}%</strong> over {s.attempts} attempt{s.attempts > 1 ? "s" : ""}.</> : "Not attempted yet."}
                  {badge ? <div style={{ marginTop: 6 }}><span className={"badge " + badge.cls}>{badge.label}</span></div> : null}
                </div>
              </div>
              <button className="btn btn-primary" onClick={() => navigate("quizzes/" + qz.id)} style={{ marginTop: "auto" }}>
                <Icon name="play" size={14} /> {s ? "Retake quiz" : "Start quiz"}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function topicBreakdown(quiz, answers) {
  const byArea = {};
  quiz.questions.forEach((q, i) => {
    if (!byArea[q.area]) byArea[q.area] = { total: 0, correct: 0 };
    byArea[q.area].total++;
    if (answers[i] === q.answer) byArea[q.area].correct++;
  });
  return byArea;
}

function QuizEngine({ quizId }) {
  const store = useStore();
  const quiz = quizId === "okta" ? window.OKTA_QUIZ : window.AUTH0_QUIZ;
  const [idx, setIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [picked, setPicked] = React.useState(null);
  const [phase, setPhase] = React.useState("quiz"); // quiz | results | review
  const [shareOpen, setShareOpen] = React.useState(false);
  const total = quiz.questions.length;
  const q = quiz.questions[idx];

  const submitPick = (oi) => { if (picked == null) setPicked(oi); };

  const next = () => {
    const newAnswers = { ...answers, [idx]: picked };
    setAnswers(newAnswers);
    setPicked(null);
    if (idx + 1 < total) { setIdx(idx + 1); window.scrollTo(0, 0); }
    else {
      const correct = quiz.questions.filter((qq, i) => newAnswers[i] === qq.answer).length;
      const pct = Math.round((correct / total) * 100);
      store.recordScore(quiz.id, { pct, correct, total, answers: newAnswers, breakdown: topicBreakdown(quiz, newAnswers) });
      setAnswers(newAnswers);
      setPhase("results");
      window.scrollTo(0, 0);
    }
  };

  const retry = () => { setIdx(0); setAnswers({}); setPicked(null); setPhase("quiz"); window.scrollTo(0, 0); };

  if (phase === "results" || phase === "review") {
    const correct = quiz.questions.filter((qq, i) => answers[i] === qq.answer).length;
    const pct = Math.round((correct / total) * 100);
    const badge = scoreBadge(pct);
    const breakdown = topicBreakdown(quiz, answers);
    return (
      <div className="anim-fade-up" style={{ maxWidth: 860 }}>
        <button className="btn btn-ghost btn-sm" onClick={() => navigate("quizzes")} style={{ marginBottom: 14, color: "var(--bone-50)" }}>
          <Icon name="arrowLeft" size={14} /> Knowledge checks
        </button>
        <div className="glass-card" style={{ textAlign: "center", padding: "32px 24px", marginBottom: 16 }}>
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 14 }}>
            <ProgressRing value={pct} size={110} stroke={8} color={pct >= quiz.passing ? "var(--ok)" : "var(--warn)"} />
          </div>
          <h1 style={{ fontSize: "1.4em", marginBottom: 6 }}>{quiz.title}</h1>
          <p style={{ color: "var(--bone-70)", marginBottom: 12 }}>
            {correct} of {total} correct · {pct >= quiz.passing ? "Passed" : `Passing score is ${quiz.passing}%`}
          </p>
          <span className={"badge " + badge.cls} style={{ fontSize: "0.85em", padding: "6px 16px" }}>{badge.label}</span>
          <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 20, flexWrap: "wrap" }}>
            <button className="btn btn-primary" onClick={retry}><Icon name="replay" size={14} /> Retry quiz</button>
            <button className="btn" onClick={() => setPhase(phase === "review" ? "results" : "review")}>
              <Icon name="list" size={14} /> {phase === "review" ? "Hide review" : "Review answers"}
            </button>
            <button className="btn" onClick={() => setShareOpen(true)}>
              <Icon name="external" size={14} /> Share score card
            </button>
          </div>
        </div>
        <ShareCardModal open={shareOpen} onClose={() => setShareOpen(false)} />

        <div className="glass-card" style={{ marginBottom: 16 }}>
          <h3 style={{ fontSize: "1em", marginBottom: 12 }}>Topic breakdown</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {Object.entries(breakdown).map(([area, b]) => (
              <div key={area} style={{ display: "grid", gridTemplateColumns: "130px 1fr 56px", gap: 12, alignItems: "center", fontSize: "0.88em" }}>
                <span style={{ color: "var(--bone-70)" }}>{area}</span>
                <div style={{ height: 8, borderRadius: 99, background: "var(--bone-12)", overflow: "hidden" }}>
                  <div style={{ height: "100%", borderRadius: 99, width: (b.correct / b.total) * 100 + "%", background: b.correct === b.total ? "var(--ok)" : b.correct / b.total >= 0.5 ? "var(--warn)" : "var(--bad)", transition: "width 0.6s ease" }} />
                </div>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: "0.85em", color: "var(--bone-50)", textAlign: "right" }}>{b.correct}/{b.total}</span>
              </div>
            ))}
          </div>
        </div>

        {phase === "review" ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {quiz.questions.map((qq, i) => {
              const user = answers[i];
              const right = user === qq.answer;
              return (
                <div key={i} className="glass-card" style={{ borderLeft: "none" }}>
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 8, alignItems: "center" }}>
                    <span className={"badge " + (right ? "badge-ok" : "badge-ember")}>
                      <Icon name={right ? "check" : "x"} size={11} /> {right ? "Correct" : "Incorrect"}
                    </span>
                    <span className="badge">{qq.area}</span>
                    <DifficultyBadge level={qq.difficulty} />
                  </div>
                  <p style={{ fontWeight: 600, fontSize: "0.95em", marginBottom: 10 }}>{i + 1}. {qq.q}</p>
                  <div style={{ fontSize: "0.88em", color: "var(--bone-70)", display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 }}>
                    {!right && user != null ? <p><strong style={{ color: "var(--bad)" }}>Your answer: </strong>{qq.options[user]}</p> : null}
                    <p><strong style={{ color: "var(--ok)" }}>Correct answer: </strong>{qq.options[qq.answer]}</p>
                    <p style={{ marginTop: 4 }}>{qq.explain}</p>
                  </div>
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
                    <button className="btn btn-sm" onClick={() => navigate("module/" + qq.module)}>
                      <Icon name="book" size={13} /> Review module
                    </button>
                    <a href={qq.source.url} target="_blank" rel="noopener noreferrer" className="btn btn-sm btn-ghost" style={{ color: "var(--bone-70)", textDecoration: "none" }}>
                      <Icon name="external" size={13} /> {qq.source.label}
                    </a>
                  </div>
                </div>
              );
            })}
          </div>
        ) : null}
      </div>
    );
  }

  /* in-quiz */
  return (
    <div className="anim-fade-up" style={{ maxWidth: 760 }}>
      <button className="btn btn-ghost btn-sm" onClick={() => navigate("quizzes")} style={{ marginBottom: 14, color: "var(--bone-50)" }}>
        <Icon name="arrowLeft" size={14} /> Exit quiz
      </button>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
        <div style={{ flex: 1, height: 8, borderRadius: 99, background: "var(--bone-12)", overflow: "hidden" }}>
          <div style={{ height: "100%", width: ((idx) / total) * 100 + "%", background: "linear-gradient(90deg, var(--ember), var(--ember-bright))", borderRadius: 99, transition: "width 0.4s ease" }} />
        </div>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "0.82em", color: "var(--bone-50)" }}>{idx + 1}/{total}</span>
      </div>

      <div className="glass-card" key={idx}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 14 }}>
          <ProductBadge product={quiz.id} />
          <span className="badge">{q.area}</span>
          <DifficultyBadge level={q.difficulty} />
        </div>
        <h2 style={{ fontSize: "1.12em", marginBottom: 18, lineHeight: 1.45 }}>{q.q}</h2>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {q.options.map((opt, oi) => {
            let cls = "quiz-option";
            if (picked != null) {
              if (oi === q.answer) cls += " correct";
              else if (oi === picked) cls += " wrong";
            }
            return (
              <button key={oi} className={cls} disabled={picked != null} onClick={() => submitPick(oi)}>
                <span className="option-key">{String.fromCharCode(65 + oi)}</span>
                <span>{opt}</span>
              </button>
            );
          })}
        </div>
        {picked != null ? (
          <div className="anim-fade-in">
            <div className="glass-inset" style={{ padding: "13px 15px", marginTop: 14, display: "flex", gap: 10, alignItems: "flex-start" }}>
              <Icon name={picked === q.answer ? "checkCircle" : "info"} size={16} style={{ color: picked === q.answer ? "var(--ok)" : "var(--warn)", marginTop: 2 }} />
              <div style={{ fontSize: "0.88em", color: "var(--bone-70)" }}>
                <p><strong style={{ color: "var(--bone)" }}>{picked === q.answer ? "Correct. " : "Not quite. "}</strong>{q.explain}</p>
                <a href={q.source.url} target="_blank" rel="noopener noreferrer" style={{ fontSize: "0.92em", display: "inline-flex", alignItems: "center", gap: 5, marginTop: 6 }}>
                  <Icon name="external" size={12} /> {q.source.label}
                </a>
              </div>
            </div>
            <button className="btn btn-primary" onClick={next} style={{ marginTop: 14, width: "100%" }}>
              {idx + 1 < total ? <>Next question <Icon name="arrowRight" size={15} /></> : <>See results <Icon name="award" size={15} /></>}
            </button>
          </div>
        ) : null}
      </div>
    </div>
  );
}

Object.assign(window, { QuizLanding, QuizEngine });
