import { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuthStore } from '@/store/auth-store';
import { apiClient } from '@/lib/api-client';
import { MainLayout } from '@/components/layout/main-layout';
import { AuthLayout } from '@/components/layout/auth-layout';
import { ProtectedRoute } from '@/components/layout/protected-route';

// Pages
import { LoginPage } from '@/pages/auth/login';
import { RegisterPage } from '@/pages/auth/register';
import { DashboardPage } from '@/pages/dashboard';
import { WebsitesPage } from '@/pages/websites';
import { WebsiteDetailPage } from '@/pages/websites/[id]';
import { ScansPage } from '@/pages/scans';
import { ScanDetailPage } from '@/pages/scans/[id]';
import { ReportsPage } from '@/pages/reports';
import { SettingsPage } from '@/pages/settings';

function App() {
  const { setAuth, setLoading, token } = useAuthStore();

  useEffect(() => {
    const initAuth = async () => {
      if (!token) {
        setLoading(false);
        return;
      }

      try {
        const user = await apiClient.getMe();
        setAuth(user, token);
      } catch (error) {
        console.error('Auth check failed:', error);
        setLoading(false);
      }
    };

    initAuth();
  }, [token, setAuth, setLoading]);

  return (
    <Routes>
      {/* Auth routes */}
      <Route element={<AuthLayout />}>
        <Route path="/login" element={<LoginPage />} />
        <Route path="/register" element={<RegisterPage />} />
      </Route>

      {/* Protected routes */}
      <Route element={<ProtectedRoute />}>
        <Route element={<MainLayout />}>
          <Route path="/" element={<Navigate to="/dashboard" replace />} />
          <Route path="/dashboard" element={<DashboardPage />} />
          <Route path="/websites" element={<WebsitesPage />} />
          <Route path="/websites/:id" element={<WebsiteDetailPage />} />
          <Route path="/scans" element={<ScansPage />} />
          <Route path="/scans/:id" element={<ScanDetailPage />} />
          <Route path="/reports" element={<ReportsPage />} />
          <Route path="/settings" element={<SettingsPage />} />
        </Route>
      </Route>

      {/* 404 */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}

export default App;