
import React, { createContext, useContext, useState, useCallback } from 'react';

const GlobalMessageContext = createContext(null);

export const GlobalMessageProvider = ({ children }) => {
  const [messageState, setMessageState] = useState({
    isVisible: false,
    text: '',
    type: 'info', // info, warning, success, error
    dismissible: true,
    scrolling: false,
    icon: 'info',
    actionLabel: null,
    onAction: null,
  });

  const showMessage = useCallback((text, options = {}) => {
    // Hard blocklist for legacy placeholders / prompt-related messaging.
    // If a legacy message tries to render (toast-like banners, announcements), do nothing.
    const msg = (text ?? '').toString().replace(/\s+/g, ' ').trim();
    const BLOCKLIST = [
      /prochain\s+demande/i,
      /prochaine\s+demande/i,
      /prochain\s+prompt/i,
      /\bprompt\b/i,
      /\bllm\b/i,
      /\bopenai\b/i,
      /\bgpt\b/i,
      /\bclaude\b/i,
      /pas\s+encore\s+impl[ée]ment/i,
      /sera\s+impl[ée]ment/i,
      /\bcoming\s+soon\b/i,
      /\bnot\s+implemented\b/i,
    ];
    if (msg && BLOCKLIST.some((re) => re.test(msg))) {
      return;
    }

    setMessageState({
      isVisible: true,
      text,
      type: options.type || 'info',
      dismissible: options.dismissible !== undefined ? options.dismissible : true,
      scrolling: options.scrolling || false,
      icon: options.icon || 'info',
      actionLabel: options.actionLabel || null,
      onAction: options.onAction || null,
    });
  }, []);

  const hideMessage = useCallback(() => {
    setMessageState(prev => ({ ...prev, isVisible: false }));
  }, []);

  const clearMessage = useCallback(() => {
    setMessageState({
      isVisible: false,
      text: '',
      type: 'info',
      dismissible: true,
      scrolling: false,
      icon: 'info',
      actionLabel: null,
      onAction: null,
    });
  }, []);

  return (
    <GlobalMessageContext.Provider value={{ messageState, showMessage, hideMessage, clearMessage }}>
      {children}
    </GlobalMessageContext.Provider>
  );
};

export const useGlobalMessage = () => {
  const context = useContext(GlobalMessageContext);
  if (!context) {
    throw new Error('useGlobalMessage must be used within a GlobalMessageProvider');
  }
  return context;
};
