import React from 'react'

type ToastKind = 'info' | 'success' | 'error'
type ToastItem = { id: number; message: string; kind: ToastKind }

let nextId = 1
const subs = new Set<(t: ToastItem) => void>()

export const toast = {
  show(message: string, kind: ToastKind = 'info') {
    const item: ToastItem = { id: nextId++, message, kind }
    subs.forEach((fn) => fn(item))
  },
  info(message: string) { toast.show(message, 'info') },
  success(message: string) { toast.show(message, 'success') },
  error(message: string) { toast.show(message, 'error') },
}

export function ToastHost() {
  const [items, setItems] = React.useState<ToastItem[]>([])

  React.useEffect(() => {
    function onPush(t: ToastItem) {
      setItems((prev) => [...prev, t])
      // auto-remove after 3.5s
      setTimeout(() => {
        setItems((prev) => prev.filter((x) => x.id !== t.id))
      }, 3500)
    }
    subs.add(onPush)
    return () => { subs.delete(onPush) }
  }, [])

  if (!items.length) return null

  return (
    <div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
      {items.map((it) => (
        <div
          key={it.id}
          role="status"
          aria-live="polite"
          className={
            `min-w-[240px] max-w-[360px] rounded shadow-lg border p-3 text-sm ` +
            (it.kind === 'success'
              ? 'bg-green-600 text-white border-green-600'
              : it.kind === 'error'
              ? 'bg-red-600 text-white border-red-600'
              : 'bg-black text-white border-black')
          }
        >
          {it.message}
        </div>
      ))}
    </div>
  )
}