/* ============================================================
   CamelWorth — QuizStepper island.
   Takes over quiz step rendering (with livelier transitions) when
   React 18 CDN loads. Drives the SAME state API as the vanilla
   engine (window.CWQuiz), so scoring/behavior are identical.
   If React fails to load, js/quiz.js renders vanilla steps.
   ============================================================ */
(function () {
  "use strict";

  // Takeover flag — read by js/quiz.js before its first render.
  window.__cwReactMounted = true;

  function mount() {
    if (!window.React || !window.ReactDOM || !window.CWQuiz) {
      // React unavailable after all: let vanilla take over.
      window.__cwReactMounted = false;
      if (window.CWQuiz && window.CWQuiz.renderVanilla) window.CWQuiz.renderVanilla();
      return;
    }

    var mountNode = document.getElementById("quiz-react-root");
    if (!mountNode) {
      window.__cwReactMounted = false;
      return;
    }
    var vanillaRoot = document.getElementById("quiz-root");
    if (vanillaRoot) vanillaRoot.style.display = "none";

    var reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    function Stepper() {
      var snapState = React.useState(window.CWQuiz.getState()),
        snap = snapState[0],
        setSnap = snapState[1];
      var prevStep = React.useRef(snap.step);
      var dirState = React.useState(1),
        dir = dirState[0],
        setDir = dirState[1];

      React.useEffect(function () {
        var handler = function (e) {
          var next = e.detail;
          setDir(next.step === "calc" || next.step > prevStep.current ? 1 : -1);
          prevStep.current = next.step;
          setSnap(next);
        };
        window.addEventListener("cw:quiz-state", handler);
        return function () { window.removeEventListener("cw:quiz-state", handler); };
      }, []);

      // Keep the vanilla progress dots/bar in sync (shared chrome).
      React.useEffect(function () {
        renderProgressChrome(snap);
      }, [snap]);

      if (snap.step === "calc") {
        return (
          <div className={"quiz-step calculating" + (reduced ? "" : " quiz-step-enter")} role="status" aria-live="polite">
            <p style={{ fontSize: "1.2rem", fontWeight: 700, color: "var(--navy)", fontFamily: "var(--font-display)" }}>
              Consulting the caravan…
            </p>
            <p style={{ color: "var(--ink-faint)" }}>Weighing your answers in premium hay.</p>
          </div>
        );
      }

      var q = window.CWQuiz.questions[snap.step];
      if (!q) return null;
      var label = window.CWQuiz.questionText(q);

      return (
        <div
          key={snap.step}
          className={"quiz-step" + (reduced ? "" : dir === 1 ? " quiz-step-enter" : " quiz-step-enter quiz-step-enter-back")}
          role="group"
          aria-labelledby="rxQ"
        >
          <h2 className="quiz-q" id="rxQ" tabIndex="-1" ref={focusHeading}>{label}</h2>
          {q.sub ? <p className="quiz-q-sub">{q.sub}</p> : null}
          <ol className="option-list">
            {q.options.map(function (o, i) { return (
              <li key={i}>
                <button type="button" className="option-btn" onClick={function () { window.CWQuiz.answer(i); }}>
                  <span className="opt-dot" aria-hidden="true"></span>
                  <span className="option-emoji" aria-hidden="true">{o.icon}</span>
                  <span>{o.label}</span>
                </button>
              </li>
            );})}
          </ol>
          <div className="quiz-nav">
            {snap.step > 0
              ? <button type="button" className="quiz-back" onClick={window.CWQuiz.back}>← Back</button>
              : <span></span>}
            <span className="quiz-hint" style={{ fontSize: ".82rem", color: "var(--ink-faint)" }}>
              Tip: press 1–{q.options.length} to answer
            </span>
          </div>
        </div>
      );
    }

    function focusHeading(node) {
      if (node) node.focus({ preventScroll: true });
    }

    // Shared progress chrome lives outside the React root; update it here.
    function renderProgressChrome(s) {
      var dots = document.getElementById("progressDots");
      if (dots) {
        var items = dots.querySelectorAll("li");
        items.forEach(function (li, i) {
          li.className = s.step === "calc" || i < s.step ? "done" : i === s.step ? "current" : "";
        });
      }
      var bar = document.getElementById("progressBarFill");
      if (bar) {
        bar.style.width = (s.step === "calc" ? 100 : Math.round((s.step / s.total) * 100)) + "%";
      }
      var label = document.getElementById("progressLabel");
      if (label) {
        label.textContent = s.step === "calc" ? "Calculating…" : "Question " + (s.step + 1) + " of " + s.total;
      }
    }

    ReactDOM.createRoot(mountNode).render(<Stepper />);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mount);
  } else {
    mount();
  }
})();
