import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";
import "./index.css";
import { ThemeProvider, useTheme } from "./theme";
import { LoginPage } from "./pages/LoginPage";
import { HomePage } from "./pages/HomePage";
import { BandPage } from "./pages/BandPage";
import { SongPage } from "./pages/SongPage";
import { SettingsPage } from "./pages/SettingsPage";
import { InvitePage } from "./pages/InvitePage";

const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
});

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const token = localStorage.getItem("rh_token");
  return token ? <>{children}</> : <Navigate to="/login" replace />;
}

function ThemeToggle() {
  const { theme, toggle } = useTheme();
  return (
    <button
      onClick={toggle}
      title={`Switch to ${theme === "dark" ? "light" : "dark"} mode`}
      style={{
        position: "fixed",
        bottom: 20,
        right: 20,
        zIndex: 9999,
        background: "var(--bg-subtle)",
        border: "1px solid var(--border)",
        borderRadius: "50%",
        width: 36,
        height: 36,
        cursor: "pointer",
        fontSize: 16,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: "var(--text-muted)",
        boxShadow: "0 2px 8px rgba(0,0,0,0.3)",
      }}
    >
      {theme === "dark" ? "☀" : "◑"}
    </button>
  );
}

export default function App() {
  return (
    <ThemeProvider>
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <Routes>
            <Route path="/login" element={<LoginPage />} />
            <Route
              path="/bands/:bandId"
              element={
                <PrivateRoute>
                  <BandPage />
                </PrivateRoute>
              }
            />
            <Route
              path="/bands/:bandId/songs/:songId"
              element={
                <PrivateRoute>
                  <SongPage />
                </PrivateRoute>
              }
            />
            <Route
              path="/settings"
              element={
                <PrivateRoute>
                  <SettingsPage />
                </PrivateRoute>
              }
            />
            <Route path="/invite/:token" element={<InvitePage />} />
            <Route path="/" element={<PrivateRoute><HomePage /></PrivateRoute>} />
          </Routes>
          <ThemeToggle />
        </BrowserRouter>
      </QueryClientProvider>
    </ThemeProvider>
  );
}
