'use client';

import { useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';

export default function PortalVerifyPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const calledRef = useRef(false);

  useEffect(() => {
    if (calledRef.current) return;
    calledRef.current = true;

    const token = searchParams.get('token');

    if (!token) {
      router.replace('/portal/login?error=missing_token');
      return;
    }

    // Redirect to the verify API route which will set the cookie and redirect
    window.location.href = `/api/portal/auth/verify?token=${encodeURIComponent(token)}`;
  }, [searchParams, router]);

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <div className="text-center">
        <Loader2 className="h-8 w-8 animate-spin text-[#1e2844] mx-auto mb-3" />
        <p className="text-sm text-gray-500">Verifying your access...</p>
      </div>
    </div>
  );
}
