// Oracle screen + Rune Detail
const RuneDetail = ({ rune, skin, onNav, onAskAI }) => {
  const [tab, setTab] = React.useState("basic");
  return (
    <div className="screen wood-grain" style={{ width: "100%", height: "100%", position: "relative", overflowY: "auto" }}>
      <div className="noise"/>
      <StatusBar/>
      <TopBar title={rune.name} subtitle={rune.phonetic} onBack={() => onNav("library")}/>

      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", padding: "8px 24px 20px" }}>
        <div className="float">
          <RuneTile rune={rune} skin={skin} reversed={rune.reversed} size={120} glow/>
        </div>
        <div className="font-display" style={{ marginTop: 16, fontSize: 24, letterSpacing: "0.15em", color: "var(--gold)" }}>{rune.name}</div>
        <div style={{ fontSize: 12, color: "var(--ash)", fontStyle: "italic", marginTop: 4 }}>
          Aett {rune.aettNum} - {rune.aett}'s Aett
        </div>
        <div style={{ marginTop: 8, display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "center" }}>
          {rune.keywords.map(k => (
            <span key={k} style={{ fontSize: 10, padding: "3px 9px", background: "rgba(201,168,76,0.1)", border: "1px solid rgba(201,168,76,0.25)", color: "var(--gold)", letterSpacing: "0.05em" }}>{k}</span>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", margin: "0 24px", borderBottom: "1px solid rgba(201,168,76,0.15)" }}>
        {[{k:"basic",l:"Core Meaning"},{k:"ai",l:"Oracle Guidance"}].map(t => (
          <div key={t.k} onClick={() => setTab(t.k)} className="font-display" style={{
            flex: 1, padding: "12px 8px", textAlign: "center",
            fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase",
            color: tab === t.k ? "var(--gold)" : "var(--ash)",
            borderBottom: tab === t.k ? "1px solid var(--gold)" : "1px solid transparent",
            marginBottom: -1, cursor: "pointer"
          }}>{t.l}</div>
        ))}
      </div>

      {tab === "basic" && (
        <div className="fade-in" style={{ padding: "20px 24px 40px" }}>
          <Section label="Upright">
            <p style={{ color: "var(--ivory)" }}>{rune.upright}</p>
          </Section>
          <Section label="Merkstave">
            <p style={{ color: rune.symmetric ? "var(--ash)" : "var(--ivory)", fontStyle: rune.symmetric ? "italic" : "normal" }}>{rune.reversed}</p>
          </Section>
          <Section label="Norse Myth">
            <p style={{ color: "var(--ivory)", fontStyle: "italic" }}>{rune.myth}</p>
          </Section>
        </div>
      )}

      {tab === "ai" && (
        <OracleTab rune={rune} onAskAI={onAskAI}/>
      )}
    </div>
  );
};

const Section = ({ label, children }) => (
  <div style={{ marginBottom: 22 }}>
    <div className="font-display" style={{ fontSize: 10, letterSpacing: "0.25em", color: "var(--gold)", textTransform: "uppercase", marginBottom: 8 }}>{label}</div>
    <div style={{ fontSize: 14, lineHeight: 1.6 }}>{children}</div>
  </div>
);

const OracleTab = ({ rune, onAskAI }) => {
  const [q, setQ] = React.useState("");
  const [response, setResponse] = React.useState(null);
  const [thinking, setThinking] = React.useState(false);

  const ask = () => {
    if (!q.trim()) return;
    setThinking(true);
    setResponse(null);
    setTimeout(() => {
      const mock = `Your question reaches the oracle through ${rune.name}. ${rune.upright.split('.')[0]}. In this situation, you are being invited toward ${rune.keywords[0]}. The light of ${rune.name} suggests that the answer is found through patience, attention, and trust in the path you have chosen.`;
      setResponse("");
      let i = 0;
      const timer = setInterval(() => {
        i += 2;
        setResponse(mock.slice(0, i));
        if (i >= mock.length) {
          clearInterval(timer);
          setThinking(false);
        }
      }, 30);
    }, 800);
  };

  return (
    <div className="fade-in" style={{ padding: "20px 24px 40px" }}>
      <div style={{ padding: "14px 16px", background: "linear-gradient(135deg, rgba(201,168,76,0.08), rgba(138,180,201,0.04))", border: "1px solid rgba(201,168,76,0.2)", marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <Icon.Sparkle color="var(--gold)" size={14}/>
          <div className="font-display" style={{ fontSize: 11, letterSpacing: "0.2em", color: "var(--gold)", textTransform: "uppercase" }}>Ask Oracle</div>
        </div>
        <div style={{ fontSize: 12, color: "var(--ash)", marginTop: 4, fontStyle: "italic" }}>Ask a question to receive a personal reading from this rune.</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="How should I respond to..."
          style={{ width: "100%", minHeight: 80, padding: 14, background: "transparent", border: "none", outline: "none", color: "var(--ivory)", fontFamily: "Cormorant Garamond, serif", fontSize: 15, fontStyle: q ? "normal" : "italic", resize: "none" }}
        />
      </div>

      <button className="btn-primary" onClick={ask} disabled={thinking || !q.trim()} style={{ width: "100%", marginTop: 12, opacity: thinking || !q.trim() ? 0.5 : 1 }}>
        {thinking ? "Oracle is reflecting..." : "Summon Oracle"}
      </button>

      {response !== null && (
        <div className="fade-in" style={{ marginTop: 20, padding: "16px 18px", background: "rgba(26,22,18,0.7)", borderLeft: "2px solid var(--gold)" }}>
          <div className="font-display" style={{ fontSize: 10, letterSpacing: "0.25em", color: "var(--gold)", textTransform: "uppercase", marginBottom: 8 }}>ᛟ &nbsp; Oracle Speaks</div>
          <div style={{ fontSize: 14, color: "var(--ivory)", lineHeight: 1.6, fontFamily: "Cormorant Garamond, serif" }}>
            {response}
            {thinking && <span style={{ animation: "flicker 1s infinite", color: "var(--gold)" }}>|</span>}
          </div>
        </div>
      )}
    </div>
  );
};

const Oracle = ({ drawn, mode, question, skin, onNav }) => {
  const [response, setResponse] = React.useState("");
  const [thinking, setThinking] = React.useState(true);
  const [followUp, setFollowUp] = React.useState("");

  React.useEffect(() => {
    const positions = mode.id === "three" ? ["Past", "Present", "Future"] :
                      mode.id === "five" ? ["Issue","Past","Present","Support","Outcome"] :
                      drawn.map((_,i) => `Position ${i+1}`);
    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;

    setThinking(true);
    setResponse("");
    let i = 0;
    const t1 = setTimeout(() => {
      const timer = setInterval(() => {
        i += 3;
        setResponse(full.slice(0, i));
        if (i >= full.length) { clearInterval(timer); setThinking(false); }
      }, 25);
    }, 900);
    return () => clearTimeout(t1);
  }, []);

  return (
    <div className="screen" style={{ width: "100%", height: "100%", position: "relative", background: "radial-gradient(ellipse at top, #1a1208 0%, #0D0D0D 60%)", overflowY: "auto" }}>
      <div className="noise"/>
      <StatusBar/>
      <TopBar title="Oracle" subtitle="Words from the nine realms" onBack={() => onNav("reading-result")}/>

      <div style={{ padding: "8px 20px", display: "flex", justifyContent: "center", gap: 8, flexWrap: "wrap" }}>
        {drawn.map((r, i) => (
          <RuneTile key={i} rune={r} skin={skin} reversed={r.reversed} size={44}/>
        ))}
      </div>

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

      <div style={{ margin: "16px 20px 20px", 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>

        {thinking && response.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" }}>
          {response}
          {thinking && response.length > 0 && <span style={{ color: "var(--gold)", animation: "flicker 1s infinite" }}>|</span>}
        </div>
      </div>

      {!thinking && (
        <div className="fade-in" style={{ padding: "0 20px 40px" }}>
          <div className="font-display" style={{ fontSize: 10, letterSpacing: "0.2em", color: "var(--gold)", textTransform: "uppercase", marginBottom: 10 }}>Ask More</div>
          <div style={{ display: "flex", gap: 8, alignItems: "stretch" }}>
            <input
              value={followUp} onChange={e => setFollowUp(e.target.value)}
              placeholder="Tell me more about..."
              style={{ flex: 1, padding: "10px 14px", background: "rgba(13,13,13,0.6)", border: "1px solid rgba(201,168,76,0.2)", color: "var(--ivory)", fontFamily: "Cormorant Garamond, serif", fontSize: 14, outline: "none", borderRadius: 0 }}
            />
            <button className="btn-ghost" style={{ padding: "10px 14px" }} onClick={() => { setFollowUp(""); }}>
              <Icon.Send color="var(--gold)" size={18}/>
            </button>
          </div>
          <button className="btn-ghost" onClick={() => onNav("home")} style={{ width: "100%", marginTop: 14 }}>Finish Ritual</button>
        </div>
      )}
    </div>
  );
};

window.RuneDetail = RuneDetail;
window.AIOracle = Oracle;
window.Oracle = Oracle;
