'use client';

import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/useAuthStore';

/**
 * Component that listens for auth:logout events and handles logout
 * This is triggered by the API client when a 401 response is received
 */
export function AuthLogoutHandler() {
  const router = useRouter();
  const logout = useAuthStore((state) => state.logout);

  useEffect(() => {
    const handleLogout = () => {
      logout();
      router.push('/login');
    };

    window.addEventListener('auth:logout', handleLogout);
    return () => window.removeEventListener('auth:logout', handleLogout);
  }, [router, logout]);

  return null;
}