import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import { api } from './api';
import SetupWizard from './components/SetupWizard';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import BoardView from './pages/BoardView';
import UserManagement from './pages/UserManagement';
import EmailSettings from './pages/EmailSettings';
import Layout from './components/Layout';

function ProtectedRoute({ children, adminOnly }) {
  const { user, loading } = useAuth();
  if (loading) return <div className="flex items-center justify-center h-screen"><div className="animate-spin h-8 w-8 border-4 border-brand-500 border-t-transparent rounded-full"></div></div>;
  if (!user) return <Navigate to="/login" />;
  if (adminOnly && user.role !== 'admin') return <Navigate to="/" />;
  return children;
}

function SetupRoute() {
  const { user, loading } = useAuth();
  if (loading) return null;
  if (user) return <Navigate to="/" />;
  return <SetupWrapper />;
}

function SetupWrapper() {
  const [status, setStatus] = React.useState(null);
  const [checking, setChecking] = React.useState(true);

  React.useEffect(() => {
    api.setup.status().then(s => { setStatus(s); setChecking(false); });
  }, []);

  if (checking) return <div className="flex items-center justify-center h-screen"><div className="animate-spin h-8 w-8 border-4 border-brand-500 border-t-transparent rounded-full"></div></div>;
  if (status?.setupComplete) return <Navigate to="/login" />;
  return <SetupWizard status={status} onStatusChange={setStatus} />;
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthProvider>
        <Routes>
          <Route path="/setup" element={<SetupRoute />} />
          <Route path="/login" element={<Login />} />
          <Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
            <Route index element={<Dashboard />} />
            <Route path="board/:id" element={<BoardView />} />
            <Route path="users" element={<ProtectedRoute adminOnly><UserManagement /></ProtectedRoute>} />
            <Route path="email-settings" element={<ProtectedRoute adminOnly><EmailSettings /></ProtectedRoute>} />
          </Route>
        </Routes>
      </AuthProvider>
    </BrowserRouter>
  );
}
