import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClientProvider } from '@tanstack/react-query';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import { AuthProvider, useAuth } from './lib/auth';
import { queryClient } from './lib/query-client';
import { LoginPage } from './pages/Login';
import { DashboardPage } from './pages/Dashboard';
import { NotFoundPage } from './pages/NotFound';
import { ComingSoonPage } from './pages/ComingSoon';
import { FeedsList } from './modules/feeds/FeedsList';
import { FeedDetail } from './modules/feeds/FeedDetail';
import { FeedNew } from './modules/feeds/FeedNew';
import { ProductsList } from './modules/products/ProductsList';
import { HomepageEditor } from './modules/content/HomepageEditor';
import { CollectionsList } from './modules/content/CollectionsList';
import { CollectionEditor } from './modules/content/CollectionEditor';
import { BrandsList } from './modules/content/BrandsList';
import { BrandEditor } from './modules/content/BrandEditor';
import { ReleaseCalendar } from './modules/content/ReleaseCalendar';
import { CategoriesList } from './modules/content/CategoriesList';
import { EmailsList } from './modules/marketing/EmailsList';
import { EmailEditor } from './modules/marketing/EmailEditor';
import { SubscribersList } from './modules/marketing/SubscribersList';
import { PushComposer } from './modules/marketing/PushComposer';
import { JobsList } from './modules/ops/JobsList';
import { AuditLog } from './modules/ops/AuditLog';
import { CronMonitor } from './modules/ops/CronMonitor';
import { SystemHealth } from './modules/ops/SystemHealth';
import { ErrorLog } from './modules/ops/ErrorLog';

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const { user, loading } = useAuth();
  const location = useLocation();
  if (loading) {
    return (
      <div className="fixed inset-0 flex items-center justify-center bg-[#0A0A0A]">
        <div className="w-7 h-7 border-2 border-[#00FF6A] border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }
  if (!user) return <Navigate to="/cms/login" state={{ from: location }} replace />;
  return <>{children}</>;
}

export default function AdminRoot() {
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  if (!mounted) return null;

  return (
    <QueryClientProvider client={queryClient}>
      <AuthProvider>
        <BrowserRouter>
          <Routes>
            <Route path="/cms/login" element={<LoginPage />} />
            <Route path="/cms" element={<PrivateRoute><DashboardPage /></PrivateRoute>} />

            <Route path="/cms/feeds" element={<PrivateRoute><FeedsList /></PrivateRoute>} />
            <Route path="/cms/feeds/new" element={<PrivateRoute><FeedNew /></PrivateRoute>} />
            <Route path="/cms/feeds/:id" element={<PrivateRoute><FeedDetail /></PrivateRoute>} />

            <Route path="/cms/products" element={<PrivateRoute><ProductsList /></PrivateRoute>} />
            <Route path="/cms/collections" element={<PrivateRoute><CollectionsList /></PrivateRoute>} />
            <Route path="/cms/collections/:id" element={<PrivateRoute><CollectionEditor /></PrivateRoute>} />
            <Route path="/cms/categories" element={<PrivateRoute><CategoriesList /></PrivateRoute>} />

            <Route path="/cms/homepage" element={<PrivateRoute><HomepageEditor /></PrivateRoute>} />
            <Route path="/cms/brands" element={<PrivateRoute><BrandsList /></PrivateRoute>} />
            <Route path="/cms/brands/:slug" element={<PrivateRoute><BrandEditor /></PrivateRoute>} />
            <Route path="/cms/calendar" element={<PrivateRoute><ReleaseCalendar /></PrivateRoute>} />

            <Route path="/cms/emails" element={<PrivateRoute><EmailsList /></PrivateRoute>} />
            <Route path="/cms/emails/:id" element={<PrivateRoute><EmailEditor /></PrivateRoute>} />
            <Route path="/cms/subscribers" element={<PrivateRoute><SubscribersList /></PrivateRoute>} />
            <Route path="/cms/push" element={<PrivateRoute><PushComposer /></PrivateRoute>} />

            <Route path="/cms/jobs" element={<PrivateRoute><JobsList /></PrivateRoute>} />
            <Route path="/cms/audit" element={<PrivateRoute><AuditLog /></PrivateRoute>} />
            <Route path="/cms/crons" element={<PrivateRoute><CronMonitor /></PrivateRoute>} />
            <Route path="/cms/health" element={<PrivateRoute><SystemHealth /></PrivateRoute>} />
            <Route path="/cms/errors" element={<PrivateRoute><ErrorLog /></PrivateRoute>} />
            <Route path="/cms/notifications" element={<PrivateRoute><ComingSoonPage title="Meldingen" /></PrivateRoute>} />

            <Route path="/cms/*" element={<NotFoundPage />} />
          </Routes>
          <Toaster
            position="bottom-right"
            toastOptions={{
              style: { background: '#1A1A1A', color: '#F5F5F5', border: '1px solid #333' },
              success: { iconTheme: { primary: '#00FF6A', secondary: '#0A0A0A' } },
              error: { iconTheme: { primary: '#FF3B3B', secondary: '#FFFFFF' } },
            }}
          />
        </BrowserRouter>
      </AuthProvider>
    </QueryClientProvider>
  );
}

// Bootstrap: mount into #cms-root when module loads (client:only="react" in Astro)
if (typeof document !== 'undefined') {
  const el = document.getElementById('cms-root');
  if (el) {
    const root = createRoot(el);
    root.render(<AdminRoot />);
  }
}
