import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from './context/AuthContext';
import Layout from './components/Layout';
import Login from './pages/Login';
import Register from './pages/Register';
import SelectOrganization from './pages/SelectOrganization';
import CreateOrganization from './pages/CreateOrganization';
import Dashboard from './pages/Dashboard';
import Issues from './pages/Issues';
import IssueDetail from './pages/IssueDetail';
import Integrations from './pages/Integrations';
import Team from './pages/Team';
import Reports from './pages/Reports';
import Settings from './pages/Settings';

function PrivateRoute({ children }) {
    const { user, loading } = useAuth();
    if (loading) return <div className="flex items-center justify-center h-screen">Loading...</div>;
    return user ? children : <Navigate to="/login" />;
}

function OrgRoute({ children }) {
    const { user, currentOrg, loading } = useAuth();
    if (loading) return <div className="flex items-center justify-center h-screen">Loading...</div>;
    if (!user) return <Navigate to="/login" />;
    if (!currentOrg) return <Navigate to="/select-organization" />;
    return children;
}

export default function App() {
    return (
        <Routes>
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/select-organization" element={
                <PrivateRoute>
                    <SelectOrganization />
                </PrivateRoute>
            } />
            <Route path="/create-organization" element={
                <PrivateRoute>
                    <CreateOrganization />
                </PrivateRoute>
            } />
            <Route path="/" element={
                <OrgRoute>
                    <Layout />
                </OrgRoute>
            }>
                <Route index element={<Dashboard />} />
                <Route path="issues" element={<Issues />} />
                <Route path="issues/:id" element={<IssueDetail />} />
                <Route path="integrations" element={<Integrations />} />
                <Route path="team" element={<Team />} />
                <Route path="reports" element={<Reports />} />
                <Route path="settings" element={<Settings />} />
            </Route>
        </Routes>
    );
}
