import { useEffect, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import { applyCoupon } from '@/lib/cart/api';
import { useCartStore } from '@/lib/cart/store';
import { toast } from 'sonner';

/**
 * CouponURLHandler
 * 
 * Global component that listens for 'coupon' or 'apply_coupon' query parameters
 * and automatically applies them to the cart session.
 */
export function CouponURLHandler() {
    const [searchParams, setSearchParams] = useSearchParams();
    const { setCart } = useCartStore();
    const processedRef = useRef(false);

    useEffect(() => {
        const couponCode = searchParams.get('coupon') || searchParams.get('apply_coupon');

        if (couponCode && !processedRef.current) {
            processedRef.current = true; // Prevent double firing in StrictMode

            const apply = async () => {
                const toastId = toast.loading(`Applying coupon: ${couponCode}...`);

                try {
                    const updatedCart = await applyCoupon(couponCode);
                    setCart(updatedCart);
                    toast.success(`Coupon "${couponCode}" applied successfully!`, { id: toastId });
                } catch (error: any) {
                    console.error('Failed to apply URL coupon:', error);
                    toast.error(error.message || `Failed to apply coupon "${couponCode}"`, { id: toastId });
                } finally {
                    // Remove the coupon param from URL to prevent re-application on refresh
                    // Use a new URLSearchParams object to avoid direct mutation issues
                    const newParams = new URLSearchParams(searchParams);
                    newParams.delete('coupon');
                    newParams.delete('apply_coupon');
                    setSearchParams(newParams, { replace: true });
                }
            };

            apply();
        }
    }, [searchParams, setSearchParams, setCart]);

    return null; // This component renders nothing
}
