'use client';

import { useEffect } from 'react';
import { useCart } from '@/lib/cartStore';

/**
 * Logs out the user when they close/leave the page
 * Works for both admin and customer sessions
 * Skips logout when navigating to external checkout (Stripe, etc)
 */
export default function LogoutOnUnload() {
  const clearCart = useCart((s) => s.clear);
  const cartItems = useCart((s) => s.items);

  useEffect(() => {
    const handleUnload = () => {
      // Don't logout if we're in the middle of checkout (navigating to Stripe)
      // The checkout component sets this flag before making the API call
      const isCheckingOut = typeof window !== 'undefined' && sessionStorage.getItem('isCheckingOut');
      console.log('🚪 LogoutOnUnload handleUnload - cart items:', cartItems.length, 'isCheckingOut:', isCheckingOut);
      if (isCheckingOut) {
        console.log('✓ Skipping logout - checkout in progress');
        return;
      }

      // Clear cart on logout
      console.log('🗑️ Clearing cart and logging out');
      clearCart();
      // Use sendBeacon to reliably send logout even when page is closing
      // This doesn't wait for a response, which is fine for logout
      navigator.sendBeacon('/api/logout');
    };

    window.addEventListener('beforeunload', handleUnload);
    window.addEventListener('unload', handleUnload);

    return () => {
      window.removeEventListener('beforeunload', handleUnload);
      window.removeEventListener('unload', handleUnload);
    };
  }, [clearCart]);

  return null;
}
