/*
  Simple toast utility that renders messages into the global #toast-root.
  Types: success | error | warning | info
*/

export type ToastType = 'success' | 'error' | 'warning' | 'info';

export function showToast(message: string, type: ToastType = 'info', opts?: { duration?: number }) {
  if (typeof window === 'undefined') return;
  const root = document.getElementById('toast-root');
  if (!root) return;

  const duration = opts?.duration ?? 3000;

  const container = document.createElement('div');
  container.className = 'fixed top-4 right-4 z-[1000] flex flex-col gap-2';

  const toast = document.createElement('div');
  toast.className = `shadow-lg rounded-lg px-4 py-3 text-sm toast-${type}`;
  toast.textContent = message;

  // Enter animation
  toast.style.opacity = '0';
  toast.style.transform = 'translateY(-8px)';
  toast.style.transition = 'opacity 150ms ease, transform 150ms ease';

  container.appendChild(toast);
  root.appendChild(container);

  requestAnimationFrame(() => {
    toast.style.opacity = '1';
    toast.style.transform = 'translateY(0)';
  });

  const remove = () => {
    toast.style.opacity = '0';
    toast.style.transform = 'translateY(-8px)';
    setTimeout(() => {
      try {
        container.remove();
      } catch {}
    }, 180);
  };

  // Auto dismiss
  const timer = setTimeout(remove, duration);

  // Close on click
  toast.addEventListener('click', () => {
    clearTimeout(timer);
    remove();
  });
}