// toaster.jsx
import React, { createContext, useContext, useState, useCallback } from 'react';
import '../../../assets/stylesheets/toaster.css';

const ToasterContext = createContext();

export function useToaster() {
    return useContext(ToasterContext);
}

function ErrorIcon() {
    return (
        <svg
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="#c62828"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
            focusable="false"
        >
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
        </svg>
    );
}

function CheckIcon() {
    return (
        <svg
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="#2e7d32"
            strokeWidth="3"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
            focusable="false"
        >
            <polyline points="20 6 9 17 4 12" />
        </svg>
    );
}

export function ToasterProvider({ children }) {
    const [toasts, setToasts] = useState([]);

    const showToast = useCallback((message, type = 'success', duration = 10000) => {
        const id = Date.now();
        setToasts(prev => [...prev, { id, message, type, duration }]);
        setTimeout(() => {
            setToasts(prev => prev.filter(toast => toast.id !== id));
        }, duration);
    }, []);

    return (
        <ToasterContext.Provider value={{ showToast }}>
            {children}
            <div className="toaster-container">
                {toasts.map(toast => (
                    <div key={toast.id} className={`toast toast-${toast.type}`}>
                        <div className="toast-content">
                            {toast.type === 'success' ? (
                                <span className="toast-icon toast-success"><CheckIcon /></span>
                             ) : (
                                <span className="toast-icon toast-error"><ErrorIcon /></span>
                            )
                            }
                            <span className="toast-message">{toast.message}</span>
                        </div>
                        <div
                            className={`toast-progress progress-${toast.type}`}
                            style={{ animationDuration: `${toast.duration}ms` }}
                        />
                    </div>
                ))}
            </div>
        </ToasterContext.Provider>
    );
}
