import { useCallback } from 'react';
import { useConsent } from '@/contexts/consent';

type AnalyticsEvent = {
  category: string;
  action: string;
  name?: string;
  value?: number;
};

export function useAnalytics() {
  const { hasConsent } = useConsent();

  const trackEvent = useCallback(
    ({ category, action, name, value }: AnalyticsEvent) => {
      if (typeof window === 'undefined') {
        return;
      }

      if (!hasConsent('analytics')) {
        return;
      }

      const queue = (window._paq = window._paq || []);
      const payload: (string | number)[] = ['trackEvent', category, action];

      if (typeof name === 'string') {
        payload.push(name);
      }

      if (typeof value === 'number') {
        if (payload.length === 3) {
          payload.push('');
        }
        payload.push(value);
      }

      queue.push(payload);
    },
    [hasConsent],
  );

  return { trackEvent };
}
