/* global React, BezaLogo, Icon, Pill, Card, Delta, Infotip, fmt,
   CRM_CLIENTS, CRM_STATUS_META, CRM_TIER_META, BIBLE_TONE_META,
   ACCESS_LEVEL_META, DEMAND_STATUS_META, HISTORY_TYPE_META, TIMELINE_TYPE_META,
   CHANNEL_META */
const { useState: useStateCrm, useMemo: useMemoCrm, useEffect: useEffectCrm } = React;

const ACTIVE_CLIENTS = CRM_CLIENTS.filter(c => !c.slug.includes('REMOVIDO'));

/* ============================================================
   CRM APP · root
   ============================================================ */
function CrmApp() {
  const [fichaSlug, setFichaSlug] = useStateCrm(null);
  const [filter, setFilter] = useStateCrm('todos');
  const [query, setQuery] = useStateCrm('');

  const filtered = CRM_CLIENTS.filter(c => {
    if (c.slug.includes('REMOVIDO')) return false;
    if (filter !== 'todos' && c.status !== filter) return false;
    if (query && !(`${c.brand} ${c.responsible} ${c.segment}`).toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <CrmListHeader />
      <CrmListToolbar filter={filter} setFilter={setFilter} query={query} setQuery={setQuery} count={filtered.length} />

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))',
        gap: 16,
      }}>
        {filtered.map(c => <CrmClientCard key={c.slug} client={c} onOpen={() => setFichaSlug(c.slug)} />)}
      </div>

      {fichaSlug && <FichaOverlay slug={fichaSlug} onClose={() => setFichaSlug(null)} />}
    </div>
  );
}

/* ============================================================
   LIST HEADER
   ============================================================ */
function CrmListHeader() {
  const ativos = ACTIVE_CLIENTS.filter(c => c.status === 'ativo').length;
  const novos = ACTIVE_CLIENTS.filter(c => c.status === 'novo').length;
  const total = ACTIVE_CLIENTS.length;

  return (
    <div style={{
      display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      gap: 24, marginBottom: 'var(--space-5)', flexWrap: 'wrap',
    }}>
      <div>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
          Módulo · CRM de clientes
        </div>
        <h2 className="t-h1" style={{ margin: 0, color: 'var(--text)' }}>
          <span className="t-light">A </span>
          <span className="punch">bíblia</span>
          <span className="t-light"> de cada cliente. Tudo num lugar só.</span>
        </h2>
      </div>
      <div style={{ display: 'flex', gap: 24, padding: 'var(--space-4)', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-card-lg)' }}>
        <SmallStat label="Ativos"     value={ativos} accent />
        <SmallStat label="Onboarding" value={novos} />
        <SmallStat label="Carteira"   value={total} />
      </div>
    </div>
  );
}

function SmallStat({ label, value, accent }) {
  return (
    <div>
      <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>{label}</div>
      <div className="num" style={{ fontSize: 24, fontWeight: 400, lineHeight: 1, color: accent ? 'var(--accent)' : 'var(--text)' }}>
        {value}
      </div>
    </div>
  );
}

/* ============================================================
   LIST TOOLBAR
   ============================================================ */
function CrmListToolbar({ filter, setFilter, query, setQuery, count }) {
  const totals = {
    todos:   ACTIVE_CLIENTS.length,
    ativo:   ACTIVE_CLIENTS.filter(c => c.status === 'ativo').length,
    novo:    ACTIVE_CLIENTS.filter(c => c.status === 'novo').length,
    pausado: ACTIVE_CLIENTS.filter(c => c.status === 'pausado').length,
    risco:   ACTIVE_CLIENTS.filter(c => c.status === 'risco').length,
  };
  const tabs = [
    { id: 'todos',   label: 'Todos',      n: totals.todos },
    { id: 'ativo',   label: 'Ativos',     n: totals.ativo },
    { id: 'novo',    label: 'Onboarding', n: totals.novo },
    { id: 'pausado', label: 'Pausados',   n: totals.pausado },
    { id: 'risco',   label: 'Em risco',   n: totals.risco },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16, flexWrap: 'wrap',
      marginBottom: 'var(--space-5)',
      padding: 'var(--space-3) var(--space-3)',
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
    }}>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
        {tabs.map(tab => {
          const active = filter === tab.id;
          return (
            <button key={tab.id} onClick={() => setFilter(tab.id)} style={{
              appearance: 'none',
              border: '1px solid', borderColor: active ? 'var(--accent)' : 'transparent',
              background: active ? 'var(--accent-soft)' : 'transparent',
              color: active ? 'var(--accent)' : 'var(--text-muted)',
              padding: '6px 12px', fontSize: 13,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {tab.label}
              <span style={{ fontSize: 11, color: 'var(--text-faint)', fontVariantNumeric: 'tabular-nums' }}>{tab.n}</span>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <input
          type="text"
          placeholder="Buscar cliente, segmento, responsável..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          style={{
            appearance: 'none',
            border: '1px solid var(--border-strong)',
            background: 'var(--bg-flat)',
            color: 'var(--text)',
            padding: '8px 14px', fontSize: 13,
            borderRadius: 'var(--r-btn)',
            fontFamily: 'inherit', minWidth: 240,
            outline: 'none',
          }}
        />
        <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{count} resultado{count === 1 ? '' : 's'}</span>
      </div>
    </div>
  );
}

/* ============================================================
   CLIENT CARD (na lista)
   ============================================================ */
function CrmClientCard({ client, onOpen }) {
  const statusMeta = CRM_STATUS_META[client.status] || CRM_STATUS_META['ativo'];
  const tierMeta = CRM_TIER_META[client.tier] || CRM_TIER_META['standard'];

  return (
    <div
      onClick={onOpen}
      onMouseEnter={(e) => {
        e.currentTarget.style.borderColor = 'var(--accent)';
        e.currentTarget.style.transform = 'translateY(-2px)';
        e.currentTarget.style.boxShadow = '0 12px 32px rgba(154,155,229,0.18)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = 'var(--border)';
        e.currentTarget.style.transform = '';
        e.currentTarget.style.boxShadow = '';
      }}
      style={{
        display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
        padding: 'var(--space-4)',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card-lg)',
        cursor: 'pointer',
        transition: 'all var(--t-base) var(--ease-out)',
        position: 'relative',
        overflow: 'hidden',
      }}>
      {client.isExample && (
        <span style={{
          position: 'absolute', top: 12, right: 12,
          fontSize: 9, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--accent)', padding: '2px 8px',
          background: 'var(--accent-soft)', border: '1px solid var(--border-strong)',
          borderRadius: 999,
        }}>
          ✨ exemplo
        </span>
      )}

      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: '50%',
          background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
          color: '#fff', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, fontWeight: 500,
        }}>{client.avatar || client.brand[0]}</div>

        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 2 }}>
            {client.segment}
          </div>
          <h3 style={{
            margin: 0, fontSize: 20, fontWeight: 500, letterSpacing: '-0.01em',
            lineHeight: 1.2, color: 'var(--text)',
          }}>
            {client.brand}
          </h3>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 2 }}>
            {client.responsible}
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <Pill tone="neutral" style={{ background: statusMeta.bg, color: statusMeta.color, borderColor: statusMeta.color + '40' }}>
          {statusMeta.label}
        </Pill>
        <Pill>{tierMeta.label}</Pill>
      </div>

      {client.lastReportSummary && (
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
          padding: 'var(--space-3) 0',
          borderTop: '1px solid var(--border)',
        }}>
          <div>
            <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 2 }}>Alcance · abr</div>
            <div className="num" style={{ fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>
              {fmt.k(client.lastReportSummary.reach)}
            </div>
          </div>
          <div>
            <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 2 }}>Engajamento</div>
            <div className="num" style={{ fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>
              {fmt.dec(client.lastReportSummary.engagement, 1)}%
            </div>
          </div>
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>
          Início {client.startedAt?.split('-').reverse().slice(0,2).join('/')}
        </span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {GUIDE_URL_MAP[client.slug] && (
            <a
              href={GUIDE_URL_MAP[client.slug]}
              target="_blank"
              rel="noopener noreferrer"
              onClick={(e) => e.stopPropagation()}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                fontSize: 11, fontWeight: 500, color: 'var(--text-muted)',
                textDecoration: 'none', padding: '3px 8px',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-pill)',
                transition: 'color 0.15s, border-color 0.15s',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--accent)'; e.currentTarget.style.borderColor = 'var(--accent)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-muted)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
            >
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                <path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>
              </svg>
              Guia
            </a>
          )}
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--accent)', fontSize: 13, fontWeight: 500 }}>
            Abrir ficha <Icon.Arrow width={14} height={14} />
          </span>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   CLIENT DETAIL VIEW · "BÍBLIA" do cliente
   ============================================================ */
/* ============================================================
   FICHA SLUG MAP — crm slug → ficha-[slug].html
   ============================================================ */
const FICHA_SLUG_MAP = {
  'anderson-guzanshe': 'anderson-guzanshe',
  'brady-bankston':    'brady-bankston',
  'daniely-jones':     'daniely-jones',
  'divine':            'divine',
  'ellem-possmozer':   'ellem-possmozer',
  'filhos-reais':      'filhos-reais',
  'possmozer-brasil':  'possmozer-brasil',
  'possmozer-usa':     'possmozer-usa',
  'projeto-eu':        'projeto-eu',
  'samara-soares':     'samara-soares',
  'agroexata':         'agroexata',
  'ge-builders':       'ge-builders',
  'hope':              'wanderson-braga',
};

const GUIDE_URL_MAP = {
  'beza-media': 'bezamedia/garimpo/referencias/index.html',
};

/* ============================================================
   FICHA OVERLAY — abre a ficha HTML completa em fullscreen
   ============================================================ */
function FichaOverlay({ slug, onClose }) {
  const guideUrl  = GUIDE_URL_MAP[slug];
  const fichaSlug = FICHA_SLUG_MAP[slug];
  if (!guideUrl && !fichaSlug) return null;
  const url = guideUrl || `clientes/ficha-${fichaSlug}.html?cb=4`;

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(0,0,0,0.55)',
      display: 'flex', flexDirection: 'column',
      backdropFilter: 'blur(4px)',
    }}>
      {/* toolbar */}
      <div style={{
        height: 48, background: 'var(--surface-strong)',
        borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 16px', flexShrink: 0, gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="assets/beza-roxo.png" style={{ height: 22 }} alt="Beza" />
          <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Ficha do Cliente</span>
        </div>
        <button onClick={onClose} style={{
          appearance: 'none', border: '1px solid var(--border)',
          background: 'var(--surface)', color: 'var(--text-muted)',
          padding: '5px 14px', fontSize: 13, fontFamily: 'inherit',
          borderRadius: 8, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
        }}>
          ✕ Fechar
        </button>
      </div>
      {/* iframe */}
      <iframe
        src={url}
        style={{ flex: 1, border: 'none', width: '100%' }}
        title="Ficha do Cliente"
      />
    </div>
  );
}

function CrmClientView({ client, onBack }) {
  const [section, setSection] = useStateCrm('overview');
  const [fichaOpen, setFichaOpen] = useStateCrm(false);

  const statusMeta = CRM_STATUS_META[client.status] || CRM_STATUS_META['ativo'];

  // se for stub (sem o template completo), mostra placeholder
  if (!client.bible) {
    return (
      <div style={{ padding: 'var(--space-6) 0 0' }}>
        <button onClick={onBack} style={btnBack}>
          <Icon.Arrow width={14} height={14} style={{ transform: 'rotate(180deg)' }} />
          Voltar pra lista
        </button>
        <div style={{
          padding: 'var(--space-7)',
          background: 'var(--surface)',
          border: '1px dashed var(--border-strong)',
          borderRadius: 'var(--r-card-lg)',
          textAlign: 'center', marginTop: 24,
        }}>
          <div style={{ marginBottom: 16, color: 'var(--accent)', display: 'inline-flex' }}>
            <Icon.Sparkle width={24} height={24} />
          </div>
          <h3 className="t-h2" style={{ margin: '0 0 12px' }}>{client.brand}</h3>
          <p style={{ margin: '0 auto 24px', fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 480 }}>
            Esta ficha ainda não foi preenchida. Os campos disponíveis são: contatos, posicionamento, tom de voz, canais, bíblia, demandas e histórico financeiro.
          </p>
        </div>
      </div>
    );
  }

  const sections = [
    { id: 'overview', label: 'Visão geral' },
    { id: 'voice',    label: 'Posicionamento + tom' },
    { id: 'references', label: 'Referências · moodboard' },
    { id: 'channels', label: 'Canais e acessos' },
    { id: 'drive',    label: 'Drive & materiais' },
    { id: 'identity', label: 'Identidade visual' },
    { id: 'portfolio',label: 'Portfólio entregue' },
    { id: 'bible',    label: 'Bíblia · pontos-chave' },
    { id: 'demands',  label: 'Demandas abertas' },
    { id: 'timeline', label: 'Próximas entregas' },
    { id: 'history',  label: 'Histórico' },
    ...(client.slug === 'beza-media' ? [{ id: 'concorrentes', label: '🔍 Concorrentes · garimpo' }] : []),
    ...(['brady-bankston','samara-soares','daniely-jones','divine','hope','projeto-eu','anderson-guzanshe','filhos-reais','possmozer-usa','agroexata','ge-builders'].includes(client.slug) ? [{ id: 'relatorio', label: '📊 Relatório · mensal' }] : []),
  ];

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <button onClick={onBack} style={btnBack}>
        <Icon.Arrow width={14} height={14} style={{ transform: 'rotate(180deg)' }} />
        Voltar pra lista
      </button>

      {/* HEADER · capa do cliente */}
      <div style={{
        marginTop: 16,
        padding: 'var(--space-6)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.12), rgba(154,155,229,0.02))',
        border: '1px solid var(--border-strong)',
        borderRadius: 'var(--r-card-lg)',
        position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-30%', right: '-10%',
          width: 500, height: 500, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(154,155,229,0.18), transparent 60%)',
          filter: 'blur(40px)', pointerEvents: 'none',
        }} />
        <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 'var(--space-6)', alignItems: 'flex-start', flexWrap: 'wrap' }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
                color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 22, fontWeight: 500,
              }}>{client.avatar}</div>
              <div>
                <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 2 }}>
                  Cliente · {client.segment}
                </div>
                <h2 className="t-h1" style={{ margin: 0, color: 'var(--text)' }}>
                  {client.brand}
                </h2>
                <div style={{ fontSize: 14, color: 'var(--text-muted)', marginTop: 4 }}>
                  {client.responsible} · {client.role}
                </div>
              </div>
            </div>

            <p style={{ margin: 0, fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 720 }}>
              {client.pitch}
            </p>

            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 16 }}>
              <Pill tone="neutral" style={{ background: statusMeta.bg, color: statusMeta.color, borderColor: statusMeta.color + '40' }}>{statusMeta.label}</Pill>
              <Pill tone="purple">{CRM_TIER_META[client.tier]?.label}</Pill>
              <Pill>{client.location}</Pill>
              <Pill>Iniciado {client.startedAt?.split('-').reverse().slice(0,2).join('/')}</Pill>
            </div>
          </div>

          <div style={{
            padding: 'var(--space-4)',
            background: 'var(--surface-strong)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--r-card)',
          }}>
            <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 12 }}>Snapshot</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <HeaderMetric label="Alcance · abr"   value={fmt.k(client.lastReportSummary.reach)} accent />
              <HeaderMetric label="Engajamento"     value={fmt.dec(client.lastReportSummary.engagement, 1) + '%'} />
              <HeaderMetric label="Novos seguidores" value={'+' + fmt.k(client.lastReportSummary.newFollowers)} />
              <HeaderMetric label="Status"          value={statusMeta.label} />
            </div>
            <div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
              <RadarBlock client={client} />
            </div>
          </div>
        </div>
      </div>

      {/* SIDE NAV + CONTEÚDO */}
      <div style={{ marginTop: 'var(--space-5)', display: 'grid', gridTemplateColumns: 'minmax(220px, 240px) minmax(0, 1fr)', gap: 'var(--space-5)', alignItems: 'flex-start' }}>
        <aside style={{ position: 'sticky', top: 130 }}>
          <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 10, padding: '0 4px' }}>Seções da ficha</div>
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {sections.map(s => {
              const active = s.id === section;
              return (
                <button key={s.id} onClick={() => setSection(s.id)} style={{
                  appearance: 'none', border: 'none',
                  background: active ? 'var(--accent-soft)' : 'transparent',
                  color: active ? 'var(--accent)' : 'var(--text-muted)',
                  padding: '10px 14px', textAlign: 'left',
                  borderRadius: 'var(--r-btn)',
                  fontSize: 13, fontWeight: active ? 500 : 400,
                  fontFamily: 'inherit', cursor: 'pointer',
                  transition: 'all var(--t-fast)',
                }}>
                  {s.label}
                </button>
              );
            })}
          </nav>

          {FICHA_SLUG_MAP[client.slug] && (
            <button onClick={() => setFichaOpen(true)} style={{
              marginTop: 20,
              appearance: 'none',
              border: '1px solid var(--accent)',
              background: 'var(--accent-soft)',
              color: 'var(--accent)',
              padding: '10px 14px',
              width: '100%',
              fontSize: 13,
              fontWeight: 500,
              fontFamily: 'inherit',
              borderRadius: 'var(--r-btn)',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 7,
              transition: 'background 0.15s',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
                <polyline points="14,2 14,8 20,8"/>
              </svg>
              Ficha Completa
            </button>
          )}

          {GUIDE_URL_MAP[client.slug] && (
            <a href={GUIDE_URL_MAP[client.slug]} target="_blank" rel="noopener noreferrer" style={{
              marginTop: 8,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
              border: '1px solid var(--border-strong)',
              background: 'var(--surface)',
              color: 'var(--text-muted)',
              padding: '10px 14px',
              width: '100%',
              fontSize: 13, fontWeight: 500,
              fontFamily: 'inherit',
              borderRadius: 'var(--r-btn)',
              cursor: 'pointer',
              textDecoration: 'none',
              transition: 'border-color 0.15s, color 0.15s',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--accent)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = ''; e.currentTarget.style.color = 'var(--text-muted)'; }}
            >
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>
              </svg>
              Super Guia
            </a>
          )}

          <div style={{
            marginTop: 16, padding: '12px 14px',
            background: 'var(--surface-soft)',
            border: '1px solid var(--border)',
            borderRadius: 'var(--r-btn)',
            fontSize: 11, color: 'var(--text-faint)', lineHeight: 1.5,
          }}>
            ✨ Esta ficha é o template. Use os marcadores <code style={{ color: 'var(--accent)' }}>// BEZA:*</code> em <code>crm-data.js</code> pra duplicar.
          </div>
        </aside>

        <div>
          {section === 'overview' && <SectionOverview client={client} />}
          {section === 'voice'    && <SectionVoice client={client} />}
          {section === 'references' && <SectionReferences client={client} />}
          {section === 'channels' && <SectionChannels client={client} />}
          {section === 'drive'    && <SectionDrive client={client} />}
          {section === 'identity' && <SectionIdentity client={client} />}
          {section === 'portfolio'&& <SectionPortfolio client={client} />}
          {section === 'bible'    && <SectionBible client={client} />}
          {section === 'demands'  && <SectionDemands client={client} />}
          {section === 'timeline' && <SectionTimeline client={client} />}
          {section === 'history'  && <SectionHistory client={client} />}
          {section === 'concorrentes' && (
            <div style={{ borderRadius: 'var(--r-card-lg)', overflow: 'hidden', border: '1px solid var(--border)', height: 'calc(100vh - 200px)', minHeight: 600 }}>
              <iframe
                src="/garimpo-beza.html"
                style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
                title="Garimpo de Referências Beza"
              />
            </div>
          )}
          {section === 'relatorio' && (
            <div style={{ borderRadius: 'var(--r-card-lg)', overflow: 'hidden', border: '1px solid var(--border)', height: 'calc(100vh - 200px)', minHeight: 600 }}>
              <iframe
                src={`/clientes/${client.slug}.html`}
                style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
                title={`Relatório ${client.brand}`}
              />
            </div>
          )}
        </div>
      </div>

      {fichaOpen && <FichaOverlay slug={client.slug} onClose={() => setFichaOpen(false)} />}
    </div>
  );
}

const btnBack = {
  appearance: 'none', border: '1px solid var(--border-strong)',
  background: 'var(--surface)', color: 'var(--text-muted)',
  padding: '8px 14px', fontSize: 13, fontFamily: 'inherit',
  borderRadius: 'var(--r-btn)', cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 8,
};

function HeaderMetric({ label, value, suffix, accent }) {
  return (
    <div>
      <div className="t-overline" style={{ color: 'var(--text-faint)', fontSize: 10, marginBottom: 4 }}>{label}</div>
      <div className="num" style={{ fontSize: 22, fontWeight: 400, color: accent ? 'var(--accent)' : 'var(--text)', lineHeight: 1 }}>
        {value}{suffix}
      </div>
    </div>
  );
}

/* ============================================================
   RADAR BLOCK · status do mês corrente
   ============================================================ */
function RadarBlock({ client }) {
  if (!client.radar) {
    return (
      <>
        <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>Radar do mês</div>
        <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>—</div>
      </>
    );
  }
  const r = client.radar;
  const meta = window.RADAR_STATUS_META?.[r.status] || { label: r.status, color: 'var(--accent)', icon: '◐' };
  const pct = Math.round(((r.delivered + r.scheduled) / r.totalPlanned) * 100);
  const formatDate = (d) => d?.split('-').reverse().slice(0,2).join('/');

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
        <div className="t-overline" style={{ color: 'var(--text-faint)' }}>Radar · {r.monthLabel}</div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 5,
          padding: '2px 8px', borderRadius: 999,
          background: meta.color + '20',
          color: meta.color,
          fontSize: 10, fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase',
          border: `1px solid ${meta.color}40`,
        }}>
          <span>{meta.icon}</span> {meta.label}
        </span>
      </div>

      <div style={{
        height: 8, background: 'var(--surface-soft)',
        borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)',
        marginBottom: 8, display: 'flex',
      }}>
        <div style={{
          height: '100%',
          width: (r.delivered / r.totalPlanned * 100) + '%',
          background: '#6FC878',
        }} />
        <div style={{
          height: '100%',
          width: (r.scheduled / r.totalPlanned * 100) + '%',
          background: '#77B8F1',
        }} />
        <div style={{
          height: '100%',
          width: (r.inApproval / r.totalPlanned * 100) + '%',
          background: '#F3AE4D',
        }} />
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        gap: 8, fontSize: 11, color: 'var(--text-muted)',
        marginBottom: 10,
      }}>
        <div>
          <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: '50%', background: '#6FC878', marginRight: 5 }} />
          Entregue · <span className="num" style={{ color: 'var(--text)', fontWeight: 500 }}>{r.delivered}</span>
        </div>
        <div>
          <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: '50%', background: '#77B8F1', marginRight: 5 }} />
          Agendado · <span className="num" style={{ color: 'var(--text)', fontWeight: 500 }}>{r.scheduled}</span>
        </div>
        <div>
          <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: '50%', background: '#F3AE4D', marginRight: 5 }} />
          Aprovação · <span className="num" style={{ color: 'var(--text)', fontWeight: 500 }}>{r.inApproval}</span>
        </div>
        <div>
          <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: '50%', background: '#9A9BE5', marginRight: 5 }} />
          Produção · <span className="num" style={{ color: 'var(--text)', fontWeight: 500 }}>{r.inProduction}</span>
        </div>
      </div>

      <div style={{
        padding: '8px 10px',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-btn)',
        fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5,
      }}>
        Já publicado até <strong style={{ color: 'var(--text)' }}>{formatDate(r.deliveredThrough)}</strong> · agendado até <strong style={{ color: 'var(--accent)' }}>{formatDate(r.scheduledThrough)}</strong>
      </div>
    </div>
  );
}

/* ============================================================
   SECTION · OVERVIEW (contatos + entregas + persona resumida)
   ============================================================ */
function SectionOverview({ client }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      {/* CONTATOS */}
      <CrmSection kicker="01 · pessoas" title="Quem **fala com a gente**">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {client.contacts.map(c => (
            <div key={c.id} style={{
              padding: 14,
              background: 'var(--surface)',
              border: c.isPrimary ? '1px solid rgba(154,155,229,0.40)' : '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              position: 'relative',
            }}>
              {c.isPrimary && (
                <span style={{
                  position: 'absolute', top: 10, right: 10,
                  fontSize: 9, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: 'var(--accent)', padding: '2px 6px',
                  background: 'var(--accent-soft)', borderRadius: 999,
                }}>
                  decisor
                </span>
              )}
              <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>{c.name}</div>
              <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 2 }}>{c.role}</div>
              <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12 }}>
                <a href={`mailto:${c.email}`} style={crmLink}>
                  <span style={{ color: 'var(--text-faint)' }}>✉</span> {c.email}
                </a>
                <a href={c.whatsapp ? `https://wa.me/${c.phone.replace(/\D/g,'')}` : `tel:${c.phone}`} style={crmLink}>
                  <span style={{ color: 'var(--text-faint)' }}>{c.whatsapp ? '✆' : '☏'}</span> {c.phone}
                  {c.whatsapp && <span style={{ marginLeft: 4, fontSize: 10, color: 'var(--success)' }}>· WhatsApp</span>}
                </a>
              </div>
            </div>
          ))}
        </div>
      </CrmSection>

      {/* ENTREGAS DO MÊS */}
      <CrmSection kicker="02 · escopo do contrato" title="Entregas **mensais**">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12 }}>
          {Object.entries(client.monthlyDeliverables).map(([k, v]) => (
            <div key={k} style={{
              padding: 14,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              textAlign: 'center',
            }}>
              <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>
                {capitalize(k.replace(/([A-Z])/g, ' $1'))}
              </div>
              <div className="num" style={{ fontSize: 26, fontWeight: 400, color: 'var(--text)', lineHeight: 1 }}>
                {typeof v === 'number' ? v : v}
              </div>
            </div>
          ))}
        </div>
      </CrmSection>

      {/* PERSONA */}
      <CrmSection kicker="03 · persona" title="Pra quem **falamos**">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          <PersonaCard label="Quem é"  text={client.persona.who} />
          <PersonaCard label="Dor"     text={client.persona.pain} />
          <PersonaCard label="Desejo"  text={client.persona.desire} />
          <PersonaCard label="Evitar"  text={client.persona.avoid} tone="warning" />
        </div>
      </CrmSection>
    </div>
  );
}

function PersonaCard({ label, text, tone }) {
  const c = tone === 'warning' ? 'var(--warning)' : 'var(--accent)';
  return (
    <div style={{
      padding: 14,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderLeft: `3px solid ${c}`,
      borderRadius: 'var(--r-card)',
    }}>
      <div className="t-overline" style={{ color: c, marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 14, color: 'var(--text)', lineHeight: 1.5 }}>{text}</div>
    </div>
  );
}

const crmLink = {
  display: 'flex', alignItems: 'center', gap: 8,
  color: 'var(--text-muted)', textDecoration: 'none',
  padding: 4, borderRadius: 'var(--r-btn)',
  transition: 'background var(--t-fast)',
};

function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase(); }

/* ============================================================
   SECTION · VOICE (posicionamento + tom)
   ============================================================ */
function SectionVoice({ client }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <CrmSection kicker="o que usar" title="**Usar** sempre">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {client.voice.use.map((v, i) => (
            <div key={i} style={voicePill('var(--success)')}>
              <span style={{ color: 'var(--success)', fontWeight: 600 }}>✓</span> {v}
            </div>
          ))}
        </div>
      </CrmSection>

      <CrmSection kicker="o que evitar" title="**Evitar** sempre">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {client.voice.avoid.map((v, i) => (
            <div key={i} style={voicePill('var(--error)')}>
              <span style={{ color: 'var(--error)', fontWeight: 600 }}>✕</span> {v}
            </div>
          ))}
        </div>
      </CrmSection>

      <CrmSection kicker="taglines" title="**Frases-marca** já aprovadas">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {client.voice.taglines.map((t, i) => (
            <blockquote key={i} style={{
              margin: 0, padding: '16px 20px',
              background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
              border: '1px solid rgba(154,155,229,0.30)',
              borderLeft: '3px solid var(--accent)',
              borderRadius: 'var(--r-card)',
              fontSize: 17, fontStyle: 'italic', fontWeight: 300, color: 'var(--text)',
              lineHeight: 1.4,
            }}>"{t}"</blockquote>
          ))}
        </div>
      </CrmSection>
    </div>
  );
}

function voicePill(color) {
  return {
    display: 'flex', alignItems: 'flex-start', gap: 10,
    padding: '10px 14px',
    background: 'var(--surface)',
    border: '1px solid var(--border)',
    borderLeft: `3px solid ${color}`,
    borderRadius: 'var(--r-btn)',
    fontSize: 14, color: 'var(--text)', lineHeight: 1.5,
  };
}

/* ============================================================
   SECTION · CHANNELS (canais com acessos)
   ============================================================ */
function SectionChannels({ client }) {
  return (
    <CrmSection kicker="onde estamos" title="**Canais** e níveis de acesso">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {client.channels.map(ch => {
          const meta = window.CHANNEL_META?.[ch.id];
          const accessMeta = ACCESS_LEVEL_META[ch.accessLevel];
          const I = meta?.Icon;
          return (
            <div key={ch.id} style={{
              padding: 16,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              display: 'grid', gridTemplateColumns: '44px minmax(0, 1fr) auto', gap: 16, alignItems: 'flex-start',
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 'var(--r-btn)',
                background: 'var(--accent-soft)', color: 'var(--accent)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {I ? <I width={20} height={20} /> : <Icon.External width={20} height={20} />}
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
                  <span style={{ fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>{ch.label}</span>
                  <a href={ch.url} target="_blank" rel="noopener noreferrer" style={{ fontSize: 13, color: 'var(--text-muted)', textDecoration: 'none' }}>
                    {ch.handle}
                  </a>
                  {ch.followers != null && (
                    <Pill>{fmt.k(ch.followers)} seguidores</Pill>
                  )}
                </div>
                <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>{ch.notes}</div>
                <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 6 }}>
                  Conectado em {ch.connectedAt?.split('-').reverse().slice(0,2).join('/')}
                </div>
              </div>
              <Pill tone="neutral" style={{ color: accessMeta.color, borderColor: accessMeta.color + '40' }}>
                {accessMeta.label}
              </Pill>
            </div>
          );
        })}
      </div>
    </CrmSection>
  );
}

/* ============================================================
   SECTION · BIBLE · pontos-chave organizados por categoria
   ============================================================ */
function SectionBible({ client }) {
  const grouped = client.bible.reduce((acc, b) => {
    (acc[b.category] = acc[b.category] || []).push(b);
    return acc;
  }, {});

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <div style={{
        padding: 'var(--space-4)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
        border: '1px solid rgba(154,155,229,0.30)',
        borderRadius: 'var(--r-card-lg)',
      }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>Bíblia do cliente</div>
        <h3 className="t-h2" style={{ margin: '0 0 8px', textWrap: 'pretty' }}>
          <Punch text="Tudo que **o time precisa saber** antes de produzir" />
        </h3>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>
          Pontos-chave organizados por gravidade. <strong style={{ color: 'var(--error)' }}>Crítico</strong> = nunca esquece. <strong style={{ color: 'var(--warning)' }}>Importante</strong> = padrão. <strong style={{ color: 'var(--info)' }}>Bom saber</strong> = contexto.
        </p>
      </div>

      {Object.entries(grouped).map(([cat, items]) => (
        <section key={cat}>
          <h4 className="t-h3" style={{ margin: '0 0 12px', color: 'var(--text)' }}>
            <span className="t-overline" style={{ color: 'var(--accent)' }}>· {cat}</span>
          </h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {items.map(b => {
              const tone = BIBLE_TONE_META[b.tone];
              return (
                <div key={b.id} style={{
                  padding: '12px 16px',
                  background: tone.bg,
                  border: `1px solid ${tone.color}40`,
                  borderLeft: `3px solid ${tone.color}`,
                  borderRadius: 'var(--r-btn)',
                  display: 'grid', gridTemplateColumns: '20px 1fr auto', gap: 12, alignItems: 'flex-start',
                }}>
                  <span style={{ color: tone.color, fontSize: 14, marginTop: 1 }}>{tone.icon}</span>
                  <span style={{ fontSize: 14, color: 'var(--text)', lineHeight: 1.5 }}>{b.text}</span>
                  <Pill tone="neutral" style={{ color: tone.color, borderColor: tone.color + '40', fontSize: 10 }}>
                    {tone.label}
                  </Pill>
                </div>
              );
            })}
          </div>
        </section>
      ))}
    </div>
  );
}

/* ============================================================
   SECTION · DEMANDS (demandas abertas)
   ============================================================ */
function SectionDemands({ client }) {
  return (
    <CrmSection kicker="conversas em aberto" title="**Demandas** ativas com o cliente">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {client.openDemands.map(d => {
          const meta = DEMAND_STATUS_META[d.status];
          return (
            <div key={d.id} style={{
              padding: 16,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 16, alignItems: 'center',
            }}>
              <div>
                <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)', lineHeight: 1.3 }}>{d.title}</div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 4 }}>
                  Adicionada em {d.addedAt?.split('-').reverse().slice(0,2).join('/')}
                </div>
              </div>
              <Pill tone={d.priority === 'alta' ? 'error' : 'warning'}>{d.priority}</Pill>
              <Pill tone="neutral" style={{ color: meta.color, borderColor: meta.color + '40' }}>
                {meta.label}
              </Pill>
            </div>
          );
        })}
      </div>
    </CrmSection>
  );
}

/* ============================================================
   SECTION · TIMELINE (próximas entregas / até onde aprovado)
   ============================================================ */
function SectionTimeline({ client }) {
  return (
    <CrmSection kicker="o que tá rolando" title="**Próximas entregas** e aprovações">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        {client.timeline.map((t, i) => {
          const meta = TIMELINE_TYPE_META[t.type] || TIMELINE_TYPE_META['planned'];
          const isPast = new Date(t.date) < new Date('2026-05-13');
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '120px 24px 1fr auto', gap: 14, alignItems: 'flex-start',
              padding: '14px 0',
              borderTop: i === 0 ? 'none' : '1px solid var(--border)',
            }}>
              <span style={{ fontSize: 12, color: 'var(--text-faint)', fontWeight: 500, whiteSpace: 'nowrap', paddingTop: 4 }}>
                {t.date.split('-').reverse().slice(0,2).join('/')}
              </span>
              <span style={{
                width: 12, height: 12, borderRadius: '50%',
                background: meta.color,
                marginTop: 6, opacity: isPast ? 1 : 0.4,
                boxShadow: `0 0 0 4px ${meta.color}20`,
              }} />
              <div>
                <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)', lineHeight: 1.3 }}>{t.title}</div>
                {t.description && (
                  <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4, lineHeight: 1.5 }}>{t.description}</div>
                )}
              </div>
              <Pill tone="neutral" style={{ color: meta.color, borderColor: meta.color + '40' }}>{meta.label}</Pill>
            </div>
          );
        })}
      </div>
    </CrmSection>
  );
}

/* ============================================================
   SECTION · HISTORY
   ============================================================ */
function SectionHistory({ client }) {
  return (
    <CrmSection kicker="linha do tempo" title="**Histórico** do relacionamento">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0, position: 'relative' }}>
        {client.history.map((h, i) => {
          const meta = HISTORY_TYPE_META[h.type] || HISTORY_TYPE_META['note'];
          return (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '110px 28px 1fr', gap: 14, alignItems: 'flex-start',
              padding: '12px 0',
              borderTop: i === 0 ? 'none' : '1px solid var(--border)',
            }}>
              <span style={{ fontSize: 12, color: 'var(--text-faint)', fontWeight: 500, whiteSpace: 'nowrap', paddingTop: 2 }}>
                {h.date.split('-').reverse().slice(0,2).join('/')}
              </span>
              <span style={{
                width: 20, height: 20, borderRadius: '50%',
                background: meta.color + '20', color: meta.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12, fontWeight: 600, marginTop: 2,
              }}>{meta.icon}</span>
              <div>
                <div style={{ fontSize: 14, color: 'var(--text)', lineHeight: 1.5 }}>{h.text}</div>
                <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>
                  por {capitalize(h.who)}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </CrmSection>
  );
}

/* ============================================================
   SECTION · DRIVE & MATERIAIS
   ============================================================ */
function SectionDrive({ client }) {
  if (!client.drive) {
    return <SectionEmpty label="Drive & materiais" body="Conecte uma pasta do Google Drive para ver os materiais aqui." />;
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <div style={{
        padding: 'var(--space-4)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
        border: '1px solid rgba(154,155,229,0.30)',
        borderRadius: 'var(--r-card-lg)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
      }}>
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>Conexão</div>
          <h3 className="t-h3" style={{ margin: 0 }}>
            <Punch text="Drive da Beza · **pasta deste cliente**" />
          </h3>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 6, fontFamily: 'monospace' }}>
            {client.drive.rootPath}
          </div>
        </div>
        <a href={client.drive.rootUrl} target="_blank" rel="noopener noreferrer" style={btnAccent}>
          Abrir no Drive <Icon.External width={14} height={14} />
        </a>
      </div>

      <CrmSection kicker="pastas" title="**Onde mora** cada coisa">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {client.drive.folders.map(f => (
            <a key={f.id} href={f.url} target="_blank" rel="noopener noreferrer" style={{
              padding: 16,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              textDecoration: 'none', color: 'inherit',
              display: 'flex', flexDirection: 'column', gap: 8,
              transition: 'border-color var(--t-fast), transform var(--t-fast)',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = ''; }}
            >
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 32, height: 32, borderRadius: 'var(--r-btn)',
                    background: 'var(--accent-soft)', color: 'var(--accent)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 14,
                  }}>{f.icon || '◻'}</span>
                  <span style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>{f.name}</span>
                </span>
                <Icon.External width={14} height={14} style={{ color: 'var(--text-faint)' }} />
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>{f.description}</div>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', fontSize: 11, color: 'var(--text-faint)' }}>
                <span>{f.itemCount} arquivos</span>
                <span>·</span>
                <span>atualizado {f.updatedAt}</span>
              </div>
            </a>
          ))}
        </div>
      </CrmSection>

      <CrmSection kicker="últimos uploads" title="**Adicionado** recentemente">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {client.drive.recent.map(r => (
            <a key={r.id} href={r.url} target="_blank" rel="noopener noreferrer" style={{
              display: 'grid', gridTemplateColumns: '32px 1fr auto auto', gap: 14, alignItems: 'center',
              padding: '10px 14px',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-btn)',
              textDecoration: 'none', color: 'inherit',
              transition: 'border-color var(--t-fast)',
            }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}
            >
              <span style={{ fontSize: 16, color: 'var(--text-faint)' }}>{r.icon}</span>
              <span style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{r.name}</span>
              <span style={{ fontSize: 11, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>{r.size}</span>
              <span style={{ fontSize: 11, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>{r.uploadedAt}</span>
            </a>
          ))}
        </div>
      </CrmSection>
    </div>
  );
}

/* ============================================================
   SECTION · IDENTIDADE VISUAL
   ============================================================ */
function SectionIdentity({ client }) {
  if (!client.identity) {
    return <SectionEmpty label="Identidade visual" body="Adicione a paleta, tipografia e arquivos da marca." />;
  }
  const id = client.identity;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <CrmSection kicker="01 · paleta" title="**Cores** da marca">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 12 }}>
          {id.colors.map((c, i) => (
            <div key={i} style={{
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              overflow: 'hidden',
            }}>
              <div style={{ height: 80, background: c.hex }} />
              <div style={{ padding: '10px 12px' }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{c.name}</div>
                <div style={{ fontSize: 12, color: 'var(--text-faint)', fontFamily: 'monospace', marginTop: 2 }}>{c.hex}</div>
                {c.use && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>{c.use}</div>}
              </div>
            </div>
          ))}
        </div>
      </CrmSection>

      <CrmSection kicker="02 · tipografia" title="**Fontes** aprovadas">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {id.fonts.map((f, i) => (
            <div key={i} style={{
              padding: 'var(--space-4)',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
            }}>
              <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>{f.role}</div>
              <div style={{ fontFamily: f.family + ', serif', fontSize: 32, fontWeight: f.weight || 500, lineHeight: 1, color: 'var(--text)' }}>
                {f.sample || 'Aa'}
              </div>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 10 }}>{f.family}</div>
              {f.notes && <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4 }}>{f.notes}</div>}
            </div>
          ))}
        </div>
      </CrmSection>

      <CrmSection kicker="03 · logo + manual" title="**Arquivos** da marca">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
          {id.assets.map((a, i) => (
            <a key={i} href={a.url} target="_blank" rel="noopener noreferrer" style={{
              padding: 'var(--space-4)',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card)',
              textDecoration: 'none', color: 'inherit',
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{
                aspectRatio: '4 / 3',
                background: a.preview || 'linear-gradient(135deg, var(--accent-soft), var(--surface))',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-btn)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--accent)', fontSize: 14, fontWeight: 500,
              }}>
                {a.label || a.format}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'baseline' }}>
                <span style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{a.name}</span>
                <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{a.format}</span>
              </div>
            </a>
          ))}
        </div>
      </CrmSection>
    </div>
  );
}

/* ============================================================
   SECTION · PORTFOLIO entregue
   ============================================================ */
function SectionPortfolio({ client }) {
  if (!client.portfolio) {
    return <SectionEmpty label="Portfólio entregue" body="As peças publicadas aparecem aqui depois que viram 'publicado' na pauta." />;
  }
  const groups = client.portfolio.reduce((acc, p) => {
    (acc[p.month] = acc[p.month] || []).push(p);
    return acc;
  }, {});
  const totalPieces = client.portfolio.length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <div style={{
        padding: 'var(--space-4)',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card-lg)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
      }}>
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>Portfólio do cliente</div>
          <h3 className="t-h3" style={{ margin: 0 }}>
            <span className="num punch">{totalPieces}</span>
            <span className="t-light"> peças entregues nos últimos meses</span>
          </h3>
        </div>
        <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>
          Atualiza automaticamente quando uma tarefa vira "publicado" na Pauta.
        </span>
      </div>

      {Object.entries(groups).map(([month, items]) => (
        <section key={month}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <h4 className="t-h3" style={{ margin: 0 }}>
              <span className="t-overline" style={{ color: 'var(--accent)' }}>· {month}</span>
            </h4>
            <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{items.length} peças</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 }}>
            {items.map(p => <PortfolioCard key={p.id} piece={p} />)}
          </div>
        </section>
      ))}
    </div>
  );
}

function PortfolioCard({ piece }) {
  const typeColors = {
    reel: 'linear-gradient(135deg, #9A9BE5, #7879C9)',
    carrossel: 'linear-gradient(135deg, #C7C6D7, #9A9BE5)',
    banner: 'linear-gradient(135deg, #F3AE4D, #9A9BE5)',
    foto: 'linear-gradient(135deg, #1E1E2E, #7879C9)',
    youtube: 'linear-gradient(135deg, #F34D4D, #9A9BE5)',
  };
  return (
    <a href={piece.url || '#'} target="_blank" rel="noopener noreferrer" style={{
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
      overflow: 'hidden',
      textDecoration: 'none', color: 'inherit',
      display: 'flex', flexDirection: 'column',
      transition: 'transform var(--t-fast), border-color var(--t-fast)',
    }}
    onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.transform = 'translateY(-2px)'; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = ''; }}
    >
      <div style={{
        aspectRatio: piece.type === 'reel' || piece.type === 'youtube' ? '9 / 16' : '1 / 1',
        background: typeColors[piece.type] || typeColors.reel,
        position: 'relative',
        display: 'flex', alignItems: 'flex-end',
        padding: 10,
        color: '#fff',
      }}>
        <span style={{
          position: 'absolute', top: 8, left: 8,
          padding: '2px 8px',
          background: 'rgba(8,8,12,0.6)', backdropFilter: 'blur(4px)',
          borderRadius: 999,
          fontSize: 9, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>{piece.type}</span>
        <span style={{
          fontSize: 11, lineHeight: 1.3, fontWeight: 500,
          textShadow: '0 1px 6px rgba(0,0,0,0.4)',
        }}>
          {piece.caption}
        </span>
      </div>
      <div style={{ padding: '10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{piece.publishedAt}</span>
        {piece.reach != null && (
          <span className="num" style={{ fontSize: 12, fontWeight: 500, color: 'var(--accent)' }}>{fmt.k(piece.reach)}</span>
        )}
      </div>
    </a>
  );
}

function SectionEmpty({ label, body }) {
  return (
    <div style={{
      padding: 'var(--space-6)',
      background: 'var(--surface)',
      border: '1px dashed var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      textAlign: 'center',
    }}>
      <div style={{ color: 'var(--accent)', display: 'inline-flex', marginBottom: 10 }}><Icon.Sparkle width={20} height={20} /></div>
      <h4 style={{ margin: '0 0 6px', fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>{label}</h4>
      <p style={{ margin: 0, fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5, maxWidth: 380 }}>{body}</p>
    </div>
  );
}

const btnAccent = {
  display: 'inline-flex', alignItems: 'center', gap: 8,
  appearance: 'none', border: '1px solid var(--accent)',
  background: 'var(--accent)', color: '#fff',
  padding: '10px 16px', borderRadius: 'var(--r-btn)',
  fontSize: 13, fontFamily: 'inherit', fontWeight: 500,
  cursor: 'pointer', textDecoration: 'none',
};

/* ============================================================
   SHARED · seção com título
   ============================================================ */
function CrmSection({ kicker, title, children }) {
  return (
    <section style={{ marginBottom: 0 }}>
      {(kicker || title) && (
        <div style={{ marginBottom: 16 }}>
          {kicker && <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>{kicker}</div>}
          {title && (
            <h3 className="t-h2" style={{ margin: 0, color: 'var(--text)', textWrap: 'pretty' }}>
              <Punch text={title} />
            </h3>
          )}
        </div>
      )}
      {children}
    </section>
  );
}

function Punch({ text }) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return (
    <>
      {parts.map((p, i) => {
        if (p.startsWith('**') && p.endsWith('**')) return <span key={i} className="punch">{p.slice(2, -2)}</span>;
        return <span key={i} className="t-light">{p}</span>;
      })}
    </>
  );
}

Object.assign(window, {
  CrmApp, CrmListHeader, CrmListToolbar, CrmClientCard, CrmClientView,
  SectionOverview, SectionVoice, SectionChannels, SectionBible,
  SectionDrive, SectionIdentity, SectionPortfolio,
  SectionDemands, SectionTimeline, SectionHistory, SectionReferences,
});

/* ============================================================
   SECTION · REFERENCES · moodboard do que o cliente curtiu
   ============================================================ */
function SectionReferences({ client }) {
  const refs = window.CLIENT_REFERENCES?.[client.slug];
  const meta = window.REFERENCE_CATEGORY_META || {};

  if (!refs || refs.length === 0) {
    return <SectionEmpty label="Referências" body="Adicione moodboards, links e materiais que o cliente passou como inspiração." />;
  }

  const grouped = refs.reduce((acc, r) => {
    (acc[r.category] = acc[r.category] || []).push(r);
    return acc;
  }, {});

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
      <div style={{
        padding: 'var(--space-4)',
        background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
        border: '1px solid rgba(154,155,229,0.30)',
        borderRadius: 'var(--r-card-lg)',
      }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>moodboard do cliente</div>
        <h3 className="t-h2" style={{ margin: '0 0 8px', textWrap: 'pretty' }}>
          <Punch text={`O que **${client.brand}** curte (e o que detesta)`} />
        </h3>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>
          Referências compartilhadas pelo cliente, organizadas por categoria. Inclui até marcas-bandeira-vermelha (o que é pra evitar).
        </p>
      </div>

      {Object.entries(grouped).map(([cat, items]) => {
        const catMeta = meta[cat] || { label: cat, color: 'var(--accent)' };
        return (
          <section key={cat}>
            <div className="t-overline" style={{ color: catMeta.color, marginBottom: 12 }}>
              · {catMeta.label}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {items.map(r => (
                <a key={r.id} href={r.url} target="_blank" rel="noopener noreferrer" style={{
                  padding: 14,
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  borderLeft: `3px solid ${catMeta.color}`,
                  borderRadius: 'var(--r-card)',
                  textDecoration: 'none', color: 'inherit',
                  display: 'flex', flexDirection: 'column', gap: 8,
                  transition: 'border-color var(--t-fast), transform var(--t-fast)',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = catMeta.color; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.transform = ''; }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ fontSize: 11, color: catMeta.color, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                      {r.source}
                    </span>
                    <Icon.External width={12} height={12} style={{ color: 'var(--text-faint)' }} />
                  </div>
                  <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)', lineHeight: 1.3 }}>
                    {r.title}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                    "{r.description}"
                  </div>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 2 }}>
                    {r.tags?.map(t => (
                      <span key={t} style={{
                        fontSize: 10, padding: '2px 7px',
                        background: 'var(--surface-soft)',
                        border: '1px solid var(--border)',
                        borderRadius: 999, color: 'var(--text-faint)',
                      }}>#{t}</span>
                    ))}
                  </div>
                  <div style={{ fontSize: 10, color: 'var(--text-faint)', marginTop: 4, paddingTop: 8, borderTop: '1px solid var(--border)' }}>
                    adicionado por {r.addedBy} · {r.addedAt?.split('-').reverse().slice(0,2).join('/')}
                  </div>
                </a>
              ))}
            </div>
          </section>
        );
      })}

      <button style={{
        appearance: 'none', border: '1px dashed var(--accent)',
        background: 'var(--accent-soft)', color: 'var(--accent)',
        padding: '12px 18px', borderRadius: 'var(--r-card)',
        fontSize: 13, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        width: '100%',
      }}>
        + Adicionar nova referência
      </button>
    </div>
  );
}
