import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import NotFound from "@/pages/NotFound";
import { Router, Route, Switch } from "wouter";
import ErrorBoundary from "./components/ErrorBoundary";
import { ThemeProvider } from "./contexts/ThemeContext";
import DashboardLayout from "./components/DashboardLayout";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Register from "./pages/Register";
import ForgotPassword from "./pages/ForgotPassword";
import ResetPassword from "./pages/ResetPassword";
import AgentDashboard from "./pages/AgentDashboard";
import WorkflowDesigner from "./pages/WorkflowDesigner";
import UserManagement from "./pages/UserManagement";
import AcceptInvite from "./pages/AcceptInvite";
import Playground from "./pages/Playground";
import Analytics from "./pages/Analytics";
import DataSources from "./pages/DataSources";

function AppRoutes() {
  return (
    <Switch>
      {/* Public pages */}
      <Route path={"/"} component={Home} />
      <Route path={"/login"} component={Login} />
      <Route path={"/register"} component={Register} />
      <Route path={"/forgot-password"} component={ForgotPassword} />
      <Route path={"/reset-password/:token"} component={ResetPassword} />
      <Route path="/invite/:token" component={AcceptInvite} />

      {/* Protected pages — DashboardLayout handles auth gating */}
      <Route path={"/dashboard"}>
        <DashboardLayout requiredRole="agent">
          <AgentDashboard />
        </DashboardLayout>
      </Route>
      <Route path={"/dashboard/users"}>
        <DashboardLayout requiredRole="admin">
          <UserManagement />
        </DashboardLayout>
      </Route>
      <Route path={"/workflow-designer"}>
        <DashboardLayout requiredRole="admin">
          <WorkflowDesigner />
        </DashboardLayout>
      </Route>
      <Route path={"/playground"}>
        <DashboardLayout requiredRole="agent">
          <Playground />
        </DashboardLayout>
      </Route>
      <Route path={"/analytics"}>
        <DashboardLayout requiredRole="admin">
          <Analytics />
        </DashboardLayout>
      </Route>
      <Route path={"/data-sources"}>
        <DashboardLayout requiredRole="admin">
          <DataSources />
        </DashboardLayout>
      </Route>

      <Route path={"/404"} component={NotFound} />
      {/* Final fallback route */}
      <Route component={NotFound} />
    </Switch>
  );
}

function App() {
  return (
    <ErrorBoundary>
      <ThemeProvider defaultTheme="light">
        <TooltipProvider>
          <Toaster />
          <Router base="/chat">
            <AppRoutes />
          </Router>
        </TooltipProvider>
      </ThemeProvider>
    </ErrorBoundary>
  );
}

export default App;
