'use client';

import React, { useState, useRef, useEffect } from 'react';
import { useToast } from './ToastContext';
import Toast from './Toast';

const ToastContainer = ({ maxToasts = 5 }) => {
    const { toasts, removeToast } = useToast();
    const [isHovered, setIsHovered] = useState(false);
    const [toastHeights, setToastHeights] = useState({});
    const hoverTimeoutRef = useRef(null);
    const toastRefs = useRef({});

    // Limit the number of visible toasts
    const visibleToasts = toasts.slice(-maxToasts);

    // Measure toast heights
    useEffect(() => {
        const newHeights = {};
        visibleToasts.forEach((toast) => {
            const element = toastRefs.current[toast.id];
            if (element) {
                newHeights[toast.id] = element.offsetHeight;
            }
        });
        
        // Update only if heights have changed
        const hasChanged = visibleToasts.some(toast => 
            newHeights[toast.id] !== toastHeights[toast.id]
        );
        
        if (hasChanged) {
            setToastHeights(newHeights);
        }
    }, [visibleToasts, toastHeights]);

    const handleMouseEnter = (isLastToast) => {
        if (hoverTimeoutRef.current) {
            clearTimeout(hoverTimeoutRef.current);
            hoverTimeoutRef.current = null;
        }
        
        // Trigger hover only on most recent toast OR if already in hover mode
        if (isLastToast || isHovered) {
            setIsHovered(true);
        }
    };

    const handleMouseLeave = () => {
        // Delay before closing to avoid flickering
        hoverTimeoutRef.current = setTimeout(() => {
            setIsHovered(false);
        }, 150);
    };

    // Calculate position of each toast based on actual heights
    const calculatePosition = (index) => {
        const isRecent = index === visibleToasts.length - 1;
        const distanceFromRecent = visibleToasts.length - 1 - index;
        
        if (isRecent) {
            return 0; // Most recent stays at 0
        }

        if (isHovered) {
            // In hover mode: add heights of more recent toasts + margin
            let totalOffset = 0;
            for (let i = index + 1; i < visibleToasts.length; i++) {
                const toastId = visibleToasts[i].id;
                const height = toastHeights[toastId] || 60; // default height
                totalOffset += height + 10; // height + 10px margin
            }
            return -totalOffset;
        } else {
            // In stack mode: reduced spacing based on height
            const recentToastHeight = toastHeights[visibleToasts[visibleToasts.length - 1].id] || 60;
            return -(distanceFromRecent * Math.min(recentToastHeight * 0.15, 12)); // Maximum 12px per level
        }
    };

    if (visibleToasts.length === 0) {
        return null;
    }

    return (
        <div
            className={`
                fixed bottom-4 right-4
                z-50 pointer-events-none
                transition-all duration-300 ease-in-out
            `}
        >
            <div className="relative">
                {visibleToasts.map((toast, index) => {
                    // The last toast (index length-1) is always the most recent
                    const isRecent = index === visibleToasts.length - 1;
                    const distanceFromRecent = visibleToasts.length - 1 - index;
                    
                    // Calculations for both modes
                    const scale = isHovered ? 1 : (isRecent ? 1 : Math.max(0.7, 1 - (distanceFromRecent * 0.08)));
                    const translateY = calculatePosition(index);
                    
                    return (
                        <div 
                            key={toast.id} 
                            ref={el => toastRefs.current[toast.id] = el}
                            className={`
                                absolute bottom-0 right-0
                                pointer-events-auto
                                transition-all duration-500 ease-out
                            `}
                            style={{
                                transform: `scale(${scale}) translateY(${translateY}px)`,
                                zIndex: isRecent ? 10 : (10 - distanceFromRecent),
                            }}
                            onMouseEnter={() => handleMouseEnter(isRecent)}
                            onMouseLeave={handleMouseLeave}
                        >
                            <Toast
                                {...toast}
                                onDismiss={removeToast}
                            />
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default ToastContainer;

