'use client';

import posthog from 'posthog-js';
import { PostHogProvider as PHProvider } from 'posthog-js/react';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';

const EMPLOYEE_PAGES = ['/auto-declaration', '/signature-salarie'];
const CONSENT_KEY = 'odentas_analytics_consent_employee';

export function PostHogProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();

  useEffect(() => {
    // Vérifier si on est sur une page salarié
    const isEmployeePage = EMPLOYEE_PAGES.some(page => pathname?.includes(page));

    // Si page salarié, vérifier le consentement
    if (isEmployeePage) {
      const consent = localStorage.getItem(CONSENT_KEY);
      
      // Si pas de consentement ou refusé, ne pas initialiser PostHog
      if (consent !== 'accepted') {
        console.log('PostHog: Désactivé (page salarié sans consentement)');
        return;
      }
    }

    // Initialiser PostHog uniquement côté client et une seule fois
    if (typeof window !== 'undefined' && !posthog.__loaded) {
      const key = process.env.NEXT_PUBLIC_POSTHOG_KEY;
      const host = process.env.NEXT_PUBLIC_POSTHOG_HOST;

      if (!key || !host) {
        console.error('PostHog: Variables d\'environnement manquantes');
        return;
      }

      posthog.init(key, {
        api_host: host,
        person_profiles: 'identified_only',
        capture_pageview: false,
        capture_pageleave: true,
        loaded: (posthog) => {
          if (process.env.NODE_ENV === 'development') {
            (window as any).posthog = posthog;
          }
        },
      });

      console.log('PostHog: Initialisé', isEmployeePage ? '(salarié avec consentement)' : '(client B2B)');
    }
  }, [pathname]);

  return <PHProvider client={posthog}>{children}</PHProvider>;
}
