import { jsxs, jsx } from 'react/jsx-runtime';
import React__default, { createContext, useState, useCallback, useMemo, useContext } from 'react';
import { AnimatePresence } from 'motion/react';
import { createPortal } from 'react-dom';
import { Toast } from './Toast.js';
import { toastTheme } from './Toast.theme.js';
import { cn } from '../../../utils/cn.js';
import { useIsClient } from '../../../hooks/useIsClient.js';

const ToastContext = createContext(undefined);
const positionStyles = {
    'top-left': 'top-4 left-4',
    'top-center': 'top-4 left-1/2 -translate-x-1/2',
    'top-right': 'top-4 right-4',
    'bottom-left': 'bottom-4 left-4',
    'bottom-center': 'bottom-4 left-1/2 -translate-x-1/2',
    'bottom-right': 'bottom-4 right-4',
};
const ToastProvider = ({ children, position = 'top-right', maxToasts = 5, defaultDuration = 5000, darkMode = false, }) => {
    const isClient = useIsClient();
    const [toasts, setToasts] = useState([]);
    const [isHovered, setIsHovered] = useState(false);
    const [toastHeights, setToastHeights] = useState({});
    const hoverTimeoutRef = React__default.useRef(null);
    const addToast = useCallback((toastData) => {
        var _a;
        const id = Math.random().toString(36).substring(2, 9);
        const newToast = {
            ...toastData,
            id,
            duration: (_a = toastData.duration) !== null && _a !== void 0 ? _a : defaultDuration,
        };
        setToasts(current => {
            const updated = [newToast, ...current];
            // Limit the number of toasts
            return updated.slice(0, maxToasts);
        });
        return id;
    }, [maxToasts, defaultDuration]);
    const removeToast = useCallback((id) => {
        setToasts(current => current.filter(toast => toast.id !== id));
        setToastHeights(current => {
            const next = { ...current };
            delete next[id];
            return next;
        });
    }, []);
    const removeAllToasts = useCallback(() => {
        setToasts([]);
    }, []);
    const handleMouseEnter = useCallback(() => {
        if (hoverTimeoutRef.current) {
            clearTimeout(hoverTimeoutRef.current);
            hoverTimeoutRef.current = null;
        }
        setIsHovered(true);
    }, []);
    const handleMouseLeave = useCallback(() => {
        // Add a small delay before collapsing to prevent flickering
        hoverTimeoutRef.current = setTimeout(() => {
            setIsHovered(false);
        }, 150);
    }, []);
    const handleToastHeight = useCallback((id, height) => {
        setToastHeights(current => {
            if (current[id] === height)
                return current;
            return { ...current, [id]: height };
        });
    }, []);
    const getExpandedOffset = useCallback((index) => {
        var _a;
        const gap = 8;
        let offset = 0;
        for (let i = 0; i < index; i++) {
            const toastId = (_a = toasts[i]) === null || _a === void 0 ? void 0 : _a.id;
            const h = toastId ? toastHeights[toastId] : undefined;
            offset += (h !== null && h !== void 0 ? h : 64) + gap;
        }
        return offset;
    }, [toasts, toastHeights]);
    // Calculate total expanded height for padding (covers gaps between toasts)
    const totalExpandedHeight = React__default.useMemo(() => {
        if (!isHovered || toasts.length <= 1)
            return 0;
        return getExpandedOffset(toasts.length);
    }, [isHovered, toasts.length, getExpandedOffset]);
    const contextValue = useMemo(() => ({
        toasts,
        addToast,
        removeToast,
        removeAllToasts,
    }), [toasts, addToast, removeToast, removeAllToasts]);
    return (jsxs(ToastContext.Provider, { value: contextValue, children: [children, isClient && createPortal(jsx("div", { className: cn(toastTheme.containerStyle, positionStyles[position]), "aria-live": "polite", "aria-label": "Notifications", children: jsx("div", { className: "relative w-80", style: { paddingBottom: isHovered && toasts.length > 1 ? totalExpandedHeight : undefined }, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, children: jsx(AnimatePresence, { mode: "popLayout", children: toasts.map((toast, index) => (jsx(Toast, { toast: toast, onDismiss: removeToast, index: index, isExpanded: isHovered, totalToasts: toasts.length, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onHeightChange: handleToastHeight, expandedOffset: getExpandedOffset(index), darkMode: darkMode }, toast.id))) }) }) }), document.body)] }));
};
const useToastContext = () => {
    const context = useContext(ToastContext);
    if (!context) {
        throw new Error('useToastContext must be used within a ToastProvider');
    }
    return context;
};

export { ToastProvider, useToastContext };
