'use client';

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

export default function ClearCartOnMount() {
  const clear = useCart((s) => s.clear);

  useEffect(() => {
    const clearCart = async () => {
      console.log('🧹 ClearCartOnMount: Clearing cart on success page');
      // Clear the in-memory state
      clear();
      // Also clear the IndexedDB storage to ensure it doesn't get restored
      try {
        await idbDel('personalize-studio-cart');
        console.log('✓ Cart cleared from IndexedDB');
      } catch (err) {
        console.error('Error clearing cart from IndexedDB:', err);
      }
      // Clear the isCheckingOut flag
      if (typeof window !== 'undefined') {
        sessionStorage.removeItem('isCheckingOut');
      }
    };

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

  return null;
}
