/* global React, Icon, Pill, fmt,
   HOOKS_LIBRARY, CONTENT_INSIGHTS, INSIGHT_TYPE_META, COMPETITOR_INTEL, GARIMPO_BEZA,
   CRM_CLIENTS,
   BlockCard, Punch, BigStat */
const { useState: useStateIntel, useMemo: useMemoIntel } = React;

/* Garimpo report paths por cliente (path relativo ao dash) */
const GARIMPO_REPORT_MAP = {
  'beza-media':          'bezamedia/garimpo/referencias/index.html',
  'samara-soares':       'samarasoares/garimpo/referencias/index.html',
  'brady-bankston':      'bradybankston/garimpo/perfil/index.html',
};

/* Overlay fullscreen que abre o garimpo HTML */
function GarimpoOverlay({ slug, label, onClose }) {
  const url = GARIMPO_REPORT_MAP[slug];
  if (!url) return null;
  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 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
            Garimpo de Referencias
          </span>
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
            {label}
          </span>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <a
            href={url} target="_blank" rel="noopener noreferrer"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              fontSize: 12, fontWeight: 500, color: 'var(--text-muted)',
              textDecoration: 'none', padding: '4px 10px',
              border: '1px solid var(--border)', borderRadius: 'var(--r-pill)',
            }}
          >Abrir em nova aba ↗</a>
          <button onClick={onClose} style={{
            appearance: 'none', border: 'none', background: 'transparent',
            cursor: 'pointer', display: 'flex', alignItems: 'center',
            justifyContent: 'center', width: 32, height: 32,
            borderRadius: 6, color: 'var(--text-muted)',
          }}>
            <svg width="16" height="16" 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>
      </div>
      {/* iframe */}
      <iframe
        src={url}
        style={{ flex: 1, border: 'none', width: '100%' }}
        title={`Garimpo ${label}`}
      />
    </div>
  );
}

/* ============================================================
   INTELIGÊNCIA · módulo público do time
   Hooks que viralizaram + insights cross-cliente
   ============================================================ */
function IntelApp() {
  const [view, setView] = useStateIntel('competitors');
  const [garimpoSlug, setGarimpoSlug] = useStateIntel(null);
  const [garimpoLabel, setGarimpoLabel] = useStateIntel('');

  const openGarimpo = (slug, label) => { setGarimpoSlug(slug); setGarimpoLabel(label); };
  const closeGarimpo = () => setGarimpoSlug(null);

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      {garimpoSlug && <GarimpoOverlay slug={garimpoSlug} label={garimpoLabel} onClose={closeGarimpo} />}
      <IntelHeader />
      <div style={{
        display: 'inline-flex', gap: 4, padding: 4,
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--r-pill)', marginBottom: 'var(--space-5)',
      }}>
        {[
          { id: 'hooks',       label: '⊕ Biblioteca de hooks' },
          { id: 'insights',    label: '✨ Insights cross-cliente' },
          { id: 'competitors', label: '◎ Concorrentes' },
        ].map(v => {
          const active = view === v.id;
          return (
            <button key={v.id} onClick={() => setView(v.id)} style={{
              appearance: 'none', border: 'none',
              background: active ? 'var(--accent)' : 'transparent',
              color: active ? '#fff' : 'var(--text-muted)',
              padding: '8px 16px', fontSize: 13,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit', whiteSpace: 'nowrap',
            }}>{v.label}</button>
          );
        })}
      </div>

      {view === 'hooks' ? <HooksLibrary /> : view === 'insights' ? <InsightsView /> : <CompetitorsView onOpenGarimpo={openGarimpo} />}
    </div>
  );
}

function IntelHeader() {
  return (
    <div style={{
      padding: 'var(--space-6)',
      background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
      border: '1px solid var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      marginBottom: 'var(--space-5)',
      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' }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>
          Módulo · Inteligência editorial
        </div>
        <h2 className="t-h1" style={{ margin: '0 0 8px', textWrap: 'pretty' }}>
          <span className="t-light">O que **funcionou** vira </span>
          <span className="punch">conhecimento da casa</span>
          <span className="t-light">.</span>
        </h2>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', maxWidth: 640, lineHeight: 1.6 }}>
          Hooks que viralizaram, padrões detectados e oportunidades cross-cliente. Atualiza automaticamente conforme o time fecha relatórios.
        </p>
      </div>
    </div>
  );
}

/* ============================================================
   HOOKS LIBRARY · biblioteca filtrável
   ============================================================ */
function HooksLibrary() {
  const [filterType, setFilterType]       = useStateIntel('todos');
  const [filterSegment, setFilterSegment] = useStateIntel('todos');
  const [filterFormat, setFilterFormat]   = useStateIntel('todos');
  const [sortBy, setSortBy] = useStateIntel('reach');

  const types     = ['todos', ...Array.from(new Set(HOOKS_LIBRARY.map(h => h.type)))];
  const segments  = ['todos', ...Array.from(new Set(HOOKS_LIBRARY.map(h => h.segment)))];
  const formats   = ['todos', ...Array.from(new Set(HOOKS_LIBRARY.map(h => h.format)))];

  const filtered = useMemoIntel(() => {
    let list = HOOKS_LIBRARY.filter(h =>
      (filterType    === 'todos' || h.type    === filterType) &&
      (filterSegment === 'todos' || h.segment === filterSegment) &&
      (filterFormat  === 'todos' || h.format  === filterFormat)
    );
    list.sort((a, b) => {
      if (sortBy === 'reach')      return b.reach - a.reach;
      if (sortBy === 'saves')      return b.saves - a.saves;
      if (sortBy === 'engagement') return b.engagement - a.engagement;
      return new Date(b.publishedAt) - new Date(a.publishedAt);
    });
    return list;
  }, [filterType, filterSegment, filterFormat, sortBy]);

  return (
    <div>
      <BlockCard kicker="ganchos premiados" title="**Hooks** que funcionaram">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12, marginBottom: 18 }}>
          <BigStat label="Hooks salvos"     value={HOOKS_LIBRARY.length} />
          <BigStat label="Alcance somado"   value={fmt.k(HOOKS_LIBRARY.reduce((a,h) => a + h.reach, 0))} accent />
          <BigStat label="Saves somados"    value={fmt.k(HOOKS_LIBRARY.reduce((a,h) => a + h.saves, 0))} />
          <BigStat label="Eng. médio"       value={fmt.dec(HOOKS_LIBRARY.reduce((a,h) => a + h.engagement, 0) / HOOKS_LIBRARY.length, 1) + '%'} />
        </div>

        {/* Filtros */}
        <div style={{ display: 'flex', gap: 16, marginBottom: 18, flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <FilterSelect label="Tipo"      value={filterType}    onChange={setFilterType}    options={types} />
          <FilterSelect label="Segmento"  value={filterSegment} onChange={setFilterSegment} options={segments} />
          <FilterSelect label="Formato"   value={filterFormat}  onChange={setFilterFormat}  options={formats} />
          <FilterSelect label="Ordenar por" value={sortBy}      onChange={setSortBy}        options={['reach', 'saves', 'engagement', 'recent']}
            labels={{ reach: 'Alcance', saves: 'Saves', engagement: 'Engajamento', recent: 'Mais recente' }} />
          <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--text-faint)' }}>
            {filtered.length} hook{filtered.length === 1 ? '' : 's'}
          </span>
        </div>

        {/* Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 14 }}>
          {filtered.map(h => <HookCard key={h.id} hook={h} />)}
        </div>
      </BlockCard>
    </div>
  );
}

function FilterSelect({ label, value, onChange, options, labels }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ fontSize: 10, color: 'var(--text-faint)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</span>
      <select value={value} onChange={(e) => onChange(e.target.value)} style={{
        appearance: 'none', border: '1px solid var(--border-strong)',
        background: 'var(--surface)', color: 'var(--text)',
        padding: '6px 12px', borderRadius: 'var(--r-btn)',
        fontFamily: 'inherit', fontSize: 13, outline: 'none',
        minWidth: 140,
      }}>
        {options.map(o => <option key={o} value={o}>{labels?.[o] || o}</option>)}
      </select>
    </label>
  );
}

function HookCard({ hook }) {
  const [copied, setCopied] = useStateIntel(false);
  const copyHook = () => {
    navigator.clipboard?.writeText(hook.text);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <div style={{
      padding: 18,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
      display: 'flex', flexDirection: 'column', gap: 12,
      position: 'relative',
      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', gap: 8, flexWrap: 'wrap' }}>
        <Pill tone="purple">{hook.type}</Pill>
        <Pill>{hook.format}</Pill>
      </div>

      <blockquote style={{
        margin: 0, padding: '14px 16px',
        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-btn)',
        fontSize: 15, fontWeight: 500, fontStyle: 'italic',
        color: 'var(--text)', lineHeight: 1.4,
      }}>
        "{hook.text}"
      </blockquote>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, fontSize: 11 }}>
        <Mini2 label="Alcance"     value={fmt.k(hook.reach)} accent />
        <Mini2 label="Saves"       value={fmt.k(hook.saves)} />
        <Mini2 label="Engaj."      value={fmt.dec(hook.engagement, 1) + '%'} />
      </div>

      <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.5, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
        <strong style={{ color: 'var(--text)' }}>{hook.client}</strong> · {hook.publishedAt?.split('-').reverse().slice(0,2).join('/')}
        {hook.notes && <div style={{ marginTop: 6, fontStyle: 'italic', color: 'var(--text-faint)' }}>{hook.notes}</div>}
      </div>

      {hook.tags && (
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {hook.tags.map(t => (
            <span key={t} style={{
              fontSize: 10, padding: '2px 8px',
              background: 'var(--surface-soft)',
              border: '1px solid var(--border)',
              borderRadius: 999,
              color: 'var(--text-faint)',
            }}>#{t}</span>
          ))}
        </div>
      )}

      <button onClick={copyHook} style={{
        appearance: 'none', border: '1px solid',
        borderColor: copied ? 'var(--success)' : 'var(--border-strong)',
        background: copied ? 'rgba(111,200,120,0.10)' : 'transparent',
        color: copied ? 'var(--success)' : 'var(--text-muted)',
        padding: '8px 14px', borderRadius: 'var(--r-btn)',
        fontSize: 12, fontFamily: 'inherit', cursor: 'pointer',
        fontWeight: 500,
      }}>
        {copied ? '✓ copiado' : '⎘ copiar hook'}
      </button>
    </div>
  );
}

function Mini2({ label, value, accent }) {
  return (
    <div>
      <div style={{ fontSize: 9, color: 'var(--text-faint)', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 2 }}>{label}</div>
      <div className="num" style={{ fontSize: 14, fontWeight: 500, color: accent ? 'var(--accent)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

/* ============================================================
   INSIGHTS VIEW · padrões cross-cliente
   ============================================================ */
function InsightsView() {
  const [filter, setFilter] = useStateIntel('todos');
  const types = ['todos', 'tendencia', 'descoberta', 'oportunidade'];
  const filtered = filter === 'todos' ? CONTENT_INSIGHTS : CONTENT_INSIGHTS.filter(i => i.type === filter);

  return (
    <BlockCard kicker="padrões detectados" title="O que **está funcionando** na carteira inteira">
      <p style={{ margin: '0 0 18px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
        O Claude analisa todos os relatórios da Beza e detecta padrões que rendem. Cada insight tem confiança estatística, amostra, clientes aos quais se aplica e ação concreta sugerida.
      </p>

      <div style={{ display: 'flex', gap: 6, marginBottom: 18, flexWrap: 'wrap' }}>
        {types.map(t => {
          const active = filter === t;
          const meta = t === 'todos' ? { color: 'var(--accent)' } : INSIGHT_TYPE_META[t];
          return (
            <button key={t} onClick={() => setFilter(t)} style={{
              appearance: 'none', border: '1px solid',
              borderColor: active ? meta.color : 'var(--border)',
              background: active ? meta.color + '15' : 'transparent',
              color: active ? meta.color : 'var(--text-muted)',
              padding: '6px 12px', fontSize: 12,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit', textTransform: 'capitalize',
            }}>
              {t === 'todos' ? 'Todos' : meta.label}
            </button>
          );
        })}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {filtered.map(i => {
          const typeMeta = INSIGHT_TYPE_META[i.type];
          return (
            <div key={i.id} style={{
              padding: 'var(--space-5)',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderLeft: `3px solid ${typeMeta.color}`,
              borderRadius: 'var(--r-card)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 10, flexWrap: 'wrap' }}>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <Pill tone="neutral" style={{ color: typeMeta.color, borderColor: typeMeta.color + '40' }}>
                    {typeMeta.icon} {typeMeta.label}
                  </Pill>
                  <Pill tone={i.confidence === 'alta' ? 'success' : 'warning'}>
                    confiança {i.confidence}
                  </Pill>
                  <Pill>amostra · {i.sample}</Pill>
                </div>
              </div>

              <h4 style={{ margin: '0 0 8px', fontSize: 17, fontWeight: 500, color: 'var(--text)', lineHeight: 1.4 }}>
                {i.title}
              </h4>
              <p style={{ margin: '0 0 14px', fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6 }}>
                {i.description}
              </p>

              <div style={{
                padding: 'var(--space-3)',
                background: 'rgba(154,155,229,0.06)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-btn)',
                marginBottom: 12,
              }}>
                <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 6 }}>
                  ✨ Ação sugerida
                </div>
                <div style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.5 }}>{i.action}</div>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap', fontSize: 11, color: 'var(--text-faint)' }}>
                <span>
                  Aplica a: {i.appliesTo.includes('todos') ? <strong style={{ color: 'var(--text)' }}>todos os clientes</strong> : i.appliesTo.map((c, idx) => (
                    <span key={c}>
                      {idx > 0 && ', '}
                      <strong style={{ color: 'var(--text)' }}>{c}</strong>
                    </span>
                  ))}
                </span>
                <button style={{
                  appearance: 'none', border: '1px solid var(--accent)',
                  background: 'var(--accent-soft)', color: 'var(--accent)',
                  padding: '6px 12px', borderRadius: 'var(--r-btn)',
                  fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
                }}>
                  Aplicar na próxima pauta →
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </BlockCard>
  );
}

/* ============================================================
   COMPETITORS VIEW · garimpos + inteligência por nicho
   ============================================================ */
function CompetitorsView({ onOpenGarimpo }) {
  const [selected, setSelected] = useStateIntel(null);

  const allClients = (typeof CRM_CLIENTS !== 'undefined' ? CRM_CLIENTS : [])
    .filter(c => !c.slug.includes('REMOVIDO'));

  const active = selected ? COMPETITOR_INTEL.find(c => c.clientSlug === selected) : null;

  return (
    <div>
      <BlockCard kicker="garimpos e inteligência" title="Todos os **clientes** da carteira">
        <p style={{ margin: '0 0 20px', fontSize: 14, color: 'var(--text-muted)', maxWidth: 720, lineHeight: 1.6 }}>
          Clique em "Ver Garimpo" para abrir o relatório completo de referências. Onde o garimpo ainda não foi feito, aparecerá em breve.
        </p>

        {/* Grid — todos os clientes CRM */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 12, marginBottom: selected ? 28 : 0 }}>
          {allClients.map(c => {
            const hasGarimpo = !!GARIMPO_REPORT_MAP[c.slug];
            const compData   = COMPETITOR_INTEL.find(ci => ci.clientSlug === c.slug);
            const isActive   = selected === c.slug;
            const accent     = compData ? compData.accent : '#9A9BE5';
            return (
              <div key={c.slug} style={{
                padding: '16px',
                background: isActive ? (accent + '12') : 'var(--surface)',
                border: `1px solid ${isActive ? accent : 'var(--border)'}`,
                borderRadius: 'var(--r-card)',
                display: 'flex', flexDirection: 'column', gap: 10,
                transition: 'border-color 0.15s',
              }}>
                {/* Avatar + nome */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: '50%',
                    background: accent, color: '#fff', flexShrink: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 13, fontWeight: 700,
                  }}>{(c.brand || c.slug)[0].toUpperCase()}</div>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', lineHeight: 1.2 }}>{c.brand || c.slug}</div>
                    {c.segment && <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>{c.segment}</div>}
                  </div>
                </div>

                {/* Botão garimpo */}
                {hasGarimpo ? (
                  <button
                    onClick={() => onOpenGarimpo && onOpenGarimpo(c.slug, c.brand || c.slug)}
                    style={{
                      appearance: 'none', border: `1px solid ${accent}45`,
                      background: accent + '14',
                      color: accent, borderRadius: 'var(--r-btn)',
                      padding: '8px 12px', fontSize: 12, fontWeight: 600,
                      cursor: 'pointer', fontFamily: 'inherit',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                      width: '100%',
                      transition: 'background 0.15s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = accent + '28'}
                    onMouseLeave={e => e.currentTarget.style.background = accent + '14'}
                  >
                    <svg width="12" height="12" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5">
                      <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
                    </svg>
                    Ver Garimpo
                  </button>
                ) : (
                  <div style={{
                    fontSize: 11, color: 'var(--text-faint)', textAlign: 'center',
                    padding: '6px 0', borderTop: '1px solid var(--border)',
                  }}>
                    Garimpo em breve
                  </div>
                )}

                {/* Botão intel competitiva (só se tiver dados) */}
                {compData && (
                  <button
                    onClick={() => setSelected(isActive ? null : c.slug)}
                    style={{
                      appearance: 'none', border: '1px solid var(--border)',
                      background: isActive ? 'var(--surface-soft)' : 'transparent',
                      color: 'var(--text-muted)', borderRadius: 'var(--r-btn)',
                      padding: '6px 12px', fontSize: 11, fontWeight: 500,
                      cursor: 'pointer', fontFamily: 'inherit',
                      width: '100%', textAlign: 'center',
                    }}
                  >
                    {isActive ? 'Fechar intel ↑' : 'Intel competitiva →'}
                  </button>
                )}
              </div>
            );
          })}
        </div>

        {/* Detalhe do nicho selecionado */}
        {active && (
          <div style={{
            padding: 'var(--space-5)',
            background: 'var(--surface)',
            border: `1px solid ${active.accent}40`,
            borderLeft: `3px solid ${active.accent}`,
            borderRadius: 'var(--r-card)',
            marginTop: 4,
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20, flexWrap: 'wrap', gap: 10 }}>
              <div>
                <div className="t-overline" style={{ color: active.accent, marginBottom: 6 }}>{active.niche}</div>
                <h3 style={{ margin: 0, fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>{active.clientLabel}</h3>
              </div>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Engaj. médio</div>
                  <div className="num" style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', marginTop: 2 }}>{active.avgEngagement}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 10, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Frequência ideal</div>
                  <div className="num" style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', marginTop: 2 }}>{active.bestPostingFreq}</div>
                </div>
              </div>
            </div>

            {/* Botao garimpo completo */}
            {GARIMPO_REPORT_MAP[active.clientSlug] && (
              <button
                onClick={() => onOpenGarimpo && onOpenGarimpo(active.clientSlug, active.clientLabel)}
                style={{
                  appearance: 'none', border: `1px solid ${active.accent}40`,
                  background: active.accent + '10',
                  color: active.accent, borderRadius: 'var(--r-btn)',
                  padding: '8px 16px', fontSize: 13, fontWeight: 600,
                  cursor: 'pointer', fontFamily: 'inherit',
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  marginBottom: 20,
                  transition: 'background 0.15s',
                }}
                onMouseEnter={e => e.currentTarget.style.background = active.accent + '20'}
                onMouseLeave={e => e.currentTarget.style.background = active.accent + '10'}
              >
                <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
                  <circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/>
                </svg>
                Abrir garimpo completo
              </button>
            )}

            {/* Concorrentes */}
            <div style={{ marginBottom: 20 }}>
              <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 10 }}>Perfis de referência</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {active.competitors.map((comp, idx) => (
                  <div key={idx} style={{
                    padding: '10px 14px',
                    background: 'var(--bg-flat)',
                    border: '1px solid var(--border)',
                    borderRadius: 'var(--r-btn)',
                    display: 'grid', gridTemplateColumns: 'auto 80px 1fr', gap: 12, alignItems: 'start',
                  }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: active.accent, minWidth: 140 }}>{comp.handle}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-faint)', paddingTop: 1 }}>{comp.followers}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>{comp.notes}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* O que está funcionando */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
              <div>
                <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 10 }}>O que está funcionando</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {active.contentWins.map((w, idx) => (
                    <div key={idx} style={{ display: 'flex', gap: 8, fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                      <span style={{ color: active.accent, flexShrink: 0, marginTop: 1 }}>✓</span>
                      <span>{w}</span>
                    </div>
                  ))}
                </div>
              </div>
              <div>
                <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 10 }}>Melhores formatos</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {active.topFormats.map(f => (
                    <span key={f} style={{
                      fontSize: 12, padding: '4px 10px',
                      background: active.accent + '14',
                      border: `1px solid ${active.accent}30`,
                      borderRadius: 999, color: active.accent, fontWeight: 500,
                    }}>{f}</span>
                  ))}
                </div>
              </div>
            </div>

            {/* Insight */}
            <div style={{
              padding: 'var(--space-3)',
              background: active.accent + '08',
              border: `1px solid ${active.accent}20`,
              borderRadius: 'var(--r-btn)',
              fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6,
              marginBottom: 20,
            }}>
              <strong style={{ color: 'var(--text)' }}>Insight-chave:</strong> {active.insights}
            </div>

            {/* Top Posts por Perfil · usa GARIMPO_BEZA quando disponível */}
            {(() => {
              const garimpoProfiles = (typeof GARIMPO_BEZA !== 'undefined' ? GARIMPO_BEZA.profiles : []) || [];
              // filtra perfis que têm dados no garimpo e que aparecem nos concorrentes deste nicho
              const competitorHandles = active.competitors.map(c => c.handle.toLowerCase());
              const withPosts = garimpoProfiles.filter(p =>
                competitorHandles.includes(p.handle.toLowerCase()) &&
                p.topPosts && p.topPosts.length > 0
              );
              if (!withPosts.length) return null;

              return (
                <div>
                  <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 14 }}>
                    Top posts por perfil
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    {withPosts.map(profile => (
                      <div key={profile.handle}>
                        <div style={{ fontSize: 12, fontWeight: 600, color: active.accent, marginBottom: 8, letterSpacing: '0.02em' }}>
                          {profile.handle}
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                          {profile.topPosts.map((post, pi) => {
                            const shortcode = post.url ? post.url.replace(/\/$/, '').split('/').pop() : null;
                            const typeColors = {
                              foto:       { bg: 'rgba(154,155,229,0.12)', color: '#9A9BE5' },
                              carrossel:  { bg: 'rgba(201,168,76,0.12)',  color: '#C9A84C' },
                              reel:       { bg: 'rgba(107,92,231,0.15)',  color: '#a89df5' },
                            };
                            const tc = typeColors[post.type] || typeColors.foto;
                            return (
                              <div key={pi} style={{
                                display: 'grid',
                                gridTemplateColumns: '40px 40px 1fr auto',
                                gap: 10,
                                alignItems: 'center',
                                padding: '8px 12px',
                                background: 'var(--bg-flat)',
                                border: '1px solid var(--border)',
                                borderRadius: 'var(--r-btn)',
                              }}>
                                {/* rank */}
                                <div style={{
                                  width: 28, height: 28, borderRadius: 6,
                                  background: pi < 3 ? (active.accent + '20') : 'var(--surface-soft)',
                                  color: pi < 3 ? active.accent : 'var(--text-faint)',
                                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                                  fontWeight: 700, fontSize: 13, flexShrink: 0,
                                }}>
                                  {post.rank || pi + 1}
                                </div>
                                {/* thumb placeholder */}
                                <div style={{
                                  width: 36, height: 44, borderRadius: 6, flexShrink: 0,
                                  background: `linear-gradient(135deg, ${active.accent}30, ${active.accent}10)`,
                                  border: `1px solid ${active.accent}20`,
                                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                                  color: active.accent, opacity: 0.7,
                                }}>
                                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                    <rect x="3" y="3" width="18" height="18" rx="2"/>
                                    <circle cx="8.5" cy="8.5" r="1.5"/>
                                    <polyline points="21 15 16 10 5 21"/>
                                  </svg>
                                </div>
                                {/* caption + meta */}
                                <div style={{ minWidth: 0 }}>
                                  <div style={{
                                    fontSize: 12.5, color: 'var(--text)', lineHeight: 1.4,
                                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                                    marginBottom: 3,
                                  }}>
                                    {post.caption}
                                  </div>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <span style={{
                                      fontSize: 10, fontWeight: 600, padding: '1px 7px',
                                      borderRadius: 99, background: tc.bg, color: tc.color,
                                    }}>{post.type}</span>
                                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 11, color: 'var(--text-faint)' }}>
                                      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
                                      {fmt.k ? fmt.k(post.likes) : post.likes.toLocaleString('pt-BR')}
                                    </span>
                                  </div>
                                </div>
                                {/* instagram link */}
                                {post.url && (
                                  <a
                                    href={post.url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    style={{
                                      display: 'inline-flex', alignItems: 'center', gap: 4,
                                      padding: '5px 10px',
                                      borderRadius: 'var(--r-btn)',
                                      border: `1px solid ${active.accent}30`,
                                      background: active.accent + '0e',
                                      color: active.accent,
                                      fontSize: 11, fontWeight: 600,
                                      textDecoration: 'none', whiteSpace: 'nowrap',
                                      flexShrink: 0,
                                    }}
                                    onMouseEnter={(e) => { e.currentTarget.style.background = active.accent + '20'; }}
                                    onMouseLeave={(e) => { e.currentTarget.style.background = active.accent + '0e'; }}
                                  >
                                    Ver ↗
                                  </a>
                                )}
                              </div>
                            );
                          })}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })()}
          </div>
        )}
      </BlockCard>
    </div>
  );
}

Object.assign(window, { IntelApp, IntelHeader, HooksLibrary, InsightsView, HookCard, CompetitorsView, GarimpoOverlay });
