import { useState, useEffect, useCallback } from 'react';

interface ToastMessage {
  id: number;
  text: string;
  type: 'success' | 'info' | 'error';
}

let addToastFn: ((text: string, type?: 'success' | 'info' | 'error') => void) | null = null;

/** Show a toast from anywhere: import { showToast } from './Toast'; showToast('Done!'); */
export function showToast(text: string, type: 'success' | 'info' | 'error' = 'success') {
  if (addToastFn) addToastFn(text, type);
}

// Also expose globally for non-React (Astro inline scripts)
if (typeof window !== 'undefined') {
  (window as any).__showToast = showToast;
}

let nextId = 0;

export default function ToastContainer() {
  const [toasts, setToasts] = useState<ToastMessage[]>([]);

  const addToast = useCallback((text: string, type: 'success' | 'info' | 'error' = 'success') => {
    const id = nextId++;
    setToasts(prev => [...prev, { id, text, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3500);
  }, []);

  useEffect(() => {
    addToastFn = addToast;
    (window as any).__showToast = addToast;
    return () => { addToastFn = null; };
  }, [addToast]);

  if (toasts.length === 0) return null;

  return (
    <div className="fixed bottom-4 left-4 right-4 z-[100] flex flex-col items-end gap-2 sm:left-auto sm:bottom-6 sm:right-6">
      {toasts.map(t => (
        <div
          key={t.id}
          className={`animate-slide-up rounded-xl px-4 py-3 text-sm font-semibold shadow-lg transition-all ${
            t.type === 'success' ? 'bg-accent text-black' :
            t.type === 'error' ? 'bg-red-500 text-white' :
            'bg-bg-card text-text border border-border/50'
          }`}
        >
          {t.text}
        </div>
      ))}
    </div>
  );
}
