'use client';

import { useEffect, useRef } from 'react';
import { clearAuthCookies } from './actions';
import { signOut } from 'next-auth/react';
import Image from 'next/image';

export default function LogoutPage() {
  const hasStarted = useRef(false);

  // Set logout flag synchronously on render to block API interceptor immediately
  if (typeof window !== 'undefined') {
    localStorage.setItem('isLoggingOut', 'true');
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
  }

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

    const performLogout = async () => {
      // Unregister FCM token before clearing auth (needs access token for API call)
      try {
        const { notificationService } = await import('@/services/notification.service');
        await notificationService.unregister();
      } catch {
        // Best-effort — ignore errors
      }

      // Clear localStorage
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');

      // Delete httpOnly cookies via server action FIRST
      // This ensures the session cookie is gone before signOut triggers session checks
      await clearAuthCookies();

      // Client-side signOut to clear NextAuth client state
      await signOut({ redirect: false });

      // Delete cookies again after signOut in case signOut recreated any
      await clearAuthCookies();

      // Clear the logout flag before redirecting so it doesn't block API calls on public pages
      localStorage.removeItem('isLoggingOut');

      // Redirect to login immediately
      window.location.href = '/';
    };

    performLogout().catch(() => {
      window.location.href = '/';
    });
  }, []);

  return (
    <div
      className="min-h-screen flex flex-col items-center justify-center"
      style={{
        background: 'linear-gradient(to bottom, #c4d9d4, #f0f5fc)',
      }}
    >
      <Image
        src="/assets/images/splash-house.png"
        alt="House illustration"
        width={150}
        height={108}
        priority
      />
      <div className="mt-[35px]">
        <Image
          src="/assets/images/splash-logo.png"
          alt="RE-Quest logo"
          width={264}
          height={55}
          priority
        />
      </div>
      <p className="mt-8 font-serif text-[14px] text-[#00293D]/60 animate-pulse">
        Signing out...
      </p>
    </div>
  );
}
