'use client';

/**
 * Auth Pages Component - Catch-all route for Next.js App Router
 * This component handles all authentication routes: login, register, forgot, reset, confirm
 */

import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import LoginPage from './pages/LoginPage.js';
import RegisterPage from './pages/RegisterPage.js';
import ForgotPasswordPage from './pages/ForgotPasswordPage.js';
import ResetPasswordPage from './pages/ResetPasswordPage.js';
import ConfirmEmailPage from './pages/ConfirmEmailPage.js';
import LogoutPage from './pages/LogoutPage.js';

export default function AuthPagesClient({ 
  params, 
  searchParams, 
  registerAction,
  loginAction,
  forgotPasswordAction,
  resetPasswordAction,
  verifyEmailAction,
  logoutAction,
  setSessionCookieAction,
  redirectAfterLogin = '/',
  currentUser = null
}) {
  const router = useRouter();
  const [currentPage, setCurrentPage] = useState(null); // null = loading
  const [isLoading, setIsLoading] = useState(true);
  const [email, setEmail] = useState('');
  const [token, setToken] = useState('');
  
  useEffect(() => {
    // Get page from params or URL
    const getPageFromParams = () => {
      if (params?.auth?.[0]) {
        return params.auth[0];
      }
      
      // Fallback: read from URL
      if (typeof window !== 'undefined') {
        const pathname = window.location.pathname;
        const match = pathname.match(/\/auth\/([^\/\?]+)/);
        return match ? match[1] : 'login';
      }
      
      return 'login';
    };
    
    const page = getPageFromParams();
    setCurrentPage(page);
    setIsLoading(false);
  }, [params]);

  // Extract email and token from searchParams (handles both Promise and regular object)
  useEffect(() => {
    const extractSearchParams = async () => {
      let resolvedParams = searchParams;
      
      // Check if searchParams is a Promise (Next.js 15+)
      if (searchParams && typeof searchParams.then === 'function') {
        resolvedParams = await searchParams;
      }
      
      // Extract email and token from URL if not in searchParams
      if (typeof window !== 'undefined') {
        const urlParams = new URLSearchParams(window.location.search);
        setEmail(resolvedParams?.email || urlParams.get('email') || '');
        setToken(resolvedParams?.token || urlParams.get('token') || '');
      } else {
        setEmail(resolvedParams?.email || '');
        setToken(resolvedParams?.token || '');
      }
    };
    
    extractSearchParams();
  }, [searchParams]);

  const navigate = (page) => {
    router.push(`/auth/${page}`);
  };

  // Don't render anything while determining the correct page
  if (isLoading || !currentPage) {
    return null;
  }

  // Page components mapping
  const pageComponents = {
    login: () => <LoginPage onSubmit={loginAction} onNavigate={navigate} onSetSessionCookie={setSessionCookieAction} redirectAfterLogin={redirectAfterLogin} currentUser={currentUser} />,
    register: () => <RegisterPage onSubmit={registerAction} onNavigate={navigate} currentUser={currentUser} />,
    forgot: () => <ForgotPasswordPage onSubmit={forgotPasswordAction} onNavigate={navigate} currentUser={currentUser} />,
    reset: () => <ResetPasswordPage onSubmit={resetPasswordAction} onNavigate={navigate} email={email} token={token} />,
    confirm: () => <ConfirmEmailPage onSubmit={verifyEmailAction} onNavigate={navigate} email={email} token={token} />,
    logout: () => <LogoutPage onLogout={logoutAction} onSetSessionCookie={setSessionCookieAction} />
  };

  // Render the appropriate page
  const PageComponent = pageComponents[currentPage];
  return PageComponent ? <PageComponent /> : <LoginPage onSubmit={loginAction} onNavigate={navigate} onSetSessionCookie={setSessionCookieAction} redirectAfterLogin={redirectAfterLogin} currentUser={currentUser} />;
}
