const ROUTES = ["landing","signup","subscription","api-setup","ext-install","dashboard"];
const ROUTE_LABELS = {
  "landing":      "Home",
  "signup":       "Sign up",
  "subscription": "Choose plan",
  "api-setup":    "API setup",
  "ext-install":  "Extension",
  "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 [path, setPath]       = React.useState(null);
  const [apiState, setApiState]   = React.useState(null);
  const [extState, setExtState]   = 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 = `Stake Sauce · ${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} selectPath={setPath} />;
      case "signup":       return <Signup goto={goto} signIn={setUser} />;
      case "api-setup":    return <ApiSetup goto={goto} path={path} apiState={apiState} setApiState={setApiState} />;
      case "ext-install":  return <ExtInstall goto={goto} path={path} extState={extState} setExtState={setExtState} />;
      case "subscription": return <Subscription goto={goto} path={path} plan={plan} setPlan={setPlan} />;
      case "dashboard":    return <Dashboard user={user} path={path || "api"} plan={plan || user?.plan || "free"} goto={goto} addToast={addToast} />;
      default:             return <Landing goto={goto} selectPath={setPath} />;
    }
  })();

  return (
    <div className="app">
      {/* Background: body::before (steak 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. */}

      <header className="topbar">
        <div className="brand">
          <span className="brand-mark">SS</span>
          <span>Stake&nbsp;Sauce</span>
        </div>
        {!isApp ? (
          <nav>
            <button className={screen === "landing" ? "active" : ""} onClick={() => goto("landing")}>Home</button>
            <button onClick={() => goto("signup")}>Pricing</button>
          </nav>
        ) : (
          <nav>
            <button className="active">Workspace</button>
          </nav>
        )}
        <div className="top-spacer"></div>
        <div className="topbar-right">
          {isApp ? (
            <>
              <Pill kind="live" dot>live</Pill>
              <span className="row" style={{ gap: 8 }}>
                <span style={{ width: 28, height: 28, borderRadius: 999, background: "var(--accent)", color: "#0f0c0a", 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>
            </>
          ) : (
            <>
              {screen !== "signup" && screen !== "landing" && (
                <Btn sm kind="ghost" onClick={() => goto("landing")}>Exit</Btn>
              )}
              {screen === "landing" && (
                <>
                  <Btn sm kind="ghost" onClick={() => goto("signup")}>Sign in</Btn>
                  <Btn sm kind="primary" onClick={() => goto("signup")}>Get started</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 />);
