import React, { useState, useEffect, useCallback } from 'react';
import ReactDOM from 'react-dom';

const USER_COLORS = ['#5865F2', '#EBA7CD', '#57F287', '#FEE75C', '#EB459E', '#ED4245'];

function getUserColor(name) {
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    return USER_COLORS[Math.abs(hash) % USER_COLORS.length];
}

const ToastContainer = ({ toasts, removeToast }) => {
    if (toasts.length === 0) return null;

    return ReactDOM.createPortal(
        <div className="toast-container">
            {toasts.map(toast => (
                <ToastItem key={toast.id} toast={toast} onDismiss={() => removeToast(toast.id)} />
            ))}
        </div>,
        document.body
    );
};

const ToastItem = ({ toast, onDismiss }) => {
    const [exiting, setExiting] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            setExiting(true);
            setTimeout(onDismiss, 300);
        }, 5000);
        return () => clearTimeout(timer);
    }, [onDismiss]);

    return (
        <div className={`toast ${exiting ? 'toast-exit' : 'toast-enter'}`}>
            <div className="toast-avatar" style={{ backgroundColor: getUserColor(toast.username || '') }}>
                {(toast.username || '?').substring(0, 1).toUpperCase()}
            </div>
            <div className="toast-body">
                <div className="toast-title">New message from <strong>{toast.username}</strong></div>
                <div className="toast-preview">{toast.preview}</div>
            </div>
            <button className="toast-close" onClick={() => { setExiting(true); setTimeout(onDismiss, 300); }}>
                &times;
            </button>
        </div>
    );
};

export function useToasts() {
    const [toasts, setToasts] = useState([]);

    const addToast = useCallback((toast) => {
        const id = Date.now() + Math.random();
        setToasts(prev => [...prev.slice(-4), { ...toast, id }]);
    }, []);

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

    return { toasts, addToast, removeToast, ToastContainer: () => <ToastContainer toasts={toasts} removeToast={removeToast} /> };
}

export default ToastContainer;
