import { useState, useEffect, useCallback } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ShoppingCart, X, CheckCircle, Zap, RotateCcw, Search, Trophy, Clock3 } from 'lucide-react'
import { RaffleAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'
import AuthModal from '../components/AuthModal'
import PixModal from '../components/PixModal'

interface Raffle {
  id: number; titulo: string; descricao?: string
  preco_numero?: number | string
  total_numeros?: number
  image_url?: string; status: string
  end_at?: string
}

interface LastWinner { winner_number: number; usuario_nome: string; created_at: string }

function maskCpf(v: string) {
  return v.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2')
}
function maskPhone(v: string) {
  return v.replace(/\D/g, '').replace(/^(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2')
}
function padNum(n: number, total: number) {
  return String(n).padStart(String(total).length, '0')
}
function maskWinnerName(name: string) {
  if (!name) return ''
  const parts = name.trim().split(' ')
  if (parts.length === 1) return parts[0][0] + '***'
  return parts[0] + ' ' + parts.slice(1).map(p => p[0] + '***').join(' ')
}

// ── Discount helpers ─────────────────────────────────────────────────────────

interface DiscountTier { id: number; min_qty: number; discount_pct: number; active: boolean }

function getBestDiscount(tiers: DiscountTier[], qty: number): DiscountTier | null {
  if (qty === 0) return null
  const eligible = tiers.filter(t => t.active && t.min_qty <= qty)
  if (!eligible.length) return null
  return eligible.reduce((best, t) => t.discount_pct > best.discount_pct ? t : best)
}

function getNextTier(tiers: DiscountTier[], qty: number): DiscountTier | null {
  const upcoming = tiers.filter(t => t.active && t.min_qty > qty)
  if (!upcoming.length) return null
  return upcoming.reduce((next, t) => t.min_qty < next.min_qty ? t : next)
}

// ── Number Grid ───────────────────────────────────────────────────────────────

type GridFilter = 'all' | 'available' | 'sold'

function NumberGrid({ total, sold, selected, onToggle }: {
  total: number; sold: number[]; selected: number[]; onToggle: (n: number) => void
}) {
  const [filter, setFilter] = useState<GridFilter>('all')
  const [search, setSearch]   = useState('')
  const soldSet     = new Set(sold)
  const selectedSet = new Set(selected)

  const numbers = Array.from({ length: total }, (_, i) => i + 1).filter(n => {
    if (filter === 'available' && soldSet.has(n)) return false
    if (filter === 'sold'      && !soldSet.has(n)) return false
    if (search.trim()) {
      const q = search.replace(/\D/g, '')
      if (!String(n).includes(q)) return false
    }
    return true
  })

  return (
    <div className="space-y-3">
      {/* Filters + Search */}
      <div className="flex flex-col sm:flex-row gap-2">
        <div className="flex gap-1 bg-zinc-900 rounded-xl p-1">
          {([['all', 'Todos'], ['available', 'Disponíveis'], ['sold', 'Vendidos']] as [GridFilter, string][]).map(([f, label]) => (
            <button key={f} onClick={() => setFilter(f)}
              className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${
                filter === f ? 'text-black' : 'text-zinc-500 hover:text-zinc-300'
              }`}
              style={filter === f ? { background: 'var(--primary)' } : {}}>
              {label}
            </button>
          ))}
        </div>
        <div className="relative flex-1">
          <Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
          <input
            type="text" value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Buscar número..."
            className="w-full pl-8 pr-3 py-2.5 bg-zinc-900 border border-zinc-800 rounded-xl text-xs text-zinc-300 placeholder-zinc-600 focus:outline-none focus:border-zinc-600"
          />
        </div>
      </div>

      {/* Grid — 5 colunas no mobile, auto-fill no desktop */}
      {numbers.length === 0 ? (
        <p className="text-center text-zinc-600 py-8 text-sm">Nenhum número encontrado</p>
      ) : (
        <div
          className="grid gap-1.5"
          style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}
        >
          {numbers.map(n => {
            const isSold     = soldSet.has(n)
            const isSelected = selectedSet.has(n)
            return (
              <button
                key={n}
                disabled={isSold}
                onClick={() => onToggle(n)}
                title={isSold ? `Número ${n} — Vendido` : `Número ${n}`}
                className={[
                  'h-11 rounded-2xl text-xs font-bold transition-all active:scale-95',
                  isSold
                    ? 'bg-zinc-900/50 text-zinc-700 cursor-not-allowed border border-zinc-900'
                    : isSelected
                    ? 'text-black font-black border-transparent'
                    : 'bg-zinc-900 text-zinc-300 hover:bg-zinc-800 hover:text-white border border-zinc-800',
                ].join(' ')}
                style={isSelected ? { background: 'var(--primary)' } : {}}>
                {padNum(n, total)}
              </button>
            )
          })}
        </div>
      )}
    </div>
  )
}

// ── Checkout Drawer ───────────────────────────────────────────────────────────

type Step = 'cart' | 'auth' | 'pay'
interface OrderResult { order_id: number; pix_code: string; pix_qr?: string; amount: number }

function CheckoutDrawer({ raffle, selected, discounts, flashPct, user, onClose, onSuccess }: {
  raffle: Raffle; selected: number[]; discounts: DiscountTier[]; flashPct: number; user: any; onClose: () => void; onSuccess: () => void
}) {
  const [step, setStep]   = useState<Step>('cart')
  const [form, setForm]   = useState({
    nome: user?.nome || '', cpf: user?.cpf || '',
    telefone: user?.telefone || '', email: user?.email || ''
  })
  const [order, setOrder] = useState<OrderResult | null>(null)
  const [err, setErr]     = useState('')
  const [loading, setLoading] = useState(false)
  const tenant   = useTenantCtx()
  const price    = Number(raffle.preco_numero || 0)
  const subtotal = price * selected.length
  const best     = getBestDiscount(discounts, selected.length)
  const qtyPct   = best ? Number(best.discount_pct) : 0
  const effectivePct = Math.max(qtyPct, flashPct)
  const isFlash  = flashPct > qtyPct && flashPct > 0
  const total    = effectivePct > 0
    ? Math.round(subtotal * (1 - effectivePct / 100) * 100) / 100
    : subtotal
  const savings  = Math.round((subtotal - total) * 100) / 100

  async function handlePay(e: React.FormEvent) {
    e.preventDefault()
    if (selected.length === 0) { setErr('Selecione ao menos um número'); return }
    setLoading(true); setErr('')
    try {
      const result = await RaffleAPI.buyTicket({
        raffle_id:        raffle.id,
        numero:           selected,
        usuario_nome:     form.nome,
        usuario_cpf:      form.cpf,
        usuario_telefone: form.telefone,
        usuario_email:    form.email || undefined,
      })
      setOrder({ order_id: result.order_id, pix_code: result.pix_code, pix_qr: result.pix_qr, amount: total })
      setStep('pay')
    } catch (ex: any) {
      setErr(ex.response?.data?.error || 'Erro ao processar pedido')
    } finally { setLoading(false) }
  }

  if (step === 'pay' && order) {
    return (
      <PixModal
        orderId={order.order_id} pixCode={order.pix_code}
        pixQr={order.pix_qr} amount={order.amount}
        onClose={onClose} onConfirmed={onSuccess}
      />
    )
  }

  if (step === 'auth') {
    return (
      <div className="fixed inset-0 bg-black/70 z-50 flex items-end md:items-center justify-center p-4">
        <div className="w-full max-w-md">
          <AuthModal inline={false}
            onSuccess={u => { setForm(f => ({ ...f, nome: u.nome||f.nome, cpf: u.cpf||f.cpf, telefone: u.telefone||f.telefone, email: u.email||f.email })); setStep('cart') }}
            onClose={() => setStep('cart')} defaultTab="login" />
        </div>
      </div>
    )
  }

  return (
    <div className="fixed inset-0 bg-black/70 z-40 flex items-end md:items-center justify-center p-4" onClick={onClose}>
      <div className="bg-zinc-950 border border-zinc-800 rounded-t-3xl md:rounded-3xl w-full max-w-md max-h-[90vh] overflow-y-auto"
        onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between p-5 border-b border-zinc-800 sticky top-0 bg-zinc-950 z-10">
          <div>
            <h3 className="font-black text-white">Finalizar Compra</h3>
            <p className="text-zinc-500 text-xs mt-0.5">{selected.length} número{selected.length !== 1 ? 's' : ''} · R$ {total.toFixed(2).replace('.', ',')}</p>
          </div>
          <button onClick={onClose} className="text-zinc-500 hover:text-white transition-colors p-1"><X size={20} /></button>
        </div>

        <form onSubmit={handlePay} className="p-5 space-y-4">
          {/* Selected numbers preview */}
          <div className="bg-zinc-900 rounded-2xl p-4">
            <p className="text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2.5">Números selecionados</p>
            <div className="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto">
              {selected.map(n => (
                <span key={n} className="text-xs font-black px-2.5 py-1 rounded-lg text-black"
                  style={{ background: tenant.primary_color }}>
                  {padNum(n, raffle.total_numeros || 100)}
                </span>
              ))}
            </div>
          </div>

          {/* Login hint */}
          {!user && (
            <div className="bg-zinc-900/50 border border-zinc-800 rounded-xl px-4 py-3 flex items-center justify-between">
              <p className="text-xs text-zinc-400">Já tem conta? Entre para preencher automaticamente.</p>
              <button type="button" onClick={() => setStep('auth')}
                className="text-xs font-black hover:opacity-80 shrink-0 ml-2" style={{ color: tenant.primary_color }}>
                Entrar →
              </button>
            </div>
          )}

          {/* Customer data */}
          {([
            { label: 'Nome completo', key: 'nome', type: 'text', mask: null, req: true },
            { label: 'CPF', key: 'cpf', type: 'text', mask: maskCpf, req: true },
            { label: 'Telefone (WhatsApp)', key: 'telefone', type: 'tel', mask: maskPhone, req: true },
            { label: 'Email (opcional)', key: 'email', type: 'email', mask: null, req: false },
          ] as const).map(({ label, key, type, mask, req }) => (
            <div key={key}>
              <label className="text-xs font-bold text-zinc-500 uppercase tracking-wider">{label}</label>
              <input
                type={type} required={req}
                value={(form as any)[key]}
                onChange={e => {
                  const v = mask ? (mask as (s: string) => string)(e.target.value) : e.target.value
                  setForm(f => ({ ...f, [key]: v }))
                }}
                className="mt-1 w-full bg-zinc-900 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-zinc-600 transition-colors"
              />
            </div>
          ))}

          {effectivePct > 0 && (
            <div className={`rounded-xl px-4 py-3 flex items-center justify-between border ${isFlash ? 'bg-orange-500/10 border-orange-500/20' : 'bg-emerald-500/10 border-emerald-500/20'}`}>
              <div>
                <p className={`text-xs font-black uppercase tracking-wide ${isFlash ? 'text-orange-400' : 'text-emerald-400'}`}>
                  {isFlash ? '⚡ ' : ''}{effectivePct}% de desconto
                </p>
                <p className="text-xs text-zinc-400">{isFlash ? 'Promoção relâmpago' : `${selected.length} números selecionados`}</p>
              </div>
              <div className="text-right">
                <p className="text-xs text-zinc-500 line-through">R$ {subtotal.toFixed(2).replace('.', ',')}</p>
                <p className={`text-sm font-black ${isFlash ? 'text-orange-400' : 'text-emerald-400'}`}>-R$ {savings.toFixed(2).replace('.', ',')}</p>
              </div>
            </div>
          )}

          {err && <p className="text-rose-400 text-sm font-medium">{err}</p>}

          <button type="submit" disabled={loading || selected.length === 0}
            className="w-full py-4 rounded-2xl font-black text-black text-base transition-all hover:opacity-90 disabled:opacity-40 flex items-center justify-center gap-2"
            style={{ background: tenant.primary_color }}>
            <ShoppingCart size={18} />
            {loading ? 'Processando…' : `Pagar R$ ${total.toFixed(2).replace('.', ',')} via PIX`}
          </button>
        </form>
      </div>
    </div>
  )
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function RafflePage({ user }: { user?: any }) {
  const [params]  = useSearchParams()
  const [raffles, setRaffles]     = useState<Raffle[]>([])
  const [active, setActive]       = useState<Raffle | null>(null)
  const [soldNums, setSoldNums]   = useState<number[]>([])
  const [selected, setSelected]   = useState<number[]>([])
  const [discounts, setDiscounts] = useState<DiscountTier[]>([])
  const [flashPromo, setFlashPromo] = useState<{ id: number; discount_pct: number; label: string; ends_at: string } | null>(null)
  const [now, setNow]             = useState(Date.now())
  const [lastWinner, setLastWinner] = useState<LastWinner | null>(null)
  const [checkout, setCheckout]   = useState(false)
  const [success, setSuccess]     = useState(false)
  const [loading, setLoading]     = useState(true)
  const tenant = useTenantCtx()

  useEffect(() => {
    RaffleAPI.list().then(d => {
      const list = (d || []).filter((r: Raffle) => r.status === 'active')
      setRaffles(list)
      const preId = params.get('id')
      const pre = preId ? list.find((r: Raffle) => r.id === Number(preId)) : list[0]
      if (pre) setActive(pre)
    }).catch(() => {}).finally(() => setLoading(false))
  }, [])

  useEffect(() => {
    if (!active) return
    setSoldNums([]); setSelected([]); setDiscounts([]); setFlashPromo(null)
    RaffleAPI.getTickets(active.id).then(setSoldNums).catch(() => {})
    RaffleAPI.getDiscounts(active.id).then(setDiscounts).catch(() => {})
    RaffleAPI.getFlashPromo(active.id).then(setFlashPromo).catch(() => {})
    RaffleAPI.getResult(active.id).then(r => setLastWinner(r ?? null)).catch(() => {})
  }, [active?.id])

  useEffect(() => {
    if (!flashPromo && !active?.end_at) return
    const t = setInterval(() => setNow(Date.now()), 1000)
    return () => clearInterval(t)
  }, [flashPromo, active?.end_at])

  const toggleNum = useCallback((n: number) => {
    setSelected(s => s.includes(n) ? s.filter(x => x !== n) : [...s, n])
  }, [])

  const price         = Number(active?.preco_numero || 0)
  const total_numeros = active?.total_numeros || 100
  const availableCount = total_numeros - soldNums.length

  const flashPct = flashPromo && new Date(flashPromo.ends_at).getTime() > now
    ? Number(flashPromo.discount_pct) : 0

  function fmtCountdown(endsAt: string) {
    const diff = Math.max(0, new Date(endsAt).getTime() - now)
    const h = Math.floor(diff / 3600000)
    const m = Math.floor((diff % 3600000) / 60000)
    const s = Math.floor((diff % 60000) / 1000)
    if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m ${String(s).padStart(2, '0')}s`
    return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
  }

  // Cart totals (used in sticky bar and sidebar)
  const cartBest    = getBestDiscount(discounts, selected.length)
  const cartQtyPct  = cartBest ? Number(cartBest.discount_pct) : 0
  const cartEffPct  = Math.max(cartQtyPct, flashPct)
  const cartSubtotal = price * selected.length
  const cartTotal   = cartEffPct > 0
    ? Math.round(cartSubtotal * (1 - cartEffPct / 100) * 100) / 100
    : cartSubtotal

  const ALL_QUICK_STEPS = [1, 3, 5, 10, 20, 30, 50, 100]
  function quickSelect(qty: number) {
    const pool = Array.from({ length: total_numeros }, (_, i) => i + 1)
      .filter(n => !soldNums.includes(n))
    setSelected([...pool].sort(() => Math.random() - 0.5).slice(0, qty))
  }

  const quickButtons = (() => {
    const reached = ALL_QUICK_STEPS.filter(s => selected.length >= s)
    const highestReachedIdx = reached.length > 0
      ? ALL_QUICK_STEPS.indexOf(reached[reached.length - 1]) : -1
    const effectiveIdx = Math.max(Math.min(highestReachedIdx + 1, ALL_QUICK_STEPS.length - 1), 3)
    const visible = ALL_QUICK_STEPS.slice(0, effectiveIdx + 1).filter(s => s <= availableCount)
    return visible.length > 4 ? visible.slice(-4) : visible
  })()

  // ── Success screen ─────────────────────────────────────────────────────────

  if (success) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center p-4">
        <div className="text-center space-y-5 max-w-sm">
          <div className="w-20 h-20 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center mx-auto">
            <CheckCircle size={36} className="text-emerald-400" />
          </div>
          <h2 className="text-3xl font-black text-white">Pagamento Confirmado!</h2>
          <p className="text-zinc-400">Seus números estão garantidos. Boa sorte! 🍀</p>
          <button onClick={() => { setSuccess(false); setSelected([]) }}
            className="px-8 py-3.5 rounded-2xl font-black text-black mt-2 transition-all hover:opacity-90"
            style={{ background: tenant.primary_color }}>
            Participar Novamente
          </button>
        </div>
      </div>
    )
  }

  // ── Loading ────────────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-zinc-800 border-t-white animate-spin" />
      </div>
    )
  }

  // ── Empty ──────────────────────────────────────────────────────────────────

  if (raffles.length === 0) {
    return (
      <div className="min-h-screen bg-black flex flex-col items-center justify-center gap-4">
        <div className="w-16 h-16 rounded-2xl bg-zinc-900 border border-zinc-800 flex items-center justify-center">
          <ShoppingCart size={24} className="text-zinc-600" />
        </div>
        <p className="text-zinc-500">Nenhum sorteio ativo no momento.</p>
      </div>
    )
  }

  // ── Main ───────────────────────────────────────────────────────────────────

  const hasEndAt = active?.end_at && new Date(active.end_at).getTime() > now

  return (
    <div className="min-h-screen bg-black pt-16 pb-28">
      <div className="max-w-6xl mx-auto px-4 pt-5">

        {/* Raffle selector tabs */}
        {raffles.length > 1 && (
          <div className="flex gap-2 overflow-x-auto pb-3 mb-5 scrollbar-none">
            {raffles.map(r => (
              <button key={r.id} onClick={() => setActive(r)}
                className={`shrink-0 px-4 py-2 rounded-xl text-sm font-bold border transition-all ${
                  active?.id === r.id ? 'text-black' : 'bg-zinc-900 border-zinc-800 text-zinc-400 hover:text-white'
                }`}
                style={active?.id === r.id
                  ? { background: tenant.primary_color, borderColor: tenant.primary_color }
                  : {}}>
                {r.titulo}
              </button>
            ))}
          </div>
        )}

        {active && (
          <>
            {/* ── Hero Card ─────────────────────────────────────────────── */}
            <div className="rounded-3xl border p-5 md:p-7 mb-5 relative overflow-hidden"
              style={{
                background: 'linear-gradient(135deg, #0a0f1e 0%, #050810 100%)',
                borderColor: `${tenant.primary_color}35`,
                boxShadow: `0 0 80px ${tenant.primary_color}12`,
              }}>
              {/* Ambient glow */}
              <div className="absolute -top-16 -right-16 w-48 h-48 rounded-full blur-3xl opacity-20 pointer-events-none"
                style={{ background: tenant.primary_color }} />

              {/* Tag */}
              <div className="flex items-center gap-2 mb-3" style={{ color: tenant.primary_color }}>
                <Trophy size={15} />
                <span className="text-xs font-black uppercase tracking-widest">Sorteio Ativo</span>
              </div>

              {/* Prize title */}
              <h2 className="text-2xl md:text-3xl font-black text-white leading-tight tracking-tighter">
                {active.titulo}
              </h2>
              {active.descricao && (
                <p className="text-sm text-zinc-400 mt-1.5 leading-relaxed line-clamp-2">{active.descricao}</p>
              )}

              {/* Stats grid */}
              <div className="grid grid-cols-3 gap-3 mt-4">
                <div className="rounded-2xl p-3 text-center" style={{ background: 'rgba(255,255,255,0.04)' }}>
                  <p className="text-xl font-black" style={{ color: tenant.primary_color }}>
                    {availableCount.toLocaleString('pt-BR')}
                  </p>
                  <p className="text-[10px] text-zinc-500 mt-0.5 font-semibold uppercase">Disponíveis</p>
                </div>
                <div className="rounded-2xl p-3 text-center" style={{ background: 'rgba(255,255,255,0.04)' }}>
                  <p className="text-xl font-black text-white">
                    {soldNums.length.toLocaleString('pt-BR')}
                  </p>
                  <p className="text-[10px] text-zinc-500 mt-0.5 font-semibold uppercase">Vendidos</p>
                </div>
                {hasEndAt ? (
                  <div className="rounded-2xl p-3 text-center" style={{ background: 'rgba(255,255,255,0.04)' }}>
                    <p className="text-xl font-black text-amber-400 tabular-nums">
                      {fmtCountdown(active.end_at!)}
                    </p>
                    <p className="text-[10px] text-zinc-500 mt-0.5 font-semibold uppercase">Para o sorteio</p>
                  </div>
                ) : (
                  <div className="rounded-2xl p-3 text-center" style={{ background: 'rgba(255,255,255,0.04)' }}>
                    <p className="text-xl font-black text-white">
                      R$ {price.toFixed(2).replace('.', ',')}
                    </p>
                    <p className="text-[10px] text-zinc-500 mt-0.5 font-semibold uppercase">Por número</p>
                  </div>
                )}
              </div>

              {/* Flash promo or urgency tag */}
              {flashPromo && flashPct > 0 ? (
                <div className="mt-4 flex items-center gap-2 rounded-2xl bg-orange-500/10 border border-orange-500/20 px-3 py-2.5 text-xs text-orange-300">
                  <Zap size={13} className="shrink-0" />
                  <span className="font-bold">{flashPromo.label}</span>
                  <span className="text-orange-400 font-black ml-auto">{flashPct}% off · {fmtCountdown(flashPromo.ends_at)}</span>
                </div>
              ) : (
                <div className="mt-4 flex items-center gap-2 rounded-2xl px-3 py-2.5 text-xs font-bold"
                  style={{ background: `${tenant.primary_color}15`, color: tenant.primary_color }}>
                  <Clock3 size={13} className="shrink-0" />
                  Garanta seu número agora
                </div>
              )}

              {/* Last winner */}
              {lastWinner && (
                <div className="mt-4 pt-3.5 border-t border-white/5 flex items-center gap-2 flex-wrap">
                  <span className="text-emerald-400 text-xs font-black">Último ganhador:</span>
                  <span className="text-zinc-400 text-xs">
                    {maskWinnerName(lastWinner.usuario_nome)} · nº {lastWinner.winner_number}
                  </span>
                </div>
              )}
            </div>

            {/* ── Grid + Sidebar ─────────────────────────────────────────── */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">

              {/* ── Left: número grid ─────────────────────────────────────── */}
              <div className="lg:col-span-2 space-y-4">

                {/* Quick picks — mobile only (desktop usa sidebar) */}
                <div className="lg:hidden">
                  <p className="text-xs font-black text-zinc-500 uppercase tracking-widest mb-2.5">Escolha Rápida</p>
                  <div className="grid grid-cols-4 gap-2">
                    {quickButtons.map(q => (
                      <button key={q} onClick={() => quickSelect(q)}
                        className="py-3.5 rounded-2xl text-sm font-black border border-zinc-800 bg-zinc-900 text-zinc-300 hover:bg-zinc-800 hover:text-white transition-all active:scale-95">
                        {q}x
                      </button>
                    ))}
                  </div>
                </div>

                {/* Number grid card */}
                <div className="bg-zinc-950 border border-zinc-900 rounded-3xl p-4">
                  <div className="flex items-center justify-between mb-4">
                    <p className="text-sm font-black text-white">
                      Escolha seus números
                    </p>
                    {selected.length > 0 && (
                      <button onClick={() => setSelected([])}
                        className="flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-300 transition-colors">
                        <RotateCcw size={11} /> Limpar
                      </button>
                    )}
                  </div>
                  <NumberGrid
                    total={total_numeros}
                    sold={soldNums}
                    selected={selected}
                    onToggle={toggleNum}
                  />
                </div>
              </div>

              {/* ── Right: sidebar cart (desktop only) ─────────────────────── */}
              <div className="hidden lg:block lg:sticky lg:top-24 h-fit space-y-4">
                <div className="bg-zinc-950 border border-zinc-900 rounded-3xl p-6 space-y-5">

                  {/* Price */}
                  <div>
                    <p className="text-xs font-bold text-zinc-500 uppercase tracking-wider">Número por</p>
                    <p className="text-3xl font-black mt-1" style={{ color: tenant.primary_color }}>
                      R$ {price.toFixed(2).replace('.', ',')}
                    </p>
                  </div>

                  {/* Quick-select */}
                  <div>
                    <p className="text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2.5">
                      <Zap size={10} className="inline mr-1" />Escolha rápida
                    </p>
                    <div className={`grid gap-1.5 ${quickButtons.length <= 4 ? 'grid-cols-4' : 'grid-cols-4'}`}>
                      {quickButtons.map(q => (
                        <button key={q} onClick={() => quickSelect(q)}
                          className="py-2.5 rounded-xl text-sm font-black bg-zinc-900 hover:bg-zinc-800 text-zinc-300 hover:text-white border border-zinc-800 hover:border-zinc-700 transition-all active:scale-95">
                          {q}x
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Cart summary */}
                  <div className="bg-zinc-900 rounded-2xl p-4 space-y-2.5">
                    <div className="flex justify-between text-sm">
                      <span className="text-zinc-400">Números selecionados</span>
                      <span className="text-white font-bold">{selected.length}</span>
                    </div>
                    <div className="h-px bg-zinc-800" />
                    {(() => {
                      const next = getNextTier(discounts, selected.length)
                      return (
                        <>
                          {cartEffPct > 0 ? (
                            <div className={`flex items-center justify-between text-xs px-2 py-1.5 rounded-xl border ${
                              flashPct >= cartQtyPct && flashPct > 0
                                ? 'bg-orange-500/10 border-orange-500/20'
                                : 'bg-emerald-500/10 border-emerald-500/20'
                            }`}>
                              <span className={`font-black ${flashPct >= cartQtyPct && flashPct > 0 ? 'text-orange-400' : 'text-emerald-400'}`}>
                                {flashPct >= cartQtyPct && flashPct > 0 ? '⚡ ' : ''}{cartEffPct}% de desconto
                              </span>
                              <span className={`font-black ${flashPct >= cartQtyPct && flashPct > 0 ? 'text-orange-400' : 'text-emerald-400'}`}>
                                -R$ {(cartSubtotal - cartTotal).toFixed(2).replace('.', ',')}
                              </span>
                            </div>
                          ) : next ? (
                            <div className="flex items-center gap-1.5 text-xs px-2 py-1.5 rounded-xl bg-yellow-500/10 border border-yellow-500/20">
                              <Zap size={11} className="text-yellow-400 shrink-0" />
                              <span className="text-yellow-300">+{next.min_qty - selected.length} números = {next.discount_pct}% off</span>
                            </div>
                          ) : discounts.length > 0 && selected.length === 0 ? (
                            <div className="flex items-center gap-1.5 text-xs px-2 py-1.5 rounded-xl bg-yellow-500/10 border border-yellow-500/20">
                              <Zap size={11} className="text-yellow-400 shrink-0" />
                              <span className="text-yellow-300">{discounts[0]?.min_qty}+ números = {discounts[0]?.discount_pct}% off</span>
                            </div>
                          ) : null}
                          <div className="flex justify-between">
                            <span className="text-zinc-400 text-sm">Total a pagar</span>
                            <div className="text-right">
                              {cartEffPct > 0 && <span className="text-zinc-500 text-xs line-through block">R$ {cartSubtotal.toFixed(2).replace('.', ',')}</span>}
                              <span className={`font-black text-lg ${cartEffPct > 0 ? 'text-emerald-400' : 'text-white'}`}>
                                R$ {cartTotal.toFixed(2).replace('.', ',')}
                              </span>
                            </div>
                          </div>
                        </>
                      )
                    })()}
                  </div>

                  {/* Selected pills */}
                  {selected.length > 0 && (
                    <div>
                      <p className="text-xs font-bold text-zinc-500 uppercase tracking-wider mb-2">Selecionados</p>
                      <div className="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto">
                        {[...selected].sort((a, b) => a - b).map(n => (
                          <button key={n} onClick={() => toggleNum(n)}
                            className="text-xs font-black px-2.5 py-1 rounded-lg text-black hover:opacity-70 transition-opacity"
                            style={{ background: tenant.primary_color }}>
                            {padNum(n, total_numeros)}
                          </button>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* CTA */}
                  <button
                    onClick={() => setCheckout(true)}
                    disabled={selected.length === 0}
                    className="w-full py-4 rounded-2xl font-black text-black flex items-center justify-center gap-2 transition-all hover:opacity-90 disabled:opacity-25 disabled:cursor-not-allowed active:scale-[.98]"
                    style={{ background: tenant.primary_color }}>
                    <ShoppingCart size={18} />
                    {selected.length > 0
                      ? `Garantir ${selected.length} número${selected.length !== 1 ? 's' : ''}`
                      : 'Escolha seus números'}
                  </button>
                </div>
              </div>

            </div>
          </>
        )}
      </div>

      {/* ── Mobile sticky cart bar ──────────────────────────────────────────── */}
      {active && selected.length > 0 && (
        <div className="fixed bottom-0 left-0 right-0 z-30 lg:hidden border-t border-zinc-900 bg-black/95 backdrop-blur-md px-4 py-3">
          <div className="max-w-6xl mx-auto flex items-center gap-3">
            <div className="flex-1 min-w-0">
              <p className="text-xs text-zinc-500">
                {selected.length} número{selected.length !== 1 ? 's' : ''}
                {cartEffPct > 0 && <span className="ml-1 text-emerald-400 font-bold">{cartEffPct}% off</span>}
              </p>
              <p className="text-lg font-black text-white leading-tight">
                R$ {cartTotal.toFixed(2).replace('.', ',')}
              </p>
            </div>
            <button
              onClick={() => setCheckout(true)}
              className="flex items-center gap-2 px-5 py-3.5 rounded-2xl font-black text-black text-sm transition-all hover:opacity-90 active:scale-[.98] shrink-0"
              style={{ background: tenant.primary_color }}>
              <ShoppingCart size={16} />
              FINALIZAR NO PIX
            </button>
          </div>
        </div>
      )}

      {/* ── Checkout drawer ─────────────────────────────────────────────────── */}
      {checkout && active && (
        <CheckoutDrawer
          raffle={active} selected={selected} discounts={discounts} flashPct={flashPct} user={user}
          onClose={() => setCheckout(false)}
          onSuccess={() => { setCheckout(false); setSuccess(true) }}
        />
      )}
    </div>
  )
}
