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

const NotificationContext = createContext({
  notifications: [],
  showNotification: () => {},
  removeNotification: () => {},
});

export const NotificationProvider = ({ children }) => {
  const [notifications, setNotifications] = useState([]);
  const notificationId = useRef(0);

  const removeNotification = useCallback((id) => {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
  }, []);

  const showNotification = useCallback(
    (message, type = 'info', duration = 5000) => {
      notificationId.current += 1;
      const id = notificationId.current;
      const notification = {
        id,
        message,
        type,
        timestamp: Date.now(),
      };

      setNotifications((prev) => [...prev, notification]);

      // Dispatch toast event for ToastContainer
      const event = new CustomEvent('prorank-show-toast', {
        detail: { message, type, options: { duration } },
      });
      window.dispatchEvent(event);

      if (duration > 0) {
        setTimeout(() => {
          removeNotification(id);
        }, duration);
      }

      return id;
    },
    [removeNotification]
  );

  return (
    <NotificationContext.Provider value={{ notifications, showNotification, removeNotification }}>
      {children}
    </NotificationContext.Provider>
  );
};

export const useNotification = () => useContext(NotificationContext);
