const ROUTES = ["landing","tutorial","signup","subscription","dashboard"];
const ROUTE_LABELS = {
  "landing":      "Home",
  "tutorial":     "Setup",
  "signup":       "API sign in",
  "subscription": "Choose plan",
  "dashboard":    "Dashboard",
};

function App() {
  const [screen, setScreen] = React.useState(() => {
    const h = location.hash.replace("#", "");
    return ROUTES.includes(h) ? h : "landing";
  });
  const [user, setUser]       = React.useState(null);
  const [plan, setPlan]       = React.useState(null);
  const [toasts, setToasts]   = React.useState([]);

  // Restore session from stored JWT
  React.useEffect(() => {
    const token = localStorage.getItem("cc_token");
    if (!token) return;
    fetch("/api/me", { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (d?.id) {
          setUser(d);
          setPlan(d.plan !== "free" ? d.plan : null);
          const cur = location.hash.replace("#", "");
          if (!cur || cur === "landing" || cur === "signup") setScreen("dashboard");
        }
      })
      .catch(() => {});
  }, []);

  // hash + title sync
  React.useEffect(() => {
    location.hash = screen;
    document.title = `WiserGuy · ${ROUTE_LABELS[screen] || screen}`;
  }, [screen]);

  const goto = (s) => setScreen(s);

  const addToast = (msg, kind = "ok") => {
    const id = Date.now() + Math.random();
    setToasts(prev => [...prev, { id, msg, kind }]);
    setTimeout(() => setToasts(prev => prev.filter(x => x.id !== id)), 3500);
  };

  const isApp = screen === "dashboard";

  const screenEl = (() => {
    switch (screen) {
      case "landing":      return <Landing goto={goto} />;
      case "tutorial":     return <Tutorial goto={goto} />;
      case "signup":       return <Signup goto={goto} signIn={setUser} />;
      case "subscription": return <Subscription goto={goto} plan={plan} setPlan={setPlan} />;
      case "dashboard":    return <Dashboard user={user} plan={plan || user?.plan || "free"} goto={goto} addToast={addToast} />;
      default:             return <Landing goto={goto} />;
    }
  })();

  return (
    <div className={"app" + (isApp ? "" : " no-topbar")}>
      {/* Background: body::before (stake tile), body::after (vignette), and
          the route-specific .landing-bg layer carry the full look. The old
          .bg-stage / .bg-noise overlays were duplicating that work and the
          brutalist theme's .bg-noise had a typo making vertical lines way too
          dark — visible stripes over everything. Removed. */}

      {/* Topbar only shows inside the admin app (logged in). Landing /
          signup pages add the .no-topbar class above so the .app grid
          collapses to a single row — without it the main content
          collapses into the 72px topbar-row gap. */}
      {isApp && (
        <header className="topbar">
          <div className="brand">
            <span className="brand-mark">WG</span>
          </div>
          <nav>
            <button className="active">{user?.is_admin ? "Ops" : user?.can_submit_codes ? "Submitter" : "Workspace"}</button>
          </nav>
          <div className="top-spacer"></div>
          <div className="topbar-right">
            <Pill kind="live" dot>live</Pill>
            <span className="row" style={{ gap: 8 }}>
              <span style={{ width: 28, height: 28, borderRadius: 999, background: "var(--accent)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 12 }}>
                {(user?.username || "U").slice(0,1).toUpperCase()}
              </span>
              <span style={{ fontSize: 13, fontWeight: 600 }}>{user?.username || "—"}</span>
            </span>
            <Btn sm kind="ghost" onClick={() => { localStorage.removeItem("cc_token"); setUser(null); setPlan(null); goto("landing"); }}>
              Sign out
            </Btn>
          </div>
        </header>
      )}

      <main className="stage">
        <div key={screen} className="screen-in">
          {screenEl}
        </div>
      </main>

      <div className="toast-wrap">
        {toasts.map(tt => (
          <Toast key={tt.id} kind={tt.kind}>
            <Icon name="check" style={{ color: "var(--ok)" }} />
            <span>{tt.msg}</span>
          </Toast>
        ))}
      </div>
    </div>
  );
}

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