"use client";

import { cookieConsentConfig } from "@/lib/cookieconsent/config";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import "vanilla-cookieconsent/dist/cookieconsent.css";
import * as CookieConsent from "vanilla-cookieconsent";

interface ConsentState {
  hasAnalyticsConsent: boolean;
  hasMarketingConsent: boolean;
  isReady: boolean;
}

const ConsentContext = createContext<ConsentState>({
  hasAnalyticsConsent: false,
  hasMarketingConsent: false,
  isReady: false,
});

export function useConsent() {
  return useContext(ConsentContext);
}

// Fonction pour ouvrir les préférences (utilisable dans le footer)
export function showCookiePreferences() {
  CookieConsent.showPreferences();
}

interface ConsentProviderProps {
  children: ReactNode;
}

export function ConsentProvider({ children }: ConsentProviderProps) {
  const [consent, setConsent] = useState<ConsentState>({
    hasAnalyticsConsent: false,
    hasMarketingConsent: false,
    isReady: false,
  });

  const updateConsent = useCallback(() => {
    setConsent({
      hasAnalyticsConsent: CookieConsent.acceptedCategory("analytics"),
      hasMarketingConsent: CookieConsent.acceptedCategory("marketing"),
      isReady: true,
    });
  }, []);

  useEffect(() => {
    // Respecter Global Privacy Control (GPC)
    const gpcEnabled =
      typeof navigator !== "undefined" &&
      "globalPrivacyControl" in navigator &&
      (navigator as Navigator & { globalPrivacyControl?: boolean })
        .globalPrivacyControl === true;

    CookieConsent.run({
      ...cookieConsentConfig,
      // Si GPC activé, refuser analytics et marketing automatiquement
      ...(gpcEnabled && {
        categories: {
          ...cookieConsentConfig.categories,
          analytics: {
            ...cookieConsentConfig.categories?.analytics,
            enabled: false,
            readOnly: true,
          },
          marketing: {
            ...cookieConsentConfig.categories?.marketing,
            enabled: false,
            readOnly: true,
          },
        },
      }),
      onFirstConsent: () => {
        updateConsent();
      },
      onConsent: () => {
        updateConsent();
      },
      onChange: () => {
        updateConsent();
      },
    });

    // Mettre à jour l'état initial si déjà consenti
    updateConsent();
  }, [updateConsent]);

  return (
    <ConsentContext.Provider value={consent}>
      {children}
    </ConsentContext.Provider>
  );
}
