// components/Toast.jsx
import React, { createContext, useCallback, useContext, useRef, useState } from 'react';
import { Check, AlertCircle, X } from 'lucide-react';
import { copyText } from '../utils/clipboard';

const ToastContext = createContext(null);

export const ToastProvider = ({ children }) => {
    const [toasts, setToasts] = useState([]);
    const nextId = useRef(1);

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

    const toast = useCallback((message, { type = 'success', detail = '', duration = 2600 } = {}) => {
        const id = nextId.current++;
        setToasts((list) => [...list.slice(-2), { id, message, type, detail }]);
        window.setTimeout(() => dismiss(id), duration);
    }, [dismiss]);

    /** Copy text and confirm with a toast showing what was copied. */
    const copy = useCallback(async (text, label = 'Shortcode copied') => {
        const ok = await copyText(text);
        if (ok) toast(label, { detail: text });
        else toast('The browser blocked copying. Select the text below and copy it:', { type: 'error', detail: text, duration: 8000 });
        return ok;
    }, [toast]);

    return (
        <ToastContext.Provider value={{ toast, copy }}>
            {children}
            <div
                className="fixed top-14 left-1/2 -translate-x-1/2 z-[100000] flex flex-col items-center gap-2 pointer-events-none"
                role="status"
                aria-live="polite"
            >
                {toasts.map((t) => (
                    <div
                        key={t.id}
                        className="pointer-events-auto flex items-start gap-3 max-w-md pl-3 pr-2 py-2.5 rounded-xl bg-slate-900 text-white shadow-2xl ring-1 ring-white/10 animate-fade-up"
                    >
                        <span className={`mt-0.5 shrink-0 rounded-full p-1 ${t.type === 'error' ? 'bg-red-500/20 text-red-300' : 'bg-emerald-500/20 text-emerald-300'}`}>
                            {t.type === 'error' ? <AlertCircle className="size-3.5" /> : <Check className="size-3.5" />}
                        </span>
                        <div className="min-w-0">
                            <p className="text-sm font-medium leading-5">{t.message}</p>
                            {t.detail && (
                                <p
                                    className={`mt-0.5 text-xs font-mono ${t.type === 'error' ? 'text-slate-200 break-all select-all' : 'text-slate-400 truncate'}`}
                                    title={t.detail}
                                >
                                    {t.detail}
                                </p>
                            )}
                        </div>
                        <button
                            onClick={() => dismiss(t.id)}
                            className="shrink-0 p-1 text-slate-500 hover:text-white rounded-md transition-colors"
                            aria-label="Dismiss"
                        >
                            <X className="size-3.5" />
                        </button>
                    </div>
                ))}
            </div>
        </ToastContext.Provider>
    );
};

export const useToast = () => {
    const ctx = useContext(ToastContext);
    if (!ctx) throw new Error('useToast must be used inside <ToastProvider>');
    return ctx;
};
