import React from 'react'
import confetti from 'canvas-confetti'
import { sfx } from '../utils/audio'

const bus = []
export const toast = (msg, type='info')=> { bus.forEach(f=>f({msg,type})) }
export const reward = ()=>{ sfx.play('reward'); confetti({ particleCount: 80, spread: 70, origin:{ y: 0.8 } }) }

export default function Toasts(){
  const [items,setItems] = React.useState([])
  React.useEffect(()=>{
    const handler = (t)=>{ const it = {id:Date.now()+Math.random(), ...t}; setItems(s=>[...s,it]); setTimeout(()=>setItems(s=>s.filter(x=>x.id!==it.id)),2000) }
    bus.push(handler); return ()=>{ const i=bus.indexOf(handler); if(i>=0) bus.splice(i,1) }
  },[])
  return (
    <div className="fixed bottom-4 left-1/2 -translate-x-1/2 flex flex-col gap-2 z-[999]">
      {items.map(it=> (
        <div key={it.id} className={`ui px-4 py-2 rounded-full text-sm font-bold shadow ${it.type==='success'?'bg-onme-lime text-black':'bg-onme-blue text-onme-whiteSoft'}`}>{it.msg}</div>
      ))}
    </div>
  )
}
