import { useState, useEffect, useCallback } from 'react'
import { Link } from 'react-router-dom'
import {
  Ticket, Bell, BellOff, CreditCard,
  Briefcase, FileText, Plus, X, GripVertical,
  AlertCircle, CheckCircle, ShoppingCart, RotateCcw,
  Pause, Play, Trash2, Calendar, ChevronDown, ChevronUp,
  User, Save, Mail, Phone, Star, ArrowRight,
  Copy, Check, Printer,
} from 'lucide-react'
import { AuthAPI, RaffleAPI, ClubAPI, JobsAPI, CotacaoClienteAPI, RecorrentesAPI } from '../api'
import { useTenantCtx } from '../context/TenantContext'

interface Props { user: any; onLogout: () => void }

function fmtDate(s: string) { return new Date(s).toLocaleDateString('pt-BR') }
function fmtCpf(cpf: string) { return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4') }

const STATUS_STYLE: Record<string, string> = {
  sold: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
  reserved: 'bg-amber-500/10 text-amber-400 border-amber-500/20',
  expired: 'bg-slate-700 text-slate-500',
  refunded: 'bg-rose-500/10 text-rose-400',
}

const CLUB_STATUS_STYLE: Record<string, string> = {
  active: 'text-emerald-400',
  pending_payment: 'text-amber-400',
  suspended: 'text-rose-400',
}

const APP_STATUS_COLOR: Record<string, string> = {
  novo: 'bg-slate-700 text-slate-300',
  em_analise: 'bg-blue-500/10 text-blue-400 border-blue-500/20',
  aprovado: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20',
  reprovado: 'bg-rose-500/10 text-rose-400 border-rose-500/20',
  contratado: 'bg-violet-500/10 text-violet-400 border-violet-500/20',
}
const APP_STATUS_LABEL: Record<string, string> = {
  novo: 'Enviada', em_analise: 'Em análise', aprovado: 'Aprovado',
  reprovado: 'Não selecionado', contratado: 'Contratado!',
}

// ── Resume Builder ────────────────────────────────────────────────────────────

function ResumeBuilder({ user }: { user: any }) {
  const tenant = useTenantCtx()
  const [resume, setResume] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)
  const [error, setError] = useState('')

  const [form, setForm] = useState({
    user_nome: user?.nome || '',
    email: user?.email || '',
    phone: user?.telefone || '',
    linkedin: '',
    portfolio: '',
    about: '',
    experience: [] as any[],
    education: [] as any[],
    skills: [] as any[],
  })

  useEffect(() => {
    JobsAPI.myResume()
      .then(r => {
        if (r) {
          setResume(r)
          setForm({
            user_nome: r.user_nome || user?.nome || '',
            email: r.email || user?.email || '',
            phone: r.phone || user?.telefone || '',
            linkedin: r.linkedin || '',
            portfolio: r.portfolio || '',
            about: r.about || '',
            experience: r.experience || [],
            education: r.education || [],
            skills: r.skills || [],
          })
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [])

  function addExp() {
    setForm(f => ({
      ...f,
      experience: [...f.experience, { company: '', role: '', start: '', end: '', current: false, description: '' }],
    }))
  }
  function removeExp(i: number) { setForm(f => ({ ...f, experience: f.experience.filter((_, idx) => idx !== i) })) }
  function setExp(i: number, key: string, val: any) {
    setForm(f => {
      const experience = [...f.experience]
      experience[i] = { ...experience[i], [key]: val }
      return { ...f, experience }
    })
  }

  function addEdu() {
    setForm(f => ({
      ...f,
      education: [...f.education, { institution: '', degree: '', course: '', start: '', end: '', current: false }],
    }))
  }
  function removeEdu(i: number) { setForm(f => ({ ...f, education: f.education.filter((_, idx) => idx !== i) })) }
  function setEdu(i: number, key: string, val: any) {
    setForm(f => {
      const education = [...f.education]
      education[i] = { ...education[i], [key]: val }
      return { ...f, education }
    })
  }

  function addSkill() { setForm(f => ({ ...f, skills: [...f.skills, { name: '', level: 'intermediario' }] })) }
  function removeSkill(i: number) { setForm(f => ({ ...f, skills: f.skills.filter((_, idx) => idx !== i) })) }
  function setSkill(i: number, key: string, val: string) {
    setForm(f => {
      const skills = [...f.skills]
      skills[i] = { ...skills[i], [key]: val }
      return { ...f, skills }
    })
  }

  async function save(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true); setSaved(false); setError('')
    try {
      await JobsAPI.saveResume(form)
      setSaved(true)
      setTimeout(() => setSaved(false), 3000)
    } catch (ex: any) {
      setError(ex.response?.data?.error || 'Erro ao salvar')
    } finally { setSaving(false) }
  }

  const inputCls = 'w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-amber-500'
  const labelCls = 'text-xs font-bold text-slate-400 uppercase tracking-wider'
  const sectionTitleCls = 'text-base font-black text-white mb-4 flex items-center justify-between'

  if (loading) return <div className="flex justify-center py-12"><div className="w-7 h-7 border-2 border-amber-500 border-t-transparent rounded-full animate-spin" /></div>

  return (
    <form onSubmit={save} className="space-y-8">
      {/* Dados pessoais */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4">
        <h3 className={sectionTitleCls}>Dados Pessoais</h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <div>
            <label className={labelCls}>Nome completo *</label>
            <input required value={form.user_nome} onChange={e => setForm(f => ({ ...f, user_nome: e.target.value }))} className={`mt-1 ${inputCls}`} />
          </div>
          <div>
            <label className={labelCls}>E-mail</label>
            <input type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} className={`mt-1 ${inputCls}`} />
          </div>
          <div>
            <label className={labelCls}>Telefone</label>
            <input value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} className={`mt-1 ${inputCls}`} />
          </div>
          <div>
            <label className={labelCls}>LinkedIn</label>
            <input value={form.linkedin} onChange={e => setForm(f => ({ ...f, linkedin: e.target.value }))} placeholder="linkedin.com/in/..." className={`mt-1 ${inputCls}`} />
          </div>
          <div className="sm:col-span-2">
            <label className={labelCls}>Portfólio / Site</label>
            <input value={form.portfolio} onChange={e => setForm(f => ({ ...f, portfolio: e.target.value }))} className={`mt-1 ${inputCls}`} />
          </div>
          <div className="sm:col-span-2">
            <label className={labelCls}>Sobre você</label>
            <textarea rows={3} value={form.about} onChange={e => setForm(f => ({ ...f, about: e.target.value }))}
              placeholder="Breve apresentação profissional..."
              className={`mt-1 ${inputCls} resize-none`} />
          </div>
        </div>
      </div>

      {/* Experiências */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4">
        <h3 className={sectionTitleCls}>
          Experiências
          <button type="button" onClick={addExp}
            className="text-xs font-black text-amber-400 hover:text-amber-300 flex items-center gap-1">
            <Plus size={13} /> Adicionar
          </button>
        </h3>
        {form.experience.length === 0 && (
          <p className="text-slate-600 italic text-sm text-center py-4">Nenhuma experiência adicionada</p>
        )}
        {form.experience.map((e, i) => (
          <div key={i} className="border border-slate-800 rounded-xl p-4 space-y-3 relative">
            <button type="button" onClick={() => removeExp(i)}
              className="absolute top-3 right-3 p-1 rounded text-slate-600 hover:text-rose-400 transition-colors">
              <X size={14} />
            </button>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelCls}>Empresa</label>
                <input value={e.company} onChange={ev => setExp(i, 'company', ev.target.value)} className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Cargo</label>
                <input value={e.role} onChange={ev => setExp(i, 'role', ev.target.value)} className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Início</label>
                <input value={e.start} onChange={ev => setExp(i, 'start', ev.target.value)} placeholder="mm/aaaa" className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Fim</label>
                <input value={e.end} onChange={ev => setExp(i, 'end', ev.target.value)} placeholder="mm/aaaa" disabled={e.current} className={`mt-1 ${inputCls} disabled:opacity-40`} />
              </div>
            </div>
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={e.current} onChange={ev => setExp(i, 'current', ev.target.checked)} className="accent-amber-500" />
              <span className="text-sm text-slate-400">Emprego atual</span>
            </label>
            <div>
              <label className={labelCls}>Descrição</label>
              <textarea rows={2} value={e.description} onChange={ev => setExp(i, 'description', ev.target.value)}
                placeholder="Atividades e conquistas..." className={`mt-1 ${inputCls} resize-none`} />
            </div>
          </div>
        ))}
      </div>

      {/* Formação */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4">
        <h3 className={sectionTitleCls}>
          Formação
          <button type="button" onClick={addEdu}
            className="text-xs font-black text-amber-400 hover:text-amber-300 flex items-center gap-1">
            <Plus size={13} /> Adicionar
          </button>
        </h3>
        {form.education.length === 0 && (
          <p className="text-slate-600 italic text-sm text-center py-4">Nenhuma formação adicionada</p>
        )}
        {form.education.map((e, i) => (
          <div key={i} className="border border-slate-800 rounded-xl p-4 space-y-3 relative">
            <button type="button" onClick={() => removeEdu(i)}
              className="absolute top-3 right-3 p-1 rounded text-slate-600 hover:text-rose-400 transition-colors">
              <X size={14} />
            </button>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className={labelCls}>Instituição</label>
                <input value={e.institution} onChange={ev => setEdu(i, 'institution', ev.target.value)} className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Grau</label>
                <select value={e.degree} onChange={ev => setEdu(i, 'degree', ev.target.value)} className={`mt-1 ${inputCls}`}>
                  <option value="">Selecione</option>
                  <option>Ensino Médio</option>
                  <option>Técnico</option>
                  <option>Graduação</option>
                  <option>Pós-Graduação</option>
                  <option>MBA</option>
                  <option>Mestrado</option>
                  <option>Doutorado</option>
                </select>
              </div>
              <div className="col-span-2">
                <label className={labelCls}>Curso</label>
                <input value={e.course} onChange={ev => setEdu(i, 'course', ev.target.value)} className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Início</label>
                <input value={e.start} onChange={ev => setEdu(i, 'start', ev.target.value)} placeholder="aaaa" className={`mt-1 ${inputCls}`} />
              </div>
              <div>
                <label className={labelCls}>Fim</label>
                <input value={e.end} onChange={ev => setEdu(i, 'end', ev.target.value)} placeholder="aaaa" disabled={e.current} className={`mt-1 ${inputCls} disabled:opacity-40`} />
              </div>
            </div>
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={e.current} onChange={ev => setEdu(i, 'current', ev.target.checked)} className="accent-amber-500" />
              <span className="text-sm text-slate-400">Em andamento</span>
            </label>
          </div>
        ))}
      </div>

      {/* Habilidades */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4">
        <h3 className={sectionTitleCls}>
          Habilidades
          <button type="button" onClick={addSkill}
            className="text-xs font-black text-amber-400 hover:text-amber-300 flex items-center gap-1">
            <Plus size={13} /> Adicionar
          </button>
        </h3>
        {form.skills.length === 0 && (
          <p className="text-slate-600 italic text-sm text-center py-4">Nenhuma habilidade adicionada</p>
        )}
        <div className="space-y-2">
          {form.skills.map((s, i) => (
            <div key={i} className="flex gap-2 items-center">
              <GripVertical size={14} className="text-slate-700 shrink-0" />
              <input value={s.name} onChange={e => setSkill(i, 'name', e.target.value)}
                placeholder="Ex: React, Excel, Atendimento..." className={`flex-1 ${inputCls}`} />
              <select value={s.level} onChange={e => setSkill(i, 'level', e.target.value)} className={`w-36 shrink-0 ${inputCls}`}>
                <option value="basico">Básico</option>
                <option value="intermediario">Intermediário</option>
                <option value="avancado">Avançado</option>
              </select>
              <button type="button" onClick={() => removeSkill(i)}
                className="p-1.5 rounded text-slate-600 hover:text-rose-400 transition-colors shrink-0">
                <X size={14} />
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* Save */}
      <div className="flex items-center gap-4">
        <button type="submit" disabled={saving}
          className="px-8 py-3 rounded-xl font-black text-black text-sm transition-all hover:opacity-90 disabled:opacity-40"
          style={{ background: tenant.primary_color }}>
          {saving ? 'Salvando…' : resume ? 'Atualizar Currículo' : 'Salvar Currículo'}
        </button>
        {saved && (
          <span className="flex items-center gap-1.5 text-sm text-emerald-400 font-bold">
            <CheckCircle size={15} /> Salvo!
          </span>
        )}
        {error && (
          <span className="flex items-center gap-1.5 text-sm text-rose-400">
            <AlertCircle size={15} /> {error}
          </span>
        )}
      </div>
    </form>
  )
}

// ── My Applications ───────────────────────────────────────────────────────────

function MyApplications() {
  const [apps, setApps]     = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    JobsAPI.myApplications()
      .then(setApps)
      .catch(() => setApps([]))
      .finally(() => setLoading(false))
  }, [])

  if (loading) return (
    <div className="flex justify-center py-12">
      <div className="w-7 h-7 border-2 border-amber-500 border-t-transparent rounded-full animate-spin" />
    </div>
  )

  if (apps.length === 0) return (
    <div className="text-center py-16">
      <Briefcase size={40} className="text-slate-700 mx-auto mb-3" />
      <p className="text-slate-600 italic text-sm">Você ainda não se candidatou a nenhuma vaga</p>
      <Link to="/vagas" className="mt-4 inline-block text-sm font-bold text-amber-400 hover:text-amber-300">
        Ver vagas disponíveis →
      </Link>
    </div>
  )

  return (
    <div className="space-y-3">
      {apps.map((a, i) => (
        <div key={a.id || i} className="bg-slate-900 border border-slate-800 rounded-2xl p-4">
          <div className="flex items-start justify-between gap-3">
            <div className="flex-1 min-w-0">
              <Link to={`/vagas/${(a as any).job_id || ''}`}
                className="font-black text-white hover:text-amber-400 transition-colors truncate block">
                {a.title || 'Vaga'}
              </Link>
              <p className="text-slate-500 text-xs mt-0.5">
                Candidatado em {fmtDate(a.applied_at)}
              </p>
            </div>
            <span className={`text-[10px] font-black px-2 py-0.5 rounded border shrink-0 ${APP_STATUS_COLOR[a.status] || 'bg-slate-700 text-slate-400'}`}>
              {APP_STATUS_LABEL[a.status] || a.status}
            </span>
          </div>
        </div>
      ))}
    </div>
  )
}

// ── Tab de Pedidos (FUT-02 + FUT-03) ──────────────────────────────────────────

// ─── Botão copiar protocolo ───────────────────────────────────────────────────
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false)
  const handleCopy = useCallback((e: React.MouseEvent) => {
    e.stopPropagation()
    e.preventDefault()
    const showOk = () => {
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
    // Fallback para contextos não seguros (HTTP/.local), onde navigator.clipboard é undefined
    const legacyCopy = () => {
      try {
        const ta = document.createElement('textarea')
        ta.value = text
        ta.setAttribute('readonly', '')
        ta.style.position = 'fixed'
        ta.style.top = '0'
        ta.style.left = '0'
        ta.style.opacity = '0'
        document.body.appendChild(ta)
        ta.focus()
        ta.select()
        const ok = document.execCommand('copy')
        document.body.removeChild(ta)
        if (ok) showOk()
      } catch {}
    }
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(showOk).catch(legacyCopy)
    } else {
      legacyCopy()
    }
  }, [text])
  return (
    <button
      onClick={handleCopy}
      title="Copiar número do pedido"
      className="ml-1 p-1 rounded-md text-slate-500 hover:text-amber-400 hover:bg-amber-500/10 transition-colors shrink-0"
    >
      {copied ? <Check size={12} className="text-emerald-400" /> : <Copy size={12} />}
    </button>
  )
}

// ─── Cupom Fiscal (80mm) ──────────────────────────────────────────────────────
function printCupom(c: any) {
  const protocolo  = c.pedido_protocolo || `Pedido #${c.pedido_id}`
  const dataFmt    = new Date(c.created_at).toLocaleString('pt-BR', { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' })
  const itens      = Array.isArray(c.itens) ? c.itens : []
  const total      = Number(c.total || 0)
  const desconto   = Number(c.desconto || 0)
  const subtotal   = total + desconto
  const pagto: Record<string,string> = { pix:'PIX', cartao:'Cartão', faturado:'Faturado', na_retirada:'Na Retirada', na_entrega:'Na Entrega' }
  const formaPagto = pagto[c.pedido_forma_pagto] ?? (c.pedido_forma_pagto || '—')
  const entrega    = c.pedido_tipo_entrega === 'retirada' ? 'Retirada na loja' : 'Entrega'
  const statusLabel: Record<string,string> = { aguardando:'Aguardando', separacao:'Em Separação', embalagem:'Embalagem', auditoria:'Auditoria', fiscal:'Fiscal', expedicao:'Expedição', entregue:'Entregue', cancelado:'Cancelado' }
  const status     = statusLabel[c.pedido_status] ?? c.pedido_status ?? '—'

  const linha  = '================================'
  const traço  = '--------------------------------'
  const br     = '\n'

  const linhaItem = (nome: string, qtd: number, sub: number) => {
    const nomeStr  = nome.length > 18 ? nome.slice(0, 17) + '…' : nome.padEnd(18)
    const qtdStr   = `${qtd}x`.padStart(4)
    const subStr   = `R$${sub.toFixed(2)}`.padStart(10)
    return `${nomeStr}${qtdStr}${subStr}`
  }

  const itensTxt = itens.map((i: any) =>
    linhaItem(i.nome_produto || '—', Number(i.quantidade), Number(i.subtotal))
  ).join(br)

  const cupom = `
${linha}
     ALEMÃO CONVENIÊNCIAS
${linha}
Data: ${dataFmt}
Pedido: ${protocolo}
Modalidade: ${entrega}
${traço}
PRODUTO           QTD     VALOR
${traço}
${itensTxt}
${traço}
${'SUBTOTAL:'.padEnd(20)}${`R$ ${subtotal.toFixed(2)}`.padStart(12)}
${desconto > 0 ? `${'DESCONTO:'.padEnd(20)}${`- R$ ${desconto.toFixed(2)}`.padStart(12)}\n` : ''}${'TOTAL:'.padEnd(20)}${`R$ ${total.toFixed(2)}`.padStart(12)}
${traço}
${'PAGAMENTO:'.padEnd(20)}${formaPagto.padStart(12)}
STATUS: ${status.toUpperCase()}
${linha}
   Obrigado pela preferência!
   alemaoconveniencias.local
${linha}
`.trim()

  const html = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Cupom ${protocolo}</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: 'Courier New', Courier, monospace;
      font-size: 11px;
      background: #fff;
      color: #000;
      width: 80mm;
      margin: 0 auto;
      padding: 6mm 4mm;
      white-space: pre;
      line-height: 1.5;
    }
    @media print {
      body { width: 80mm; padding: 0; }
      @page { margin: 4mm; size: 80mm auto; }
    }
  </style>
</head>
<body>${cupom}</body>
</html>`

  const win = window.open('', '_blank', 'width=400,height=700,scrollbars=yes')
  if (!win) return
  win.document.write(html)
  win.document.close()
  win.focus()
  setTimeout(() => { win.print() }, 300)
}

// ─── Mini timeline de status ──────────────────────────────────────────────────
const TIMELINE_ETAPAS = [
  { key: 'aguardando', label: 'Recebido',  icon: '📋' },
  { key: 'separacao',  label: 'Separação', icon: '📦' },
  { key: 'embalagem',  label: 'Embalagem', icon: '🎁' },
  { key: 'expedicao',  label: 'Expedição', icon: '🚚' },
  { key: 'entregue',   label: 'Entregue',  icon: '✅' },
]
function fmtHora(iso: string) {
  const d = new Date(iso)
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) +
    ' ' + d.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' })
}
function MiniTimeline({ log, statusAtual, tipoEntrega }: {
  log: { status: string; created_at: string }[]
  statusAtual: string
  tipoEntrega?: string
}) {
  if (statusAtual === 'cancelado') {
    const ts = log?.find(l => l.status === 'cancelado')?.created_at
    return (
      <div className="flex items-center gap-2 text-xs text-rose-400 bg-rose-500/10 border border-rose-500/20 rounded-xl px-3 py-2">
        ❌ <span className="font-semibold">Pedido cancelado</span>
        {ts && <span className="ml-auto text-rose-500">{fmtHora(ts)}</span>}
      </div>
    )
  }
  const etapas = tipoEntrega === 'retirada'
    ? TIMELINE_ETAPAS.filter(e => e.key !== 'expedicao')
    : TIMELINE_ETAPAS
  const logMap: Record<string, string> = {}
  for (const l of (log || [])) logMap[l.status] = l.created_at
  const idxAtual = etapas.findIndex(e => e.key === statusAtual)
  return (
    <div className="flex items-start gap-0">
      {etapas.map((etapa, idx) => {
        const concluida = idx < idxAtual || (statusAtual === etapa.key && etapa.key === 'entregue')
        const atual = etapa.key === statusAtual
        return (
          <div key={etapa.key} className="flex-1 flex flex-col items-center">
            <div className="flex items-center w-full">
              <div className={`h-0.5 flex-1 ${idx === 0 ? 'opacity-0' : concluida || atual ? 'bg-amber-500' : 'bg-slate-700'}`} />
              <div className={`w-6 h-6 rounded-full flex items-center justify-center text-xs shrink-0 border-2 ${
                concluida || atual ? 'bg-amber-500 border-amber-500 text-black' : 'bg-slate-800 border-slate-700 text-slate-600'
              } ${atual && etapa.key !== 'entregue' ? 'ring-2 ring-amber-500/30' : ''}`}>
                {concluida || atual ? etapa.icon : '○'}
              </div>
              <div className={`h-0.5 flex-1 ${idx === etapas.length - 1 ? 'opacity-0' : concluida ? 'bg-amber-500' : 'bg-slate-700'}`} />
            </div>
            <div className="mt-1 text-center">
              <p className={`text-[9px] font-bold leading-tight ${atual ? 'text-amber-400' : concluida ? 'text-slate-400' : 'text-slate-600'}`}>
                {etapa.label}
              </p>
              {logMap[etapa.key] && (
                <p className="text-[8px] text-slate-500">{fmtHora(logMap[etapa.key])}</p>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}

// ─── Alertas de item (loja → comprador) ──────────────────────────────────────
const ALERTA_INFO: Record<string, { emoji: string; label: string; border: string; bg: string; text: string }> = {
  falta:           { emoji: '🚫', label: 'Falta no estoque',  border: 'border-rose-500/40',  bg: 'bg-rose-500/10',  text: 'text-rose-400'  },
  marca_diferente: { emoji: '🔄', label: 'Marca diferente',   border: 'border-amber-500/40', bg: 'bg-amber-500/10', text: 'text-amber-400' },
  substituicao:    { emoji: '📸', label: 'Substituição',      border: 'border-blue-500/40',  bg: 'bg-blue-500/10',  text: 'text-blue-400'  },
}

function AlertaItem({
  item, onConfirmar,
}: {
  item: any
  onConfirmar: (itemId: number) => Promise<void>
}) {
  const [confirming, setConfirming] = useState(false)
  const info = ALERTA_INFO[item.alerta_tipo] ?? {
    emoji: '⚠️', label: item.alerta_tipo,
    border: 'border-slate-600', bg: 'bg-slate-800', text: 'text-slate-300',
  }
  async function handleConfirmar() {
    setConfirming(true)
    try { await onConfirmar(item.id) } finally { setConfirming(false) }
  }
  return (
    <div className={`rounded-xl border ${info.border} ${info.bg} p-3 space-y-2`}>
      <div className="flex items-start gap-2">
        <span className="text-base leading-none mt-0.5">{info.emoji}</span>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <span className={`text-xs font-black ${info.text}`}>{info.label}</span>
            <span className="text-xs text-slate-400 truncate">{item.nome_produto}</span>
          </div>
          {item.alerta_obs && (
            <p className="text-xs text-slate-300 mt-1 leading-snug">{item.alerta_obs}</p>
          )}
        </div>
        {item.alerta_confirmado && (
          <span className="shrink-0 text-[10px] font-black text-emerald-400 bg-emerald-500/10 border border-emerald-500/30 px-2 py-0.5 rounded-full">
            Confirmado ✓
          </span>
        )}
      </div>
      {/* Foto */}
      {item.alerta_foto && (
        <img
          src={item.alerta_foto}
          alt="Foto do item"
          className="rounded-lg w-full max-h-48 object-contain bg-slate-900 border border-white/5"
          onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}
        />
      )}
      {/* Botão confirmar substituição */}
      {item.alerta_tipo === 'substituicao' && !item.alerta_confirmado && (
        <button
          onClick={handleConfirmar}
          disabled={confirming}
          className="w-full py-2 rounded-lg bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/40 text-blue-300 font-black text-xs transition-colors disabled:opacity-50"
        >
          {confirming ? 'Confirmando…' : '✓ Confirmar substituição'}
        </button>
      )}
    </div>
  )
}

const STATUS_PEDIDO: Record<string, { label: string; color: string }> = {
  aguardando: { label: 'Aguardando',  color: 'text-amber-400' },
  separacao:  { label: 'Separação',   color: 'text-blue-400'  },
  embalagem:  { label: 'Embalagem',   color: 'text-violet-400'},
  auditoria:  { label: 'Auditoria',   color: 'text-orange-400'},
  fiscal:     { label: 'Fiscal',      color: 'text-yellow-400'},
  expedicao:  { label: 'Expedição',   color: 'text-cyan-400'  },
  entregue:   { label: 'Entregue',    color: 'text-emerald-400'},
  cancelado:  { label: 'Cancelado',   color: 'text-rose-400'  },
}

const FREQ_LABEL: Record<string, string> = {
  semanal:    'Semanal',
  quinzenal:  'Quinzenal',
  mensal:     'Mensal',
  bimestral:  'Bimestral',
  trimestral: 'Trimestral',
}

function PedidosTab({ clubCards }: { clubCards: any[] }) {
  const [cotacoes, setCotacoes]   = useState<any[]>([])
  const [recorrentes, setRec]     = useState<any[]>([])
  const [sub, setSub]             = useState<'historico' | 'recorrentes'>('historico')
  const [loading, setLoading]     = useState(true)
  const [expanded, setExpanded]   = useState<number | null>(null)
  const tenant = useTenantCtx()

  // FUT-03: verifica se é sócio ativo
  const isSocio = clubCards.some(c => c.status === 'active')

  useEffect(() => {
    Promise.all([
      CotacaoClienteAPI.minhas().catch(() => []),
      RecorrentesAPI.list().catch(() => []),
    ]).then(([c, r]) => {
      setCotacoes(c)
      setRec(r)
    }).finally(() => setLoading(false))
  }, [])

  async function confirmarAlerta(cotacaoId: number, itemId: number) {
    await CotacaoClienteAPI.confirmarAlerta(itemId)
    setCotacoes(prev => prev.map(c => {
      if (c.id !== cotacaoId) return c
      return {
        ...c,
        itens: (c.itens || []).map((i: any) =>
          i.id === itemId ? { ...i, alerta_confirmado: true } : i
        ),
      }
    }))
  }

  async function togglePausa(id: number) {
    try {
      const r = await RecorrentesAPI.togglePausa(id)
      setRec(prev => prev.map(p => p.id === id ? { ...p, pausado: r.pausado } : p))
    } catch {}
  }

  async function removerRec(id: number) {
    if (!confirm('Remover pedido recorrente?')) return
    try {
      await RecorrentesAPI.remove(id)
      setRec(prev => prev.filter(p => p.id !== id))
    } catch {}
  }

  if (loading) return (
    <div className="flex items-center justify-center py-12 text-slate-500 text-sm">
      Carregando…
    </div>
  )

  return (
    <div className="space-y-4">
      {/* FUT-03 — Badge de sócio */}
      {isSocio && (
        <div className="bg-amber-500/10 border border-amber-500/20 rounded-2xl px-4 py-3 flex items-center gap-3">
          <span className="text-lg">⭐</span>
          <div>
            <p className="text-amber-400 font-bold text-sm">Benefício de Sócio</p>
            <p className="text-amber-300/60 text-xs">Sua assinatura ativa inclui prioridade de atendimento nas cotações</p>
          </div>
        </div>
      )}

      {/* Sub-tabs */}
      <div className="flex gap-1 bg-slate-900 rounded-xl p-1 border border-slate-800">
        {([
          { key: 'historico',   label: 'Histórico',    icon: ShoppingCart },
          { key: 'recorrentes', label: 'Recorrentes',  icon: RotateCcw   },
        ] as const).map(({ key, label, icon: Icon }) => (
          <button key={key} onClick={() => setSub(key)}
            className={`flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-xs font-bold transition-all ${
              sub === key ? 'bg-slate-800 text-white' : 'text-slate-500 hover:text-slate-300'
            }`}>
            <Icon size={13} /> {label}
          </button>
        ))}
      </div>

      {/* Histórico de cotações */}
      {sub === 'historico' && (
        cotacoes.length === 0 ? (
          <div className="text-center py-12 text-slate-600">
            <ShoppingCart size={40} className="mx-auto mb-2 opacity-40" />
            <p className="text-sm">Nenhum pedido realizado ainda</p>
            <Link to="/catalogo"
              className="mt-3 inline-block px-4 py-2 rounded-xl text-sm font-bold text-black"
              style={{ background: tenant.primary_color }}>
              Ir ao Catálogo
            </Link>
          </div>
        ) : (
          <div className="space-y-2">
            {cotacoes.filter((c: any) => c.status !== 'rascunho').map((c: any) => {
              const temPedido = !!c.pedido_id
              const statusKey = temPedido ? c.pedido_status : c.status
              const st = STATUS_PEDIDO[statusKey] || { label: statusKey, color: 'text-slate-400' }
              const titulo = temPedido
                ? (c.pedido_protocolo || `Pedido #${c.pedido_id}`)
                : `Cotação #${c.id}`
              const open = expanded === c.id
              return (
                <div key={c.id} className="bg-slate-900 border border-white/8 rounded-2xl overflow-hidden">
                  <button
                    onClick={() => setExpanded(open ? null : c.id)}
                    className="w-full flex items-center gap-3 px-4 py-3 text-left"
                  >
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-0.5">
                        <p className="text-white text-sm font-bold truncate">{titulo}</p>
                        {temPedido && c.pedido_protocolo && (
                          <CopyButton text={c.pedido_protocolo} />
                        )}
                        {temPedido && (
                          <button
                            onClick={e => { e.stopPropagation(); e.preventDefault(); printCupom(c) }}
                            title="Imprimir cupom fiscal"
                            className="ml-0.5 p-1 rounded-md text-slate-500 hover:text-amber-400 hover:bg-amber-500/10 transition-colors shrink-0"
                          >
                            <Printer size={12} />
                          </button>
                        )}
                      </div>
                      <p className="text-slate-500 text-xs">{new Date(c.created_at).toLocaleDateString('pt-BR')}</p>
                    </div>
                    <span className={`text-xs font-black shrink-0 ${st.color}`}>{st.label}</span>
                    <span className="text-xs font-black text-slate-300 shrink-0">
                      R$ {Number(c.total || 0).toFixed(2).replace('.', ',')}
                    </span>
                    {open ? <ChevronUp size={14} className="text-slate-500 shrink-0" /> : <ChevronDown size={14} className="text-slate-500 shrink-0" />}
                  </button>
                  {open && (
                    <div className="border-t border-white/5 px-4 pb-4 pt-3 space-y-3">
                      {/* Timeline de status */}
                      {temPedido && c.pedido_status && c.pedido_status !== 'cancelado' && (
                        <MiniTimeline
                          log={c.pedido_status_log || []}
                          statusAtual={c.pedido_status}
                          tipoEntrega={c.pedido_tipo_entrega}
                        />
                      )}
                      {temPedido && c.pedido_status === 'cancelado' && (
                        <MiniTimeline
                          log={c.pedido_status_log || []}
                          statusAtual="cancelado"
                        />
                      )}
                      {/* Itens do pedido */}
                      {c.itens && c.itens.length > 0 && (
                        <div className="space-y-1 pt-1 border-t border-white/5">
                          {c.itens.map((item: any) => (
                            <div key={item.id} className="flex justify-between text-xs text-slate-400">
                              <span className="truncate flex-1">{item.nome_produto}</span>
                              <span className="shrink-0 ml-2">×{item.quantidade}</span>
                            </div>
                          ))}
                        </div>
                      )}
                      {/* Alertas da loja */}
                      {c.itens?.some((i: any) => i.alerta_tipo) && (
                        <div className="space-y-2 pt-2 border-t border-white/5">
                          <p className="text-[10px] uppercase tracking-widest text-slate-500 font-black">
                            ⚠️ Atenção da loja
                          </p>
                          {c.itens.filter((i: any) => i.alerta_tipo).map((item: any) => (
                            <AlertaItem
                              key={item.id}
                              item={item}
                              onConfirmar={(itemId) => confirmarAlerta(c.id, itemId)}
                            />
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )
      )}

      {/* Pedidos Recorrentes */}
      {sub === 'recorrentes' && (
        <div className="space-y-3">
          {recorrentes.length === 0 ? (
            <div className="text-center py-12 text-slate-600">
              <RotateCcw size={40} className="mx-auto mb-2 opacity-40" />
              <p className="text-sm">Nenhum pedido recorrente configurado</p>
              <p className="text-xs text-slate-700 mt-1">Configure recompras automáticas a partir do catálogo</p>
            </div>
          ) : (
            recorrentes.map((r: any) => (
              <div key={r.id}
                className={`bg-slate-900 border rounded-2xl p-4 ${r.pausado ? 'border-slate-700 opacity-60' : 'border-white/10'}`}>
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1 min-w-0">
                    <p className="text-white font-bold text-sm truncate">{r.nome}</p>
                    <div className="flex items-center gap-3 mt-1 text-xs text-slate-500">
                      <span className="flex items-center gap-1"><Calendar size={11} /> {FREQ_LABEL[r.frequencia] || r.frequencia}</span>
                      <span>Próximo: {new Date(r.proximo_em).toLocaleDateString('pt-BR')}</span>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button onClick={() => togglePausa(r.id)}
                      className={`p-1.5 rounded-lg transition-colors ${r.pausado ? 'text-emerald-400 hover:bg-emerald-500/10' : 'text-amber-400 hover:bg-amber-500/10'}`}>
                      {r.pausado ? <Play size={15} /> : <Pause size={15} />}
                    </button>
                    <button onClick={() => removerRec(r.id)}
                      className="p-1.5 rounded-lg text-rose-400 hover:bg-rose-500/10 transition-colors">
                      <Trash2 size={15} />
                    </button>
                  </div>
                </div>
                {/* Itens */}
                <div className="mt-2 flex flex-wrap gap-1">
                  {(Array.isArray(r.itens) ? r.itens : []).slice(0, 3).map((item: any, i: number) => (
                    <span key={i} className="text-[10px] bg-slate-800 text-slate-400 px-2 py-0.5 rounded-full">
                      {item.nome_produto || item.nome} ×{item.quantidade}
                    </span>
                  ))}
                  {(Array.isArray(r.itens) ? r.itens : []).length > 3 && (
                    <span className="text-[10px] bg-slate-800 text-slate-500 px-2 py-0.5 rounded-full">
                      +{r.itens.length - 3} mais
                    </span>
                  )}
                </div>
                {r.pausado && (
                  <p className="text-xs text-amber-500 mt-2 font-bold">⏸ Pausado</p>
                )}
              </div>
            ))
          )}
        </div>
      )}
    </div>
  )
}

// ── Conta Tab ────────────────────────────────────────────────────────────────

function ContaTab({ user }: { user: any }) {
  const [nome, setNome]         = useState(user?.nome || '')
  const [email, setEmail]       = useState(user?.email || '')
  const [telefone, setTelefone] = useState(user?.telefone || '')
  const [saving, setSaving]     = useState(false)
  const [saved, setSaved]       = useState(false)
  const [erroSave, setErroSave] = useState('')

  const [optin, setOptin]       = useState(user?.whatsapp_optin !== false)
  const [savingOptin, setSavingOptin] = useState(false)

  const [notifs, setNotifs]   = useState<any[]>([])
  const [unread, setUnread]   = useState(0)
  const [loadingN, setLoadingN] = useState(true)

  useEffect(() => {
    AuthAPI.getNotifications()
      .then(d => { setNotifs(d.notifications); setUnread(d.unread) })
      .catch(() => {})
      .finally(() => setLoadingN(false))
  }, [])

  async function toggleOptin() {
    setSavingOptin(true)
    try { await AuthAPI.updateOptin(!optin); setOptin(o => !o) }
    catch {} finally { setSavingOptin(false) }
  }

  async function salvarDados(e: React.FormEvent) {
    e.preventDefault()
    if (!nome.trim()) return
    setSaving(true); setErroSave(''); setSaved(false)
    try {
      await AuthAPI.updateMe({ nome, email, telefone })
      setSaved(true)
      setTimeout(() => setSaved(false), 3000)
    } catch (err: any) {
      setErroSave(err?.response?.data?.error ?? 'Erro ao salvar')
    } finally { setSaving(false) }
  }

  async function marcarLida(id: number) {
    await AuthAPI.markNotificationRead(id).catch(() => {})
    setNotifs(ns => ns.map(n => n.id === id ? { ...n, read_at: new Date().toISOString() } : n))
    setUnread(u => Math.max(0, u - 1))
  }

  const fmtDt = (d: string) => d ? new Date(d).toLocaleString('pt-BR', { day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit' }) : '—'
  const inp = 'w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2.5 text-sm text-white focus:outline-none focus:border-amber-500 placeholder:text-slate-600'

  return (
    <div className="space-y-6">
      {/* Meus Dados */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5">
        <h3 className="text-base font-black text-white mb-4 flex items-center gap-2">
          <User size={16} className="text-amber-400" /> Meus Dados
        </h3>
        <form onSubmit={salvarDados} className="space-y-4">
          <div className="grid sm:grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">Nome completo</label>
              <input value={nome} onChange={e => setNome(e.target.value)} required className={`mt-1 ${inp}`} />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider">CPF</label>
              <input value={user?.cpf || ''} disabled className={`mt-1 ${inp} opacity-40 cursor-not-allowed`} />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1"><Mail size={11} /> E-mail</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" className={`mt-1 ${inp}`} />
            </div>
            <div>
              <label className="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1"><Phone size={11} /> Telefone</label>
              <input type="tel" value={telefone} onChange={e => setTelefone(e.target.value)} placeholder="(11) 99999-9999" className={`mt-1 ${inp}`} />
            </div>
          </div>
          {erroSave && <p className="text-rose-400 text-xs flex items-center gap-1"><AlertCircle size={12} /> {erroSave}</p>}
          <div className="flex items-center gap-3">
            <button type="submit" disabled={saving}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-amber-500 hover:bg-amber-400 text-black font-black text-sm transition-colors disabled:opacity-50">
              {saving ? <div className="w-4 h-4 border-2 border-black border-t-transparent rounded-full animate-spin" /> : <Save size={14} />}
              Salvar alterações
            </button>
            {saved && <span className="text-emerald-400 text-sm flex items-center gap-1"><CheckCircle size={14} /> Salvo!</span>}
          </div>
        </form>
      </div>

      {/* WhatsApp optin */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className={`p-3 rounded-2xl ${optin ? 'bg-emerald-500/10 text-emerald-400' : 'bg-slate-800 text-slate-500'}`}>
            {optin ? <Bell size={20} /> : <BellOff size={20} />}
          </div>
          <div>
            <p className="font-bold text-white text-sm">Notificações WhatsApp</p>
            <p className="text-slate-500 text-xs">{optin ? 'Ativas — você recebe alertas de sorteios' : 'Desativadas'}</p>
          </div>
        </div>
        <button onClick={toggleOptin} disabled={savingOptin}
          className={`relative w-12 h-6 rounded-full transition-all disabled:opacity-60 ${optin ? 'bg-emerald-500' : 'bg-slate-700'}`}>
          <span className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${optin ? 'translate-x-6' : ''}`} />
        </button>
      </div>

      {/* Notificações */}
      <div className="bg-slate-900 border border-slate-800 rounded-2xl p-5">
        <h3 className="text-base font-black text-white mb-4 flex items-center gap-2">
          <Bell size={16} className="text-amber-400" />
          Notificações
          {unread > 0 && (
            <span className="ml-auto text-[11px] bg-rose-500 text-white font-black px-2 py-0.5 rounded-full">{unread} nova{unread > 1 ? 's' : ''}</span>
          )}
        </h3>
        {loadingN ? (
          <div className="space-y-2">{[1,2,3].map(i => <div key={i} className="h-12 bg-slate-800 rounded-xl animate-pulse" />)}</div>
        ) : notifs.length === 0 ? (
          <div className="text-center py-10">
            <Bell size={32} className="text-slate-700 mx-auto mb-2" />
            <p className="text-slate-600 text-sm italic">Nenhuma notificação ainda.</p>
          </div>
        ) : (
          <ul className="space-y-2">
            {notifs.map(n => (
              <li key={n.id} onClick={() => !n.read_at && marcarLida(n.id)}
                className={`flex items-start gap-3 rounded-xl p-3 transition-colors cursor-pointer
                  ${n.read_at ? 'opacity-50' : 'bg-slate-800 hover:bg-slate-700/80'}`}>
                <div className={`w-2 h-2 rounded-full mt-1.5 shrink-0 ${n.read_at ? 'bg-slate-600' : 'bg-amber-400'}`} />
                <div className="flex-1 min-w-0">
                  {n.title && <p className="text-sm font-bold text-white leading-tight">{n.title}</p>}
                  <p className="text-sm text-slate-400">{n.message}</p>
                  <p className="text-xs text-slate-600 mt-0.5">{fmtDt(n.created_at)}</p>
                </div>
                {!n.read_at && <span className="text-[10px] text-amber-400 font-bold shrink-0">Marcar lida</span>}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  )
}

// ── Sorteios Tab ─────────────────────────────────────────────────────────────

function SorteiosTab({ tickets }: { tickets: any[] }) {
  const [ativos, setAtivos] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    RaffleAPI.list()
      .then(d => setAtivos(Array.isArray(d) ? d.filter((r: any) => r.status === 'active' || r.active) : []))
      .catch(() => setAtivos([]))
      .finally(() => setLoading(false))
  }, [])

  return (
    <div className="space-y-6">
      {/* Sorteios ativos */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-xs font-black text-slate-400 uppercase tracking-widest">Sorteios em andamento</h3>
          <Link to="/raffle" className="flex items-center gap-1 text-xs text-amber-400 font-bold hover:text-amber-300">
            Ver todos <ArrowRight size={12} />
          </Link>
        </div>
        {loading ? (
          <div className="space-y-2">{[1,2].map(i => <div key={i} className="h-20 bg-slate-900 rounded-2xl animate-pulse" />)}</div>
        ) : ativos.length === 0 ? (
          <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 text-center">
            <Star size={28} className="text-slate-700 mx-auto mb-2" />
            <p className="text-slate-500 text-sm">Nenhum sorteio ativo no momento</p>
          </div>
        ) : (
          <div className="space-y-2">
            {ativos.map((r: any) => (
              <Link key={r.id} to="/raffle"
                className="flex items-center gap-4 bg-slate-900 border border-amber-500/20 hover:border-amber-500/50 rounded-2xl p-4 transition-colors group">
                <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center shrink-0">
                  <Star size={18} className="text-amber-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="font-bold text-white text-sm truncate">{r.titulo || r.name || 'Sorteio'}</p>
                  <p className="text-slate-500 text-xs mt-0.5">
                    {r.preco_bilhete != null ? `R$ ${Number(r.preco_bilhete).toFixed(2).replace('.', ',')} por número` : 'Participar'}
                  </p>
                </div>
                <div className="shrink-0 flex items-center gap-2">
                  <span className="text-[10px] bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 font-black px-2 py-0.5 rounded-full">Ativo</span>
                  <ArrowRight size={14} className="text-slate-600 group-hover:text-amber-400 transition-colors" />
                </div>
              </Link>
            ))}
          </div>
        )}
        <Link to="/raffle"
          className="mt-3 w-full flex items-center justify-center gap-2 py-3 rounded-2xl border border-amber-500/30 bg-amber-500/5 hover:bg-amber-500/10 text-amber-400 font-black text-sm transition-colors">
          <Ticket size={16} /> Participar de um Sorteio
        </Link>
      </div>

      {/* Meus bilhetes */}
      <div>
        <h3 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-3">Meus bilhetes</h3>
        {tickets.length === 0 ? (
          <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 text-center">
            <Ticket size={28} className="text-slate-700 mx-auto mb-2" />
            <p className="text-slate-500 text-sm">Você ainda não tem bilhetes</p>
          </div>
        ) : (
          <div className="space-y-2">
            {tickets.map((t, i) => (
              <div key={t.id || i}
                className="bg-slate-900 border border-slate-800 rounded-2xl px-4 py-3 flex items-center justify-between">
                <div>
                  <p className="font-bold text-white text-sm">{t.raffle_name || 'Sorteio'}</p>
                  <p className="text-slate-500 text-xs mt-0.5">
                    Nº <span className="font-black text-amber-400">#{t.numero || t.number}</span>
                    <span className="ml-2 text-slate-600">{fmtDate(t.data_compra || t.created_at)}</span>
                  </p>
                </div>
                <span className={`text-xs font-bold px-2.5 py-1 rounded-full border ${STATUS_STYLE[t.status] || 'bg-slate-700 text-slate-400'}`}>
                  {t.status === 'sold' ? 'Pago' : t.status === 'reserved' ? 'Reservado' : t.status}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

// ── Dashboard ─────────────────────────────────────────────────────────────────

type Tab = 'sorteios' | 'clube' | 'pedidos' | 'vagas' | 'conta'

const NAV_ITEMS: { key: Tab; label: string; icon: any }[] = [
  { key: 'sorteios', label: 'Sorteios', icon: Ticket       },
  { key: 'clube',    label: 'Clube',    icon: CreditCard   },
  { key: 'pedidos',  label: 'Pedidos',  icon: ShoppingCart },
  { key: 'vagas',    label: 'Vagas',    icon: Briefcase    },
  { key: 'conta',    label: 'Conta',    icon: User         },
]

function Avatar({ nome }: { nome: string }) {
  const initials = (nome || 'Cliente').split(' ').slice(0, 2).map((w: string) => w?.[0] || '').join('').toUpperCase()
  return (
    <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center shrink-0">
      <span className="text-black font-black text-lg">{initials}</span>
    </div>
  )
}

export default function DashboardPage({ user }: Props) {
  const [tickets, setTickets]     = useState<any[]>([])
  const [clubCards, setClubCards] = useState<any[]>([])
  const [tab, setTab]             = useState<Tab>('sorteios')
  const [vagasTab, setVagasTab]   = useState<'candidaturas' | 'curriculo'>('candidaturas')
  const tenant = useTenantCtx()

  useEffect(() => {
    RaffleAPI.myTickets().then(setTickets).catch(() => {})
    if (user?.cpf) {
      ClubAPI.getCard(user.cpf.replace(/\D/g, '')).then(setClubCards).catch(() => {})
    }
  }, [])

  const firstName = user?.nome?.split(' ')[0] || 'Cliente'

  return (
    <div className="min-h-screen bg-black pt-16">
      <div className="max-w-5xl mx-auto flex min-h-[calc(100vh-4rem)]">

        {/* ── Sidebar (desktop) ─────────────────────────────────────────────── */}
        <aside className="hidden md:flex flex-col w-64 shrink-0 border-r border-white/5 px-4 py-8 sticky top-16 self-start h-[calc(100vh-4rem)]">
          {/* Profile card */}
          <div className="flex items-center gap-3 mb-8 px-2">
            <Avatar nome={user?.nome || 'U'} />
            <div className="min-w-0">
              <p className="font-black text-white truncate">{user?.nome || 'Cliente'}</p>
              <p className="text-slate-500 text-xs truncate">{user?.email || fmtCpf(user?.cpf || '')}</p>
            </div>
          </div>

          {/* Nav */}
          <nav className="flex flex-col gap-1 flex-1">
            {NAV_ITEMS.map(({ key, label, icon: Icon }) => (
              <button key={key} onClick={() => setTab(key)}
                className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-bold transition-all text-left w-full ${
                  tab === key
                    ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20'
                    : 'text-slate-400 hover:text-white hover:bg-white/5'
                }`}>
                <Icon size={16} className={tab === key ? 'text-amber-400' : 'text-slate-500'} />
                {label}
              </button>
            ))}
          </nav>

          {/* Atalhos */}
          <div className="mt-auto pt-6 border-t border-white/5 space-y-1">
            <Link to="/catalogo" className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm text-slate-500 hover:text-white hover:bg-white/5 font-medium transition-all">
              <ShoppingCart size={15} /> Catálogo
            </Link>
            <Link to="/raffle" className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm text-slate-500 hover:text-white hover:bg-white/5 font-medium transition-all">
              <Star size={15} /> Sorteios
            </Link>
            <a
              href="https://wa.me/556799138694"
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm text-emerald-500 hover:text-emerald-400 hover:bg-emerald-500/10 font-medium transition-all"
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
              </svg>
              Fale no WhatsApp
            </a>
          </div>
        </aside>

        {/* ── Main content ──────────────────────────────────────────────────── */}
        <main className="flex-1 px-4 md:px-8 py-6 md:py-8 pb-24 md:pb-8">
          {/* Mobile header */}
          <div className="flex items-center gap-3 mb-6 md:hidden">
            <Avatar nome={user?.nome || 'U'} />
            <div>
              <p className="text-white font-black text-lg leading-tight">Olá, {firstName}!</p>
              <p className="text-slate-500 text-xs">{user?.email || fmtCpf(user?.cpf || '')}</p>
            </div>
          </div>

          {/* Desktop section title */}
          <div className="hidden md:block mb-6">
            <h1 className="text-2xl font-black text-white tracking-tight">
              {NAV_ITEMS.find(n => n.key === tab)?.label}
            </h1>
            <p className="text-slate-500 text-sm mt-0.5">Olá, {firstName}!</p>
          </div>

          {/* ── Tab content ───────────────────────────────────────────────── */}
          {tab === 'sorteios' && <SorteiosTab tickets={tickets} />}

          {tab === 'clube' && (
            <div className="space-y-3">
              {clubCards.length === 0 ? (
                <div className="text-center py-16">
                  <CreditCard size={48} className="text-slate-700 mx-auto mb-3" />
                  <p className="text-slate-500 mb-5">Você não possui assinatura ativa</p>
                  <div className="flex gap-3 justify-center">
                    <Link to="/clube/odonto" className="px-5 py-2.5 rounded-xl text-sm font-black text-black transition-all hover:opacity-90" style={{ background: tenant.primary_color }}>
                      Clube Odonto
                    </Link>
                    <Link to="/clube/medico" className="px-5 py-2.5 rounded-xl text-sm font-black text-black transition-all hover:opacity-90" style={{ background: tenant.secondary_color }}>
                      Clube Médico
                    </Link>
                  </div>
                </div>
              ) : clubCards.map((c, i) => (
                <div key={c.id || i} className="bg-slate-900 border border-slate-800 rounded-2xl p-5 space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-black text-white text-base">{c.club_name}</p>
                      <p className="text-slate-500 text-sm">{c.plan_name}</p>
                    </div>
                    <span className={`font-bold text-sm ${CLUB_STATUS_STYLE[c.status] || 'text-slate-400'}`}>
                      {c.status === 'active' ? '● Ativo' : c.status === 'pending_payment' ? '◎ Aguard. Pgto' : '○ Suspenso'}
                    </span>
                  </div>
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    {[
                      ['CPF', fmtCpf(c.user_cpf)],
                      ['Próx. cobrança', c.next_billing_at ? fmtDate(c.next_billing_at) : '—'],
                      ['Mensalidade', `R$ ${Number(c.price_monthly).toFixed(2).replace('.', ',')}`],
                      ['Membro desde', c.started_at ? fmtDate(c.started_at) : '—'],
                    ].map(([label, value]) => (
                      <div key={label} className="bg-slate-800/50 rounded-xl p-3">
                        <p className="text-slate-500 text-xs mb-0.5">{label}</p>
                        <p className="text-white font-bold">{value}</p>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}

          {tab === 'pedidos' && <PedidosTab clubCards={clubCards} />}

          {tab === 'vagas' && (
            <div className="space-y-6">
              <div className="flex gap-1 border-b border-slate-800">
                {([
                  { key: 'candidaturas', label: 'Candidaturas', icon: Briefcase },
                  { key: 'curriculo',    label: 'Meu Currículo', icon: FileText  },
                ] as const).map(({ key, label, icon: Icon }) => (
                  <button key={key} onClick={() => setVagasTab(key)}
                    className={`flex items-center gap-2 px-4 py-3 text-sm font-bold border-b-2 transition-all ${
                      vagasTab === key ? 'border-amber-400 text-amber-400' : 'border-transparent text-slate-500 hover:text-slate-300'
                    }`}>
                    <Icon size={14} /> {label}
                  </button>
                ))}
              </div>
              {vagasTab === 'candidaturas' && <MyApplications />}
              {vagasTab === 'curriculo'    && <ResumeBuilder user={user} />}
            </div>
          )}

          {tab === 'conta' && <ContaTab user={user} />}
        </main>
      </div>

      {/* ── WhatsApp FAB (mobile) ────────────────────────────────────────────── */}
      <a
        href="https://wa.me/556799138694"
        target="_blank"
        rel="noopener noreferrer"
        className="md:hidden fixed bottom-20 right-4 z-50 flex items-center gap-2 bg-[#25d366] text-white pl-3 pr-4 py-2.5 rounded-full shadow-lg shadow-green-900/40 active:scale-95 transition-transform"
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
        </svg>
        <span className="text-xs font-black">WhatsApp</span>
      </a>

      {/* ── Bottom nav (mobile) ───────────────────────────────────────────────── */}
      <nav className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-slate-950 border-t border-white/10 flex">
        {NAV_ITEMS.map(({ key, label, icon: Icon }) => (
          <button key={key} onClick={() => setTab(key)}
            className={`flex-1 flex flex-col items-center gap-0.5 py-2.5 transition-colors ${
              tab === key ? 'text-amber-400' : 'text-slate-500'
            }`}>
            <Icon size={20} strokeWidth={tab === key ? 2.5 : 1.8} />
            <span className="text-[10px] font-bold">{label}</span>
          </button>
        ))}
      </nav>
    </div>
  )
}
