'use client'

import { useEffect, useRef, useState } from 'react'

const COPY: Record<string, { title: string; hint: string; tone: string }> = {
  pending_payment: { title: 'Esperando el pago', hint: 'Cuando se acredite, tu pedido pasa a la barra.', tone: 'bg-amber-500/15 text-amber-200' },
  paid: { title: 'Pago recibido', hint: 'La barra ya tiene tu pedido.', tone: 'bg-brand-500/15 text-brand-200' },
  preparing: { title: 'Preparando', hint: 'Ya casi. Te avisamos cuando esté listo.', tone: 'bg-brand-500/15 text-brand-200' },
  ready: { title: '¡Listo para retirar!', hint: 'Acercate a la barra y mostrá la pantalla.', tone: 'bg-live/20 text-green-200' },
  delivered: { title: 'Validado y entregado', hint: '¡Que lo disfrutes!', tone: 'bg-ink-800 text-gray-300' },
  cancelled: { title: 'Pedido cancelado', hint: 'No se cobró nada. Podés pedir de nuevo.', tone: 'bg-red-500/15 text-red-200' },
}
const STEPS = ['paid', 'preparing', 'ready', 'delivered']

export default function TicketLive(props: {
  orderId: string; eventId: string; number: number; initialStatus: string
  method: 'mercadopago' | 'cash'; paymentFailed: boolean; eventSlug: string
}) {
  const [status, setStatus] = useState(props.initialStatus)
  const [retrying, setRetrying] = useState(false)
  const [flash, setFlash] = useState(false)
  const prev = useRef(status)

  useEffect(() => {
    try { // guardar el ticket en el celular
      const key = `tickets:${props.eventId}`
      const list: { id: string }[] = JSON.parse(localStorage.getItem(key) ?? '[]')
      if (!list.some(t => t.id === props.orderId)) localStorage.setItem(key, JSON.stringify([{ id: props.orderId }, ...list].slice(0, 20)))
    } catch {}
  }, [props.eventId, props.orderId])

  useEffect(() => {
    if (['delivered', 'cancelled'].includes(status)) return
    const es = new EventSource(`/api/stream/${props.eventId}?order=${props.orderId}`)
    es.onmessage = m => { try { setStatus(JSON.parse(m.data).status) } catch {} }
    // Respaldo: si el stream se corta, se consulta cada 8 s.
    const poll = setInterval(async () => {
      try { const r = await fetch(`/api/orders/${props.orderId}`); if (r.ok) setStatus((await r.json()).status) } catch {}
    }, 8000)
    return () => { es.close(); clearInterval(poll) }
  }, [props.eventId, props.orderId, status])

  useEffect(() => {
    if (status === 'ready' && prev.current !== 'ready') {
      try { navigator.vibrate?.([200, 100, 200, 100, 400]) } catch {}
    }
    // Destello menta al ser entregado (manual §5.1: feedback de validación)
    if (status === 'delivered' && prev.current !== 'delivered') {
      setFlash(true)
      try { navigator.vibrate?.([60, 40, 60]) } catch {}
      setTimeout(() => setFlash(false), 900)
    }
    prev.current = status
  }, [status])

  async function retry() {
    setRetrying(true)
    const r = await fetch(`/api/orders/${props.orderId}/pay`, { method: 'POST' })
    const d = await r.json()
    if (r.ok) window.location.href = d.redirect
    else { alert(d.error); setRetrying(false) }
  }

  const c = COPY[status] ?? COPY.pending_payment
  const step = STEPS.indexOf(status)
  const isReady = status === 'ready'

  return (
    <div className="mt-2 text-center">
      {flash && <div className="pointer-events-none fixed inset-0 z-50 animate-flash bg-live" aria-hidden="true" />}
      <p className="text-xs uppercase tracking-widest text-gray-500">Tu número</p>
      <p className={`font-bold tabular-nums leading-none tracking-tight transition-all duration-500 ${isReady ? 'animate-scale-in text-[7rem] text-live' : 'text-[6rem]'}`}>
        {props.number}
      </p>
      <div className={`mt-4 rounded-card px-4 py-4 ${c.tone}`}>
        <p className="text-lg font-semibold">{c.title}</p>
        <p className="mt-0.5 text-sm opacity-80">
          {status === 'pending_payment' && props.method === 'cash' ? `Pagá en la caja diciendo el número ${props.number}.` : c.hint}
        </p>
        {status === 'pending_payment' && props.method === 'mercadopago' && (
          <button onClick={retry} disabled={retrying} className="btn-brand mt-3 w-full py-2.5">{retrying ? 'Abriendo…' : props.paymentFailed ? 'Reintentar el pago' : 'Pagar con MercadoPago'}</button>
        )}
      </div>
      {step >= 0 && (
        <div className="mt-5 flex gap-1.5">
          {STEPS.map((s, i) => <div key={s} className={`h-1.5 flex-1 rounded-full transition-colors duration-500 ${i <= step ? 'bg-brand-400' : 'bg-ink-700'}`} />)}
        </div>
      )}
    </div>
  )
}
