/* App router — 1st C&A: Traitors (Firebase-backed) */
(function () {
  const { useState, useEffect } = React;
  const S = () => window.TraitorsStore;

  /* ---- transient in-app toast (foreground push) ---- */
  function Toast({ toast }) {
    useEffect(() => {
      if (!toast) return;
      const t = setTimeout(() => S().clearToast(), 4200);
      return () => clearTimeout(t);
    }, [toast]);
    if (!toast) return null;
    return (
      <div className="t-enter" style={{
        position: "fixed", top: "calc(10px + env(safe-area-inset-top))", left: 12, right: 12, zIndex: 60,
        maxWidth: 496, margin: "0 auto", background: "linear-gradient(180deg,var(--t-panel2),var(--t-panel))",
        border: "1px solid var(--t-gold-dim)", borderRadius: "var(--t-r-md)", padding: "12px 16px",
        boxShadow: "0 12px 40px rgba(0,0,0,.6)",
      }} onClick={() => S().clearToast()}>
        <div style={{ fontWeight: 900, color: "var(--t-gold)", fontSize: ".95rem" }}>{toast.title}</div>
        {toast.body && <div className="t-body" style={{ fontSize: ".88rem", marginTop: 2 }}>{toast.body}</div>}
      </div>
    );
  }

  /* ---- install nudge (unlocks notifications, esp. on iOS) ---- */
  function InstallBanner() {
    const [, force] = useState(0);
    useEffect(() => {
      const h = () => force((n) => n + 1);
      window.addEventListener("pwa-install-changed", h);
      return () => window.removeEventListener("pwa-install-changed", h);
    }, []);
    const I = window.Install;
    if (!I || I.isStandalone() || I.dismissed()) return null;
    const canPrompt = I.canPrompt();
    const ios = I.isIOS();
    return (
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "11px 16px calc(11px + env(safe-area-inset-top))",
        background: "linear-gradient(180deg, var(--t-panel2), var(--t-panel))",
        borderBottom: "1px solid var(--t-gold-dim)",
      }}>
        <span style={{ fontSize: "1.3rem" }}>📲</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 900, color: "var(--t-gold)", fontSize: ".84rem" }}>Install for alerts</div>
          <div className="t-body" style={{ fontSize: ".76rem", marginTop: 1 }}>
            {canPrompt
              ? "Add Traitors to your home screen to get buzzed when it's your turn — even on a locked phone."
              : ios
                ? "Tap Share ⬆ then “Add to Home Screen”, and open it from there for alerts."
                : "Use your browser menu → “Install app” / “Add to Home Screen” for alerts."}
          </div>
        </div>
        {canPrompt && (
          <button className="t-btn t-btn--gold t-btn--sm" style={{ width: "auto", flex: "0 0 auto" }} onClick={() => I.prompt()}>Install</button>
        )}
        <button onClick={() => I.dismiss()} aria-label="Dismiss" style={{
          appearance: "none", border: 0, background: "transparent", color: "var(--t-fg3)",
          fontSize: "1.3rem", lineHeight: 1, cursor: "pointer", padding: "0 2px", flex: "0 0 auto",
        }}>×</button>
      </div>
    );
  }

  /* ---- connection state strip ---- */
  function OfflineBanner({ online }) {
    if (online) return null;
    return (
      <div style={{
        position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 55, textAlign: "center",
        padding: "7px 12px calc(7px + env(safe-area-inset-bottom))", background: "var(--t-traitor-deep)",
        color: "#ffd9dc", fontSize: ".76rem", fontWeight: 800, letterSpacing: ".06em",
      }}>
        ⚠ Offline — your taps are saved and will send when wifi returns
      </div>
    );
  }

  function Splash({ label }) {
    return (
      <div className="t-screen t-center" style={{ gap: 16 }}>
        <div style={{ display: "flex", gap: 12 }}><Candle scale={1.2} /><Candle scale={1.5} /><Candle scale={1.2} /></div>
        <p className="t-kicker">{label || "Lighting the candles…"}</p>
      </div>
    );
  }

  function LostSession() {
    return (
      <div className="t-screen t-center" style={{ gap: 14 }}>
        <Candle scale={1.4} />
        <h2 className="t-h2">The castle is dark</h2>
        <p className="t-body" style={{ maxWidth: 300 }}>
          This game has ended or you were removed. Head back to the doors.
        </p>
        <button className="t-btn t-btn--gold" style={{ maxWidth: 320 }} onClick={() => S().leave()}>Back to start</button>
      </div>
    );
  }

  function App() {
    const [snap, setSnap] = useState(() => S().snapshot());
    const [route, setRoute] = useState("home");
    useEffect(() => S().subscribe(setSnap), []);

    const { ready, session, game, me, isGM, myRole, lost } = snap;

    let view;
    if (!ready) {
      view = <Splash />;
    } else if (!session) {
      if (route === "host") view = <HostCreateScreen back={() => setRoute("home")} />;
      else if (route === "join") view = <JoinScreen back={() => setRoute("home")} />;
      else view = <HomeScreen go={setRoute} />;
    } else if (lost) {
      view = <LostSession />;
    } else if (!game) {
      view = <Splash label="Reconnecting to the castle…" />;
      // if still no game after a moment, the snapshot stays null — offer a way out
    } else if (isGM) {
      view = game.status === "lobby"
        ? <HostLobby snap={snap} />
        : <HostControl snap={snap} />;
    } else if (!me) {
      view = <LostSession />;
    } else if (game.status === "lobby") {
      view = <PlayerLobby snap={snap} />;
    } else if (myRole && !me.hasSeenRole) {
      view = <RoleReveal snap={snap} />;
    } else {
      view = <PlayerApp snap={snap} />;
    }

    return (
      <React.Fragment>
        <Room />
        <Toast toast={snap.toast} />
        <div className="t-app">
          <InstallBanner />
          {view}
        </div>
        <OfflineBanner online={snap.online} />
      </React.Fragment>
    );
  }

  ReactDOM.createRoot(document.getElementById("root")).render(<App />);

  // register the combined service worker (offline shell + push)
  if ("serviceWorker" in navigator) {
    window.addEventListener("load", () => navigator.serviceWorker.register("sw.js").catch(() => {}));
  }
})();
