/**
 * Toast Container Component
 *
 * Manages and displays multiple toast notifications.
 * Handles positioning, stacking, and lifecycle of toasts.
 *
 * @since 0.1.0
 */

import React, { useState, useCallback, useEffect } from 'react';
import ToastNotification from './ToastNotification';

const containerClasses = {
  'top-right': 'pr:top-0 pr:right-0',
  'top-left': 'pr:top-0 pr:left-0',
  'bottom-right': 'pr:bottom-0 pr:right-0',
  'bottom-left': 'pr:bottom-0 pr:left-0',
  'top-center': 'pr:top-0 pr:left-1/2 pr:transform pr:-translate-x-1/2',
  'bottom-center': 'pr:bottom-0 pr:left-1/2 pr:transform pr:-translate-x-1/2',
};

const ToastContainer = ({ position = 'bottom-right' }) => {
  const [toasts, setToasts] = useState([]);

  const addToast = useCallback((message, type = 'info', options = {}) => {
    const id = `toast-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const newToast = {
      id,
      message,
      type,
      duration: options.duration ?? 5000,
      dismissible: options.dismissible !== false,
      actions: Array.isArray(options.actions) ? options.actions : [],
    };
    setToasts((prevToasts) => [...prevToasts, newToast]);
  }, []);

  const removeToast = useCallback((id) => {
    setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id));
  }, []);

  // Set up global event listener and showToast function
  useEffect(() => {
    const handleAddToast = (event) => {
      const { message, type, options } = event.detail;
      addToast(message, type, options);
    };

    const showToast = (message, type, options = {}) => {
      const event = new CustomEvent('prorank-show-toast', {
        detail: { message, type, options },
      });
      window.dispatchEvent(event);
    };

    window.addEventListener('prorank-show-toast', handleAddToast);
    window.proRankSEO = window.proRankSEO || {};
    window.proRankSEO.showToast = showToast;

    return () => {
      window.removeEventListener('prorank-show-toast', handleAddToast);
      if (
        typeof window.proRankSEO === 'object' &&
        window.proRankSEO !== null &&
        window.proRankSEO.showToast === showToast
      ) {
        delete window.proRankSEO.showToast;
      }
    };
  }, [addToast]);

  const currentContainerClass = Object.prototype.hasOwnProperty.call(containerClasses, position)
    ? containerClasses[position]
    : containerClasses['bottom-right'];
  const stackDirection = position.includes('top') ? 'pr:flex-col' : 'pr:flex-col-reverse';

  return (
    <div className={`pr:fixed pr:z-50 pr:p-4 pr:pointer-events-none ${currentContainerClass}`}>
      <div className={`pr:flex ${stackDirection} pr:space-y-2`}>
        {Array.isArray(toasts) &&
          toasts.map((toast) => (
            <div key={toast.id} className="pr:pointer-events-auto">
              <ToastNotification {...toast} position="relative" onDismiss={removeToast} />
            </div>
          ))}
      </div>
    </div>
  );
};

export default ToastContainer;
