import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

// ─── Lazy page imports ────────────────────────────────────────────────────────
// Each route bundle is loaded only when the route is first visited.

const LoginPage = React.lazy(() =>
  import('../../pages/LoginPage').then(m => ({ default: m.LoginPage }))
);
const ForgotPasswordPage = React.lazy(() =>
  import('../../pages/ForgotPasswordPage').then(m => ({ default: m.ForgotPasswordPage }))
);
const VerifyEmailPage = React.lazy(() =>
  import('../../pages/VerifyEmailPage').then(m => ({ default: m.VerifyEmailPage }))
);
const ResetPasswordPage = React.lazy(() =>
  import('../../pages/ResetPasswordPage').then(m => ({ default: m.ResetPasswordPage }))
);
const HomePage = React.lazy(() =>
  import('../../pages/HomePage').then(m => ({ default: m.HomePage }))
);
const TemplatePage = React.lazy(() =>
  import('../../pages/TemplatePage').then(m => ({ default: m.TemplatePage }))
);
const AssistantPage = React.lazy(() =>
  import('../../pages/AssistantPage').then(m => ({ default: m.AssistantPage }))
);

// ─── Route guards ─────────────────────────────────────────────────────────────

/** Redirects unauthenticated visitors to /login. */
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { user, isLoading } = useAuth();
  if (isLoading) return null;
  if (!user) return <Navigate to="/login" replace />;
  return <>{children}</>;
}

/** Redirects authenticated users away from auth-only pages. */
function GuestRoute({ children }: { children: React.ReactNode }) {
  const { user, isLoading } = useAuth();
  if (isLoading) return null;
  if (user) return <Navigate to="/home" replace />;
  return <>{children}</>;
}

// ─── Bridge for LoginPage ─────────────────────────────────────────────────────
// LoginPage expects an onLogin prop — this bridge wires AuthContext.login to it,
// keeping the LoginPage component decoupled from the AuthContext.

function LoginPageWithAuth() {
  const { login } = useAuth();
  return <LoginPage onLogin={login} />;
}

// ─── Route tree ───────────────────────────────────────────────────────────────

export function AuthGuard() {
  const { user } = useAuth();

  return (
    <div className="h-screen bg-muted overflow-hidden max-w-full">
      <Routes>
        {/* Auth pages — redirect to /home when already signed in */}
        <Route
          path="/login"
          element={
            <GuestRoute>
              <LoginPageWithAuth />
            </GuestRoute>
          }
        />
        <Route
          path="/forgot-password"
          element={
            <GuestRoute>
              <ForgotPasswordPage />
            </GuestRoute>
          }
        />
        <Route
          path="/verify-email"
          element={
            <GuestRoute>
              <VerifyEmailPage />
            </GuestRoute>
          }
        />
        <Route
          path="/reset-password"
          element={
            <GuestRoute>
              <ResetPasswordPage />
            </GuestRoute>
          }
        />

        {/* Protected pages */}
        <Route
          path="/home"
          element={
            <ProtectedRoute>
              <HomePage />
            </ProtectedRoute>
          }
        />
        <Route
          path="/template"
          element={
            <ProtectedRoute>
              <TemplatePage />
            </ProtectedRoute>
          }
        />
        <Route
          path="/assistente"
          element={
            <ProtectedRoute>
              <AssistantPage />
            </ProtectedRoute>
          }
        />

        {/* Fallback */}
        <Route path="/" element={<Navigate to={user ? '/home' : '/login'} replace />} />
        <Route path="*" element={<Navigate to={user ? '/home' : '/login'} replace />} />
      </Routes>
    </div>
  );
}
