'use client';

import { createContext, useContext, useEffect, useState } from 'react';
import { toast } from 'sonner';
import { detectDemoModeClient } from '@/lib/demo-detector';

interface DemoModeContextType {
  isDemoMode: boolean;
  showDemoAlert: (action: string) => void;
}

const DemoModeContext = createContext<DemoModeContextType | null>(null);

export const useDemoMode = () => {
  const context = useContext(DemoModeContext);
  if (!context) {
    // Si pas de provider, on n'est pas en mode démo
    return {
      isDemoMode: false,
      showDemoAlert: () => {}
    };
  }
  return context;
};

// Utilise le nouveau système de détection centralisé
export const detectDemoMode = (): boolean => {
  return detectDemoModeClient();
};

interface DemoModeProviderProps {
  children: React.ReactNode;
  forceDemoMode?: boolean;
}

export const DemoModeProvider = ({ children, forceDemoMode }: DemoModeProviderProps) => {
  const [isDemoMode, setIsDemoMode] = useState(false);

  useEffect(() => {
    const demoMode = forceDemoMode || detectDemoMode();
    setIsDemoMode(demoMode);

    // Ajouter une classe CSS pour styliser différemment en mode démo
    if (demoMode) {
      document.documentElement.classList.add('demo-mode');
    } else {
      document.documentElement.classList.remove('demo-mode');
    }

    return () => {
      document.documentElement.classList.remove('demo-mode');
    };
  }, [forceDemoMode]);

  const showDemoAlert = (action: string) => {
    toast.info(`Mode démo : ${action} non disponible`, {
      description: "Cette action est désactivée en mode démonstration"
    });
  };

  return (
    <DemoModeContext.Provider value={{ isDemoMode, showDemoAlert }}>
      {children}
    </DemoModeContext.Provider>
  );
};