// Órbita — Consulentes (lista + perfil) com 2 variações e estados completos

const { useState: useStateC, useMemo: useMemoC } = React;

// ── helpers ─────────────────────────────────────────────────
const fmtDate = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' });
};
const fmtRelative = (iso) => {
  if (!iso) return '—';
  const ms = Date.now() - new Date(iso).getTime();
  const h = Math.floor(ms / 36e5);
  if (h < 1)   return 'agora';
  if (h < 24)  return `${h} h atrás`;
  const d = Math.floor(h / 24);
  if (d < 7)   return `${d} d atrás`;
  if (d < 30)  return `${Math.floor(d/7)} sem atrás`;
  return `${Math.floor(d/30)} m atrás`;
};
const ageFromIso = (iso) => {
  const b = new Date(iso); const now = new Date();
  let a = now.getFullYear() - b.getFullYear();
  const m = now.getMonth() - b.getMonth();
  if (m < 0 || (m === 0 && now.getDate() < b.getDate())) a--;
  return a;
};
const zodiacOf = (iso) => {
  const d = new Date(iso); const m = d.getMonth() + 1; const day = d.getDate();
  const list = [
    [1,20,'Capricórnio'],[2,19,'Aquário'],[3,21,'Peixes'],[4,20,'Áries'],
    [5,21,'Touro'],[6,21,'Gêmeos'],[7,23,'Câncer'],[8,23,'Leão'],
    [9,23,'Virgem'],[10,23,'Libra'],[11,22,'Escorpião'],[12,22,'Sagitário'],
    [12,31,'Capricórnio'],
  ];
  for (const [mm, dd, sign] of list) if (m < mm || (m === mm && day <= dd)) return sign;
  return 'Capricórnio';
};

// ── topo contextual das telas do app (SHELL) ────────────────
// Sem logo e sem "voltar": a barra lateral é a navegação. Só título + ações + menu
// do usuário. Deixa folga à esquerda no mobile pro botão de menu flutuante.
const ScreenHeader = ({ title, action, onOpenSettings }) => {
  const { theme } = useTheme();
  const { astrologer } = window.ORBITA_DATA;
  return (
    <header className="orbita-shell-header" style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: theme.headerBg, backdropFilter: 'blur(16px)',
      borderBottom: '1px solid rgba(255,255,255,0.09)',
      padding: '0 32px', height: 60,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <style>{`@media (max-width: 899px){ .orbita-shell-header{ padding-left: 64px !important; } }`}</style>
      <span style={{ fontFamily: '"Instrument Serif", serif', fontSize: 19, color: '#F5F1E8' }}>{title}</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {action}
        <ThemeSwitcher name={astrologer.name} onOpenSettings={onOpenSettings} />
      </div>
    </header>
  );
};

// ── ConsulentesScreen ───────────────────────────────────────
const ConsulentesScreen = ({ onOpenSession, onNewSession, onOpenSettings, state = 'data', variant = 'cards' }) => {
  const { theme } = useTheme();
  const [allConsulentes, setAllConsulentes] = useStateC([]);
  const [localState, setLocalState] = useStateC(state === 'data' ? 'loading' : state);

  // `state !== 'data'` só acontece vindo do atalho de protótipo ("Consulentes ·
  // vazio"/"· erro", ver PROTO_SCREENS em orbita-app.jsx) — força o estado de
  // revisão visual sem bater na API. Na navegação real (`state === 'data'`),
  // busca a lista de verdade em GET /api/consulentes (já vem enriquecida com
  // sessions_count/check_ins/engagement — ver app/api/consulentes/route.ts).
  const loadConsulentes = React.useCallback(() => {
    if (state !== 'data') { setLocalState(state); return; }
    setLocalState('loading');
    fetch('/api/consulentes')
      .then(res => res.json().catch(() => ({})).then(data => { if (!res.ok) throw new Error(data.error || 'Falha ao carregar.'); return data; }))
      .then(data => {
        const list = (data.consulentes || []).map(c => ({ ...c, tags: c.tags || [] }));
        setAllConsulentes(list);
        setLocalState(list.length === 0 ? 'empty' : 'data');
      })
      .catch(() => setLocalState('error'));
  }, [state]);

  React.useEffect(() => { loadConsulentes(); }, [loadConsulentes]);
  const consulentes = localState === 'empty' ? [] : allConsulentes;

  // Card ↔ tabela: toggle de verdade (antes era só indicador do painel de Tweaks).
  const [view, setView] = useStateC(variant);

  const [query, setQuery] = useStateC('');
  const [tag, setTag] = useStateC('all');
  const [sign, setSign] = useStateC('all');
  const [sel, setSel] = useStateC(null); // selected consulente id
  const [sortBy, setSortBy] = useStateC('recent');
  const [showAddModal, setShowAddModal] = useStateC(false);

  const retry = loadConsulentes;

  // Otimista: atualiza a UI na hora, persiste em paralelo. Falha aqui é
  // silenciosa de propósito — pior caso, a tag some no próximo reload.
  const addTag = (consulenteId, newTag) => {
    const target = allConsulentes.find(c => c.id === consulenteId);
    if (!target || target.tags.includes(newTag)) return;
    const nextTags = [...target.tags, newTag];
    setAllConsulentes(prev => prev.map(c => c.id === consulenteId ? { ...c, tags: nextTags } : c));
    fetch(`/api/consulentes/${consulenteId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ tags: nextTags }),
    }).catch(() => {});
  };

  const allTags = useMemoC(() => {
    const set = new Set();
    consulentes.forEach(c => c.tags.forEach(t => set.add(t)));
    return Array.from(set).sort();
  }, [consulentes]);

  const filtered = useMemoC(() => {
    let out = consulentes.filter(c => {
      const q = query.toLowerCase().trim();
      if (q && !c.name.toLowerCase().includes(q) && !c.email.toLowerCase().includes(q)) return false;
      if (tag !== 'all' && !c.tags.includes(tag)) return false;
      if (sign !== 'all' && zodiacOf(c.birth_date) !== sign) return false;
      return true;
    });
    if (sortBy === 'recent') out.sort((a,b) => new Date(b.last_active) - new Date(a.last_active));
    if (sortBy === 'engagement') out.sort((a,b) => b.engagement - a.engagement);
    if (sortBy === 'name') out.sort((a,b) => a.name.localeCompare(b.name));
    return out;
  }, [consulentes, query, tag, sign, sortBy]);

  const selected = sel ? consulentes.find(c => c.id === sel) : null;

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.fg, fontFamily: 'Inter, sans-serif' }}>
      <GrainOverlay />
      <ScreenHeader title="Consulentes" onOpenSettings={onOpenSettings} action={
        localState !== 'empty' && localState !== 'loading' && (
          <BtnPrimary small onClick={() => setShowAddModal(true)}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
            Novo consulente
          </BtnPrimary>
        )
      } />

      <div className="orbita-page" style={{ maxWidth: 1100, margin: '0 auto', padding: '32px 32px 100px', position: 'relative' }}>
        <RadialGlow opacity={0.08} top="-100px" />

        {/* Title row */}
        <div style={{ marginBottom: 28, position: 'relative', zIndex: 1, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
          <div>
            <p style={{ margin: '0 0 4px', fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Sua base</p>
            <h1 style={{ margin: 0, fontSize: 36, fontFamily: '"Instrument Serif", serif', fontWeight: 400, letterSpacing: '-0.01em' }}>
              Consulentes
            </h1>
          </div>
          {localState === 'data' && (
            <p style={{ margin: 0, fontSize: 13, color: theme.fgMuted, textAlign: 'right' }}>
              <span style={{ color: theme.fg, fontWeight: 500 }}>{filtered.length}</span> de {consulentes.length} mostrados<br/>
              <span style={{ fontSize: 11, color: theme.fgDim }}>{consulentes.filter(c => c.engagement > 0.7).length} com engajamento alto</span>
            </p>
          )}
        </div>

        {/* States */}
        {localState === 'loading' && <ConsulentesLoading />}
        {localState === 'error'   && <ConsulentesError onRetry={retry} />}
        {localState === 'empty'   && <ConsulentesEmpty onCreate={() => setShowAddModal(true)} />}

        {localState === 'data' && (
          <>
            {/* Toolbar */}
            <div style={{
              display: 'flex', gap: 10, marginBottom: 20, flexWrap: 'wrap', alignItems: 'center',
              position: 'relative', zIndex: 1,
            }}>
              <div style={{
                flex: '1 1 280px', position: 'relative', minWidth: 220,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.fgMuted} strokeWidth="2" style={{
                  position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
                }}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/></svg>
                <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Buscar por nome ou e-mail…" style={{
                  width: '100%', background: theme.inputBg, border: `1px solid ${theme.border}`,
                  borderRadius: 10, padding: '11px 14px 11px 38px', color: theme.fg,
                  fontFamily: 'Inter', fontSize: 14, outline: 'none',
                }} onFocus={e => e.target.style.borderColor = `${theme.accent}60`} onBlur={e => e.target.style.borderColor = theme.border} />
              </div>
              <ConsTagPills value={tag} onChange={setTag} options={[
                { id: 'all', label: 'Todas as tags' },
                ...allTags.map(t => ({ id: t, label: t.charAt(0).toUpperCase() + t.slice(1) })),
              ]} />
              <SignFilter value={sign} onChange={setSign} />
              <SortMenu value={sortBy} onChange={setSortBy} />
              <CopyEmailsButton emails={filtered.map(c => c.email).filter(Boolean)} />
              <ViewToggle value={view} onChange={setView} />
            </div>

            {filtered.length === 0 ? (
              <div style={{
                padding: '60px 20px', textAlign: 'center', color: theme.fgMuted,
                background: theme.card, border: `1px dashed ${theme.border}`, borderRadius: 16,
              }}>
                <div style={{ fontSize: 22, marginBottom: 8, opacity: 0.4 }}>◌</div>
                Nenhum consulente corresponde aos filtros.
              </div>
            ) : view === 'cards' ? (
              <ConsulentesGrid list={filtered} onSelect={setSel} />
            ) : (
              <ConsulentesTable list={filtered} onSelect={setSel} />
            )}
          </>
        )}

        {/* Drawer */}
        {selected && (
          <ConsulenteDrawer
            consulente={selected}
            onClose={() => setSel(null)}
            onOpenSession={onOpenSession}
            onNewSession={onNewSession}
            onAddTag={addTag}
            onDeleted={() => { setSel(null); loadConsulentes(); }}
          />
        )}
      </div>
      {showAddModal && (
        <ConsulenteFormModal
          onClose={() => setShowAddModal(false)}
          onSaved={loadConsulentes}
        />
      )}
    </div>
  );
};

// ── Filter pills (renamed to avoid collision with editor's FilterPills) ──
const ConsTagPills = ({ value, onChange, options }) => {
  const { theme } = useTheme();
  return (
    <div style={{ display: 'inline-flex', gap: 4, padding: 4, background: theme.inputBg, borderRadius: 999, border: `1px solid ${theme.border}` }}>
      {options.map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          padding: '6px 14px', borderRadius: 999, border: 'none',
          background: value === o.id ? theme.accent : 'transparent',
          color: value === o.id ? (theme.id === 'light' ? '#FDFAF5' : '#100D0A') : theme.fgMuted,
          fontFamily: 'Inter', fontSize: 12, fontWeight: 500, cursor: 'pointer',
        }}>{o.label}</button>
      ))}
    </div>
  );
};

const ZODIAC_SIGNS = ['Áries','Touro','Gêmeos','Câncer','Leão','Virgem','Libra','Escorpião','Sagitário','Capricórnio','Aquário','Peixes'];

const SignFilter = ({ value, onChange }) => {
  const { theme } = useTheme();
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      padding: '10px 14px', background: theme.inputBg, border: `1px solid ${theme.border}`,
      borderRadius: 10, color: theme.fg, fontSize: 13, fontFamily: 'Inter', outline: 'none', cursor: 'pointer',
    }}>
      <option value="all">Todos os signos</option>
      {ZODIAC_SIGNS.map(s => <option key={s} value={s}>{s}</option>)}
    </select>
  );
};

const CopyEmailsButton = ({ emails }) => {
  const { theme } = useTheme();
  const [copied, setCopied] = useStateC(false);
  return (
    <button
      disabled={emails.length === 0}
      onClick={() => {
        navigator.clipboard.writeText(emails.join(', '));
        setCopied(true);
        setTimeout(() => setCopied(false), 1800);
      }}
      title="Copia os e-mails da lista filtrada, pronta pra colar no seu disparo de e-mail"
      style={{
        padding: '10px 14px', borderRadius: 10, border: `1px solid ${theme.border}`,
        background: theme.inputBg, color: emails.length === 0 ? theme.fgDim : theme.fg,
        fontSize: 12, fontWeight: 500, cursor: emails.length === 0 ? 'default' : 'pointer',
        fontFamily: 'Inter, sans-serif', whiteSpace: 'nowrap',
      }}
    >{copied ? '✓ e-mails copiados' : `Copiar e-mails (${emails.length})`}</button>
  );
};

const SortMenu = ({ value, onChange }) => {
  const { theme } = useTheme();
  return (
    <select value={value} onChange={e => onChange(e.target.value)} style={{
      padding: '10px 14px', background: theme.inputBg, border: `1px solid ${theme.border}`,
      borderRadius: 10, color: theme.fg, fontSize: 13, fontFamily: 'Inter', outline: 'none', cursor: 'pointer',
    }}>
      <option value="recent">Mais recentes</option>
      <option value="engagement">Engajamento</option>
      <option value="name">Nome (A-Z)</option>
    </select>
  );
};

const ViewToggle = ({ value, onChange }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      display: 'inline-flex', gap: 0, padding: 3, background: theme.inputBg,
      borderRadius: 10, border: `1px solid ${theme.border}`, marginLeft: 'auto',
    }}>
      {[{id:'cards',label:'Cards',svg:<><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></>},
        {id:'table',label:'Tabela',svg:<><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></>}].map(o => (
        <button key={o.id} onClick={() => onChange(o.id)} title={o.label} style={{
          padding: '6px 10px', borderRadius: 7, border: 'none', cursor: 'pointer',
          background: value === o.id ? `${theme.accent}22` : 'transparent',
          color: value === o.id ? theme.accent : theme.fgDim,
          display: 'inline-flex', alignItems: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">{o.svg}</svg>
        </button>
      ))}
    </div>
  );
};

// ── Variant 1: Card grid ───────────────────────────────────
const ConsulentesGrid = ({ list, onSelect }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
      gap: 14, position: 'relative', zIndex: 1,
    }}>
      {list.map(c => {
        const lvl = c.engagement >= 0.75 ? 'alto' : c.engagement >= 0.4 ? 'médio' : 'baixo';
        const lvlC = c.engagement >= 0.75 ? theme.success : c.engagement >= 0.4 ? theme.accent : theme.fgDim;
        return (
          <Card key={c.id} onClick={() => onSelect(c.id)} style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
              <Avatar name={c.name} size={46} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: theme.fg, marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                <div style={{ fontSize: 11, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>{zodiacOf(c.birth_date)} · {ageFromIso(c.birth_date)} anos</div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 14 }}>
              <Stat label="sessões" value={c.sessions_count} />
              <Stat label="check-ins" value={c.check_ins} />
              <Stat label="engaj." value={`${Math.round(c.engagement*100)}%`} colorOverride={lvlC} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', gap: 6 }}>
                {c.tags.length === 0 && <span style={{ fontSize: 10, color: theme.fgDim, padding: '2px 8px', background: theme.inputBg, borderRadius: 999 }}>sem tag</span>}
                {c.tags.map(t => <TagChip key={t} tag={t} />)}
              </div>
              <span style={{ fontSize: 11, color: theme.fgDim }}>{fmtRelative(c.last_active)}</span>
            </div>
          </Card>
        );
      })}
    </div>
  );
};

const Stat = ({ label, value, colorOverride }) => {
  const { theme } = useTheme();
  return (
    <div>
      <div style={{ fontSize: 18, fontFamily: '"Instrument Serif", serif', color: colorOverride || theme.fg, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 9, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 4 }}>{label}</div>
    </div>
  );
};

const TagChip = ({ tag }) => {
  const { theme } = useTheme();
  const colorMap = { vip: theme.accent, mensal: theme.info, avulso: theme.fgMuted };
  const c = colorMap[tag] || theme.fgMuted;
  return (
    <span style={{
      fontSize: 10, color: c, background: `${c}18`, padding: '2px 8px', borderRadius: 999,
      textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 500,
    }}>{tag}</span>
  );
};

// ── Variant 2: Dense table ─────────────────────────────────
const ConsulentesTable = ({ list, onSelect }) => {
  const { theme } = useTheme();
  const cols = '1.6fr 1fr 0.8fr 0.8fr 1.2fr 0.8fr';
  return (
    <div style={{
      background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16,
      position: 'relative', zIndex: 1, overflowX: 'auto',
    }}>
      <div style={{ minWidth: 640 }}>
        <div style={{
          display: 'grid', gridTemplateColumns: cols,
          padding: '12px 20px', gap: 12,
          borderBottom: `1px solid ${theme.border}`, background: theme.inputBg,
          fontSize: 10, fontWeight: 600, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.08em',
        }}>
          <span>Nome</span><span>Signo · idade</span><span>Sessões</span><span>Check-ins</span><span>Engajamento</span><span>Última ativ.</span>
        </div>
        {list.map((c, i) => {
          const pct = Math.round(c.engagement * 100);
          const lvlC = c.engagement >= 0.75 ? theme.success : c.engagement >= 0.4 ? theme.accent : theme.fgDim;
          return (
            <div key={c.id} onClick={() => onSelect(c.id)} style={{
              display: 'grid', gridTemplateColumns: cols,
              padding: '14px 20px', gap: 12, alignItems: 'center', cursor: 'pointer',
              borderBottom: i === list.length - 1 ? 'none' : `1px solid ${theme.border}`,
              transition: 'background 0.12s',
            }}
            onMouseEnter={e => e.currentTarget.style.background = theme.inputBg}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <Avatar name={c.name} size={32} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: theme.fg, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                  <div style={{ fontSize: 10, color: theme.fgDim, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.email}</div>
                </div>
              </div>
              <div style={{ fontSize: 12, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>
                {zodiacOf(c.birth_date)}<br/>
                <span style={{ fontSize: 10, color: theme.fgDim }}>{ageFromIso(c.birth_date)} anos</span>
              </div>
              <div style={{ fontSize: 14, color: theme.fg, fontFamily: '"Instrument Serif", serif' }}>{c.sessions_count}</div>
              <div style={{ fontSize: 14, color: theme.fg, fontFamily: '"Instrument Serif", serif' }}>{c.check_ins}</div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ flex: 1, height: 4, background: theme.inputBg, borderRadius: 2, overflow: 'hidden', maxWidth: 100 }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: lvlC }} />
                  </div>
                  <span style={{ fontSize: 11, color: lvlC, fontFamily: 'DM Mono, monospace', minWidth: 32 }}>{pct}%</span>
                </div>
              </div>
              <div style={{ fontSize: 11, color: theme.fgMuted }}>{fmtRelative(c.last_active)}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ── Drawer (perfil) ─────────────────────────────────────────
const ConsulenteDrawer = ({ consulente, onClose, onOpenSession, onNewSession, onAddTag, onDeleted }) => {
  const { theme } = useTheme();
  const [sessions, setSessions] = useStateC([]);
  const [sessionsLoaded, setSessionsLoaded] = useStateC(false);
  React.useEffect(() => {
    setSessionsLoaded(false);
    fetch(`/api/leituras?consulente_id=${consulente.id}`)
      .then(res => res.json().catch(() => ({})))
      .then(data => setSessions(data.leituras || []))
      .catch(() => setSessions([]))
      .finally(() => setSessionsLoaded(true));
  }, [consulente.id]);
  const [tab, setTab] = useStateC('overview');
  const [newTag, setNewTag] = useStateC('');
  const [showDelete, setShowDelete] = useStateC(false);
  const [sessionNotes, setSessionNotes] = useStateC({});
  const [openNoteFor, setOpenNoteFor] = useStateC(null);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(4px)',
      zIndex: 200, display: 'flex', justifyContent: 'flex-end',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(620px, 92vw)', background: theme.bg, height: '100vh', overflowY: 'auto',
        borderLeft: `1px solid ${theme.border}`, animation: 'slideIn 0.22s ease',
      }}>
        <style>{`@keyframes slideIn { from { transform: translateX(40px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }`}</style>

        {/* Drawer header */}
        <div style={{
          padding: '20px 28px', borderBottom: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          position: 'sticky', top: 0, background: theme.bg, zIndex: 2,
        }}>
          <span style={{ fontSize: 11, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Perfil</span>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: theme.fgMuted, cursor: 'pointer', padding: 4 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>

        {/* Identity */}
        <div style={{ padding: '32px 28px 24px', borderBottom: `1px solid ${theme.border}` }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 20 }}>
            <Avatar name={consulente.name} size={64} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 style={{ margin: '0 0 4px', fontSize: 26, fontFamily: '"Instrument Serif", serif', fontWeight: 400, color: theme.fg }}>{consulente.name}</h2>
              <div style={{ fontSize: 12, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>
                {zodiacOf(consulente.birth_date)} · {ageFromIso(consulente.birth_date)} anos · {consulente.birth_city}
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap', alignItems: 'center' }}>
                {consulente.tags.map(t => <TagChip key={t} tag={t} />)}
                <input value={newTag} onChange={e => setNewTag(e.target.value)} onKeyDown={e => {
                  if (e.key === 'Enter' && newTag.trim()) { onAddTag(consulente.id, newTag.trim().toLowerCase()); setNewTag(''); }
                }} placeholder="+ tag" style={{
                  width: 64, background: theme.inputBg, border: `1px dashed ${theme.border}`, borderRadius: 999,
                  padding: '2px 10px', fontSize: 10, color: theme.fg, outline: 'none', fontFamily: 'Inter, sans-serif',
                }} />
              </div>
            </div>
          </div>

          {/* Quick info */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            <InfoRow label="E-mail" value={consulente.email} />
            <InfoRow label="Telefone" value={consulente.phone} />
            <InfoRow label="Nascimento" value={`${fmtDate(consulente.birth_date)} · ${consulente.birth_time}`} />
            <InfoRow label="Cliente desde" value={fmtDate(consulente.first_session)} />
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 0, padding: '0 28px', borderBottom: `1px solid ${theme.border}`, position: 'sticky', top: 60, background: theme.bg, zIndex: 1 }}>
          {[
            { id: 'overview', label: 'Visão geral' },
            { id: 'sessions', label: `Sessões (${sessions.length})` },
            { id: 'activity', label: 'Atividade' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '14px 0', marginRight: 24, background: 'transparent', border: 'none',
              borderBottom: `2px solid ${tab === t.id ? theme.accent : 'transparent'}`,
              color: tab === t.id ? theme.accent : theme.fgMuted, fontSize: 13, fontWeight: 500,
              cursor: 'pointer', fontFamily: 'Inter',
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ padding: '24px 28px 60px' }}>
          {tab === 'overview' && (
            <div>
              <SectionHeader title="Engajamento (90 dias)" />
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 28 }}>
                <BigStat label="Sessões"     value={consulente.sessions_count} />
                <BigStat label="Check-ins"   value={consulente.check_ins} />
                <BigStat label="Engajamento" value={`${Math.round(consulente.engagement*100)}%`} colorKey={consulente.engagement >= 0.75 ? 'success' : consulente.engagement >= 0.4 ? 'accent' : 'fgDim'} />
              </div>

              <SectionHeader title="Notas privadas" />
              <div style={{
                padding: '16px 18px', background: theme.inputBg, border: `1px dashed ${theme.border}`,
                borderRadius: 12, fontSize: 13, color: theme.fgMuted, lineHeight: 1.5, marginBottom: 28,
              }}>
                <span style={{ color: theme.fgDim }}>Privado · só você vê.</span><br/>
                {consulente.notes || 'Nenhuma nota registrada ainda.'}
              </div>

              <SectionHeader title="Zona de risco" />
              <button onClick={() => setShowDelete(true)} style={{
                padding: '9px 16px', borderRadius: 10, border: `1px solid ${theme.hot}40`,
                background: `${theme.hot}0c`, color: theme.hot, fontSize: 12, cursor: 'pointer', fontFamily: 'Inter, sans-serif',
              }}>Excluir consulente e todos os dados (LGPD)</button>
            </div>
          )}

          {tab === 'sessions' && (
            <div>
              {!sessionsLoaded ? (
                <div style={{ padding: 40, textAlign: 'center', color: theme.fgMuted, fontSize: 13 }}>Carregando…</div>
              ) : sessions.length === 0 ? (
                <div style={{ padding: 40, textAlign: 'center', color: theme.fgMuted, fontSize: 13 }}>
                  Nenhuma sessão ainda.<br/>
                  <BtnGhost small style={{ marginTop: 12 }} onClick={onNewSession}>Criar primeira sessão</BtnGhost>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {sessions.map(s => (
                    <Card key={s.id} hover={false} style={{ padding: '14px 18px' }}>
                      <div onClick={() => onOpenSession && onOpenSession(s)} style={{ display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' }}>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 14, fontWeight: 500, color: theme.fg, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 8 }}>
                            {s.title || 'Sessão sem título'}
                            <Badge status={s.status} small />
                          </div>
                          <div style={{ fontSize: 11, color: theme.fgMuted, fontFamily: 'DM Mono, monospace' }}>{fmtDate(s.created_at)}</div>
                        </div>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={theme.fgDim} strokeWidth="2"><path d="M9 18l6-6-6-6"/></svg>
                      </div>
                      <button onClick={(e) => { e.stopPropagation(); setOpenNoteFor(p => p === s.id ? null : s.id); }} style={{
                        marginTop: 10, background: 'none', border: 'none', color: theme.fgDim, fontSize: 11,
                        cursor: 'pointer', padding: 0, fontFamily: 'Inter, sans-serif',
                      }}>{openNoteFor === s.id ? '− ocultar' : '+ nota privada desta sessão'}</button>
                      {openNoteFor === s.id && (
                        <textarea
                          value={sessionNotes[s.id] || ''}
                          onChange={e => setSessionNotes(p => ({ ...p, [s.id]: e.target.value }))}
                          placeholder="O que vale lembrar sobre esta sessão…"
                          rows={2}
                          onClick={e => e.stopPropagation()}
                          style={{
                            width: '100%', marginTop: 8, background: theme.inputBg, border: `1px dashed ${theme.border}`,
                            borderRadius: 10, padding: '8px 12px', color: theme.fg, fontSize: 12,
                            fontFamily: 'Inter, sans-serif', resize: 'vertical', outline: 'none', boxSizing: 'border-box',
                          }}
                        />
                      )}
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {tab === 'activity' && (
            <div>
              <SectionHeader title="Linha do tempo" />
              {/* Só eventos reais que dá pra montar sem um endpoint novo de
                  atividade agregada (cadastro + publicações). Check-in/visita
                  por evento individual ainda não tem API própria — sem isso,
                  melhor não mostrar nada do que inventar horário. */}
              {(() => {
                const events = [
                  { key: 'created', label: 'Consulente cadastrada', when: consulente.created_at },
                  ...sessions
                    .filter(s => s.published_at)
                    .map(s => ({ key: `pub-${s.id}`, label: `Recebeu acesso ao portal · ${s.title || 'sessão'}`, when: s.published_at })),
                ].sort((a, b) => new Date(b.when) - new Date(a.when));
                if (events.length === 0) {
                  return <p style={{ fontSize: 13, color: theme.fgMuted }}>Sem eventos registrados ainda.</p>;
                }
                return (
                  <div style={{ position: 'relative', paddingLeft: 22 }}>
                    <div style={{ position: 'absolute', left: 6, top: 8, bottom: 8, width: 1, background: theme.border }} />
                    {events.map(ev => (
                      <div key={ev.key} style={{ position: 'relative', paddingBottom: 18 }}>
                        <div style={{
                          position: 'absolute', left: -22, top: 4, width: 11, height: 11, borderRadius: '50%',
                          background: theme.bg, border: `2px solid ${theme.accent}`,
                        }} />
                        <div style={{ fontSize: 13, color: theme.fg, marginBottom: 2 }}>{ev.label}</div>
                        <div style={{ fontSize: 11, color: theme.fgDim, fontFamily: 'DM Mono, monospace' }}>{fmtDate(ev.when)}</div>
                      </div>
                    ))}
                  </div>
                );
              })()}
            </div>
          )}
        </div>
      </div>
      {showDelete && (
        <DeleteConsulenteModal consulente={consulente} onClose={() => setShowDelete(false)} onDeleted={onDeleted} />
      )}
    </div>
  );
};

const InfoRow = ({ label, value }) => {
  const { theme } = useTheme();
  return (
    <div>
      <div style={{ fontSize: 10, color: theme.fgDim, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 13, color: theme.fg }}>{value}</div>
    </div>
  );
};

const BigStat = ({ label, value, colorKey = 'fg' }) => {
  const { theme } = useTheme();
  return (
    <div style={{ padding: '14px 16px', background: theme.inputBg, border: `1px solid ${theme.border}`, borderRadius: 12 }}>
      <div style={{ fontSize: 26, fontFamily: '"Instrument Serif", serif', color: theme[colorKey] || theme.fg, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 10, color: theme.fgMuted, textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 6 }}>{label}</div>
    </div>
  );
};

// ── States: empty, loading, error ──────────────────────────
// Importar CSV (`ImportCsvModal`, orbita-flows-new.jsx) ainda é 100% mock —
// desligado aqui até existir um endpoint real de criação em lote, pra não
// prometer um import que some no próximo reload.
const ConsulentesEmpty = ({ onCreate }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      padding: '90px 32px', textAlign: 'center', position: 'relative', zIndex: 1,
      background: theme.card, border: `1px dashed ${theme.border}`, borderRadius: 24,
    }}>
      <svg width="64" height="64" viewBox="0 0 64 64" fill="none" style={{ marginBottom: 20, opacity: 0.7 }}>
        <circle cx="32" cy="32" r="6" fill={theme.accent} opacity="0.6" />
        <circle cx="32" cy="32" r="14" stroke={theme.accent} strokeWidth="1" opacity="0.35" fill="none" />
        <circle cx="32" cy="32" r="22" stroke={theme.accent} strokeWidth="0.8" opacity="0.18" fill="none" />
        <circle cx="32" cy="32" r="30" stroke={theme.accent} strokeWidth="0.5" opacity="0.08" fill="none" />
      </svg>
      <h2 style={{ margin: '0 0 8px', fontSize: 26, fontFamily: '"Instrument Serif", serif', fontWeight: 400 }}>
        Sua órbita ainda está vazia
      </h2>
      <p style={{ margin: '0 auto 28px', fontSize: 14, color: theme.fgMuted, maxWidth: 400, lineHeight: 1.6 }}>
        Quando você cadastrar suas consulentes, elas aparecem aqui. Você pode começar com uma — o Órbitas preenche o resto à medida que você cria sessões.
      </p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
        <BtnPrimary onClick={onCreate}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14"/></svg>
          Cadastrar primeira consulente
        </BtnPrimary>
      </div>
    </div>
  );
};

const ConsulentesLoading = () => {
  const { theme } = useTheme();
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
      {Array.from({ length: 6 }).map((_, i) => (
        <div key={i} style={{
          background: theme.card, border: `1px solid ${theme.border}`, borderRadius: 16, padding: 18, height: 158,
          animation: `pulse 1.4s ease-in-out ${i * 0.08}s infinite`,
        }}>
          <style>{`@keyframes pulse { 0%, 100% { opacity: 0.55; } 50% { opacity: 1; } }`}</style>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{ width: 46, height: 46, borderRadius: '50%', background: theme.inputBg }} />
            <div style={{ flex: 1 }}>
              <div style={{ height: 12, width: '60%', background: theme.inputBg, borderRadius: 4, marginBottom: 6 }} />
              <div style={{ height: 9, width: '40%', background: theme.inputBg, borderRadius: 4 }} />
            </div>
          </div>
          <div style={{ height: 36, background: theme.inputBg, borderRadius: 8, marginBottom: 14 }} />
          <div style={{ height: 18, width: '40%', background: theme.inputBg, borderRadius: 999 }} />
        </div>
      ))}
    </div>
  );
};

const ConsulentesError = ({ onRetry }) => {
  const { theme } = useTheme();
  return (
    <div style={{
      padding: '60px 32px', textAlign: 'center',
      background: theme.card, border: `1px solid ${theme.hot}40`, borderRadius: 16,
    }}>
      <div style={{ fontSize: 28, color: theme.hot, marginBottom: 16, fontFamily: '"Instrument Serif", serif' }}>⚠</div>
      <h3 style={{ margin: '0 0 8px', fontSize: 18, color: theme.fg }}>Não foi possível carregar suas consulentes</h3>
      <p style={{ margin: '0 0 20px', fontSize: 13, color: theme.fgMuted }}>
        Verifique sua conexão e tente novamente. Se persistir, fale com o suporte.
      </p>
      <BtnGhost onClick={onRetry}>Tentar novamente</BtnGhost>
    </div>
  );
};

Object.assign(window, { ConsulentesScreen });
