/**
 * AnalyticsProvider - App-wide analytics context.
 *
 * Wraps the application to provide analytics tracking via useAnalytics() hook.
 * Automatically tracks page views and manages session state.
 *
 * Usage (macro pattern):
 *   <AnalyticsProvider>
 *     <App />
 *   </AnalyticsProvider>
 *
 * ⚠️ AUTO-GENERATED BY PRISM — DO NOT EDIT
 */

import React, { createContext, useCallback, useEffect, useRef } from 'react';
{% if has_google_analytics %}
import { GoogleAnalytics } from '../components/analytics/GoogleAnalytics';
{% endif %}
import { analyticsApi, type AnalyticsEvent } from '../lib/analyticsApi';

export interface AnalyticsContextValue {
  trackEvent: (name: string, properties?: Record<string, unknown>) => void;
  trackPageView: (url: string, title?: string) => void;
  sessionId: string;
}

export const AnalyticsContext = createContext<AnalyticsContextValue | null>(null);

function generateSessionId(): string {
  return `sess_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
}

interface AnalyticsProviderProps {
  children: React.ReactNode;
{% if cookie_consent_required %}
  cookieConsent?: boolean;
{% endif %}
}

export function AnalyticsProvider({ children{% if cookie_consent_required %}, cookieConsent = false{% endif %} }: AnalyticsProviderProps) {
  const sessionIdRef = useRef<string>(
    sessionStorage.getItem('analytics_session_id') || generateSessionId()
  );

  useEffect(() => {
    sessionStorage.setItem('analytics_session_id', sessionIdRef.current);
  }, []);

{% if track_page_views %}
  // Auto-track page views on navigation
  useEffect(() => {
    const handleRouteChange = () => {
      analyticsApi.trackPageView(window.location.pathname, document.title, sessionIdRef.current);
    };

    // Track initial page view
    handleRouteChange();

    // Listen for popstate (browser back/forward)
    window.addEventListener('popstate', handleRouteChange);
    return () => window.removeEventListener('popstate', handleRouteChange);
  }, []);
{% endif %}

  const trackEvent = useCallback(
    (name: string, properties?: Record<string, unknown>) => {
{% if cookie_consent_required %}
      if (!cookieConsent) return;
{% endif %}
      analyticsApi.trackEvent({
        event_name: name,
        properties,
        session_id: sessionIdRef.current,
        page_url: window.location.pathname,
      });
    },
{% if cookie_consent_required %}
    [cookieConsent]
{% else %}
    []
{% endif %}
  );

  const trackPageView = useCallback(
    (url: string, title?: string) => {
{% if cookie_consent_required %}
      if (!cookieConsent) return;
{% endif %}
      analyticsApi.trackPageView(url, title, sessionIdRef.current);
    },
{% if cookie_consent_required %}
    [cookieConsent]
{% else %}
    []
{% endif %}
  );

  const value: AnalyticsContextValue = {
    trackEvent,
    trackPageView,
    sessionId: sessionIdRef.current,
  };

  return (
    <AnalyticsContext.Provider value={value}>
{% if has_google_analytics %}
{% if cookie_consent_required %}
      {cookieConsent && <GoogleAnalytics />}
{% else %}
      <GoogleAnalytics />
{% endif %}
{% endif %}
      {children}
    </AnalyticsContext.Provider>
  );
}
