import { useEffect, useState, Suspense, lazy } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { TOKEN_KEY } from "./api";

const Profile = lazy(() => import("./Profile"));
const HackGame = lazy(() => import("./HackGame"));
const AdminDashboard = lazy(() => import("./AdminDashboard"));

function AuthHandler({ children }: { children: React.ReactNode }) {
  const [isProcessing, setIsProcessing] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    const hash = window.location.hash;
    if (hash.includes("token=")) {
      const params = new URLSearchParams(hash.replace("#", "?"));
      const token = params.get("token");
      if (token) {
        localStorage.setItem(TOKEN_KEY, token);
        window.history.replaceState(null, "", window.location.pathname);
      }
    }

    if (localStorage.getItem(TOKEN_KEY)) {
      setIsAuthenticated(true);
    }
    setIsProcessing(false);
  }, []);

  if (isProcessing) {
    return (
      <div className="flex h-full w-full items-center justify-center bg-[#05050A]">
        <span className="text-secondary animate-pulse font-mono tracking-widest text-sm uppercase">
          Инициализация защищенного соединения...
        </span>
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="flex h-full w-full items-center justify-center bg-[#05050A] font-mono">
        <h1 className="text-[#FF003C] text-xl tracking-widest uppercase animate-pulse drop-shadow-[0_0_15px_rgba(255,0,60,0.5)]">
          [ERROR] UNAUTHORIZED ACCESS
        </h1>
      </div>
    );
  }

  return (
    <div className="relative h-full w-full overflow-hidden bg-black">
      <Suspense
        fallback={
          <div className="flex items-center justify-center h-full text-secondary font-mono">
            Загрузка модулей...
          </div>
        }
      >
        {children}
      </Suspense>
    </div>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthHandler>
        <Routes>
          <Route path="/" element={<Profile />} />
          <Route path="/profile" element={<Profile />} />
          <Route path="/hack" element={<HackGame />} />
          <Route path="/admin" element={<AdminDashboard />} />
        </Routes>
      </AuthHandler>
    </BrowserRouter>
  );
}
