import React, { useEffect, useState } from "react";
import { Routes, Route } from "react-router-dom";
import { useApp } from "./store";
import { getMe } from "./api";
import * as streamManager from "./streamManager";
import LoginPage from "./pages/LoginPage";
import ChatPage from "./pages/ChatPage";
import AdminPage from "./pages/AdminPage";
import KnowledgePage from "./pages/KnowledgePage";
import GitLabPage from "./pages/GitLabPage";
import { Flame } from "lucide-react";

export default function App() {
  const { state, dispatch } = useApp();
  const [authChecked, setAuthChecked] = useState(!state.token);

  useEffect(() => { streamManager.setDispatch(dispatch); }, [dispatch]);

  useEffect(() => {
    if (!state.token) { setAuthChecked(true); return; }
    if (state.user) { setAuthChecked(true); return; }
    (async () => {
      try {
        const user = await getMe(state.token);
        dispatch({ type: "SET_USER", user });
      } catch { dispatch({ type: "LOGOUT" }); }
      finally { setAuthChecked(true); }
    })();
  }, [state.token, state.user, dispatch]);

  if (!authChecked) {
    return (
      <div className="h-dvh flex items-center justify-center bg-anton-bg">
        <div className="flex flex-col items-center gap-4 animate-fade-in">
          <div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-anton-accent to-red-600 flex items-center justify-center shadow-lg shadow-anton-accent/20">
            <Flame size={32} className="text-white animate-pulse" />
          </div>
          <p className="text-anton-muted text-sm">Loading...</p>
        </div>
      </div>
    );
  }

  if (!state.token) return <LoginPage />;

  return (
    <Routes>
      <Route path="/admin" element={<AdminPage />} />
      <Route path="/knowledge" element={<KnowledgePage />} />
      <Route path="/gitlab" element={<GitLabPage />} />
      <Route path="/*" element={<ChatPage />} />
    </Routes>
  );
}