'use client';

import { validateAnalyticsEvent, type AnalyticsContext, type AnalyticsEventName } from './events';

declare global {
  interface Window {
    __rdgAnalyticsTestSink?: Array<{ name: AnalyticsEventName; context: AnalyticsContext }>;
  }
}

function analyticsMode(): 'disabled' | 'test' {
  return process.env.NEXT_PUBLIC_ANALYTICS_MODE === 'test' ? 'test' : 'disabled';
}

function consentGranted(): boolean {
  return document.documentElement.dataset.analyticsConsent === 'granted';
}

export function trackAnalytics(name: AnalyticsEventName, context: AnalyticsContext): boolean {
  const event = validateAnalyticsEvent(name, context);
  if (!event || analyticsMode() !== 'test' || !consentGranted()) return false;
  window.__rdgAnalyticsTestSink ??= [];
  window.__rdgAnalyticsTestSink.push(event);
  return true;
}
