'use client'

import { useEffect, useState } from 'react'

let globalShowToast: ((msg: string, type?: 'success'|'error'|'info') => void) | null = null

export function showToast(msg: string, type: 'success'|'error'|'info' = 'info') {
  globalShowToast?.(msg, type)
}

export function ToastProvider() {
  const [toasts, setToasts] = useState<{ id: number; msg: string; type: string }[]>([])

  useEffect(() => {
    globalShowToast = (msg, type = 'info') => {
      const id = Date.now()
      setToasts(t => [...t, { id, msg, type }])
      setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 2800)
    }
    return () => { globalShowToast = null }
  }, [])

  return (
    <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[999] flex flex-col gap-2 pointer-events-none">
      {toasts.map(t => (
        <div
          key={t.id}
          className="toast-enter bg-gray-900 text-white px-5 py-2.5 rounded-lg text-sm shadow-xl font-medium pointer-events-auto select-none"
        >
          {t.msg}
        </div>
      ))}
    </div>
  )
}
