const { useState, useEffect } = React;

const renderTextWithBold = (text) => {
  if (!text) return null;
  const segments = text.split(/(\*\*[^*]+\*\*)/g);
  return segments.map((segment, index) => {
    const match = segment.match(/^\*\*(.+)\*\*$/);
    if (match) {
      return (
        <strong key={index}>
          {match[1]}
        </strong>
      );
    }
    return <span key={index}>{segment}</span>;
  });
};

const App = () => {
  const [topic, setTopic] = useState(() => {
    if (typeof window === "undefined") return "";
    try {
      const storedTopic = window.sessionStorage.getItem("kc_preloaded_topic");
      if (storedTopic) return storedTopic;
    } catch {
      // ignore storage issues
    }
    return "";
  });
  const [plan, setPlan] = useState(null);
  const [currentStepIndex, setCurrentStepIndex] = useState(-1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [mode, setMode] = useState("idle"); // idle | overview | slides | summary
  const [secondsElapsed, setSecondsElapsed] = useState(0);
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [quizMode, setQuizMode] = useState(false);
  const [quizQuestionIndex, setQuizQuestionIndex] = useState(0);
  const [quizSelectedIndex, setQuizSelectedIndex] = useState(null);
  const [quizFeedback, setQuizFeedback] = useState(null);
  const [completedQuizzes, setCompletedQuizzes] = useState({});
  const [planReady, setPlanReady] = useState(false);
  const [loadingHintIndex, setLoadingHintIndex] = useState(0);
  const [quizResults, setQuizResults] = useState({});
  const [courseCompleted, setCourseCompleted] = useState(false);
  const [stepCorrectCount, setStepCorrectCount] = useState(0);
  const [showStepScore, setShowStepScore] = useState(false);
  const [reviewMode, setReviewMode] = useState(false);
  const [quizAnswers, setQuizAnswers] = useState({});
  const [bootstrapDone, setBootstrapDone] = useState(false);

  const loadingHints = [
    "Your learning coach is sketching the clearest path for this topic…",
    "We’re picking the key ideas so you don’t have to read long, boring explanations…",
    "We’re shaping mini quizzes that check real understanding, not just memorisation…",
  ];

  const handleGeneratePlan = () => {
    if (!topic.trim()) {
      setError("Please enter a topic.");
      setPlan(null);
      return;
    }
    setError(null);
    setIsLoading(true);
    setPlan(null);
    setCurrentStepIndex(-1);
    setMode("idle");
    setQuizMode(false);
    setQuizQuestionIndex(0);
    setQuizSelectedIndex(null);
    setQuizFeedback(null);
    setCompletedQuizzes({});
    setPlanReady(false);
    setQuizResults({});
    setCourseCompleted(false);
    setStepCorrectCount(0);
    setShowStepScore(false);
    setReviewMode(false);
    setQuizAnswers({});

    let apiBase = "";
    if (typeof window !== "undefined" && window.KC_API_BASE_PATH) {
      apiBase = window.KC_API_BASE_PATH.replace(/\/$/, "");
    }
    const apiPath = `${apiBase || ""}/learning-plan`;

    fetch(apiPath, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ topic: topic.trim() }),
    })
      .then(async (res) => {
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          const message = data.error || "Something went wrong while creating your plan.";
          throw new Error(message);
        }
        return res.json();
      })
      .then((data) => {
        setPlan(data);
        setCurrentStepIndex(-1);
        // Go straight to the lesson plan overview once it is ready.
        setMode("overview");
        setSecondsElapsed(0);
        setQuizMode(false);
        setQuizQuestionIndex(0);
        setQuizSelectedIndex(null);
        setQuizFeedback(null);
        setCompletedQuizzes({});
        setPlanReady(true);
      })
      .catch((err) => {
        console.error(err);
        setError(err.message);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  const handleNewLearning = () => {
    setTopic("");
    setPlan(null);
    setCurrentStepIndex(-1);
    setMode("idle");
    setIsLoading(false);
    setError(null);
    setSecondsElapsed(0);
    setIsSpeaking(false);
    setQuizMode(false);
    setQuizQuestionIndex(0);
    setQuizSelectedIndex(null);
    setQuizFeedback(null);
    setCompletedQuizzes({});
    setPlanReady(false);
    setQuizResults({});
    setCourseCompleted(false);
    setStepCorrectCount(0);
    setShowStepScore(false);
    setReviewMode(false);
    setQuizAnswers({});
  };

  const selectedStep =
    plan && currentStepIndex >= 0 && plan.steps?.[currentStepIndex]
      ? plan.steps[currentStepIndex]
      : null;

  const totalSteps = plan?.steps?.length || 0;
  const progressPercent =
    mode === "slides" && totalSteps > 0 && currentStepIndex >= 0
      ? ((currentStepIndex + 1) / totalSteps) * 100
      : 0;

  const stepCount = plan?.steps?.length || 0;
  const totalQuizQuestions = stepCount * 2;

  const handleStartSlides = () => {
    if (!plan || !plan.steps || plan.steps.length === 0) return;
    setCurrentStepIndex(0);
    setMode("slides");
    setQuizMode(false);
    setQuizQuestionIndex(0);
    setQuizSelectedIndex(null);
    setQuizFeedback(null);
    setShowStepScore(false);
    setReviewMode(false);
  };

  const handlePlayAudio = () => {
    if (!selectedStep || !selectedStep.content) return;
    if (typeof window === "undefined" || !window.speechSynthesis) {
      setError("Audio playback is not supported in this browser.");
      return;
    }
    const synth = window.speechSynthesis;
    synth.cancel();
    const utterance = new SpeechSynthesisUtterance(selectedStep.content);
    utterance.onend = () => setIsSpeaking(false);
    utterance.onerror = () => setIsSpeaking(false);
    setIsSpeaking(true);
    synth.speak(utterance);
  };

  useEffect(() => {
    if (bootstrapDone) return;
    if (typeof window === "undefined") return;
    setBootstrapDone(true);
    try {
      const storedPlan = window.sessionStorage.getItem("kc_preloaded_plan");
      const storedTopic = window.sessionStorage.getItem("kc_preloaded_topic");
      if (storedTopic && !topic) {
        setTopic(storedTopic);
      }
      if (storedPlan) {
        const parsed = JSON.parse(storedPlan);
        setPlan(parsed);
        setCurrentStepIndex(-1);
        setMode("overview");
        setSecondsElapsed(0);
        setQuizMode(false);
        setQuizQuestionIndex(0);
        setQuizSelectedIndex(null);
        setQuizFeedback(null);
        setCompletedQuizzes({});
        setPlanReady(true);
        window.sessionStorage.removeItem("kc_preloaded_plan");
        window.sessionStorage.removeItem("kc_preloaded_topic");
        return;
      }
    } catch (e) {
      // If anything goes wrong, we fall back to normal manual flow.
      console.error(e);
    }
  }, [bootstrapDone, topic]);

  const handleStopAudio = () => {
    if (typeof window === "undefined" || !window.speechSynthesis) return;
    window.speechSynthesis.cancel();
    setIsSpeaking(false);
  };

  useEffect(() => {
    if (mode !== "slides") return;

    const id = setInterval(() => {
      setSecondsElapsed((prev) => prev + 1);
    }, 1000);

    return () => clearInterval(id);
  }, [mode]);

  const formatSeconds = (totalSeconds) => {
    const minutes = Math.floor(totalSeconds / 60)
      .toString()
      .padStart(2, "0");
    const seconds = (totalSeconds % 60).toString().padStart(2, "0");
    return `${minutes}:${seconds}`;
  };

  const questions = selectedStep?.quiz?.questions || [];
  const currentQuestion =
    quizMode && questions.length > 0
      ? questions[Math.min(quizQuestionIndex, questions.length - 1)]
      : null;
  const stepKey =
    selectedStep && (selectedStep.id || String(currentStepIndex));
  const hasQuiz = questions.length > 0;
  const isQuizDoneForStep = hasQuiz
    ? !!(stepKey && completedQuizzes[stepKey])
    : true;
  const stepResult = stepKey ? quizResults[stepKey] : null;
  const isLastStep =
    plan && plan.steps && currentStepIndex === plan.steps.length - 1;

  useEffect(() => {
    if (!isLoading) {
      setLoadingHintIndex(0);
      return;
    }
    const id = setInterval(() => {
      setLoadingHintIndex((prev) => (prev + 1) % loadingHints.length);
    }, 3500);
    return () => clearInterval(id);
  }, [isLoading]);

  const scoreSummary = (() => {
    if (!plan || !plan.steps || plan.steps.length === 0) return null;
    let totalCorrect = 0;
    let totalQuestions = 0;
    const perStep = plan.steps.map((step, index) => {
      const key = step.id || String(index);
      const result = quizResults[key];
      if (result) {
        totalCorrect += result.correct || 0;
        totalQuestions += result.total || 0;
      }
      return {
        title: step.title,
        correct: result?.correct || 0,
        total: result?.total || 0,
      };
    });
    if (totalQuestions === 0) {
      return null;
    }
    return { totalCorrect, totalQuestions, perStep };
  })();

  const handleNextOrComplete = () => {
    if (!plan?.steps || currentStepIndex >= plan.steps.length - 1) {
      setMode("summary");
      setCurrentStepIndex(-1);
      setQuizMode(false);
      setQuizQuestionIndex(0);
      setQuizSelectedIndex(null);
      setQuizFeedback(null);
      setCourseCompleted(true);
    } else {
      setCurrentStepIndex((idx) => idx + 1);
      setQuizMode(false);
      setQuizQuestionIndex(0);
      setQuizSelectedIndex(null);
      setQuizFeedback(null);
    }
    setShowStepScore(false);
    setReviewMode(false);
  };

  return (
    <div className="kc-page">
      <header className="kc-header">
        <div className="kc-logo-wrap">
          {/* Save your logo image as "logo.png" in this folder */}
          <img src="logo.png" alt="Krit.club logo" className="kc-logo" />
        </div>
        <div className="kc-header-text">
          <h1 className="kc-title">Welcome to Kritclub Learning coach</h1>
          <p className="kc-subtitle">
            A playful space where ideas light up, learning feels magical, and
            every session turns curiosity into clarity.
          </p>
        </div>
      </header>

      <main className="kc-main">
        <section className="kc-card">
          {mode === "idle" && (
            <div className="kc-card-header">
              <h2 className="kc-card-title">
                Start your learning journey
              </h2>
              <p className="kc-card-text">
                Enter any concept you&apos;re curious about, and we&apos;ll turn it into a{" "}
                <strong>short, guided lesson</strong> with clear topics, audio explanations,
                and quick quizzes so you can check your understanding as you go.
              </p>

              <div className="kc-welcome-box">
                <p className="kc-welcome-title">Here&apos;s how your mini-lesson will work:</p>
                <ul className="kc-welcome-list">
                  <li>
                    We&apos;ll pick a few <strong>focused topics</strong> so you don&apos;t feel overwhelmed.
                  </li>
                  <li>
                    For each topic, you can <strong>read the explanation</strong> or{" "}
                    <strong>tap play to listen</strong> like a mini audio lesson.
                  </li>
                  <li>
                    At the end of every topic, a <strong>short quiz</strong> will help you see what
                    you&apos;ve really understood.
                  </li>
                  <li>
                    You&apos;ll see your progress as you move from <strong>Topic 1</strong> all the
                    way to the end of your <strong>15-minute journey</strong>.
                  </li>
                </ul>
                <p className="kc-welcome-footer">
                  When you&apos;re ready, type what you want to learn and{" "}
                  <strong>create your learning plan</strong>.
                </p>
              </div>

              <div className="kc-topic-row">
                <input
                  type="text"
                  className="kc-input"
                  placeholder="e.g. Fractions for Grade 5, Python loops, Photosynthesis..."
                  value={topic}
                  onChange={(e) => setTopic(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && !isLoading) {
                      e.preventDefault();
                      handleGeneratePlan();
                    }
                  }}
                />

                <button
                  className="kc-btn kc-btn-primary kc-topic-button"
                  onClick={handleGeneratePlan}
                  disabled={isLoading}
                >
                  {isLoading ? "Creating plan..." : "Create learning plan"}
                </button>
              </div>

              {isLoading && (
                <div className="kc-loading">
                  <div className="kc-loading-icon" aria-hidden="true">
                    ✨
                  </div>
                  <div className="kc-loading-body">
                    <p className="kc-loading-text">
                      Creating your personalised 15-minute learning path
                      {topic.trim() ? ` for “${topic.trim()}”` : ""}…
                    </p>
                    <div className="kc-loading-bar">
                      <div className="kc-loading-bar-fill" />
                    </div>
                  </div>
                  <div className="kc-loading-dots" aria-hidden="true">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              )}

              {error && <div className="kc-error">{error}</div>}

              {/* No secondary “plan ready” screen here anymore; we jump straight to overview. */}
            </div>
          )}

          {plan && mode === "slides" && (
            <div className="kc-detail-header">
              <h2 className="kc-card-title kc-detail-title">
                {plan.topic || topic}
              </h2>
              <div className="kc-detail-duration">
                <span className="kc-timer-label">🕒 Plan time</span>
                <span className="kc-timer-value">
                  {plan.totalDurationMinutes} min
                </span>
                <span className="kc-live-timer">
                  ⏱ {formatSeconds(secondsElapsed)}
                </span>
              </div>
            </div>
          )}

          {plan && mode === "overview" && (
            <div className="kc-overview-header">
              <h2 className="kc-card-title kc-detail-title">
                {plan.topic || topic}
              </h2>
            </div>
          )}

          {plan && mode === "overview" && (
            <div className="kc-chat">
              <div className="kc-chat-message kc-chat-message--coach">
                {planReady && (
                  <div className="kc-plan-ready">
                    <div className="kc-plan-ready-title">
                      ✨ Your learning plan is ready!
                    </div>
                    <div className="kc-plan-ready-text">
                      Review the topics below, then click{" "}
                      <strong>Start learning</strong> to move through each topic,
                      listen to audio explanations, and take short quizzes.
                    </div>
                  </div>
                )}
                <h3 className="kc-content-title">
                  Learning plan for {plan.topic || topic}
                </h3>
                <p className="kc-results-summary">
                  {renderTextWithBold(plan.overview)}
                </p>
                {plan.totalDurationMinutes && (
                  <p className="kc-card-text">
                    Total time:{" "}
                    <strong>{plan.totalDurationMinutes} min</strong>
                  </p>
                )}
                <p className="kc-card-text">
                  Here are the topics we&apos;ll cover in this quick session:
                </p>
                {plan.steps && plan.steps.length > 0 && (
                  <ul className="kc-topic-list-inner">
                    {plan.steps.map((step, index) => (
                      <li key={step.id || index}>
                        <div className="kc-topic-card kc-topic-card--static">
                          <div className="kc-topic-card-main">
                            <span className="kc-topic-card-index">{index + 1}</span>
                            <span className="kc-topic-card-title">
                              {step.funIcon ? `${step.funIcon} ` : ""}
                              {step.title}
                            </span>
                          </div>
                          {step.summary && (
                            <p className="kc-topic-summary">
                              {step.summary}
                            </p>
                          )}
                          <p className="kc-topic-card-meta">
                            ~{step.durationMinutes} min • Key idea: {step.keyIdea}
                          </p>
                        </div>
                      </li>
                    ))}
                  </ul>
                )}
                <div className="kc-chat-controls kc-chat-controls--split">
                  <button
                    type="button"
                    className="kc-btn kc-btn-ghost kc-results-btn"
                    onClick={handleNewLearning}
                  >
                    New learning
                  </button>
                  <button
                    type="button"
                    className="kc-btn kc-btn-primary kc-results-btn"
                    onClick={handleStartSlides}
                  >
                    Start learning
                  </button>
                </div>
              </div>
            </div>
          )}

          {plan && mode === "slides" && selectedStep && (
            <div className="kc-chat">
              <div className="kc-timer-bar-wrap">
                <div className="kc-timer-bar-track">
                  <div
                    className="kc-timer-bar-fill"
                    style={{ width: `${progressPercent}%` }}
                  />
                </div>
                <span className="kc-timer-bar-label">
                  Topic {currentStepIndex + 1} of {totalSteps}
                </span>
              </div>
              <div className="kc-chat-message kc-chat-message--coach kc-chat-step">
                <div className="kc-chat-step-header">
                  <span className="kc-topic-card-title">
                    {selectedStep.funIcon ? `${selectedStep.funIcon} ` : ""}
                    {selectedStep.title}
                  </span>
                  <span className="kc-topic-card-meta">
                    ~{selectedStep.durationMinutes} min
                  </span>
                </div>
                {!quizMode && !showStepScore && !reviewMode && (
                  <>
                    <div className="kc-audio-controls">
                      <button
                        type="button"
                        className="kc-btn kc-btn-ghost kc-btn-audio"
                        onClick={isSpeaking ? handleStopAudio : handlePlayAudio}
                      >
                        {isSpeaking ? "⏹ Stop audio" : "▶️ Play audio"}
                      </button>
                    </div>
                    {selectedStep.content && (
                      <p className="kc-content-overview">
                        {renderTextWithBold(selectedStep.content)}
                      </p>
                    )}
                    {selectedStep.codeExample &&
                      selectedStep.codeExample.trim() && (
                        <pre className="kc-code-block">
                          <code>{selectedStep.codeExample}</code>
                        </pre>
                      )}
                    <p className="kc-topic-card-meta">
                      Try this: {selectedStep.activityPrompt}
                    </p>
                    {questions.length > 0 && !completedQuizzes[stepKey] && (
                      <div className="kc-chat-controls">
                        <button
                          type="button"
                          className="kc-btn kc-btn-primary kc-results-btn"
                          onClick={() => {
                            setQuizMode(true);
                            setQuizQuestionIndex(0);
                            setQuizSelectedIndex(null);
                            setQuizFeedback(null);
                          }}
                        >
                          Take quiz
                        </button>
                      </div>
                    )}
                    {questions.length > 0 && completedQuizzes[stepKey] && (
                      <div className="kc-quiz-topic-summary">
                        <p className="kc-topic-card-meta">
                          ✅ Quiz completed for this lesson.
                        </p>
                        <div className="kc-chat-controls kc-chat-controls--topic-cta">
                          <button
                            type="button"
                            className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                            onClick={() => {
                              setShowStepScore(false);
                              setReviewMode(true);
                              setQuizQuestionIndex(0);
                            }}
                          >
                            Review quiz
                          </button>
                          <button
                            type="button"
                            className="kc-btn kc-btn-primary kc-quiz-nav-btn"
                            onClick={() => {
                              handleNextOrComplete();
                            }}
                          >
                            {isLastStep ? "Complete learning" : "Next topic"}
                          </button>
                        </div>
                      </div>
                    )}
                  </>
                )}

                {quizMode && currentQuestion && (
                  <div className="kc-quiz">
                    <p className="kc-quiz-question">
                      <span className="kc-quiz-question-index">
                        Question {quizQuestionIndex + 1} of {questions.length}
                      </span>
                      <span className="kc-quiz-question-text">
                        {currentQuestion.question}
                      </span>
                    </p>
                    <div className="kc-quiz-options">
                      {currentQuestion.options.map((opt, idx) => {
                        const isSelected = quizSelectedIndex === idx;
                        let cls = "kc-quiz-option";
                        if (quizFeedback) {
                          if (idx === currentQuestion.correctOptionIndex) {
                            cls += " kc-quiz-option--correct";
                          } else if (isSelected) {
                            cls += " kc-quiz-option--incorrect";
                          }
                        } else if (isSelected) {
                          cls += " kc-quiz-option--selected";
                        }
                        return (
                          <button
                            key={idx}
                            type="button"
                            className={cls}
                            onClick={() => {
                              if (quizFeedback) return;
                              setQuizSelectedIndex(idx);
                              const correct =
                                idx === currentQuestion.correctOptionIndex;
                              if (stepKey) {
                                setQuizAnswers((prev) => ({
                                  ...prev,
                                  [stepKey]: {
                                    ...(prev[stepKey] || {}),
                                    [quizQuestionIndex]: idx,
                                  },
                                }));
                              }
                              if (correct) {
                                setStepCorrectCount((prev) => prev + 1);
                              }
                              setQuizFeedback({
                                correct,
                                explanation: currentQuestion.explanation,
                              });
                            }}
                          >
                            <span className="kc-quiz-option-label">
                              {String.fromCharCode(65 + idx)}.
                            </span>
                            <span className="kc-quiz-option-text">{opt}</span>
                          </button>
                        );
                      })}
                    </div>
                    {quizFeedback && (
                      <>
                        <p className="kc-quiz-explanation">
                          {quizFeedback.correct ? "Correct! " : "Not quite. "}
                          {quizFeedback.explanation}
                        </p>
                        <div className="kc-quiz-reaction">
                          <span className="kc-quiz-emoji" aria-hidden="true">
                            {quizFeedback.correct ? "🎉" : "😔"}
                          </span>
                          <span className="kc-quiz-reaction-text">
                            {quizFeedback.correct ? (
                              <>
                                <strong>Awesome!</strong> You nailed this one.
                              </>
                            ) : (
                              <>
                                <strong>That&apos;s okay</strong> — use the explanation above and you&apos;ll
                                crack the next one.
                              </>
                            )}
                          </span>
                        </div>
                        {quizFeedback.correct && (
                          <div className="kc-confetti" aria-hidden="true">
                            {Array.from({ length: 14 }).map((_, i) => (
                              <span key={i} className="kc-confetti-piece" />
                            ))}
                          </div>
                        )}
                      </>
                    )}
                    <div className="kc-quiz-nav">
                      <button
                        type="button"
                        className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                        onClick={() => {
                          setQuizMode(false);
                          setQuizQuestionIndex(0);
                          setQuizSelectedIndex(null);
                          setQuizFeedback(null);
                        }}
                      >
                        {`Back to Lesson #${currentStepIndex + 1}`}
                      </button>
                      <button
                        type="button"
                        className="kc-btn kc-btn-primary kc-quiz-nav-btn"
                        disabled={!quizFeedback}
                        onClick={() => {
                          const nextIndex = quizQuestionIndex + 1;
                          if (nextIndex < questions.length) {
                            setQuizQuestionIndex(nextIndex);
                            setQuizSelectedIndex(null);
                            setQuizFeedback(null);
                          } else {
                            if (stepKey) {
                              setCompletedQuizzes((prev) => ({
                                ...prev,
                                [stepKey]: true,
                              }));
                              setQuizResults((prev) => ({
                                ...prev,
                                [stepKey]: {
                                  correct: stepCorrectCount,
                                  total: questions.length,
                                },
                              }));
                            }
                            setQuizMode(false);
                            setQuizQuestionIndex(0);
                            setQuizSelectedIndex(null);
                            setQuizFeedback(null);
                            setShowStepScore(true);
                            setStepCorrectCount(0);
                          }
                        }}
                      >
                        {quizQuestionIndex + 1 < questions.length
                          ? "Next question"
                          : "Finish quiz"}
                      </button>
                    </div>
                  </div>
                )}
                {!quizMode && reviewMode && questions.length > 0 && (
                  <div className="kc-quiz kc-quiz-review">
                    <h3 className="kc-content-title">
                      Review quiz for Lesson {currentStepIndex + 1}
                    </h3>
                    <p className="kc-results-summary">
                      Here&apos;s a quick look back at the questions for{" "}
                      <strong>{selectedStep.title}</strong>. Answers are locked in, so this
                      is just for review.
                    </p>
                    {(() => {
                      const q =
                        questions[Math.min(quizQuestionIndex, questions.length - 1)];
                      const answersForStep = stepKey ? quizAnswers[stepKey] || {} : {};
                      const chosenIndex = answersForStep[quizQuestionIndex];
                      if (!q) return null;
                      return (
                        <div className="kc-quiz-review-block">
                          <p className="kc-quiz-question">
                            <span className="kc-quiz-question-index">
                              Question {quizQuestionIndex + 1} of {questions.length}
                            </span>
                            <span className="kc-quiz-question-text">{q.question}</span>
                          </p>
                          <div className="kc-quiz-options">
                            {q.options.map((opt, idx) => {
                              let cls = "kc-quiz-option";
                              if (idx === q.correctOptionIndex) {
                                cls += " kc-quiz-option--correct";
                              } else if (
                                chosenIndex !== undefined &&
                                idx === chosenIndex &&
                                idx !== q.correctOptionIndex
                              ) {
                                cls += " kc-quiz-option--incorrect";
                              } else if (idx === chosenIndex) {
                                cls += " kc-quiz-option--selected";
                              }
                              return (
                                <div key={idx} className={cls}>
                                  <span className="kc-quiz-option-label">
                                    {String.fromCharCode(65 + idx)}.
                                  </span>
                                  <span className="kc-quiz-option-text">{opt}</span>
                                </div>
                              );
                            })}
                          </div>
                          {q.explanation && (
                            <p className="kc-quiz-explanation">{q.explanation}</p>
                          )}
                        </div>
                      );
                    })()}
                    <div className="kc-quiz-nav">
                      <button
                        type="button"
                        className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                        disabled={quizQuestionIndex <= 0}
                        onClick={() => {
                          setQuizQuestionIndex((idx) => Math.max(0, idx - 1));
                        }}
                      >
                        Previous question
                      </button>
                      <button
                        type="button"
                        className="kc-btn kc-btn-primary kc-quiz-nav-btn"
                        disabled={quizQuestionIndex >= questions.length - 1}
                        onClick={() => {
                          setQuizQuestionIndex((idx) =>
                            Math.min(questions.length - 1, idx + 1),
                          );
                        }}
                      >
                        Next question
                      </button>
                      <button
                        type="button"
                        className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                        onClick={() => {
                          setReviewMode(false);
                          setShowStepScore(true);
                        }}
                      >
                        Back to score
                      </button>
                    </div>
                  </div>
                )}
                {!quizMode && showStepScore && stepResult && (
                  <div className="kc-quiz-score">
                    <h3 className="kc-content-title">
                      Lesson {currentStepIndex + 1} quiz summary
                    </h3>
                    <p className="kc-results-summary">
                      You&apos;ve just finished the check-in for{" "}
                      <strong>{selectedStep.title}</strong>.
                    </p>
                    <div className="kc-results">
                      <h4 className="kc-results-title">Your score for this lesson</h4>
                      <p className="kc-results-summary">
                        <strong>
                          {stepResult.correct} / {stepResult.total}
                        </strong>{" "}
                        questions answered correctly.
                      </p>
                      <p className="kc-results-summary">
                        {stepResult.correct === 0 ? (
                          <>
                            😔 This quiz didn&apos;t go as planned, and{" "}
                            <strong>that&apos;s okay</strong>. Use the explanations and Review quiz option to
                            see what clicked and what didn&apos;t—this is exactly how deep understanding is
                            built.
                          </>
                        ) : stepResult.correct === stepResult.total ? (
                          <>
                            ✨ <strong>Brilliant!</strong> You aced this lesson&apos;s quiz. If it feels clear,
                            you&apos;re ready to move on—or do a quick review if you&apos;d like.
                          </>
                        ) : (
                          <>
                            👏 <strong>Nice work!</strong> You&apos;ve built a solid understanding of this
                            lesson. You can review the quiz for clarity, then flow into the next topic when
                            you&apos;re ready.
                          </>
                        )}
                      </p>
                    </div>
                    <div className="kc-chat-controls kc-chat-controls--topic-cta">
                      <button
                        type="button"
                        className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                        onClick={() => {
                          // Return to the lesson content for this topic
                          setShowStepScore(false);
                          setReviewMode(false);
                          setQuizMode(false);
                          setQuizQuestionIndex(0);
                          setQuizSelectedIndex(null);
                          setQuizFeedback(null);
                        }}
                      >
                        {`Back to Lesson #${currentStepIndex + 1}`}
                      </button>
                      <button
                        type="button"
                        className="kc-btn kc-btn-primary kc-quiz-nav-btn"
                        onClick={() => {
                          handleNextOrComplete();
                        }}
                      >
                        {isLastStep ? "Complete learning" : "Next topic"}
                      </button>
                    </div>
                  </div>
                )}
              </div>

              <div className="kc-chat-controls">
                {currentStepIndex > 0 && (
                  <button
                    type="button"
                    className="kc-btn kc-btn-ghost kc-quiz-nav-btn"
                    onClick={() => {
                      setCurrentStepIndex((idx) => Math.max(0, idx - 1));
                      setQuizMode(false);
                      setQuizQuestionIndex(0);
                      setQuizSelectedIndex(null);
                      setQuizFeedback(null);
                      setShowStepScore(false);
                    }}
                  >
                    Previous lesson
                  </button>
                )}
                {!hasQuiz && (
                  <button
                    type="button"
                    className="kc-btn kc-btn-primary kc-quiz-nav-btn"
                    onClick={handleNextOrComplete}
                  >
                    {isLastStep ? "Complete learning" : "Next topic"}
                  </button>
                )}
              </div>
            </div>
          )}

          {plan && mode === "summary" && courseCompleted && scoreSummary && (
            <div className="kc-chat kc-summary">
              <div className="kc-certificate">
                <div className="kc-certificate-header">
                  <div className="kc-certificate-logo-wrap">
                    <img src="logo.png" alt="Krit.club logo" className="kc-certificate-logo" />
                  </div>
                  <div>
                    <h2 className="kc-certificate-title">Kritclub Learning Coach</h2>
                    <p className="kc-certificate-subtitle">Certificate of Quick Learning</p>
                  </div>
                </div>
                <div className="kc-certificate-body">
                  <p className="kc-certificate-text">
                    This certifies that <strong>Kritclub Explorer</strong> has completed the mini-course
                    on <strong>{plan.topic || topic}</strong> and stayed curious for a focused{" "}
                    <strong>15-minute learning journey</strong>.
                  </p>
                  <div className="kc-certificate-score-pill">
                    Overall score:{" "}
                    <strong>
                      {scoreSummary.totalCorrect} / {scoreSummary.totalQuestions}
                    </strong>
                  </div>
                  <div className="kc-results">
                    <h4 className="kc-results-title">Topic-wise score</h4>
                    <ul className="kc-results-list">
                      {scoreSummary.perStep.map((row, idx) => (
                        <li key={idx} className="kc-results-row">
                          <span className="kc-results-topic">{row.title}</span>
                          <span className="kc-results-score">
                            {row.correct} / {row.total}
                          </span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
                <div className="kc-certificate-footer">
                  <span className="kc-certificate-sign">krit.club — Learning Coach</span>
                </div>
              </div>
              <div className="kc-summary-actions">
                <button
                  type="button"
                  className="kc-btn kc-btn-primary"
                  onClick={handleNewLearning}
                >
                  Start new learning
                </button>
              </div>
            </div>
          )}
        </section>
      </main>

      <footer className="kc-footer">
        <span className="kc-tag">krit.club — Learning Coach</span>
      </footer>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);


