// App v1.5 - JWT Migration Final Check
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';
import { SystemSettingsProvider } from './context/SystemSettingsContext';
import { NotificationProvider } from './contexts/NotificationContext';
import { Layout } from './components/Layout';
import { ProtectedRoute } from './components/ProtectedRoute';
import { ToastProvider } from './components/Toast';
import { ProjectList } from './pages/ProjectList';
import { ProjectDetails } from './pages/ProjectDetails';
import { SchemesList } from './pages/SchemesList';
import { InspectionsList } from './pages/InspectionsList';
import { DataSheetLibrary } from './pages/DataSheetLibrary';
import { YieldStudyDashboard } from './pages/YieldStudyDashboard';
import { AdminDashboard } from './pages/AdminDashboard';
import { DeveloperDashboard } from './pages/DeveloperDashboard';
import { CalculatorDashboard } from './pages/CalculatorDashboard';
import { StockDashboard } from './pages/StockDashboard';
import { GuestDashboard } from './pages/GuestDashboard';
import { Login } from './pages/Login';
import { OrganizationSelector } from './pages/OrganizationSelector';
import InstrumentList from './pages/InstrumentList';

const DeveloperRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isDeveloper, isLoading } = useAuth();

  if (isLoading) return null;
  if (!isDeveloper()) return <Navigate to="/" replace />;

  return <>{children}</>;
};

const AppContent: React.FC = () => {
  const { appUser, isLoading } = useAuth();
  
  if (isLoading) return <div className="flex h-screen items-center justify-center">Carregando...</div>;

  // AppUser exists but hasn't selected an org yet (if your business logic requires orgs)
  if (appUser && !appUser.organizationId) {
    return <OrganizationSelector />;
  }

  return (
    <Layout>
      <Routes>
        <Route path="/" element={<ProjectList />} />
        <Route path="/guest-dashboard" element={<GuestDashboard />} />
        <Route path="/projects" element={<ProjectList />} />
        <Route path="/project/:id" element={<ProjectDetails />} />
        <Route path="/schemes" element={<SchemesList />} />
        <Route path="/inspections" element={<InspectionsList />} />
        <Route path="/library" element={
          <ProtectedRoute allowedRoles={['user', 'admin']}>
            <DataSheetLibrary />
          </ProtectedRoute>
        } />
        <Route path="/instruments" element={
          <ProtectedRoute allowedRoles={['user', 'admin', 'guest']}>
            <InstrumentList />
          </ProtectedRoute>
        } />
        <Route path="/yield-study" element={
          <ProtectedRoute allowedRoles={['user', 'admin']}>
            <YieldStudyDashboard />
          </ProtectedRoute>
        } />
        <Route path="/calculators" element={<CalculatorDashboard />} />
        <Route
          path="/admin"
          element={
            <ProtectedRoute allowedRoles={['admin']}>
              <AdminDashboard />
            </ProtectedRoute>
          }
        />
        <Route
          path="/stock"
          element={
            <ProtectedRoute allowedRoles={['user', 'admin', 'guest']}>
              <StockDashboard />
            </ProtectedRoute>
          }
        />
        <Route
          path="/developer"
          element={
            <DeveloperRoute>
              <DeveloperDashboard />
            </DeveloperRoute>
          }
        />
      </Routes>
    </Layout>
  );
};

const MainRouter: React.FC = () => {
  const { appUser, isLoading } = useAuth();
  
  if (isLoading) {
      return <div className="flex h-screen items-center justify-center">Verificando sessão...</div>;
  }

  return (
      <Router>
        {!appUser ? (
            <Login />
        ) : (
            <AppContent />
        )}
      </Router>
  );
};

function App() {
  return (
    <ToastProvider>
      <AuthProvider>
        <SystemSettingsProvider>
          <NotificationProvider>
             <MainRouter />
          </NotificationProvider>
        </SystemSettingsProvider>
      </AuthProvider>
    </ToastProvider>
  );
}

export default App;
