'use client';

import { useEffect, useState } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

export default function FacebookPixel() {
    const [loaded, setLoaded] = useState(false);
    const pathname = usePathname();
    const searchParams = useSearchParams();

    useEffect(() => {
        // Only load if ID is present
        const pixelId = process.env.NEXT_PUBLIC_FACEBOOK_PIXEL_ID;
        if (!pixelId) return;

        // Check consent
        const cookieConsent = localStorage.getItem('cookieConsent');
        if (cookieConsent !== 'accepted') return;

        if (!loaded) {
            import('react-facebook-pixel')
                .then((x) => x.default)
                .then((ReactPixel) => {
                    ReactPixel.init(pixelId);
                    ReactPixel.pageView();
                    setLoaded(true);
                });
        } else {
            import('react-facebook-pixel')
                .then((x) => x.default)
                .then((ReactPixel) => {
                    ReactPixel.pageView();
                });
        }
    }, [pathname, searchParams, loaded]);

    return null;
}
