/* Entry screens — Home, Host create (admin-key gated), Join */
(function () {
  const { useState, useEffect } = React;
  const S = () => window.TraitorsStore;

  function readCodeParam() {
    try { return (new URLSearchParams(location.search).get("code") || "").toUpperCase(); }
    catch (e) { return ""; }
  }

  function HomeScreen({ go }) {
    // deep-link: /?code=ABCDE jumps straight to join
    useEffect(() => { if (readCodeParam()) go("join"); }, []);
    return (
      <div className="t-screen t-center t-enter" style={{ gap: 0 }}>
        <div style={{ position: "absolute", top: 18, left: 0, right: 0, display: "flex", justifyContent: "center" }}>
          <Brand />
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", gap: 14, marginBottom: 18 }}>
          <Candle scale={1.3} /><Candle scale={1.7} /><Candle scale={1.3} />
        </div>
        <p className="t-eyebrow" style={{ marginBottom: 14 }}>Depot Corner presents</p>
        <h1 className="t-h1" style={{ marginBottom: 10 }}>
          <span style={{ color: "var(--t-fg)" }}>The</span><br />
          <span style={{ color: "var(--t-gold)", textShadow: "0 0 30px rgba(230,179,77,.4)" }}>Traitors</span>
        </h1>
        <p className="t-body" style={{ maxWidth: 300, marginBottom: 8 }}>
          Faithful or Traitor? Complete the missions, earn the points — and trust no one at the Round Table.
        </p>
        <div style={{ flex: 1 }} />
        <div className="t-stack" style={{ gap: 12, width: "100%", maxWidth: 360 }}>
          <button className="t-btn t-btn--gold" onClick={() => go("join")}>Join a game</button>
          <button className="t-btn t-btn--ghost" onClick={() => go("host")}>Host a game</button>
        </div>
        <p className="t-muted" style={{ fontSize: ".72rem", marginTop: 18 }}>#SkillsForLife · a 1st C&amp;A event</p>
      </div>
    );
  }

  function HostCreateScreen({ back }) {
    const [name, setName] = useState("");
    const [key, setKey] = useState("");
    const [error, setError] = useState("");
    const [busy, setBusy] = useState(false);

    async function create() {
      if (busy) return;
      setBusy(true); setError("");
      try {
        await S().hostCreate(name.trim() || "Host", key.trim());
      } catch (e) {
        setError(e && e.message ? e.message : "Couldn't open the castle.");
        setBusy(false);
      }
    }
    return (
      <div className="t-screen t-enter">
        <button className="t-pill" style={{ alignSelf: "flex-start" }} onClick={back}>← Back</button>
        <div style={{ flex: 1 }} />
        <p className="t-eyebrow">Host the castle</p>
        <h2 className="t-h2" style={{ marginBottom: 6 }}>You hold the keys</h2>
        <p className="t-body" style={{ marginBottom: 22 }}>
          You'll run the game from this device — deal roles, set missions, open the Round Table and keep the score. Hosting is for leaders only.
        </p>
        <label className="t-kicker" style={{ marginBottom: 8, display: "block" }}>Your name</label>
        <input className="t-field" value={name} maxLength={40} placeholder="e.g. Claudia"
          onChange={(e) => setName(e.target.value)} />
        <label className="t-kicker" style={{ margin: "16px 0 8px", display: "block" }}>Leader admin key</label>
        <input className="t-field" value={key} type="password" maxLength={60} placeholder="Shared leader key"
          autoComplete="off" onChange={(e) => setKey(e.target.value)} onKeyDown={(e) => e.key === "Enter" && create()} />
        {error && <p style={{ color: "#ff9aa0", fontWeight: 700, marginTop: 14, fontSize: ".9rem" }}>{error}</p>}
        <div style={{ flex: 1 }} />
        <button className="t-btn t-btn--gold" disabled={busy || !key.trim()} onClick={create}>
          {busy ? "Opening…" : "Open the castle"}
        </button>
      </div>
    );
  }

  function JoinScreen({ back }) {
    const [code, setCode] = useState(readCodeParam());
    const [name, setName] = useState("");
    const [error, setError] = useState("");
    const [step, setStep] = useState(readCodeParam() ? 1 : 0);
    const [busy, setBusy] = useState(false);

    function continueCode() {
      if (code.trim().length < 4) { setError("That code looks too short."); return; }
      setError(""); setStep(1);
    }
    async function doJoin() {
      if (busy) return;
      setBusy(true); setError("");
      try {
        await S().join(code.trim().toUpperCase(), name.trim());
      } catch (e) {
        setError(e && e.message ? e.message : "Couldn't take your seat.");
        setBusy(false);
      }
    }
    return (
      <div className="t-screen t-enter">
        <button className="t-pill" style={{ alignSelf: "flex-start" }}
          onClick={step === 0 ? back : () => { setStep(0); setError(""); }}>← Back</button>
        <div style={{ flex: 1 }} />
        {step === 0 ? (
          <React.Fragment>
            <p className="t-eyebrow">Enter the castle</p>
            <h2 className="t-h2" style={{ marginBottom: 24 }}>Got a code?</h2>
            <input className="t-field t-code-field" value={code} maxLength={6} placeholder="•••••"
              autoCapitalize="characters" inputMode="text"
              onChange={(e) => setCode(e.target.value.toUpperCase().replace(/\s/g, ""))}
              onKeyDown={(e) => e.key === "Enter" && continueCode()} />
            {error && <p style={{ color: "#ff9aa0", fontWeight: 700, marginTop: 14, fontSize: ".9rem" }}>{error}</p>}
            <div style={{ flex: 1 }} />
            <button className="t-btn t-btn--gold" disabled={code.trim().length < 4} onClick={continueCode}>Continue</button>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <p className="t-eyebrow">Castle {code.toUpperCase()}</p>
            <h2 className="t-h2" style={{ marginBottom: 24 }}>What's your name?</h2>
            <input className="t-field" value={name} maxLength={40} placeholder="Your name"
              autoFocus onChange={(e) => setName(e.target.value)} onKeyDown={(e) => e.key === "Enter" && doJoin()} />
            {error && <p style={{ color: "#ff9aa0", fontWeight: 700, marginTop: 14, fontSize: ".9rem" }}>{error}</p>}
            <div style={{ flex: 1 }} />
            <button className="t-btn t-btn--gold" disabled={busy || !name.trim()} onClick={doJoin}>
              {busy ? "Entering…" : "Take my seat"}
            </button>
          </React.Fragment>
        )}
      </div>
    );
  }

  Object.assign(window, { HomeScreen, HostCreateScreen, JoinScreen });
})();
