"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";

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

export type ConsentStatus = "pending" | "accepted" | "rejected";

export function useAnalyticsConsent() {
  const pathname = usePathname();
  const [consentStatus, setConsentStatus] = useState<ConsentStatus>("pending");
  
  // Détecte si on est sur une page salarié
  const isEmployeePage = EMPLOYEE_PAGES.some(page => pathname?.includes(page));
  
  useEffect(() => {
    if (!isEmployeePage) {
      // Pas sur une page salarié, pas besoin de consentement
      setConsentStatus("accepted");
      return;
    }

    // Vérifier si un consentement existe déjà
    try {
      const savedConsent = localStorage.getItem(CONSENT_KEY);
      if (savedConsent === "accepted") {
        setConsentStatus("accepted");
      } else if (savedConsent === "rejected") {
        setConsentStatus("rejected");
      } else {
        setConsentStatus("pending");
      }
    } catch {
      setConsentStatus("pending");
    }
  }, [isEmployeePage, pathname]);

  const acceptConsent = () => {
    try {
      localStorage.setItem(CONSENT_KEY, "accepted");
      setConsentStatus("accepted");
    } catch {
      console.error("Impossible de sauvegarder le consentement");
    }
  };

  const rejectConsent = () => {
    try {
      localStorage.setItem(CONSENT_KEY, "rejected");
      setConsentStatus("rejected");
    } catch {
      console.error("Impossible de sauvegarder le refus");
    }
  };

  return {
    isEmployeePage,
    consentStatus,
    hasConsent: consentStatus === "accepted",
    needsConsent: isEmployeePage && consentStatus === "pending",
    acceptConsent,
    rejectConsent,
  };
}
