import { useState, useEffect } from 'react';
import { ClienteService } from '../services/api';
import {
  Users, Plus, Search, RefreshCw, X, Check, ChevronDown,
  Building2, User, Phone, MapPin, UserCheck, Pencil, Trash2,
  ChevronRight, ChevronLeft,
} from 'lucide-react';

// ─── helpers ──────────────────────────────────────────────────────────────────

function Badge({ children, color = 'slate' }: { children: React.ReactNode; color?: string }) {
  const cls: Record<string, string> = {
    emerald: 'bg-emerald-400/10 text-emerald-400 border-emerald-400/20',
    rose:    'bg-rose-400/10 text-rose-400 border-rose-400/20',
    cyan:    'bg-cyan-400/10 text-cyan-400 border-cyan-400/20',
    purple:  'bg-purple-400/10 text-purple-400 border-purple-400/20',
    slate:   'bg-slate-800 text-slate-400 border-slate-700',
  };
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded-lg text-[10px] font-black uppercase tracking-widest border ${cls[color] || cls.slate}`}>
      {children}
    </span>
  );
}

function Input({ label, ...props }: { label: string } & React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <div>
      <label className="block text-xs font-black text-slate-500 uppercase tracking-widest mb-1">{label}</label>
      <input {...props}
        className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 placeholder:text-slate-600 disabled:opacity-50" />
    </div>
  );
}

function Select({ label, children, ...props }: { label: string } & React.SelectHTMLAttributes<HTMLSelectElement>) {
  return (
    <div>
      <label className="block text-xs font-black text-slate-500 uppercase tracking-widest mb-1">{label}</label>
      <select {...props}
        className="w-full bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500 appearance-none cursor-pointer">
        {children}
      </select>
    </div>
  );
}

const maskCPF  = (v: string) => v.replace(/\D/g,'').slice(0,11).replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d{1,2})$/,'$1-$2');
const maskCNPJ = (v: string) => v.replace(/\D/g,'').slice(0,14).replace(/(\d{2})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1/$2').replace(/(\d{4})(\d{1,2})$/,'$1-$2');

async function buscaCEP(cep: string) {
  const c = cep.replace(/\D/g,'');
  if (c.length !== 8) return null;
  try {
    const r = await fetch(`https://viacep.com.br/ws/${c}/json/`);
    const d = await r.json();
    if (d.erro) return null;
    return d;
  } catch { return null; }
}

// ─── Modal principal ──────────────────────────────────────────────────────────

type Tab = 'dados' | 'enderecos' | 'telefones' | 'responsaveis';

function ClienteModal({ cliente, onClose, onSave }: {
  cliente: any | null;
  onClose: () => void;
  onSave: () => void;
}) {
  const isEdit = !!cliente;
  const [tab, setTab] = useState<Tab>('dados');
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');

  // Dados gerais
  const [tipo,    setTipo]    = useState<'PF'|'PJ'>(cliente?.tipo || 'PF');
  const [nome,    setNome]    = useState(cliente?.nome || '');
  const [doc,     setDoc]     = useState(cliente?.cpf_cnpj || '');
  const [email,   setEmail]   = useState(cliente?.email || '');
  const [status,  setStatus]  = useState(cliente?.status || 'ativo');

  // Endereços
  const [enderecos, setEnderecos] = useState<any[]>([]);
  const [loadingEnd, setLoadingEnd] = useState(false);
  const [novoEnd, setNovoEnd] = useState<any>({tipo:'entrega',cep:'',rua:'',numero:'',complemento:'',bairro:'',cidade:'',estado:'',referencia:'',principal:false});

  // Telefones
  const [telefones, setTelefones] = useState<any[]>([]);
  const [novoTel, setNovoTel] = useState<any>({tipo:'celular',numero:'',ramal:'',aceita_whatsapp:false,principal:false});

  // Responsáveis
  const [responsaveis, setResponsaveis] = useState<any[]>([]);
  const [novoResp, setNovoResp] = useState<any>({nome:'',cargo:'',setor:'',email:'',permissao:''});

  useEffect(() => {
    if (!isEdit || !cliente?.id) return;
    if (tab === 'enderecos' && enderecos.length === 0) {
      setLoadingEnd(true);
      ClienteService.listEnderecos(cliente.id).then(setEnderecos).finally(() => setLoadingEnd(false));
    }
    if (tab === 'telefones' && telefones.length === 0)
      ClienteService.listTelefones(cliente.id).then(setTelefones);
    if (tab === 'responsaveis' && responsaveis.length === 0)
      ClienteService.listResponsaveis(cliente.id).then(setResponsaveis);
  }, [tab]);

  // Salva dados gerais
  async function salvarDados() {
    setErr('');
    if (!nome.trim()) return setErr('Nome é obrigatório');
    if (!doc.trim())  return setErr('CPF/CNPJ é obrigatório');
    setSaving(true);
    try {
      const payload = { tipo, nome: nome.trim(), cpf_cnpj: doc.replace(/\D/g,''), email, status };
      if (isEdit) await ClienteService.update(cliente.id, payload);
      else        await ClienteService.create(payload);
      onSave();
    } catch (e: any) {
      setErr(e.response?.data?.error || 'Erro ao salvar');
    } finally { setSaving(false); }
  }

  // Endereço
  async function autoPreencherCEP() {
    const d = await buscaCEP(novoEnd.cep);
    if (d) setNovoEnd((p: any) => ({ ...p, rua: d.logradouro, bairro: d.bairro, cidade: d.localidade, estado: d.uf }));
  }
  async function addEndereco() {
    if (!novoEnd.rua) return;
    await ClienteService.addEndereco(cliente.id, novoEnd);
    const list = await ClienteService.listEnderecos(cliente.id);
    setEnderecos(list);
    setNovoEnd({tipo:'entrega',cep:'',rua:'',numero:'',complemento:'',bairro:'',cidade:'',estado:'',referencia:'',principal:false});
  }
  async function delEndereco(eid: number) {
    await ClienteService.deleteEndereco(cliente.id, eid);
    setEnderecos(e => e.filter(x => x.id !== eid));
  }

  // Telefone
  async function addTelefone() {
    if (!novoTel.numero) return;
    await ClienteService.addTelefone(cliente.id, novoTel);
    const list = await ClienteService.listTelefones(cliente.id);
    setTelefones(list);
    setNovoTel({tipo:'celular',numero:'',ramal:'',aceita_whatsapp:false,principal:false});
  }
  async function delTelefone(tid: number) {
    await ClienteService.deleteTelefone(cliente.id, tid);
    setTelefones(t => t.filter(x => x.id !== tid));
  }

  // Responsável
  async function addResponsavel() {
    if (!novoResp.nome) return;
    await ClienteService.addResponsavel(cliente.id, novoResp);
    const list = await ClienteService.listResponsaveis(cliente.id);
    setResponsaveis(list);
    setNovoResp({nome:'',cargo:'',setor:'',email:'',permissao:''});
  }
  async function delResponsavel(rid: number) {
    await ClienteService.deleteResponsavel(cliente.id, rid);
    setResponsaveis(r => r.filter(x => x.id !== rid));
  }

  const TABS: {id: Tab; label: string; icon: any; disabled?: boolean}[] = [
    { id: 'dados',        label: 'Dados Gerais',  icon: User },
    { id: 'enderecos',    label: 'Endereços',      icon: MapPin,     disabled: !isEdit },
    { id: 'telefones',    label: 'Telefones',      icon: Phone,      disabled: !isEdit },
    { id: 'responsaveis', label: 'Responsáveis',   icon: UserCheck,  disabled: !isEdit },
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
      <div className="bg-slate-900 border border-slate-800 rounded-3xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[90vh]">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-800 shrink-0">
          <h3 className="text-lg font-black text-white">{isEdit ? 'Editar Cliente' : 'Novo Cliente'}</h3>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors"><X size={20} /></button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-slate-800 px-6 shrink-0 overflow-x-auto">
          {TABS.map(t => (
            <button key={t.id} onClick={() => !t.disabled && setTab(t.id)} disabled={t.disabled}
              className={`flex items-center gap-2 px-4 py-3 text-xs font-black uppercase tracking-widest border-b-2 transition-colors whitespace-nowrap
                ${tab === t.id ? 'border-cyan-500 text-cyan-400' : t.disabled ? 'border-transparent text-slate-700 cursor-not-allowed' : 'border-transparent text-slate-500 hover:text-slate-300'}`}>
              <t.icon size={14} />{t.label}
              {t.disabled && <span className="text-[9px] text-slate-700">(salve primeiro)</span>}
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {err && <p className="text-rose-400 text-sm bg-rose-400/10 px-3 py-2 rounded-xl">{err}</p>}

          {/* ── Dados Gerais ── */}
          {tab === 'dados' && (
            <div className="space-y-4">
              <div className="flex gap-3">
                {(['PF','PJ'] as const).map(t => (
                  <button key={t} onClick={() => setTipo(t)}
                    className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl border font-black text-sm transition-colors
                      ${tipo === t ? 'border-cyan-500 bg-cyan-500/10 text-cyan-400' : 'border-slate-700 text-slate-500 hover:border-slate-600'}`}>
                    {t === 'PF' ? <User size={16} /> : <Building2 size={16} />}
                    {t === 'PF' ? 'Pessoa Física' : 'Pessoa Jurídica'}
                  </button>
                ))}
              </div>
              <Input label={tipo === 'PF' ? 'Nome completo *' : 'Razão Social *'} value={nome} onChange={e => setNome(e.target.value)} placeholder={tipo === 'PF' ? 'João da Silva' : 'Empresa Ltda'} />
              <Input label={tipo === 'PF' ? 'CPF *' : 'CNPJ *'} value={tipo === 'PF' ? maskCPF(doc) : maskCNPJ(doc)}
                onChange={e => setDoc(e.target.value)} placeholder={tipo === 'PF' ? '000.000.000-00' : '00.000.000/0000-00'} />
              <Input label="E-mail" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="email@exemplo.com" />
              {isEdit && (
                <Select label="Status" value={status} onChange={e => setStatus(e.target.value)}>
                  <option className="bg-slate-900 text-white" value="ativo">Ativo</option>
                  <option className="bg-slate-900 text-white" value="inativo">Inativo</option>
                </Select>
              )}
            </div>
          )}

          {/* ── Endereços ── */}
          {tab === 'enderecos' && (
            <div className="space-y-4">
              {loadingEnd ? <p className="text-slate-500 text-sm">Carregando...</p> : (
                <>
                  {enderecos.map(e => (
                    <div key={e.id} className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 flex items-start justify-between gap-3">
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <Badge color="cyan">{e.tipo}</Badge>
                          {e.principal && <Badge color="emerald">Principal</Badge>}
                        </div>
                        <p className="text-sm text-white font-medium">{e.rua}, {e.numero} {e.complemento || ''}</p>
                        <p className="text-xs text-slate-400">{e.bairro} — {e.cidade}/{e.estado} · CEP {e.cep}</p>
                        {e.referencia && <p className="text-xs text-slate-500 mt-0.5">Ref: {e.referencia}</p>}
                      </div>
                      <button onClick={() => delEndereco(e.id)} className="p-1.5 text-slate-600 hover:text-rose-400 transition-colors shrink-0"><Trash2 size={14} /></button>
                    </div>
                  ))}

                  <div className="bg-slate-800/30 border border-dashed border-slate-700 rounded-xl p-4 space-y-3">
                    <p className="text-xs font-black text-slate-500 uppercase tracking-widest">Adicionar endereço</p>
                    <div className="grid grid-cols-2 gap-3">
                      <Select label="Tipo" value={novoEnd.tipo} onChange={(e:any) => setNovoEnd((p:any)=>({...p,tipo:e.target.value}))}>
                        {['entrega','cobranca','retirada','matriz','filial'].map(t=><option className="bg-slate-900 text-white" key={t}>{t}</option>)}
                      </Select>
                      <div>
                        <label className="block text-xs font-black text-slate-500 uppercase tracking-widest mb-1">CEP</label>
                        <div className="flex gap-2">
                          <input value={novoEnd.cep} onChange={e=>setNovoEnd((p:any)=>({...p,cep:e.target.value}))} onBlur={autoPreencherCEP} placeholder="00000-000"
                            className="flex-1 bg-slate-800 border border-slate-700 rounded-xl px-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-3 gap-3">
                      <div className="col-span-2">
                        <Input label="Rua" value={novoEnd.rua} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,rua:e.target.value}))} placeholder="Rua..." />
                      </div>
                      <Input label="Número" value={novoEnd.numero} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,numero:e.target.value}))} placeholder="123" />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <Input label="Bairro" value={novoEnd.bairro} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,bairro:e.target.value}))} placeholder="Bairro" />
                      <Input label="Cidade" value={novoEnd.cidade} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,cidade:e.target.value}))} placeholder="Cidade" />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <Input label="Estado (UF)" value={novoEnd.estado} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,estado:e.target.value.toUpperCase().slice(0,2)}))} placeholder="SP" />
                      <Input label="Complemento" value={novoEnd.complemento} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,complemento:e.target.value}))} placeholder="Apto, bloco..." />
                    </div>
                    <Input label="Referência" value={novoEnd.referencia} onChange={(e:any)=>setNovoEnd((p:any)=>({...p,referencia:e.target.value}))} placeholder="Próximo ao mercado..." />
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input type="checkbox" checked={novoEnd.principal} onChange={e=>setNovoEnd((p:any)=>({...p,principal:e.target.checked}))} className="accent-cyan-500" />
                      <span className="text-sm text-slate-300">Definir como endereço principal</span>
                    </label>
                    <button onClick={addEndereco} className="px-4 py-2 bg-cyan-500 hover:bg-cyan-400 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
                      <Plus size={14} /> Adicionar
                    </button>
                  </div>
                </>
              )}
            </div>
          )}

          {/* ── Telefones ── */}
          {tab === 'telefones' && (
            <div className="space-y-4">
              {telefones.map(t => (
                <div key={t.id} className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 flex items-center justify-between gap-3">
                  <div className="flex items-center gap-3">
                    <Phone size={16} className="text-slate-500" />
                    <div>
                      <div className="flex items-center gap-2">
                        <Badge color="cyan">{t.tipo}</Badge>
                        {t.principal && <Badge color="emerald">Principal</Badge>}
                        {t.aceita_whatsapp && <Badge color="purple">WhatsApp</Badge>}
                      </div>
                      <p className="text-sm text-white font-medium mt-1">{t.numero}{t.ramal ? ` · Ramal ${t.ramal}` : ''}</p>
                    </div>
                  </div>
                  <button onClick={() => delTelefone(t.id)} className="p-1.5 text-slate-600 hover:text-rose-400 transition-colors"><Trash2 size={14} /></button>
                </div>
              ))}
              <div className="bg-slate-800/30 border border-dashed border-slate-700 rounded-xl p-4 space-y-3">
                <p className="text-xs font-black text-slate-500 uppercase tracking-widest">Adicionar telefone</p>
                <div className="grid grid-cols-2 gap-3">
                  <Select label="Tipo" value={novoTel.tipo} onChange={(e:any)=>setNovoTel((p:any)=>({...p,tipo:e.target.value}))}>
                    {['celular','comercial','whatsapp','financeiro','compras'].map(t=><option className="bg-slate-900 text-white" key={t}>{t}</option>)}
                  </Select>
                  <Input label="Número" value={novoTel.numero} onChange={(e:any)=>setNovoTel((p:any)=>({...p,numero:e.target.value}))} placeholder="(11) 99999-9999" />
                </div>
                <div className="flex gap-4">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={novoTel.aceita_whatsapp} onChange={e=>setNovoTel((p:any)=>({...p,aceita_whatsapp:e.target.checked}))} className="accent-cyan-500" />
                    <span className="text-sm text-slate-300">Aceita WhatsApp</span>
                  </label>
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={novoTel.principal} onChange={e=>setNovoTel((p:any)=>({...p,principal:e.target.checked}))} className="accent-cyan-500" />
                    <span className="text-sm text-slate-300">Principal</span>
                  </label>
                </div>
                <button onClick={addTelefone} className="px-4 py-2 bg-cyan-500 hover:bg-cyan-400 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
                  <Plus size={14} /> Adicionar
                </button>
              </div>
            </div>
          )}

          {/* ── Responsáveis ── */}
          {tab === 'responsaveis' && (
            <div className="space-y-4">
              {tipo === 'PF' && <p className="text-slate-500 text-xs italic">PF normalmente tem 1 responsável (o próprio titular).</p>}
              {responsaveis.map(r => (
                <div key={r.id} className="bg-slate-800/60 border border-slate-700 rounded-xl p-4 flex items-start justify-between gap-3">
                  <div>
                    <p className="text-sm font-bold text-white">{r.nome}</p>
                    <p className="text-xs text-slate-400">{[r.cargo, r.setor].filter(Boolean).join(' · ')}</p>
                    {r.email && <p className="text-xs text-slate-500">{r.email}</p>}
                    {r.permissao && <Badge color="purple">{r.permissao}</Badge>}
                  </div>
                  <button onClick={() => delResponsavel(r.id)} className="p-1.5 text-slate-600 hover:text-rose-400 transition-colors shrink-0"><Trash2 size={14} /></button>
                </div>
              ))}
              <div className="bg-slate-800/30 border border-dashed border-slate-700 rounded-xl p-4 space-y-3">
                <p className="text-xs font-black text-slate-500 uppercase tracking-widest">Adicionar responsável</p>
                <div className="grid grid-cols-2 gap-3">
                  <Input label="Nome *" value={novoResp.nome} onChange={(e:any)=>setNovoResp((p:any)=>({...p,nome:e.target.value}))} placeholder="Nome do responsável" />
                  <Input label="Cargo" value={novoResp.cargo} onChange={(e:any)=>setNovoResp((p:any)=>({...p,cargo:e.target.value}))} placeholder="Gerente, Comprador..." />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <Input label="Setor" value={novoResp.setor} onChange={(e:any)=>setNovoResp((p:any)=>({...p,setor:e.target.value}))} placeholder="Financeiro, Compras..." />
                  <Input label="E-mail" type="email" value={novoResp.email} onChange={(e:any)=>setNovoResp((p:any)=>({...p,email:e.target.value}))} placeholder="email@empresa.com" />
                </div>
                <Input label="Permissão" value={novoResp.permissao} onChange={(e:any)=>setNovoResp((p:any)=>({...p,permissao:e.target.value}))} placeholder="compras, financeiro, recebimento..." />
                <button onClick={addResponsavel} className="px-4 py-2 bg-cyan-500 hover:bg-cyan-400 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
                  <Plus size={14} /> Adicionar
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Footer — só mostra salvar na aba dados */}
        <div className="p-6 border-t border-slate-800 flex gap-3 justify-end shrink-0">
          <button onClick={onClose} className="px-4 py-2 text-slate-400 hover:text-white transition-colors text-sm font-bold">Fechar</button>
          {tab === 'dados' && (
            <button onClick={salvarDados} disabled={saving}
              className="px-6 py-2 bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 rounded-xl text-black font-black text-sm transition-colors flex items-center gap-2">
              {saving ? <RefreshCw size={14} className="animate-spin" /> : <Check size={14} />}
              {isEdit ? 'Salvar' : 'Criar e continuar'}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function ClientesPage() {
  const [clientes, setClientes]   = useState<any[]>([]);
  const [loading, setLoading]     = useState(true);
  const [search, setSearch]       = useState('');
  const [tipo, setTipo]           = useState('');
  const [status, setStatus]       = useState('ativo');
  const [modal, setModal]         = useState<'new'|'edit'|null>(null);
  const [selected, setSelected]   = useState<any>(null);
  const [page, setPage]           = useState(0);
  const PER = 50;

  async function load() {
    setLoading(true);
    try {
      const rows = await ClienteService.list({ search: search||undefined, tipo: tipo||undefined, status: status||undefined, limit: PER, offset: page * PER });
      setClientes(rows);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }

  useEffect(() => { load(); }, [search, tipo, status, page]);

  async function deletar(id: number) {
    if (!confirm('Remover cliente?')) return;
    await ClienteService.delete(id);
    load();
  }

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <header className="flex flex-wrap justify-between items-start gap-4">
        <div>
          <h2 className="text-3xl font-black text-white tracking-tighter flex items-center gap-3">
            <Users className="text-cyan-400" size={28} /> Clientes
          </h2>
          <p className="text-slate-400 mt-1 font-medium">Cadastro PF e PJ · endereços · telefones · responsáveis</p>
        </div>
        <button onClick={() => { setSelected(null); setModal('new'); }}
          className="flex items-center gap-2 px-4 py-2 bg-cyan-500 hover:bg-cyan-400 rounded-xl text-black font-black text-sm transition-colors">
          <Plus size={16} /> Novo Cliente
        </button>
      </header>

      {/* Filtros */}
      <div className="flex gap-3 flex-wrap">
        <div className="relative flex-1 min-w-48">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
          <input value={search} onChange={e => { setSearch(e.target.value); setPage(0); }} placeholder="Buscar por nome, CPF, CNPJ, e-mail..."
            className="w-full bg-slate-900 border border-slate-800 rounded-xl pl-9 pr-3 py-2 text-sm text-white focus:outline-none focus:border-cyan-500" />
        </div>
        <div className="relative">
          <select value={tipo} onChange={e => { setTipo(e.target.value); setPage(0); }}
            className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-sm text-slate-300 focus:outline-none focus:border-cyan-500 appearance-none cursor-pointer pr-8">
            <option className="bg-slate-900 text-white" value="">PF + PJ</option>
            <option className="bg-slate-900 text-white" value="PF">Pessoa Física</option>
            <option className="bg-slate-900 text-white" value="PJ">Pessoa Jurídica</option>
          </select>
          <ChevronDown size={14} className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none" />
        </div>
        <div className="relative">
          <select value={status} onChange={e => { setStatus(e.target.value); setPage(0); }}
            className="bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-sm text-slate-300 focus:outline-none focus:border-cyan-500 appearance-none cursor-pointer pr-8">
            <option className="bg-slate-900 text-white" value="">Todos</option>
            <option className="bg-slate-900 text-white" value="ativo">Ativos</option>
            <option className="bg-slate-900 text-white" value="inativo">Inativos</option>
          </select>
          <ChevronDown size={14} className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none" />
        </div>
        <button onClick={load} className="p-2 bg-slate-900 border border-slate-800 rounded-xl text-slate-400 hover:text-white transition-colors">
          <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
        </button>
      </div>

      {/* Tabela */}
      <div className="bg-slate-900/40 border border-slate-800 rounded-3xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-800 text-left">
                <th className="px-6 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Cliente</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Tipo</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">CPF / CNPJ</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">E-mail</th>
                <th className="px-4 py-4 text-xs font-black text-slate-500 uppercase tracking-widest">Status</th>
                <th className="px-4 py-4" />
              </tr>
            </thead>
            <tbody>
              {loading ? (
                [...Array(6)].map((_, i) => (
                  <tr key={i} className="border-b border-slate-800/50 animate-pulse">
                    {[...Array(6)].map((_, j) => (
                      <td key={j} className="px-4 py-4"><div className="h-4 bg-slate-800 rounded w-full" /></td>
                    ))}
                  </tr>
                ))
              ) : clientes.length === 0 ? (
                <tr><td colSpan={6} className="px-6 py-16 text-center text-slate-600 text-sm italic">Nenhum cliente encontrado.</td></tr>
              ) : (
                clientes.map(c => (
                  <tr key={c.id} className="border-b border-slate-800/50 hover:bg-slate-800/20 transition-colors group">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <div className={`w-9 h-9 rounded-xl flex items-center justify-center shrink-0 ${c.tipo==='PJ' ? 'bg-purple-400/10 text-purple-400' : 'bg-cyan-400/10 text-cyan-400'}`}>
                          {c.tipo === 'PJ' ? <Building2 size={16} /> : <User size={16} />}
                        </div>
                        <span className="font-bold text-white">{c.nome}</span>
                      </div>
                    </td>
                    <td className="px-4 py-4"><Badge color={c.tipo==='PJ'?'purple':'cyan'}>{c.tipo}</Badge></td>
                    <td className="px-4 py-4 font-mono text-xs text-slate-400">{c.cpf_cnpj}</td>
                    <td className="px-4 py-4 text-slate-400 text-xs">{c.email || '—'}</td>
                    <td className="px-4 py-4"><Badge color={c.status==='ativo'?'emerald':'rose'}>{c.status}</Badge></td>
                    <td className="px-4 py-4">
                      <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity justify-end">
                        <button onClick={() => { setSelected(c); setModal('edit'); }}
                          className="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition-colors" title="Editar">
                          <Pencil size={14} />
                        </button>
                        <button onClick={() => deletar(c.id)}
                          className="p-2 rounded-lg bg-slate-800 hover:bg-rose-500/20 text-slate-400 hover:text-rose-400 transition-colors" title="Remover">
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Paginação */}
        {clientes.length > 0 && (
          <div className="flex items-center justify-between px-6 py-4 border-t border-slate-800">
            <span className="text-xs text-slate-500">{page * PER + 1}–{page * PER + clientes.length}</span>
            <div className="flex gap-2">
              <button onClick={() => setPage(p => Math.max(0, p-1))} disabled={page === 0}
                className="p-2 rounded-lg bg-slate-800 disabled:opacity-30 text-slate-400 hover:text-white transition-colors">
                <ChevronLeft size={16} />
              </button>
              <button onClick={() => setPage(p => p+1)} disabled={clientes.length < PER}
                className="p-2 rounded-lg bg-slate-800 disabled:opacity-30 text-slate-400 hover:text-white transition-colors">
                <ChevronRight size={16} />
              </button>
            </div>
          </div>
        )}
      </div>

      {(modal === 'new' || modal === 'edit') && (
        <ClienteModal
          cliente={modal === 'edit' ? selected : null}
          onClose={() => setModal(null)}
          onSave={() => { if (modal === 'new') { setModal(null); load(); } else load(); }}
        />
      )}
    </div>
  );
}
