'use client';

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

export function Analytics() {
    const pathname = usePathname();

    useEffect(() => {
        // Send beacon on mount and path change
        const sendBeacon = async () => {
            try {
                // Send beacon to THIS website's API, which will relay it to the admin dash
                await fetch('/api/analytics', {
                    method: 'POST',
                    body: JSON.stringify({ path: pathname, timestamp: Date.now() }),
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Analytics-Key': process.env.NEXT_PUBLIC_ANALYTICS_KEY || 'default-analytics-key',
                    },
                    keepalive: true,
                });
            } catch (e) {
                // Fail silently
                console.error('Analytics fail', e);
            }
        };

        sendBeacon();
    }, [pathname]);

    return null;
}
