/* ═══════════════════════════════════════════
   MECHANISM QUIZ v5 — Main app
   ═══════════════════════════════════════════ */

const { useState, useCallback, useEffect, useMemo, useRef } = React;

// ─── Bottom block: primary CTA + restart link + brand footer ───
function BottomBlock({ onRestart, marginTop = 28 }) {
  return (
    <div style={{ textAlign: "center", marginTop }}>
      <a
        href="https://mechanism.seproject.me"
        target="_blank"
        rel="noopener noreferrer"
        style={QS.primaryCta}
      >
        看完整系列 ⚙
      </a>
      <div style={{ marginTop: 18 }}>
        <button onClick={onRestart} style={QS.restartBtn}>重新測一次</button>
      </div>
      <p style={{ ...QS.hint, marginTop: 28, lineHeight: 1.7, fontSize: 11 }}>
        煩惱的常見機制 ⚙<br />mechanism.seproject.me
      </p>
    </div>
  );
}

// ─── Welcome ───
function Welcome({ onStart }) {
  return (
    <div style={{ textAlign: "center", padding: "12px 0 0" }}>
      <window.GearCluster scores={{}} mode="welcome" size={180} />
      <p style={{ fontSize: 12, color: "#B0A69D", letterSpacing: "0.16em", marginBottom: 14, marginTop: 8 }}>
        ⚙　6 個機制
      </p>
      <h1 style={QS.h1}>你的煩惱，<br />是怎麼運作的？</h1>
      <p style={QS.sub}>幾個日常場景，<br />選最像你的那個。</p>
      <div style={{ marginTop: 32 }}>
        <button onClick={onStart} style={QS.primaryCta}>開始</button>
      </div>
      <p style={{ ...QS.hint, marginTop: 48, lineHeight: 1.7 }}>
        煩惱的常見機制 ⚙<br />
        <span style={{ fontSize: 11 }}>mechanism.seproject.me</span>
      </p>
    </div>
  );
}

// ─── Results (high signal path) ───
function ResultsHigh({ results, scores, onRestart }) {
  const [show, setShow] = useState(false);
  useEffect(() => { const t = setTimeout(() => setShow(true), 400); return () => clearTimeout(t); }, []);

  const narrative = useMemo(() => window.buildNarrative(results), [results]);

  const labelString = results.map(k => window.M[k].label).join("、");
  const shareText = `我的煩惱裡，這三個齒輪轉得最積極：${labelString}。\n原來是這樣。\n→ mechanism.seproject.me`;

  const shareForFriend = () => {
    if (navigator.share) {
      navigator.share({ text: shareText }).catch(() => {});
    } else {
      navigator.clipboard?.writeText(shareText).then(() => alert("已複製 ✓")).catch(() => {});
    }
  };

  return (
    <div>
      {/* Result card */}
      <div style={QS.resultFrame}>
        <p style={{ fontSize: 13, color: "#B0A69D", textAlign: "center", marginBottom: 8 }}>
          原來是這幾個在轉。
        </p>
        <window.GearCluster scores={scores} mode="results" highlighted={results} size={240} />
        <div style={{ display: "flex", justifyContent: "center", gap: 8, marginTop: 14, flexWrap: "wrap" }}>
          {results.map(k => (
            <span key={k} style={{
              fontSize: 13, padding: "4px 12px", borderRadius: 14,
              background: window.M[k].color, color: "#fff", fontWeight: 500, letterSpacing: "0.03em"
            }}>
              {window.M[k].label}
            </span>
          ))}
        </div>
        <p style={{
          fontSize: 14, lineHeight: 1.95, color: "#3D3530",
          marginTop: 18, textAlign: "left", padding: "0 4px",
          textWrap: "pretty",
          opacity: show ? 1 : 0, transform: show ? "none" : "translateY(8px)",
          transition: "all 0.6s ease 0.2s",
          fontFamily: "'Noto Serif TC', serif",
        }}>
          {narrative}
        </p>
      </div>

      {/* Share section — text + button, inline with the "seeing" moment */}
      <div style={{
        marginTop: 28, textAlign: "center",
        opacity: show ? 1 : 0, transition: "opacity 0.6s ease 0.4s"
      }}>
        <p style={{ fontSize: 13, color: "#B0A69D", marginBottom: 14, lineHeight: 1.8 }}>
          上次那個找你訴苦的人——<br />也許他也會想測測看。
        </p>
        <button onClick={shareForFriend} style={QS.shareBtn}>傳給他</button>
      </div>

      {/* Go deeper — EP cards */}
      <div style={{ marginTop: 40, opacity: show ? 1 : 0, transition: "opacity 0.6s ease 0.5s" }}>
        <p style={{ fontSize: 14, lineHeight: 1.8, color: "#6B5E54", textAlign: "center", marginBottom: 16 }}>
          這只是表面，點進去看——它是怎麼運作的。
        </p>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {results.map(k => {
            const m = window.M[k];
            return (
              <a key={k} href={m.url} target="_blank" rel="noopener noreferrer"
                style={{ ...QS.resultCard, borderLeftColor: m.color }}
              >
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                  <span style={{
                    fontSize: 11, padding: "2px 8px", borderRadius: 10,
                    background: m.color, color: "#fff", fontWeight: 500
                  }}>{m.ep}</span>
                  <span style={{ fontFamily: "'Noto Serif TC', serif", fontSize: 15, fontWeight: 600 }}>
                    {m.label}
                  </span>
                </div>
                <p style={{ fontSize: 13, color: "#A09890", lineHeight: 1.7 }}>{m.desc}</p>
              </a>
            );
          })}
        </div>
      </div>

      <BottomBlock onRestart={onRestart} marginTop={32} />
    </div>
  );
}

// ─── Results (low signal path) ───
function ResultsLow({ scores, onRestart }) {
  const [show, setShow] = useState(false);
  useEffect(() => { const t = setTimeout(() => setShow(true), 400); return () => clearTimeout(t); }, []);

  const shareText = `做了一個關於煩惱的小測驗。你的煩惱，是怎麼運作的？\n→ mechanism.seproject.me`;
  const shareForFriend = () => {
    if (navigator.share) navigator.share({ text: shareText }).catch(() => {});
    else navigator.clipboard?.writeText(shareText).then(() => alert("已複製 ✓")).catch(() => {});
  };

  return (
    <div style={{ textAlign: "center" }}>
      <window.GearCluster scores={scores} mode="results" highlighted={[]} size={180} />
      <h2 style={{ ...QS.h1, fontSize: 20, marginTop: 4 }}>你的齒輪，<br />目前轉得比較慢。</h2>
      <p style={{ ...QS.sub, marginTop: 12, fontSize: 14, lineHeight: 1.9 }}>這是好事。</p>
      <div style={{
        ...QS.softCard, marginTop: 24, textAlign: "left",
        opacity: show ? 1 : 0, transform: show ? "none" : "translateY(10px)",
        transition: "all 0.6s ease 0.3s"
      }}>
        <p style={{ fontSize: 14, lineHeight: 1.9, color: "#3D3530" }}>
          如果你身邊有人正在煩惱——<br />
          這個系列也許可以幫你更理解他正在經歷的。
        </p>
        <p style={{ fontSize: 13, lineHeight: 1.8, color: "#8B7E74", marginTop: 12 }}>
          下次聽他說的時候，試著在心裡問：<br />
          他的預測是什麼？他的預測怎麼來的？<br />
          有哪些機制正在運作？
        </p>
      </div>

      {/* Share section — text + button */}
      <div style={{
        marginTop: 28, opacity: show ? 1 : 0, transition: "opacity 0.6s ease 0.5s"
      }}>
        <p style={{ fontSize: 13, color: "#B0A69D", marginBottom: 14, lineHeight: 1.8 }}>
          也許身邊的人會想測測看。
        </p>
        <button onClick={shareForFriend} style={QS.shareBtn}>傳給他</button>
      </div>

      <BottomBlock onRestart={onRestart} marginTop={32} />
    </div>
  );
}

// ─── Main ───
function MechanismQuiz() {
  const [phase, setPhase] = useState("welcome");
  const [qi, setQi] = useState(0);
  const [picked, setPicked] = useState(null);
  const [scores, setScores] = useState({});
  const [results, setResults] = useState([]);
  const [isLow, setIsLow] = useState(false);
  const [fade, setFade] = useState(true);
  const [pulseMap, setPulseMap] = useState({});
  const [hintText, setHintText] = useState("");

  const shuffled = useMemo(() => window.shuffleOpts(window.QUESTIONS[qi].options), [qi]);

  const go = useCallback(fn => {
    setFade(false);
    setTimeout(() => { fn(); setFade(true); }, 280);
  }, []);

  const pick = idx => {
    if (picked !== null) return;
    setPicked(idx);
    const opt = shuffled[idx];

    const ns = { ...scores };
    Object.entries(opt.scores || {}).forEach(([k, v]) => { ns[k] = (ns[k] || 0) + v; });
    setScores(ns);

    // Pulse the affected gears
    const newPulse = { ...pulseMap };
    Object.keys(opt.scores || {}).forEach(k => { newPulse[k] = (newPulse[k] || 0) + 1; });
    setPulseMap(newPulse);

    // Progressive narrative — refresh every other question
    if ((qi + 1) % 2 === 0) {
      setHintText(window.buildProgressHint(ns));
    }

    setTimeout(() => {
      if (qi < window.QUESTIONS.length - 1) {
        go(() => { setQi(qi + 1); setPicked(null); });
      } else {
        const total = Object.values(ns).reduce((a, b) => a + b, 0);
        const normed = window.MKEYS
          .map(k => ({ key: k, raw: ns[k] || 0, pct: ((ns[k] || 0) / window.MAX_S[k]) * 100 }))
          .sort((a, b) => b.pct - a.pct)
          .filter(x => x.raw > 0);
        const top = normed.slice(0, 3).map(x => x.key);
        go(() => {
          setResults(top);
          setIsLow(total < window.LOW_T);
          setPhase("results");
        });
      }
    }, 480);
  };

  const restart = () => go(() => {
    setPhase("welcome");
    setQi(0); setPicked(null);
    setScores({}); setResults([]); setIsLow(false);
    setPulseMap({}); setHintText("");
  });

  return (
    <div style={QS.root}>
      <div style={QS.shell}>
        <div style={{ ...QS.fade, opacity: fade ? 1 : 0, transform: fade ? "none" : "translateY(6px)" }}>
          {phase === "welcome" && <Welcome onStart={() => go(() => setPhase("quiz"))} />}

          {phase === "quiz" && (
            <div>
              <div style={{ marginBottom: 14 }}>
                <window.GearCluster
                  scores={scores}
                  mode="quiz"
                  size={200}
                  pulseMap={pulseMap}
                />
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <div style={QS.track}>
                  <div style={{ ...QS.fill, width: `${(qi / window.QUESTIONS.length) * 100}%` }} />
                </div>
                <span style={QS.hint}>{qi + 1}/{window.QUESTIONS.length}</span>
              </div>
              <div style={{
                minHeight: 18, marginBottom: 18,
                fontSize: 11.5, color: "#B0A69D", letterSpacing: "0.04em",
                opacity: hintText ? 1 : 0, transition: "opacity 0.5s ease",
              }}>
                {hintText || "\u00A0"}
              </div>
              <p style={QS.question}>{window.QUESTIONS[qi].situation}</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 24 }}>
                {shuffled.map((o, i) => {
                  const sel = picked === i, dim = picked !== null && !sel;
                  return (
                    <button key={i} onClick={() => pick(i)} style={{
                      ...QS.opt,
                      background: sel ? "#EDE8E0" : "#FEFCF9",
                      borderColor: sel ? "#C8BEB0" : "#E8E2DA",
                      opacity: dim ? 0.4 : 1,
                      transform: sel ? "scale(0.985)" : "none",
                      cursor: picked !== null ? "default" : "pointer",
                    }}>
                      {o.text}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {phase === "results" && !isLow && (
            <ResultsHigh results={results} scores={scores} onRestart={restart} />
          )}
          {phase === "results" && isLow && (
            <ResultsLow scores={scores} onRestart={restart} />
          )}
        </div>
      </div>

      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Noto+Serif+TC:wght@400;500;600;700&family=Noto+Sans+TC:wght@300;400;500&display=swap');
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body, button, input { font-family: 'Noto Sans TC', sans-serif; }
        button { cursor: pointer; }
        button:focus, a:focus { outline: 2px solid #C8BEB0; outline-offset: 2px; }
      `}</style>
    </div>
  );
}

const QS = {
  root: {
    minHeight: "100vh", background: "#FAF8F5",
    fontFamily: "'Noto Sans TC', sans-serif", color: "#3D3530",
    display: "flex", justifyContent: "center",
  },
  shell: { width: "100%", maxWidth: 420, padding: "28px 24px 48px" },
  fade: { transition: "opacity 0.35s ease, transform 0.35s ease" },
  h1: {
    fontFamily: "'Noto Serif TC', serif",
    fontSize: 22, fontWeight: 600, lineHeight: 1.65, color: "#3D3530",
    marginBottom: 14, letterSpacing: "0.01em",
  },
  sub: { fontSize: 15, lineHeight: 1.85, color: "#8B7E74", marginBottom: 6 },
  hint: { fontSize: 13, color: "#B0A69D" },
  primaryCta: {
    display: "inline-block",
    padding: "12px 36px", borderRadius: 24,
    border: "none", background: "#8B7E74", color: "#FEFCF9",
    fontSize: 15, fontFamily: "'Noto Sans TC', sans-serif",
    letterSpacing: "0.04em", textDecoration: "none",
  },
  linkCta: {
    display: "inline-block",
    padding: "10px 30px", borderRadius: 22,
    border: "1px solid #C8BEB0", background: "transparent",
    color: "#6B5E54", fontSize: 14,
    fontFamily: "'Noto Sans TC', sans-serif",
    letterSpacing: "0.03em", textDecoration: "none",
  },
  track: { flex: 1, height: 2, background: "#E8E2DA", borderRadius: 1, overflow: "hidden" },
  fill: { height: "100%", background: "#B8AEA4", borderRadius: 1, transition: "width 0.5s ease" },
  question: {
    fontFamily: "'Noto Serif TC', serif",
    fontSize: 19, fontWeight: 400, lineHeight: 1.8, color: "#3D3530",
    whiteSpace: "pre-line", textWrap: "pretty",
  },
  opt: {
    width: "100%", padding: "14px 18px", borderRadius: 10,
    border: "1px solid", fontSize: 15, color: "#4A423C",
    textAlign: "left", lineHeight: 1.6, transition: "all 0.2s ease",
    fontFamily: "'Noto Sans TC', sans-serif",
  },
  resultFrame: {
    padding: "24px 20px",
    background: "#FEFCF9", borderRadius: 14, border: "1px solid #E8E2DA",
    boxShadow: "0 2px 24px rgba(0,0,0,0.04)",
  },
  resultCard: {
    display: "block", padding: "14px 16px",
    borderRadius: 10, border: "1px solid #E8E2DA",
    borderLeftWidth: 3, borderLeftStyle: "solid",
    background: "#FEFCF9", textDecoration: "none", color: "inherit",
  },
  softCard: { padding: "18px 20px", background: "#F5F0EA", borderRadius: 12 },
  shareBtn: {
    padding: "10px 28px", borderRadius: 20,
    border: "1px solid #C8BEB0", background: "#FEFCF9",
    fontSize: 14, color: "#6B5E54",
    fontFamily: "'Noto Sans TC', sans-serif",
  },
  restartBtn: {
    marginTop: 4, padding: "6px 14px",
    background: "none", border: "none",
    fontSize: 13, color: "#A09890",
    fontFamily: "'Noto Sans TC', sans-serif",
    textDecoration: "underline", textUnderlineOffset: 4,
  },
};

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