
// ============================================================
// JuFlow — Client Detail (5-tab full profile)
// ============================================================
const { useState: useStCD, useMemo: useMemoCD } = React;
const UCD = window.JFUtils;

const ClientDetail = ({ client, appointments, onClose, onNewAppt, addToast }) => {
  const [tab, setTab] = useStCD('dados');
  const [editMode, setEditMode] = useStCD(false);
  const [formData, setFormData] = useStCD({ ...client });

  if (!client) return null;

  const setF = (k, v) => setFormData(f => ({ ...f, [k]: v }));
  const setAnamnese = (k, v) => setFormData(f => ({ ...f, anamnese: { ...f.anamnese, [k]: v } }));

  const clientAppts = useMemoCD(() =>
    appointments
      .filter(a => a.clientId === client.id)
      .sort((a, b) => new Date(b.datetime) - new Date(a.datetime))
  , [appointments, client.id]);

  const completedAppts = clientAppts.filter(a => a.status === 'completed');
  const clientPkgs     = window.JF.CLIENT_PACKAGES.filter(p => p.clientId === client.id);
  const totalSpent     = completedAppts.reduce((s, a) => s + a.price, 0);
  const avgTicket      = completedAppts.length ? totalSpent / completedAppts.length : 0;

  // ── TAB: Dados Pessoais ─────────────────────────────────
  const TabDados = () => (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
      {/* Profile header */}
      <div style={{
        background:'linear-gradient(135deg, #0A1F44, #0d2a5e)',
        borderRadius:14, padding:'24px', display:'flex', alignItems:'center', gap:20,
      }}>
        <div style={{ position:'relative' }}>
          <Avatar name={client.name} color="#FF6B35" size={72} style={{ fontSize:26, fontWeight:800 }} />
          <button style={{
            position:'absolute', bottom:0, right:0,
            width:24, height:24, borderRadius:'50%',
            background:'#FF6B35', border:'2px solid #fff',
            cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <Icon name="Camera" size={11} color="white" />
          </button>
        </div>
        <div style={{ flex:1 }}>
          <h2 style={{ margin:'0 0 4px', fontSize:22, fontWeight:800, color:'#fff' }}>{client.name}</h2>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:10 }}>
            {client.tags.map(tag => <TagChip key={tag} tag={tag} />)}
            {client.status === 'inactive' && <Badge status="inactive" />}
          </div>
          <div style={{ display:'flex', gap:16 }}>
            {[
              { label:'Sessões', value: completedAppts.length, icon:'Calendar' },
              { label:'Total gasto', value: UCD.formatCurrency(totalSpent), icon:'DollarSign' },
              { label:'Ticket médio', value: UCD.formatCurrency(avgTicket), icon:'TrendingUp' },
            ].map(stat => (
              <div key={stat.label} style={{ textAlign:'center' }}>
                <div style={{ fontSize:16, fontWeight:800, color:'#fff' }}>{stat.value}</div>
                <div style={{ fontSize:10, color:'rgba(255,255,255,.5)', textTransform:'uppercase', letterSpacing:.5 }}>{stat.label}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          <Button variant="primary" size="sm" icon="CalendarPlus" onClick={() => onNewAppt({ clientId: client.id })}>Agendar</Button>
          <Button size="sm" icon={editMode ? 'Check' : 'Edit2'} onClick={() => setEditMode(e => !e)}
            style={{ background: editMode ? '#22C55E' : 'rgba(255,255,255,.15)', color:'#fff', border:'1px solid rgba(255,255,255,.2)' }}>
            {editMode ? 'Salvar' : 'Editar'}
          </Button>
        </div>
      </div>

      {/* Personal data grid */}
      <div style={{ background:'#fff', border:'1px solid #E2E8F0', borderRadius:14, padding:20 }}>
        <h3 style={{ fontSize:14, fontWeight:700, color:'#0A1F44', margin:'0 0 16px', display:'flex', alignItems:'center', gap:8 }}>
          <Icon name="User" size={16} color="#FF6B35" /> Dados Pessoais
        </h3>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14 }}>
          {[
            { label:'Nome completo', key:'name', icon:'User' },
            { label:'Telefone/WhatsApp', key:'phone', icon:'Phone' },
            { label:'E-mail', key:'email', icon:'Mail' },
            { label:'CPF', key:'cpf', icon:'CreditCard' },
            { label:'Data de nascimento', key:'birthdate', icon:'Cake', format:v => v ? `${UCD.formatDate(v)} (${UCD.age(v)} anos)` : '—' },
            { label:'Endereço', key:'address', icon:'MapPin', span:2 },
          ].map(field => (
            <div key={field.key} style={{ gridColumn: field.span ? `span ${field.span}` : 'span 1' }}>
              <div style={{ fontSize:11, fontWeight:600, color:'#9CA3AF', marginBottom:4, textTransform:'uppercase', letterSpacing:.5 }}>{field.label}</div>
              {editMode
                ? <Input value={formData[field.key] || ''} onChange={v => setF(field.key, v)} icon={field.icon} />
                : <div style={{ fontSize:13, color:'#0A1F44', fontWeight:500, padding:'8px 0', borderBottom:'1px solid #F0F4F8' }}>
                    {field.format ? field.format(client[field.key]) : (client[field.key] || '—')}
                  </div>
              }
            </div>
          ))}
        </div>
      </div>

      {/* Tags */}
      <div style={{ background:'#fff', border:'1px solid #E2E8F0', borderRadius:14, padding:20 }}>
        <h3 style={{ fontSize:14, fontWeight:700, color:'#0A1F44', margin:'0 0 12px', display:'flex', alignItems:'center', gap:8 }}>
          <Icon name="Tag" size={16} color="#FF6B35" /> Tags
        </h3>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {client.tags.map(tag => <TagChip key={tag} tag={tag} />)}
          {['VIP','Aniversariante','Inadimplente','Regular'].filter(t => !client.tags.includes(t)).map(tag => (
            <button key={tag} style={{
              padding:'3px 10px', borderRadius:20, fontSize:11, fontWeight:600,
              background:'#F3F4F6', color:'#6B7280', border:'1px dashed #D1D5DB', cursor:'pointer',
            }}
              onMouseEnter={e => { e.currentTarget.style.borderColor='#FF6B35'; e.currentTarget.style.color='#FF6B35'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor='#D1D5DB'; e.currentTarget.style.color='#6B7280'; }}
            >+ {tag}</button>
          ))}
        </div>
      </div>

      {/* Notes */}
      <div style={{ background:'#FFFBF0', border:'1px solid #FDE68A', borderRadius:14, padding:20 }}>
        <h3 style={{ fontSize:14, fontWeight:700, color:'#92400E', margin:'0 0 8px', display:'flex', alignItems:'center', gap:8 }}>
          <Icon name="StickyNote" size={16} color="#D97706" /> Observações
        </h3>
        {editMode
          ? <Textarea value={formData.notes || ''} onChange={v => setF('notes',v)} rows={3} />
          : <p style={{ fontSize:13, color:'#374151', margin:0, lineHeight:1.7 }}>{client.notes || 'Nenhuma observação registrada.'}</p>
        }
      </div>
    </div>
  );

  // ── TAB: Anamnese ───────────────────────────────────────
  const TabAnamnese = () => {
    const fields = [
      { key:'healthHistory', label:'Histórico de saúde', icon:'Heart', rows:3 },
      { key:'allergies', label:'Alergias', icon:'AlertTriangle', rows:2 },
      { key:'medications', label:'Medicamentos em uso', icon:'Pill', rows:2 },
      { key:'contraindications', label:'Contraindicações', icon:'ShieldAlert', rows:2 },
      { key:'goals', label:'Objetivos do cliente', icon:'Target', rows:3 },
    ];
    return (
      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <div>
            <h3 style={{ fontSize:16, fontWeight:700, color:'#0A1F44', margin:0 }}>Ficha de Anamnese</h3>
            <p style={{ fontSize:12, color:'#9CA3AF', margin:'3px 0 0' }}>Histórico médico e informações clínicas</p>
          </div>
          <Button size="sm" icon={editMode ? 'Check' : 'Edit2'} variant={editMode ? 'primary' : 'secondary'} onClick={() => { setEditMode(e=>!e); if(editMode) addToast('Anamnese salva!','success'); }}>
            {editMode ? 'Salvar ficha' : 'Editar ficha'}
          </Button>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
          {fields.map(f => (
            <div key={f.key} style={{
              background:'#fff', border:'1px solid #E2E8F0', borderRadius:12, padding:16,
              gridColumn: f.rows >= 3 ? 'span 2' : 'span 1',
            }}>
              <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:8 }}>
                <Icon name={f.icon} size={14} color="#FF6B35" />
                <span style={{ fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:.5 }}>{f.label}</span>
              </div>
              {editMode
                ? <Textarea value={formData.anamnese?.[f.key] || ''} onChange={v => setAnamnese(f.key,v)} rows={f.rows} />
                : <p style={{ fontSize:13, color:'#374151', margin:0, lineHeight:1.6 }}>{client.anamnese?.[f.key] || 'Não informado'}</p>
              }
            </div>
          ))}
        </div>

        {/* Before/After photos placeholder */}
        <div style={{ background:'#fff', border:'1px solid #E2E8F0', borderRadius:12, padding:16 }}>
          <div style={{ fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:.5, marginBottom:12 }}>📸 Fotos Antes e Depois</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:10 }}>
            {['Antes (Frente)','Antes (Lado)','Depois (Frente)','Depois (Lado)'].map(label => (
              <div key={label} style={{
                aspectRatio:'1', borderRadius:10,
                background:'#F9FAFB', border:'1.5px dashed #D1D5DB',
                display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:6,
                cursor:'pointer', transition:'all .15s',
              }}
                onMouseEnter={e => { e.currentTarget.style.borderColor='#FF6B35'; e.currentTarget.style.background='#FFF0EA'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor='#D1D5DB'; e.currentTarget.style.background='#F9FAFB'; }}
              >
                <Icon name="Camera" size={20} color="#C4CDD6" />
                <span style={{ fontSize:10, color:'#9CA3AF', textAlign:'center', padding:'0 8px' }}>{label}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  };

  // ── TAB: Histórico ──────────────────────────────────────
  const TabHistorico = () => (
    <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div>
          <h3 style={{ fontSize:16, fontWeight:700, color:'#0A1F44', margin:0 }}>Histórico de Atendimentos</h3>
          <p style={{ fontSize:12, color:'#9CA3AF', margin:'3px 0 0' }}>{completedAppts.length} atendimentos realizados</p>
        </div>
        <Button size="sm" icon="CalendarPlus" variant="primary" onClick={() => onNewAppt({ clientId: client.id })}>Novo agendamento</Button>
      </div>
      {clientAppts.length === 0 ? (
        <EmptyState icon="Calendar" title="Sem histórico" message="Este cliente não possui atendimentos registrados." />
      ) : (
        <div style={{ position:'relative', paddingLeft:24 }}>
          {/* Timeline line */}
          <div style={{ position:'absolute', left:8, top:0, bottom:0, width:2, background:'#E2E8F0', borderRadius:99 }} />
          {clientAppts.map((appt, i) => {
            const service = UCD.getService(appt.serviceId);
            const prof    = UCD.getProfessional(appt.professionalId);
            return (
              <div key={appt.id} style={{ position:'relative', marginBottom:12 }}>
                {/* Timeline dot */}
                <div style={{
                  position:'absolute', left:-20, top:14,
                  width:12, height:12, borderRadius:'50%',
                  background: appt.status==='completed' ? prof?.color || '#FF6B35' : '#D1D5DB',
                  border:'2px solid #fff', boxShadow:'0 0 0 2px #E2E8F0',
                }} />
                <div style={{
                  background:'#fff', border:'1px solid #E2E8F0', borderRadius:12,
                  padding:'14px 16px', transition:'border-color .15s',
                }}
                  onMouseEnter={e => e.currentTarget.style.borderColor='#C4B5FD'}
                  onMouseLeave={e => e.currentTarget.style.borderColor='#E2E8F0'}
                >
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8 }}>
                    <div>
                      <div style={{ fontSize:14, fontWeight:700, color:'#0A1F44' }}>{service?.name}</div>
                      <div style={{ fontSize:12, color:'#6B7280', marginTop:2, display:'flex', alignItems:'center', gap:8 }}>
                        <span style={{ display:'flex', alignItems:'center', gap:3 }}>
                          <Icon name="Calendar" size={11} color="#9CA3AF" /> {UCD.formatDateTime(appt.datetime)}
                        </span>
                        <span style={{ display:'flex', alignItems:'center', gap:3 }}>
                          <div style={{ width:7, height:7, borderRadius:'50%', background: prof?.color }} />
                          {prof?.name}
                        </span>
                      </div>
                    </div>
                    <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                      <span style={{ fontSize:14, fontWeight:700, color:'#0A1F44' }}>{UCD.formatCurrency(appt.price)}</span>
                      <Badge status={appt.status} />
                    </div>
                  </div>
                  {appt.sessionNotes && (
                    <div style={{ background:'#F9FAFB', borderRadius:8, padding:'8px 10px', fontSize:12, color:'#374151', marginTop:6 }}>
                      <Icon name="MessageSquare" size={11} color="#9CA3AF" style={{ marginRight:5 }} />
                      {appt.sessionNotes}
                    </div>
                  )}
                  {appt.paymentMethod && (
                    <div style={{ marginTop:6, fontSize:11, color:'#9CA3AF', display:'flex', gap:4, alignItems:'center' }}>
                      <Icon name="CreditCard" size={11} color="#9CA3AF" /> {appt.paymentMethod} · {appt.duration}min
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );

  // ── TAB: Financeiro ─────────────────────────────────────
  const TabFinanceiro = () => {
    const pending = clientAppts.filter(a => a.status==='confirmed' && !a.paymentMethod);
    return (
      <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14 }}>
          <MetricCard title="Total Gasto" value={UCD.formatCurrency(totalSpent)} icon="DollarSign" color="#059669" subtitle="histórico total" />
          <MetricCard title="Ticket Médio" value={UCD.formatCurrency(avgTicket)} icon="TrendingUp" color="#0891B2" subtitle="por sessão" />
          <MetricCard title="Sessões Pagas" value={completedAppts.length} icon="CheckCircle" color="#FF6B35" subtitle="realizadas" />
        </div>

        {pending.length > 0 && (
          <div style={{ background:'#FEF9C3', border:'1px solid #FDE047', borderRadius:12, padding:16 }}>
            <div style={{ fontSize:13, fontWeight:700, color:'#854D0E', marginBottom:8, display:'flex', gap:6, alignItems:'center' }}>
              <Icon name="AlertTriangle" size={14} color="#D97706" /> {pending.length} pagamento(s) pendente(s)
            </div>
            {pending.map(a => {
              const svc = UCD.getService(a.serviceId);
              return (
                <div key={a.id} style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:'#374151', padding:'4px 0' }}>
                  <span>{svc?.name} — {UCD.formatDate(a.datetime)}</span>
                  <strong>{UCD.formatCurrency(a.price)}</strong>
                </div>
              );
            })}
            <Button size="sm" variant="primary" icon="DollarSign" style={{ marginTop:10 }} onClick={() => addToast('Pagamento registrado!','success')}>
              Registrar pagamento
            </Button>
          </div>
        )}

        <div style={{ background:'#fff', border:'1px solid #E2E8F0', borderRadius:14, overflow:'hidden' }}>
          <div style={{ padding:'14px 16px', borderBottom:'1px solid #E2E8F0' }}>
            <h3 style={{ fontSize:14, fontWeight:700, color:'#0A1F44', margin:0 }}>Transações</h3>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead>
              <tr style={{ background:'#F9FAFB' }}>
                {['Data','Serviço','Profissional','Valor','Pagamento','Status'].map(h => (
                  <th key={h} style={{ padding:'10px 14px', fontSize:11, fontWeight:700, color:'#6B7280', textAlign:'left', textTransform:'uppercase', letterSpacing:.5 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {completedAppts.slice(0, 10).map((a, i) => {
                const svc  = UCD.getService(a.serviceId);
                const prof = UCD.getProfessional(a.professionalId);
                return (
                  <tr key={a.id} style={{ borderTop:'1px solid #F0F4F8' }}>
                    <td style={{ padding:'10px 14px', fontSize:12, color:'#374151' }}>{UCD.formatDate(a.datetime)}</td>
                    <td style={{ padding:'10px 14px', fontSize:12, fontWeight:600, color:'#0A1F44' }}>{svc?.name}</td>
                    <td style={{ padding:'10px 14px', fontSize:12, color:'#6B7280' }}>{prof?.name}</td>
                    <td style={{ padding:'10px 14px', fontSize:13, fontWeight:700, color:'#059669' }}>{UCD.formatCurrency(a.price)}</td>
                    <td style={{ padding:'10px 14px', fontSize:12, color:'#6B7280' }}>{a.paymentMethod || '—'}</td>
                    <td style={{ padding:'10px 14px' }}><Badge status={a.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  };

  // ── TAB: Pacotes ────────────────────────────────────────
  const TabPacotes = () => (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <h3 style={{ fontSize:16, fontWeight:700, color:'#0A1F44', margin:0 }}>Pacotes e Sessões</h3>
        <Button size="sm" icon="Plus" variant="primary">Adicionar pacote</Button>
      </div>
      {clientPkgs.length === 0 ? (
        <EmptyState icon="Package" title="Nenhum pacote ativo" message="Este cliente não possui pacotes ativos no momento." action={<Button icon="Plus" variant="primary" size="sm">Adicionar pacote</Button>} />
      ) : (
        clientPkgs.map(cp => {
          const pkg = UCD.getPackage(cp.packageId);
          if (!pkg) return null;
          const remaining = pkg.totalSessions - cp.sessionsUsed;
          const pct = (cp.sessionsUsed / pkg.totalSessions) * 100;
          const svc = UCD.getService(pkg.serviceId);
          return (
            <div key={cp.id} style={{
              background:'#fff', border:'1px solid #E2E8F0', borderRadius:14, padding:20,
              boxShadow:'0 2px 8px rgba(10,31,68,.04)',
            }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14 }}>
                <div>
                  <div style={{ fontSize:15, fontWeight:700, color:'#0A1F44', marginBottom:3 }}>{pkg.name}</div>
                  <div style={{ fontSize:12, color:'#6B7280' }}>
                    {svc?.name} · Vence em {UCD.formatDate(cp.expiryDate)}
                  </div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontSize:22, fontWeight:800, color: remaining <= 2 ? '#EF4444' : '#059669' }}>
                    {remaining}
                  </div>
                  <div style={{ fontSize:11, color:'#9CA3AF' }}>sessões restantes</div>
                </div>
              </div>
              <ProgressBar value={cp.sessionsUsed} max={pkg.totalSessions} color={remaining <= 2 ? '#EF4444' : '#FF6B35'} />
              <div style={{ display:'flex', justifyContent:'space-between', marginTop:8, fontSize:12, color:'#9CA3AF' }}>
                <span>{cp.sessionsUsed} de {pkg.totalSessions} sessões utilizadas</span>
                <span>{Math.round(pct)}% concluído</span>
              </div>
              <div style={{ display:'flex', gap:8, marginTop:14 }}>
                <Button size="sm" variant="secondary" icon="Minus">Registrar sessão</Button>
                <Button size="sm" variant="ghost" icon="RotateCcw">Renovar pacote</Button>
              </div>
            </div>
          );
        })
      )}

      {/* Available packages to purchase */}
      <div style={{ background:'#F9FAFB', border:'1px solid #E2E8F0', borderRadius:14, padding:20 }}>
        <div style={{ fontSize:13, fontWeight:700, color:'#374151', marginBottom:14 }}>Pacotes disponíveis</div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {window.JF.PACKAGES.slice(0, 4).map(pkg => (
            <div key={pkg.id} style={{
              background:'#fff', border:'1px solid #E2E8F0', borderRadius:10, padding:14,
              display:'flex', justifyContent:'space-between', alignItems:'center',
            }}>
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'#0A1F44' }}>{pkg.name}</div>
                <div style={{ fontSize:11, color:'#9CA3AF' }}>{pkg.totalSessions} sessões</div>
                <div style={{ display:'flex', gap:6, marginTop:4, alignItems:'center' }}>
                  <span style={{ fontSize:14, fontWeight:800, color:'#059669' }}>{UCD.formatCurrency(pkg.price)}</span>
                  <span style={{ fontSize:11, color:'#9CA3AF', textDecoration:'line-through' }}>{UCD.formatCurrency(pkg.originalPrice)}</span>
                </div>
              </div>
              <Button size="sm" variant="primary" icon="ShoppingCart" onClick={() => addToast(`Pacote "${pkg.name}" adicionado!`,'success')}>
                Comprar
              </Button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const tabContent = { dados:<TabDados/>, anamnese:<TabAnamnese/>, historico:<TabHistorico/>, financeiro:<TabFinanceiro/>, pacotes:<TabPacotes/> };

  return (
    <div style={{ position:'fixed', inset:0, zIndex:900, background:'rgba(10,31,68,.5)', backdropFilter:'blur(4px)', display:'flex', alignItems:'flex-start', justifyContent:'center', padding:24, overflow:'auto' }}>
      <div style={{
        background:'#F5F7FA', borderRadius:20, width:'100%', maxWidth:860,
        boxShadow:'0 32px 80px rgba(10,31,68,.25)', position:'relative',
        animation:'modalIn .2s ease',
      }}>
        {/* Close button */}
        <button onClick={onClose} style={{
          position:'absolute', top:16, right:16, width:36, height:36,
          borderRadius:10, border:'1px solid #E2E8F0', background:'#fff',
          cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', zIndex:10,
        }}>
          <Icon name="X" size={16} color="#6B7280" />
        </button>

        {/* Tabs */}
        <div style={{ background:'#fff', borderRadius:'20px 20px 0 0', padding:'0 24px', borderBottom:'1px solid #E2E8F0' }}>
          <Tabs
            tabs={[
              { id:'dados',       label:'Dados Pessoais', icon:'User' },
              { id:'anamnese',    label:'Anamnese', icon:'Stethoscope' },
              { id:'historico',   label:'Histórico', icon:'History', count:clientAppts.length },
              { id:'financeiro',  label:'Financeiro', icon:'DollarSign' },
              { id:'pacotes',     label:'Pacotes', icon:'Package', count:clientPkgs.length },
            ]}
            activeTab={tab}
            onTabChange={setTab}
          />
        </div>

        {/* Tab content */}
        <div style={{ padding:24, maxHeight:'70vh', overflow:'auto' }}>
          {tabContent[tab]}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ClientDetail });
