import * as React from 'react';
import { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { getToken } from './api';
import { Layout } from './components/Layout';
import { Login } from './components/Login';
import { ProjectsPage } from './pages/Projects';
import { ProjectPromptsPage } from './pages/ProjectPrompts';
import { AgentsPage } from './pages/Agents';
import { AgentDetailPage } from './pages/AgentDetail';
import { PersonalityDetailPage } from './pages/PersonalityDetail';
import { DashboardPage } from './pages/Dashboard';
import { SkillsPage } from './pages/Skills';
import { SkillDetailPage } from './pages/SkillDetail';
import { ProposalsPage } from './pages/Proposals';
import { ProposalDetailPage } from './pages/ProposalDetail';

export function App(): React.JSX.Element {
  const [tokenPresent, setTokenPresent] = useState(getToken() !== null);

  // Listen for storage changes from other tabs.
  useEffect(() => {
    const onStorage = (): void => setTokenPresent(getToken() !== null);
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);

  if (!tokenPresent) {
    return <Login onLogin={() => setTokenPresent(true)} />;
  }

  return (
    <BrowserRouter basename="/ui">
      <Routes>
        <Route element={<Layout />}>
          <Route path="/" element={<Navigate to="/dashboard" replace />} />
          <Route path="/dashboard" element={<DashboardPage />} />
          <Route path="/projects" element={<ProjectsPage />} />
          <Route path="/projects/:name/prompts" element={<ProjectPromptsPage />} />
          <Route path="/agents" element={<AgentsPage />} />
          <Route path="/agents/:name" element={<AgentDetailPage />} />
          <Route path="/personalities/:id" element={<PersonalityDetailPage />} />
          {/* PR-6: Skills + Proposals UI. */}
          <Route path="/skills" element={<SkillsPage />} />
          <Route path="/skills/:name" element={<SkillDetailPage />} />
          <Route path="/proposals" element={<ProposalsPage />} />
          <Route path="/proposals/:id" element={<ProposalDetailPage />} />
          <Route path="*" element={<Navigate to="/dashboard" replace />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}
