import { type ReactNode } from "react";
import { NavLink, Navigate, Route, Routes } from "react-router-dom";
import { 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();
  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>
        <div className="header-right">
          <span className="meta">{user}</span>
          <button
            type="button"
            className="btn ghost"
            onClick={() => {
              clearSession();
              window.location.href = "/login";
            }}
          >
            退出
          </button>
        </div>
      </header>
      <main className="main">{children}</main>
    </div>
  );
}

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

export default function App() {
  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route
        path="/monitor"
        element={
          <RequireAuth>
            <MonitorPage />
          </RequireAuth>
        }
      />
      <Route
        path="/settings"
        element={
          <RequireAuth>
            <SettingsPage />
          </RequireAuth>
        }
      />
      <Route path="/" element={<Navigate to="/monitor" replace />} />
      <Route path="*" element={<Navigate to="/monitor" replace />} />
    </Routes>
  );
}
