'use client'

import { useEffect, useState } from 'react'

interface ToastData {
  id: string
  userName: string
  productName: string
}

export default function PurchaseToast() {
  const [toasts, setToasts] = useState<ToastData[]>([])

  useEffect(() => {
    const es = new EventSource('/api/events')

    es.addEventListener('purchase_success', (e) => {
      const data = JSON.parse(e.data)
      const id = Math.random().toString(36).slice(2)
      
      setToasts(prev => [...prev.slice(-4), { id, userName: data.userName, productName: data.productName }])
      
      // Auto-remove after 5s
      setTimeout(() => {
        setToasts(prev => prev.filter(t => t.id !== id))
      }, 5000)
    })

    return () => es.close()
  }, [])

  if (toasts.length === 0) return null

  return (
    <div style={{
      position: 'fixed',
      bottom: '80px',
      left: '20px',
      zIndex: 9999,
      display: 'flex',
      flexDirection: 'column',
      gap: '10px',
      pointerEvents: 'none',
    }}>
      {toasts.map(toast => (
        <div
          key={toast.id}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            background: 'rgba(16, 22, 31, 0.95)',
            border: '1px solid rgba(16, 185, 129, 0.4)',
            borderRadius: '12px',
            padding: '12px 16px',
            backdropFilter: 'blur(16px)',
            boxShadow: '0 4px 24px rgba(0,0,0,0.5), 0 0 0 1px rgba(16,185,129,0.1)',
            animation: 'slideInLeft 0.4s ease',
            maxWidth: '280px',
          }}
        >
          <div style={{
            width: '36px',
            height: '36px',
            borderRadius: '50%',
            background: 'linear-gradient(135deg, #10b981, #059669)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '16px',
            flexShrink: 0,
          }}>
            🎉
          </div>
          <div>
            <div style={{ fontSize: '12px', color: '#10b981', fontWeight: 700, marginBottom: '2px' }}>
              Pembelian Berhasil!
            </div>
            <div style={{ fontSize: '13px', color: '#f1f5f9', fontWeight: 600 }}>
              {toast.userName}
            </div>
            <div style={{ fontSize: '11px', color: '#94a3b8', marginTop: '1px' }}>
              baru membeli {toast.productName.slice(0, 35)}{toast.productName.length > 35 ? '...' : ''}
            </div>
          </div>
        </div>
      ))}
      <style>{`
        @keyframes slideInLeft {
          from { opacity: 0; transform: translateX(-40px); }
          to { opacity: 1; transform: translateX(0); }
        }
      `}</style>
    </div>
  )
}
