'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');
    // Broadcast to other open tabs so they also log out.
    // 'storage' events only fire in OTHER tabs, not the one that wrote the value.
    localStorage.setItem('re-quest-logout-broadcast', String(Date.now()));
  }

  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');

      // Call NextAuth signOut first (clears session via NextAuth's own logic)
      try {
        await signOut({ redirect: false });
      } catch {
        // Continue even if signOut fails
      }

      // Hit our explicit logout route handler — returns Set-Cookie headers
      // that nuke ALL auth cookies. Route handlers are more reliable than
      // server actions for cookie deletion in production.
      try {
        await fetch('/api/logout', {
          method: 'POST',
          credentials: 'include',
          cache: 'no-store',
        });
      } catch {
        // Continue
      }

      // Server action fallback
      try {
        await clearAuthCookies();
      } catch {
        // Continue
      }

      // Clear the logout flag before redirecting
      localStorage.removeItem('isLoggingOut');

      // Hard reload (replace, not push) so all in-memory state and cached responses are flushed
      window.location.replace('/');
    };

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

  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>
  );
}
