// Reading flow: mode select -> question -> bag/pull -> result
const READING_MODES = [
  { id: "daily", count: 1, name: "Daily Rune", desc: "Guidance for today", layout: "single" },
  { id: "three", count: 3, name: "Three Rune Spread", desc: "Past - Present - Future", layout: "row" },
  { id: "five", count: 5, name: "Five Rune Spread", desc: "A deeper look at the situation", layout: "cross" },
  { id: "scatter", count: 7, name: "Rune Cast", desc: "Cast runes into the unknown", layout: "scatter" }
];

const ReadingModeSelect = ({ onNav, onPick }) => (
  <div className="screen wood-grain" style={{ width: "100%", height: "100%", position: "relative", overflowY: "auto" }}>
    <div className="noise"/>
    <StatusBar/>
    <TopBar title="Spread Method" subtitle="Choose a spread" onBack={() => onNav("home")}/>
    <div style={{ padding: "8px 20px 40px", display: "flex", flexDirection: "column", gap: 12 }}>
      {READING_MODES.map(m => (
        <div key={m.id} className="ornate-card" onClick={() => onPick(m)} style={{ padding: 18, cursor: "pointer", display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ width: 56, height: 56, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(201,168,76,0.08)", borderRadius: 4, border: "1px solid rgba(201,168,76,0.2)" }}>
            <span className="rune-glyph" style={{ fontSize: 28, color: "var(--gold)" }}>{["ᛟ","ᚱ","ᛉ","ᛊ"][READING_MODES.indexOf(m)]}</span>
          </div>
          <div style={{ flex: 1 }}>
            <div className="font-display" style={{ fontSize: 16, color: "var(--ivory)", letterSpacing: "0.1em" }}>{m.name}</div>
            <div style={{ fontSize: 12, color: "var(--ivory)", marginTop: 6, opacity: 0.7 }}>{m.desc}</div>
          </div>
          <div className="font-display" style={{ fontSize: 28, color: "var(--gold-soft)", fontWeight: 300 }}>{m.count}</div>
        </div>
      ))}
    </div>
  </div>
);

const QuestionInput = ({ mode, onNav, onSubmit }) => {
  const [q, setQ] = React.useState("");
  return (
    <div className="screen wood-grain" style={{ width: "100%", height: "100%", position: "relative", display: "flex", flexDirection: "column" }}>
      <div className="noise"/>
      <StatusBar/>
      <TopBar title={mode.name} subtitle="Prepare your question" onBack={() => onNav("reading-mode")}/>

      <div style={{ flex: 1, padding: "20px 24px", display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <Icon.Sparkle size={20} color="var(--gold)"/>
          <div className="font-display" style={{ fontSize: 14, letterSpacing: "0.25em", color: "var(--gold)", marginTop: 12, textTransform: "uppercase" }}>Ask a Question</div>
          <div style={{ fontSize: 12, color: "var(--ash)", fontStyle: "italic", marginTop: 4 }}>Pose your question, or leave it open</div>
        </div>

        <div className="ornate-card" style={{ padding: 0, background: "rgba(13,13,13,0.6)" }}>
          <textarea
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Hold your question in mind..."
            style={{
              width: "100%", minHeight: 140, padding: 18, background: "transparent",
              border: "none", outline: "none", color: "var(--ivory)",
              fontFamily: "Cormorant Garamond, serif", fontSize: 17,
              fontStyle: q ? "normal" : "italic", resize: "none", lineHeight: 1.5
            }}
          />
        </div>

        <div style={{ marginTop: 12, fontSize: 11, color: "var(--ash)", textAlign: "center", fontStyle: "italic" }}>
          "A clear question invites a clear answer" - Havamal
        </div>
      </div>

      <div style={{ padding: "0 24px 32px", display: "flex", flexDirection: "column", gap: 10 }}>
        <button className="btn-primary" onClick={() => onSubmit(q)}>Enter the Ritual</button>
        <button className="btn-ghost" onClick={() => onSubmit("")}>Skip</button>
      </div>
    </div>
  );
};

const RuneBag = ({ mode, question, skin, onComplete }) => {
  const [phase, setPhase] = React.useState("idle");
  const [drawn, setDrawn] = React.useState([]);

  const draw = () => {
    if (phase !== "idle") return;
    if (window.navigator.vibrate) window.navigator.vibrate(40);
    const pool = [...window.RUNES];
    const picks = [];
    for (let i = 0; i < mode.count; i++) {
      const idx = Math.floor(Math.random() * pool.length);
      const r = pool.splice(idx, 1)[0];
      picks.push({ ...r, reversed: !r.symmetric && Math.random() < 0.35 });
    }
    setDrawn(picks);
    setPhase("drawing");
    setTimeout(() => setPhase("revealing"), 1800);
    setTimeout(() => onComplete(picks), 3400);
  };

  return (
    <div className="screen" style={{ width: "100%", height: "100%", position: "relative", background: "radial-gradient(ellipse at center, #1a1208 0%, #0D0D0D 70%)", overflow: "hidden" }}>
      <div className="noise"/>

      {phase !== "idle" && Array.from({ length: 20 }).map((_, i) => (
        <div key={i} style={{
          position: "absolute",
          left: `${10 + (i * 4.5) % 80}%`,
          top: `${20 + (i * 7) % 60}%`,
          width: 2, height: 2, borderRadius: "50%",
          background: "var(--gold)",
          boxShadow: "0 0 6px var(--gold)",
          opacity: 0.6,
          animation: `float ${2 + (i % 4)}s ease-in-out ${i * 0.1}s infinite`
        }}/>
      ))}

      <StatusBar/>

      <div style={{ position: "absolute", top: 60, left: 0, right: 0, textAlign: "center", padding: "0 32px", zIndex: 5 }}>
        <div className="font-archaic" style={{ fontSize: 12, color: "var(--gold)", fontStyle: "italic", letterSpacing: "0.1em" }}>
          {phase === "idle" ? "Breathe. Focus. Touch the rune bag." :
           phase === "drawing" ? "The runes are choosing you..." :
           "Read what has appeared"}
        </div>
        {question && phase === "idle" && (
          <div style={{ marginTop: 10, fontSize: 13, color: "var(--ivory)", fontStyle: "italic", opacity: 0.8 }}>
            "{question}"
          </div>
        )}
      </div>

      <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
        {phase === "idle" && (
          <div onClick={draw} className="float" style={{ cursor: "pointer", position: "relative" }}>
            <div className="glow-pulse" style={{ borderRadius: "50%", padding: 10 }}>
              <Icon.Bag size={220}/>
            </div>
            <div style={{ position: "absolute", bottom: -36, left: 0, right: 0, textAlign: "center", fontFamily: "Cinzel", fontSize: 11, letterSpacing: "0.3em", color: "var(--gold)", textTransform: "uppercase" }}>Tap to Draw</div>
          </div>
        )}

        {phase === "drawing" && (
          <div style={{ position: "relative", width: 240, height: 240, animation: "spin-slow 6s linear infinite" }}>
            {Array.from({ length: mode.count }).map((_, i) => (
              <div key={i} style={{
                position: "absolute", left: "50%", top: "50%",
                transform: `translate(-50%,-50%) rotate(${i * 360 / mode.count}deg) translateY(-90px)`,
                animation: "glowpulse 1.5s ease-in-out infinite"
              }}>
                <div className={`rune-${skin}`} style={{ width: 46, height: 60, display: "flex", alignItems: "center", justifyContent: "center", borderRadius: 4 }}>
                  <span className="rune-glyph" style={{ fontSize: 24 }}>?</span>
                </div>
              </div>
            ))}
            <div style={{ position: "absolute", left: "50%", top: "50%", transform: "translate(-50%,-50%)", width: 80, height: 80, borderRadius: "50%", background: "radial-gradient(circle, rgba(201,168,76,0.6), transparent)", filter: "blur(12px)" }}/>
          </div>
        )}

        {phase === "revealing" && (
          <div className="fade-in" style={{ display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center", padding: 20 }}>
            {drawn.map((r, i) => (
              <div key={i} style={{ animation: `fadeIn 0.6s ease-out ${i * 0.15}s both` }}>
                <RuneTile rune={r} skin={skin} reversed={r.reversed} size={mode.count > 3 ? 56 : 76} glow/>
              </div>
            ))}
          </div>
        )}
      </div>

      {phase === "idle" && (
        <div style={{ position: "absolute", bottom: 40, left: 0, right: 0, textAlign: "center", fontSize: 11, color: "var(--ash)", fontStyle: "italic" }}>
          ᚦ &nbsp; Fate whispers to those who know how to listen &nbsp; ᚦ
        </div>
      )}
    </div>
  );
};

const ReadingResult = ({ mode, question, drawn, skin, onNav, onAI, onSave }) => {
  const [selected, setSelected] = React.useState(0);
  const [oracleOpen, setOracleOpen] = React.useState(false);
  const [oracleText, setOracleText] = React.useState("");
  const [oracleThinking, setOracleThinking] = React.useState(false);
  const oracleRef = React.useRef(null);

  const positions = mode.id === "three" ? ["Past", "Present", "Future"] :
                    mode.id === "five" ? ["Issue", "Past", "Present", "Support", "Outcome"] :
                    mode.id === "daily" ? ["Today"] :
                    drawn.map((_,i) => `Rune ${i+1}`);

  const summonOracle = () => {
    if (oracleOpen) return;
    setOracleOpen(true);
    setOracleThinking(true);
    setOracleText("");
    const lines = drawn.map((r, i) =>
      `\n\n${positions[i]} - ${r.name}${r.reversed ? " (merkstave)" : ""}: ${(r.reversed ? r.reversed : r.upright).split('.')[0]}.`
    ).join("");
    const intro = question
      ? `Your question - "${question}" - has been heard by the Norns. The ${mode.name} reveals a clear pattern:`
      : `You spoke no question aloud, but your attention still shaped the casting. The ${mode.name} answers with these signs:`;
    const summary = `\n\nOverall, the runes point to one movement: ${drawn[0].keywords[0]} transforming into ${drawn[drawn.length-1].keywords[0]}. This is not a fixed prediction. It is a map, and the choices remain yours.`;
    const full = intro + lines + summary;
    let i = 0;
    setTimeout(() => {
      const timer = setInterval(() => {
        i += 3;
        setOracleText(full.slice(0, i));
        if (oracleRef.current) oracleRef.current.scrollIntoView && oracleRef.current.parentElement && oracleRef.current.parentElement.scrollTo({ top: oracleRef.current.offsetTop, behavior: "smooth" });
        if (i >= full.length) { clearInterval(timer); setOracleThinking(false); }
      }, 25);
    }, 700);
  };

  return (
    <div className="screen wood-grain" style={{ width: "100%", height: "100%", position: "relative", overflowY: "auto" }}>
      <div className="noise"/>
      <StatusBar/>
      <TopBar title="Rune Reading" subtitle={mode.name} onBack={() => onNav("home")} right={<Icon.Share size={18} color="var(--gold)"/>}/>

      {question && (
        <div style={{ margin: "0 24px 16px", padding: "12px 16px", background: "rgba(201,168,76,0.05)", borderLeft: "1px solid var(--gold)", fontSize: 13, color: "var(--ivory)", fontStyle: "italic" }}>
          "{question}"
        </div>
      )}

      <div style={{ padding: "8px 24px 16px" }}>
        {mode.layout === "scatter" ? (
          <div style={{ position: "relative", height: 260, background: "radial-gradient(ellipse at center, rgba(201,168,76,0.04), transparent)" }}>
            {drawn.map((r, i) => {
              const seed = (r.id * 13 + i * 7) % 100;
              const x = 10 + (seed * 1.8) % 70;
              const y = 10 + ((r.id * 17 + i * 11) % 100 * 0.8) % 75;
              const rot = ((r.id * 23 + i * 5) % 60) - 30;
              return (
                <div key={i} onClick={() => setSelected(i)} style={{
                  position: "absolute", left: `${x}%`, top: `${y}%`,
                  transform: `rotate(${rot}deg) ${selected === i ? "scale(1.15)" : ""}`,
                  transition: "transform 0.2s", cursor: "pointer", zIndex: selected === i ? 10 : i
                }}>
                  <RuneTile rune={r} skin={skin} reversed={r.reversed} size={48} selected={selected === i}/>
                </div>
              );
            })}
          </div>
        ) : (
          <div style={{ display: "flex", justifyContent: "center", gap: mode.count > 3 ? 8 : 14, flexWrap: mode.count > 3 ? "wrap" : "nowrap" }}>
            {drawn.map((r, i) => (
              <div key={i} onClick={() => setSelected(i)} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, cursor: "pointer" }}>
                <div className="font-display" style={{ fontSize: 9, color: "var(--gold)", letterSpacing: "0.2em", textTransform: "uppercase" }}>{positions[i]}</div>
                <RuneTile rune={r} skin={skin} reversed={r.reversed} size={mode.count > 3 ? 58 : 72} selected={selected === i}/>
                <div className="font-display" style={{ fontSize: 11, color: "var(--ivory)" }}>{r.name}</div>
                {r.reversed && <div style={{ fontSize: 9, color: "var(--ice)", fontStyle: "italic" }}>Merkstave</div>}
              </div>
            ))}
          </div>
        )}
      </div>

      <Ornament width={220} opacity={0.4}/>

      {drawn[selected] && (
        <div className="fade-in" style={{ margin: "16px 20px 0", padding: "16px", background: "rgba(26,22,18,0.6)", border: "1px solid rgba(201,168,76,0.15)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <div className="font-display" style={{ fontSize: 18, color: "var(--gold)", letterSpacing: "0.1em" }}>{drawn[selected].name}</div>
            <div style={{ fontSize: 11, color: "var(--ash)", fontStyle: "italic" }}>{positions[selected]}</div>
          </div>
          <div className="font-archaic" style={{ fontSize: 12, color: "var(--ash)", marginTop: 2 }}>{drawn[selected].phonetic} - Aett {drawn[selected].aett}</div>
          <div style={{ marginTop: 10, fontSize: 14, color: "var(--ivory)", lineHeight: 1.5 }}>
            {drawn[selected].reversed ? drawn[selected].reversed : drawn[selected].upright}
          </div>
          <div style={{ marginTop: 12, display: "flex", gap: 6, flexWrap: "wrap" }}>
            {drawn[selected].keywords.map(k => (
              <span key={k} style={{ fontSize: 10, padding: "4px 10px", background: "rgba(201,168,76,0.1)", border: "1px solid rgba(201,168,76,0.25)", color: "var(--gold)", letterSpacing: "0.05em", textTransform: "uppercase" }}>{k}</span>
            ))}
          </div>
        </div>
      )}

      <div style={{ padding: "20px 20px 40px", display: "flex", flexDirection: "column", gap: 10 }}>
        {!oracleOpen && (
          <button className="btn-primary" onClick={summonOracle}>
            <Icon.Sparkle color="currentColor" size={12}/> &nbsp; Ask Oracle for a Synthesis
          </button>
        )}

        {oracleOpen && (
          <div ref={oracleRef} className="fade-in" style={{ margin: "0 0 8px", padding: "20px 22px", background: "rgba(26,22,18,0.7)", border: "1px solid rgba(201,168,76,0.2)", position: "relative" }}>
            <div style={{ position: "absolute", top: -10, left: 16, padding: "2px 10px", background: "var(--bg)", display: "flex", alignItems: "center", gap: 6 }}>
              <Icon.Sparkle color="var(--gold)" size={12}/>
              <span className="font-display" style={{ fontSize: 10, letterSpacing: "0.25em", color: "var(--gold)", textTransform: "uppercase" }}>Oracle Speaks</span>
            </div>

            {oracleThinking && oracleText.length === 0 && (
              <div style={{ display: "flex", gap: 6, padding: "8px 0", alignItems: "center" }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--gold)", animation: "flicker 1s infinite" }}/>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--gold)", animation: "flicker 1s infinite 0.3s" }}/>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--gold)", animation: "flicker 1s infinite 0.6s" }}/>
                <span style={{ marginLeft: 8, fontSize: 12, color: "var(--ash)", fontStyle: "italic" }}>Oracle is reflecting...</span>
              </div>
            )}

            <div style={{ fontSize: 15, color: "var(--ivory)", lineHeight: 1.65, whiteSpace: "pre-wrap", fontFamily: "Cormorant Garamond, serif" }}>
              {oracleText}
              {oracleThinking && oracleText.length > 0 && <span style={{ color: "var(--gold)", animation: "flicker 1s infinite" }}>|</span>}
            </div>
          </div>
        )}

        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn-ghost" style={{ flex: 1 }} onClick={onSave}>Save to Journal</button>
          <button className="btn-ghost" style={{ flex: 1 }} onClick={() => onNav("home")}>Done</button>
        </div>
      </div>
    </div>
  );
};

window.READING_MODES = READING_MODES;
window.ReadingModeSelect = ReadingModeSelect;
window.QuestionInput = QuestionInput;
window.RuneBag = RuneBag;
window.ReadingResult = ReadingResult;
