'use client';

import { useEffect } from 'react';
import { useCart } from '@/lib/cartStore';
import { del as idbDel } from 'idb-keyval';

export default function ClearCartOnMount() {
  useEffect(() => {
    const clearCart = async () => {
      try {
        console.log('🧹 ClearCartOnMount: Clearing cart on success page');

        // Delete IndexedDB storage first
        await idbDel('personalize-studio-cart');
        console.log('✓ Deleted cart from IndexedDB');

        // Then clear the in-memory state by getting a fresh reference
        // This ensures we're using the current store state
        const { clear: clearStore } = useCart.getState();
        clearStore();
        console.log('✓ Cleared cart store state');

        // Clear the isCheckingOut flag
        if (typeof window !== 'undefined') {
          sessionStorage.removeItem('isCheckingOut');
          console.log('✓ Cleared checkout flag');
        }
      } catch (err) {
        console.error('Error clearing cart:', err);
      }
    };

    clearCart();
  }, []); // Empty dependency array - run once on mount

  return null;
}
