'use client'
import { useEffect, useState } from 'react'
import { cn } from '@/lib/utils'

type Toast = { id: string; message: string; type: 'success' | 'error' | 'info' }

let toastListeners: ((toast: Toast) => void)[] = []

export function toast(message: string, type: Toast['type'] = 'info') {
  const id = Math.random().toString(36).slice(2)
  toastListeners.forEach((fn) => fn({ id, message, type }))
}

export function Toaster() {
  const [toasts, setToasts] = useState<Toast[]>([])

  useEffect(() => {
    const handler = (t: Toast) => {
      setToasts((prev) => [...prev, t])
      setTimeout(() => setToasts((prev) => prev.filter((x) => x.id !== t.id)), 4000)
    }
    toastListeners.push(handler)
    return () => { toastListeners = toastListeners.filter((l) => l !== handler) }
  }, [])

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col gap-2">
      {toasts.map((t) => (
        <div
          key={t.id}
          className={cn(
            'px-5 py-3 text-xs tracking-widest uppercase font-medium shadow-2xl border-l-2 bg-[#0f0f0f]',
            t.type === 'success' && 'border-[#C9A84C] text-[#C9A84C]',
            t.type === 'error'   && 'border-red-600 text-red-400',
            t.type === 'info'    && 'border-[#444] text-[#888]'
          )}
        >
          {t.message}
        </div>
      ))}
    </div>
  )
}
