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

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

    const performLogout = async () => {
      // Clear localStorage
      localStorage.setItem('isLoggingOut', 'true');
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      localStorage.removeItem('user');

      await signOut({ redirect: false });
      // Delete httpOnly cookies via server action (Next.js cookies() API)
      await clearAuthCookies();

      setTimeout(() => {
        // Redirect to login
        window.location.reload();
        window.location.href = '/login';
      }, 3000);
    };

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

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