import { Toaster } from "@/components/ui/toaster"
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClientInstance } from '@/lib/query-client'
import { BrowserRouter as Router, Navigate, Route, Routes } from 'react-router-dom';
import PageNotFound from './lib/PageNotFound';
import { AuthProvider, useAuth } from '@/lib/AuthContext';
import UserNotRegisteredError from '@/components/UserNotRegisteredError';
import ScrollToTop from './components/ScrollToTop';
import ProtectedRoute from '@/components/ProtectedRoute';
import Login from '@/pages/Login';
import Register from '@/pages/Register';
import ForgotPassword from '@/pages/ForgotPassword';
import ResetPassword from '@/pages/ResetPassword';
import WorkshopLayout from '@/components/workshop/WorkshopLayout';
import Dashboard from '@/pages/Dashboard';
import Customers from '@/pages/Customers';
import CustomerDetail from '@/pages/CustomerDetail';
import Projects from '@/pages/Projects';
import Components from '@/pages/Components';
import ComponentDimensions from '@/pages/ComponentDimensions';
import NewCover from '@/pages/NewCover';
import Measurements from '@/pages/Measurements';
import MeasurementSession from '@/pages/MeasurementSession';
import Reports from '@/pages/Reports';
import MigrationReadiness from '@/pages/MigrationReadiness';
import Settings from '@/pages/Settings';
import NotImplemented from '@/pages/NotImplemented';
import ViewportV2Test from '@/pages/ViewportV2Test';
import DesignYourCover from '@/pages/DesignYourCover';
import ProjectDetail from '@/pages/ProjectDetail';
import IntakeRequests from '@/pages/IntakeRequests';
import Quotes from '@/pages/Quotes';
import Orders from '@/pages/Orders';
import OrderDetail from '@/pages/OrderDetail';
import CompletedCovers from '@/pages/CompletedCovers';
import CompletedCoverDetail from '@/pages/CompletedCoverDetail';
import Manufacturing from '@/pages/Manufacturing';
import ManufacturingJobDetail from '@/pages/ManufacturingJobDetail';
import Shipping from '@/pages/Shipping';
import OssiguardLibrary from '@/pages/OssiguardLibrary';
import OssiguardDetail from '@/pages/OssiguardDetail';
import OssiguardWizard from '@/pages/OssiguardWizard';
import DesignForge from '@/pages/DesignForge';
import Validation from '@/pages/Validation';
import { AccountProvider } from '@/lib/AccountContext';
import RoleRouter from '@/components/RoleRouter';
import RoleGuard from '@/components/RoleGuard';
import AdminLayout from '@/components/admin/AdminLayout';
import BuilderLayout from '@/components/builder/BuilderLayout';
import PortalLayout from '@/components/portal/PortalLayout';
import AdminConsole from '@/pages/admin/AdminConsole';
import AdminUsers from '@/pages/admin/AdminUsers';
import AdminUserDetail from '@/pages/admin/AdminUserDetail';
import Invitations from '@/pages/admin/Invitations';
import PermissionMatrix from '@/pages/admin/PermissionMatrix';
import Assignments from '@/pages/admin/Assignments';
import AdminSettings from '@/pages/admin/AdminSettings';
import ReleaseReadiness from '@/pages/admin/ReleaseReadiness';
import NewBuilder from '@/pages/admin/NewBuilder';
import BuilderWorkspace from '@/pages/builder/BuilderWorkspace';
import BuilderProjectDetail from '@/pages/builder/BuilderProjectDetail';
import BuilderTasks from '@/pages/builder/BuilderTasks';
import CustomerPortal from '@/pages/portal/CustomerPortal';
import PortalProject from '@/pages/portal/PortalProject';
import PortalSection from '@/pages/portal/PortalSection';
import PortalDetail from '@/pages/portal/PortalDetail';
import InvitationAccept from '@/pages/InvitationAccept';

const AuthenticatedApp = () => {
  const { isLoadingAuth, isLoadingPublicSettings, authError } = useAuth();

  // Show loading spinner while checking app public settings or auth
  if (isLoadingPublicSettings || isLoadingAuth) {
    return (
      <div className="fixed inset-0 flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"></div>
      </div>
    );
  }

  // Registered accounts only; public auth routes remain reachable when signed out.
  if (authError?.type === 'user_not_registered') return <UserNotRegisteredError />;

  return (
    <AccountProvider>
    <Routes>
      <Route path="/design-your-cover" element={<DesignYourCover />} />
      <Route path="/invitation/:token" element={<InvitationAccept />} />
      <Route path="/login" element={<Login />} />
      <Route path="/register" element={<Register />} />
      <Route path="/forgot-password" element={<ForgotPassword />} />
      <Route path="/reset-password" element={<ResetPassword />} />
      <Route element={<ProtectedRoute unauthenticatedElement={<Navigate to="/login" replace />} />}>
        <Route path="/" element={<RoleRouter />} />
        <Route path="/viewport-v2-test" element={<ViewportV2Test />} />
        <Route element={<RoleGuard roles={['owner_admin','admin','builder']} />}>
          <Route element={<WorkshopLayout />}>
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/customers" element={<Customers />} />
            <Route path="/customers/:uuid" element={<CustomerDetail />} />
            <Route path="/projects" element={<Projects />} />
            <Route path="/projects/:projectId" element={<ProjectDetail />} />
            <Route path="/intake-requests" element={<IntakeRequests />} />
            <Route path="/quotes" element={<Quotes />} />
            <Route path="/orders" element={<Orders />} />
            <Route path="/orders/:orderId" element={<OrderDetail />} />
            <Route path="/completed-covers" element={<CompletedCovers />} />
            <Route path="/completed-covers/:coverId" element={<CompletedCoverDetail />} />
            <Route path="/manufacturing" element={<Manufacturing />} />
            <Route path="/manufacturing/:jobId" element={<ManufacturingJobDetail />} />
            <Route path="/shipping" element={<Shipping />} />
            <Route path="/components" element={<Components />} />
            <Route path="/components/:uuid/dimensions" element={<ComponentDimensions />} />
            <Route path="/ossiguard" element={<OssiguardLibrary />} />
            <Route path="/ossiguard-connectors" element={<OssiguardLibrary />} />
            <Route path="/ossiguard-connectors/new" element={<OssiguardWizard />} />
            <Route path="/ossiguard-connectors/:connectorId/edit" element={<OssiguardWizard />} />
            <Route path="/ossiguard/:uuid" element={<OssiguardDetail />} />
            <Route path="/design-forge" element={<DesignForge />} />
            <Route path="/projects/:projectId/design-forge" element={<DesignForge />} />
            <Route path="/validation" element={<Validation />} />
            <Route path="/projects/:projectId/ossiguard" element={<ProjectDetail />} />
            <Route path="/new-cover" element={<NewCover />} />
            <Route path="/measurements" element={<Measurements />} />
            <Route path="/measurements/:uuid" element={<MeasurementSession />} />
            <Route path="/reports" element={<Reports />} />
            <Route path="/migration-readiness" element={<MigrationReadiness />} />
            <Route path="/settings" element={<Settings />} />
            <Route path="/not-implemented" element={<NotImplemented />} />
          </Route>
        </Route>
        <Route element={<RoleGuard roles={['owner_admin','admin']} />}>
          <Route element={<AdminLayout />}>
            <Route path="/admin" element={<AdminConsole />} />
            <Route path="/admin/users" element={<AdminUsers />} />
            <Route path="/admin/users/new-builder" element={<NewBuilder />} />
            <Route path="/admin/users/:userId" element={<AdminUserDetail />} />
            <Route path="/admin/invitations" element={<Invitations />} />
            <Route path="/admin/permissions" element={<PermissionMatrix />} />
            <Route path="/admin/assignments" element={<Assignments />} />
            <Route path="/admin/settings" element={<AdminSettings />} />
            <Route path="/admin/release-readiness" element={<ReleaseReadiness />} />
          </Route>
        </Route>
        <Route element={<RoleGuard roles={['builder','owner_admin','admin']} />}>
          <Route element={<BuilderLayout />}>
            <Route path="/builder" element={<BuilderWorkspace />} />
            <Route path="/builder/tasks" element={<BuilderTasks />} />
            <Route path="/builder/projects/:projectId" element={<BuilderProjectDetail />} />
          </Route>
        </Route>
        <Route element={<RoleGuard roles={['customer']} />}>
          <Route element={<PortalLayout />}>
            <Route path="/portal" element={<CustomerPortal />} />
            <Route path="/portal/requests" element={<PortalSection section="requests" />} />
            <Route path="/portal/projects/:projectId" element={<PortalProject />} />
            <Route path="/portal/quotes" element={<PortalSection section="quotes" />} />
            <Route path="/portal/quotes/:quoteId" element={<PortalDetail section="quotes" />} />
            <Route path="/portal/orders" element={<PortalSection section="orders" />} />
            <Route path="/portal/orders/:orderId" element={<PortalDetail section="orders" />} />
            <Route path="/portal/shipping" element={<PortalSection section="shipping" />} />
            <Route path="/portal/completed-covers" element={<PortalSection section="completed-covers" />} />
            <Route path="/portal/completed-covers/:coverId" element={<PortalDetail section="completed-covers" />} />
            <Route path="/portal/designs/:designId" element={<PortalDetail section="designs" />} />
            <Route path="/portal/messages" element={<CustomerPortal />} />
            <Route path="/portal/profile" element={<CustomerPortal />} />
          </Route>
        </Route>
      </Route>
      <Route path="*" element={<PageNotFound />} />
    </Routes>
    </AccountProvider>
  );
};


function App() {

  return (
    <AuthProvider>
      <QueryClientProvider client={queryClientInstance}>
        <Router>
          <ScrollToTop />
          <AuthenticatedApp />
        </Router>
        <Toaster />
      </QueryClientProvider>
    </AuthProvider>
  )
}

export default App