import { type ReactNode, useEffect, useState } from "react";
import {
  NavLink,
  Navigate,
  Route,
  Routes,
  useLocation,
} from "react-router-dom";
import { apiFetch, clearSession, getToken, getUsername } from "./api";
import LoginPage from "./pages/Login";
import MonitorPage from "./pages/Monitor";
import SettingsPage from "./pages/Settings";

function Shell({ children }: { children: ReactNode }) {
  const user = getUsername();
  const [lanClient, setLanClient] = useState(false);

  useEffect(() => {
    apiFetch<{ lan_client?: boolean }>("/api/auth/me")
      .then((m) => setLanClient(!!m.lan_client))
      .catch(() => setLanClient(false));
  }, []);

  return (
    <div className="shell">
      <header className="header">
        <div className="brand">比特骆驼中控</div>
        <nav className="nav">
          <NavLink to="/monitor" className={({ isActive }) => (isActive ? "active" : "")}>
            监控区
          </NavLink>
          <NavLink to="/settings" className={({ isActive }) => (isActive ? "active" : "")}>
            系统设置
          </NavLink>
        </nav>
        {!lanClient ? (
          <div className="header-right">
            <span className="meta">{user}</span>
            <button
              type="button"
              className="btn ghost"
              onClick={() => {
                clearSession();
                window.location.href = "/login";
              }}
            >
              退出
            </button>
          </div>
        ) : null}
      </header>
      <main className="main">{children}</main>
    </div>
  );
}

/** 监控页保活：切设置不断 SSE、不丢卡片状态 */
function AuthedPages() {
  const loc = useLocation();
  const onMonitor =
    loc.pathname === "/" ||
    loc.pathname === "/monitor" ||
    loc.pathname.startsWith("/monitor/");
  const onSettings =
    loc.pathname === "/settings" || loc.pathname.startsWith("/settings/");
  return (
    <Shell>
      <div className={onMonitor ? "page-pane" : "page-pane hidden"} aria-hidden={!onMonitor}>
        <MonitorPage />
      </div>
      <div className={onSettings ? "page-pane" : "page-pane hidden"} aria-hidden={!onSettings}>
        <SettingsPage />
      </div>
      {!onMonitor && !onSettings ? <Navigate to="/monitor" replace /> : null}
    </Shell>
  );
}

function RequireAuth({ children }: { children: ReactNode }) {
  if (!getToken()) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/*"
        element={
          <RequireAuth>
            <AuthedPages />
          </RequireAuth>
        }
      />
    </Routes>
  );
}
