import { Toaster } from "@/components/ui/toaster"
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClientInstance } from '@/lib/query-client'
import { BrowserRouter as Router, 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 { Navigate } from 'react-router-dom';
import ProtectedRoute from '@/components/ProtectedRoute';
import ErrorBoundary from '@/components/ErrorBoundary';

function AppFallback({ error, retry }) {
  return (
    <div className="grid min-h-screen place-items-center bg-[#0a0d12] p-6 text-center text-slate-200">
      <div className="max-w-md">
        <h1 className="font-heading text-xl font-semibold text-white">LimbForge encountered a problem.</h1>
        <p className="mt-2 text-sm text-slate-400">The application hit an unexpected error. You can retry or reload the page.</p>
        <div className="mt-4 flex justify-center gap-2">
          <button onClick={retry} className="btn-primary">Retry</button>
          <button onClick={() => window.location.reload()} className="btn-ghost">Reload page</button>
        </div>
        {import.meta.env?.DEV && (
          <pre className="mt-4 max-h-48 overflow-auto rounded border border-white/10 bg-black/40 p-2 text-left text-[10px] text-red-300">{String(error)}</pre>
        )}
      </div>
    </div>
  );
}
import Login from '@/pages/Login';
import Register from '@/pages/Register';
import ForgotPassword from '@/pages/ForgotPassword';
import ResetPassword from '@/pages/ResetPassword';
import AppShell from '@/components/app/AppShell';
import Dashboard from '@/pages/Dashboard';
import NewProject from '@/pages/NewProject';
import CoverLibrary from '@/pages/CoverLibrary';
import SketchTo3D from '@/pages/SketchTo3D';
import Studio from '@/pages/Studio';
import Validation from '@/pages/Validation';
import Jobs from '@/pages/Jobs';
import Settings from '@/pages/Settings';
import ImageApply from '@/pages/ImageApply';
import PromptForge from '@/pages/PromptForge';
import ProjectHistory from '@/pages/ProjectHistory';
import UniversalDesigns from '@/pages/UniversalDesigns';
import CreateDesign from '@/pages/CreateDesign';
import FitDesign from '@/pages/FitDesign';
import CoverVariants from '@/pages/CoverVariants';
import CompareVariants from '@/pages/CompareVariants';
import UniversalDesignCanvas from '@/pages/UniversalDesignCanvas';

const AuthenticatedApp = () => {
  const { isLoadingAuth, isLoadingPublicSettings, authError, navigateToLogin } = 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>
    );
  }

  // Handle authentication errors
  if (authError) {
    if (authError.type === 'user_not_registered') {
      return <UserNotRegisteredError />;
    } else if (authError.type === 'auth_required') {
      // Redirect to login automatically
      navigateToLogin();
      return null;
    }
  }

  // Render the main app
  return (
    <Routes>
      <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 element={<AppShell />}>
          <Route path="/" element={<Dashboard />} />
          <Route path="/new-project" element={<NewProject />} />
          <Route path="/designs" element={<UniversalDesigns />} />
          <Route path="/create-design" element={<CreateDesign />} />
          <Route path="/fit-design" element={<FitDesign />} />
          <Route path="/cover-variants" element={<CoverVariants />} />
          <Route path="/compare" element={<CompareVariants />} />
          <Route path="/design-canvas" element={<UniversalDesignCanvas />} />
          <Route path="/covers" element={<CoverLibrary />} />
          <Route path="/image-apply" element={<ImageApply />} />
          <Route path="/sketch-3d" element={<SketchTo3D />} />
          <Route path="/promptforge" element={<PromptForge />} />
          <Route path="/studio" element={<Studio />} />
          <Route path="/validation" element={<Validation />} />
          <Route path="/jobs" element={<Jobs />} />
          <Route path="/history" element={<ProjectHistory />} />
          <Route path="/settings" element={<Settings />} />
        </Route>
      </Route>
      <Route path="*" element={<PageNotFound />} />
    </Routes>
  );
};


function App() {

  return (
    <AuthProvider>
      <QueryClientProvider client={queryClientInstance}>
        <Router>
          <ScrollToTop />
          <ErrorBoundary label="App" fallback={AppFallback}>
            <AuthenticatedApp />
          </ErrorBoundary>
        </Router>
        <Toaster />
      </QueryClientProvider>
    </AuthProvider>
  )
}

export default App