// Main app shell — single brand (Stadium) with dark/light toggle.
// Screens: landing → profile-form → dashboard → analysis|map|list|player → (IAMGPT overlays any screen)

function App() {
  const [mode, setMode] = useState(() => localStorage.getItem("ias.mode") || "light");
  const [screen, setScreen] = useState(() => localStorage.getItem("ias.screen") || "landing");
  const [playerId, setPlayerId] = useState(() => {
    const v = localStorage.getItem("ias.playerId");
    return v ? Number(v) : null;
  });
  const [profile, setProfile] = useState(() => {
    try { return JSON.parse(localStorage.getItem("ias.profile")) || DEFAULT_PROFILE(); }
    catch { return DEFAULT_PROFILE(); }
  });
  const [editMode, setEditMode] = useState(false);
  const [gptOpen, setGptOpen] = useState(false);

  useEffect(() => {
    document.documentElement.setAttribute("data-mode", mode);
    localStorage.setItem("ias.mode", mode);
  }, [mode]);
  useEffect(() => { localStorage.setItem("ias.screen", screen); }, [screen]);
  useEffect(() => {
    if (playerId != null) localStorage.setItem("ias.playerId", String(playerId));
  }, [playerId]);
  useEffect(() => { localStorage.setItem("ias.profile", JSON.stringify(profile)); }, [profile]);

  // Supabase sync: on mount, hydrate profile from the server if signed in.
  // On every change, debounce-save to the server.
  const authedRef = useRef(null);
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const s = await fetch("/api/session", { cache: "no-store" }).then(r => r.json());
        if (cancelled) return;
        authedRef.current = !!s.email;
        if (!s.email) return;
        const resp = await fetch("/api/club-profile", { cache: "no-store" });
        if (!resp.ok) return;
        const { profile: serverProfile } = await resp.json();
        if (cancelled || !serverProfile) return;
        // Only overwrite if the server has meaningful data (name present).
        if (serverProfile.name && serverProfile.name !== "Untitled Club") {
          setProfile(prev => ({ ...prev, ...serverProfile }));
        }
      } catch {
        // Offline / unauth — localStorage already populated the state.
      }
    })();
    return () => { cancelled = true; };
  }, []);
  useEffect(() => {
    if (!authedRef.current) return;
    const t = setTimeout(() => {
      fetch("/api/club-profile", {
        method: "PUT",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(profile),
      }).catch(() => { /* keep localStorage only on failure */ });
    }, 800);
    return () => clearTimeout(t);
  }, [profile]);

  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === "__activate_edit_mode") setEditMode(true);
      if (e.data?.type === "__deactivate_edit_mode") setEditMode(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const openPlayer = (id) => { setPlayerId(id); setScreen("player"); };
  const nav = (s) => {
    if (s === "iamgpt") { setGptOpen(true); return; }
    setScreen(s);
  };

  // Build GPT context
  const gptContext = (() => {
    if (screen === "player" && playerId != null) {
      return { screen: "player", player: window.IAMS_DATA.findPlayer(playerId) };
    }
    return { screen };
  })();

  const screenEl = (() => {
    if (screen === "landing")      return <Landing onStart={() => setScreen("profile-form")} />;
    if (screen === "profile-form") return <ClubProfile profile={profile} onChange={setProfile} onDone={() => setScreen("dashboard")} />;
    if (screen === "dashboard")    return <Dashboard profile={profile} onNav={nav} onOpenPlayer={openPlayer} />;
    if (screen === "analysis")     return <ClubAnalysis profile={profile} onOpenPlayer={openPlayer} onNav={nav} />;
    if (screen === "map")          return <MapScreen profile={profile} onOpenPlayer={openPlayer} onNav={nav} />;
    if (screen === "list")         return <ListScreen profile={profile} onOpenPlayer={openPlayer} onNav={nav} />;
    if (screen === "shadow")       return <ShadowTeam profile={profile} onOpenPlayer={openPlayer} onNav={nav} />;
    if (screen === "camelot")      return <CamelotScreen profile={profile} onOpenPlayer={openPlayer} onNav={nav} />;
    if (screen === "player")       return <PlayerScreen id={playerId} onBack={() => setScreen("analysis")} profile={profile} />;
    if (screen === "profile")      return <ClubProfile profile={profile} onChange={setProfile} onDone={() => setScreen("dashboard")} />;
    return null;
  })();

  const showChrome = ["dashboard", "analysis", "map", "list", "shadow", "camelot", "player", "profile"].includes(screen);
  const chromeActive =
    screen === "player" ? "analysis" :
    screen === "profile-form" ? "profile" :
    screen;

  return (
    <div className="app-shell">
      <ModeSwitcher mode={mode} setMode={setMode} screen={screen} setScreen={setScreen} />
      {showChrome && <AppChrome screen={chromeActive} onNav={nav} clubName={profile.name} />}
      <main>{screenEl}</main>

      {/* IAMGPT floating launcher + panel (hidden on landing/profile-form) */}
      {showChrome && (
        <>
          {!gptOpen && (
            <button className="iamgpt-fab" onClick={() => setGptOpen(true)} title="Ask IAMGPT">
              <span style={{ fontFamily: "var(--mono)", fontWeight: 700, fontSize: 12, letterSpacing: "0.08em" }}>GPT</span>
              <span style={{ marginLeft: 8, fontSize: 13 }}>Ask IAMGPT</span>
            </button>
          )}
          <IamGpt
            open={gptOpen}
            onClose={() => setGptOpen(false)}
            context={gptContext}
            profile={profile}
            onOpenPlayer={openPlayer}
            onNav={nav}
          />
        </>
      )}

      {editMode && (
        <Tweaks
          mode={mode} setMode={setMode}
          profile={profile} setProfile={setProfile}
          onClose={() => setEditMode(false)}
        />
      )}
    </div>
  );
}

function DEFAULT_PROFILE() {
  // BVB 2025 — the worked example from the IAMS spec.
  return {
    name: "Borussia Dortmund",
    country: "Germany",
    league: "Bundesliga",
    tier: "1",
    budget: "high",
    philosophy: "pressing",
    philoFree: "",
    styleTags: ["pressing", "vertical", "transition"],
    lang1: "German",
    lang2: "English",
    goal: "gap",
    gapPos: null,
  };
}

function ModeSwitcher({ mode, setMode, screen, setScreen }) {
  const screens = [
    { id: "landing",      label: "01 Landing" },
    { id: "profile-form", label: "02 Profile" },
    { id: "dashboard",    label: "03 Dashboard" },
    { id: "analysis",     label: "04 Analysis" },
    { id: "map",          label: "05 Map" },
    { id: "list",         label: "06 Shortlist" },
    { id: "player",       label: "07 Player" },
    { id: "shadow",       label: "08 Shadow Team" },
    { id: "camelot",      label: "09 Camelot" },
  ];
  return (
    <div className="mode-switcher" data-screen-label="00 Nav">
      <span className="label">Mode</span>
      <button className="mode-toggle" onClick={() => setMode(mode === "light" ? "dark" : "light")}
        title="Toggle dark / light">
        <span className="sun">☀</span>
        <span className="dot"/>
        <span className="moon">☾</span>
        <span style={{ marginLeft: 6, color: "var(--ink-dim)" }}>{mode === "light" ? "Grass" : "Volt"}</span>
      </button>
      <span className="spacer"/>
      <span className="label">Jump</span>
      <div className="screens" style={{ display: "flex" }}>
        {screens.map(s => (
          <button key={s.id}
            className={"tab " + (screen === s.id ? "active" : "")}
            onClick={() => { if (s.id === "player") return; setScreen(s.id); }}
            style={s.id === "player" ? { opacity: 0.5, cursor: "default" } : {}}>{s.label}</button>
        ))}
      </div>
    </div>
  );
}

function Tweaks({ mode, setMode, profile, setProfile, onClose }) {
  return (
    <div style={{
      position: "fixed", right: 20, bottom: 20, zIndex: 80,
      width: 320,
      background: "var(--panel)",
      border: "1px solid var(--rule-strong)",
      boxShadow: "0 18px 40px rgba(0,0,0,0.18)",
      padding: 16,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
        <div className="display" style={{ fontSize: 16, fontWeight: 600 }}>Tweaks</div>
        <div style={{ flex: 1 }}/>
        <button className="btn sm ghost" onClick={onClose}>close</button>
      </div>
      <div style={{ display: "grid", gap: 14 }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Mode</div>
          <div className="seg">
            {["light","dark"].map(t => (
              <button key={t} className={mode === t ? "on" : ""} onClick={() => setMode(t)}>{t === "light" ? "Grass / White" : "Pitch / Volt"}</button>
            ))}
          </div>
        </div>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Budget band (live)</div>
          <div className="seg">
            {["low","mid","high","top"].map(b => (
              <button key={b} className={profile.budget === b ? "on" : ""} onClick={() => setProfile({ ...profile, budget: b })}>{b}</button>
            ))}
          </div>
        </div>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Philosophy (live)</div>
          <div className="seg">
            {["possession","pressing","direct","structured","hybrid"].map(p => (
              <button key={p} className={profile.philosophy === p ? "on" : ""} onClick={() => setProfile({ ...profile, philosophy: p })}>{p}</button>
            ))}
          </div>
        </div>
        <div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 6 }}>Scouting goal</div>
          <div className="seg">
            {["short-term","u23","sales","gap"].map(g => (
              <button key={g} className={profile.goal === g ? "on" : ""} onClick={() => setProfile({ ...profile, goal: g })}>{g}</button>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 11, color: "var(--ink-muted)", lineHeight: 1.45 }}>
          Changes apply immediately across the prototype.
        </div>
      </div>
    </div>
  );
}

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