// Telas do Proof Manager — editorial, escuro, verde #3ECF8E, alinhamento rígido.

/* ───────── átomos ───────── */

// Iniciais do cliente para o monograma (fallback dos thumbnails pequenos).
function initials(name) {
  const clean = (name || '').replace(/\([^)]*\)/g, ' ').replace(/[^\p{L}\s]/gu, ' ').trim();
  const w = clean.split(/\s+/).filter(Boolean);
  if (!w.length) return '—';
  if (w.length === 1) return w[0].slice(0, 2).toUpperCase();
  return (w[0][0] + w[1][0]).toUpperCase();
}

// Sem arquivo de mídia (depoimento de texto/doc). Em thumbnail pequeno mostra um
// MONOGRAMA com as iniciais do cliente (limpo, identifica quem é). Em tile grande,
// mostra as aspas verdes + a citação. Nunca um ícone de "imagem quebrada".
function QuoteTile({ quote = '', name = '', compact = false, className = '' }) {
  const bg = { backgroundImage: 'radial-gradient(120% 120% at 50% 0%, rgba(62,207,142,0.07), transparent 60%)' };
  if (!quote) {
    return (
      <div className={'relative flex items-center justify-center bg-bg-elev ' + className} style={bg}>
        <span className="num font-semibold text-acc-green/80 tracking-wide" style={{ fontSize: compact ? '14px' : '20px' }}>{initials(name)}</span>
      </div>
    );
  }
  return (
    <div className={'relative flex flex-col items-center justify-center gap-2.5 text-center bg-bg-elev px-4 ' + className} style={bg}>
      <Quote size={compact ? 16 : 24} className="text-acc-green opacity-60 shrink-0" />
      <p className="text-[12.5px] text-ink-sub leading-snug line-clamp-4 max-w-[34ch]">“{quote}”</p>
    </div>
  );
}

function Media({ media, className = '', compact = false, quote = '', name = '' }) {
  const k = media && media.kind ? media.kind : 'imagem';
  const files = media && media.files ? media.files : [];
  const stop = e => e.stopPropagation();
  if (k === 'imagem' || k === 'print') {
    if (files[0]) return (
      <div className={'relative overflow-hidden bg-black ' + className}>
        <img src={files[0]} alt="" loading="lazy" className={'w-full h-full ' + (compact ? 'object-cover' : 'object-contain')} />
        {files.length > 1 && <span className="absolute bottom-2 right-2 text-[10px] font-medium px-1.5 py-0.5 rounded-md bg-black/70 text-white">+{files.length - 1}</span>}
      </div>
    );
    return <QuoteTile quote={quote} name={name} compact={compact} className={className} />;
  }
  if (k === 'video') {
    if (!compact && files[0]) return <div className={'relative overflow-hidden bg-black ' + className} onClick={stop}><video src={files[0]} poster={media.poster || undefined} controls preload="metadata" playsInline className="w-full h-full object-contain bg-black" /></div>;
    if (media && media.poster) return (
      <div className={'relative overflow-hidden bg-black ' + className}>
        <img src={media.poster} alt="" loading="lazy" className="w-full h-full object-cover opacity-80" />
        <div className="absolute inset-0 flex items-center justify-center"><span className={'rounded-full bg-white/90 text-bg flex items-center justify-center ' + (compact ? 'w-8 h-8' : 'w-12 h-12')}><Play size={compact ? 13 : 18} className="ml-0.5" strokeWidth={2.5} /></span></div>
      </div>
    );
    return <QuoteTile quote={quote} name={name} compact={compact} className={className} />;
  }
  if (k === 'audio') {
    if (!compact && files[0]) return <div className={'flex items-center px-4 bg-bg-elev ' + className} onClick={stop}><audio src={files[0]} controls preload="metadata" className="w-full" /></div>;
    return <div className={'flex items-center justify-center gap-2 bg-bg-elev text-ink-sub ' + className}><Headphones size={compact ? 15 : 20} /><span className="text-[11px] uppercase tracking-[0.14em]">Áudio</span></div>;
  }
  return <QuoteTile quote={quote} name={name} compact={compact} className={className} />;
}

// Dropdown customizado na identidade do app (substitui o <select> nativo do SO).
function FilterSelect({ value, onChange, placeholder, options }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const h = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    document.addEventListener('keydown', k => { if (k.key === 'Escape') setOpen(false); });
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  const cur = options.find(o => o.value === value);
  const Row = ({ active, label, count, onClick }) => (
    <button type="button" onClick={onClick}
      className={'w-full text-left px-3 py-2 rounded-lg text-[12.5px] flex items-center justify-between gap-3 transition ' + (active ? 'text-ink bg-white/[0.05]' : 'text-ink-sub hover:bg-white/[0.05] hover:text-ink')}>
      <span className="truncate">{label}</span>
      <span className="flex items-center gap-2 shrink-0">
        {typeof count === 'number' && <span className="text-[11px] text-ink-mute num">{count}</span>}
        {active && <CheckIcon size={13} className="text-acc-green" strokeWidth={3} />}
      </span>
    </button>
  );
  return (
    <div className="relative w-full sm:w-[210px]" ref={ref}>
      <button type="button" onClick={() => setOpen(o => !o)}
        className={'field rounded-lg text-[12.5px] h-9 px-3 w-full flex items-center justify-between gap-2 ' + (value ? 'text-ink' : 'text-ink-mute') + (open ? ' border-white/25' : '')}>
        <span className="truncate">{cur ? cur.label : placeholder}</span>
        <ChevronDown size={14} className={'shrink-0 text-ink-mute transition-transform duration-150 ' + (open ? 'rotate-180' : '')} />
      </button>
      {open && (
        <div className="absolute left-0 z-40 mt-1.5 w-[max(100%,250px)] max-h-[330px] overflow-y-auto rounded-xl border border-white/12 bg-bg-elev p-1.5 shadow-2xl"
          style={{ boxShadow: '0 16px 40px -8px rgba(0,0,0,0.6)' }}>
          <Row active={!value} label={placeholder} onClick={() => { onChange(''); setOpen(false); }} />
          <div className="my-1 h-px bg-white/[0.06]"></div>
          {options.map(o => <Row key={o.value} active={value === o.value} label={o.label} count={o.count} onClick={() => { onChange(o.value); setOpen(false); }} />)}
        </div>
      )}
    </div>
  );
}

function Eyebrow({ children, right }) {
  return (
    <div className="flex items-center justify-between gap-4 mb-5">
      <div className="flex items-start gap-2.5 min-w-0">
        <span className="diamond" style={{ width: 7, height: 7, marginTop: 2 }}></span>
        <span className="eyebrow" style={{ lineHeight: 1.5 }}>{children}</span>
      </div>
      {right}
    </div>
  );
}

function Money({ t, size = '15px', color = '#3ECF8E', w = '5.4em' }) {
  if (!t || !t.valorCurto) return null;
  // Coluna rígida (R$ alinhado) só nas listas, quando w é fixo. Valor solto = inline normal.
  if (t.valorRS && w !== 'auto') return <span className="mny" style={{ fontSize: size, color, width: w }}><span>R$</span><span className="v">{t.valorMag}</span></span>;
  return <span className="num" style={{ fontSize: size, color, fontWeight: 700, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>{t.valorCurto}</span>;
}

function TipoBadge({ t }) {
  return <span className="text-[10.5px] font-semibold uppercase tracking-[0.1em] px-2 py-1 rounded-md" style={{ color: t.tipoColor, background: hexA(t.tipoColor, 0.13) }}>{t.tipoLabel}</span>;
}
function ClassBadges({ t }) {
  return (t.classes || []).map((c, i) => (
    <span key={i} className="text-[10px] font-semibold uppercase tracking-[0.08em] px-2 py-1 rounded-md" style={{ color: '#3ECF8E', background: hexA('#3ECF8E', 0.12) }}>{c}</span>
  ));
}
function ForteTag() {
  return <span className="inline-flex items-center gap-1.5 text-[10.5px] font-semibold uppercase tracking-[0.1em] text-acc-green"><span className="w-1.5 h-1.5 rounded-full bg-acc-green"></span>Forte</span>;
}
function PageWrap({ children, max = '1040px' }) {
  return <div className="px-5 sm:px-8 py-10 lg:py-12 mx-auto" style={{ maxWidth: max }}>{children}</div>;
}

/* ───────── Painel ───────── */

function Painel({ navigate }) {
  const featured = rankFinanceiro()[0];
  const mag = (DASH.somaLabel || '').replace(/^R\$\s*/, '');
  const parts = mag.split(' ');

  return (
    <PageWrap>
      <Eyebrow>Prova social</Eyebrow>

      <div className="flex items-end gap-5 flex-wrap mt-1">
        <div className="bignum num" style={{ fontSize: 'clamp(3rem, 9vw, 5.25rem)' }}>
          <span style={{ fontWeight: 600 }}>R$ </span>{parts[0]}<span style={{ fontSize: '0.46em', fontWeight: 600 }}> {parts[1] || ''}</span>
        </div>
        <p className="text-[13.5px] text-ink-sub leading-relaxed pb-2 max-w-[240px]">em resultados financeiros somados, de <span className="text-ink">{DASH.total} clientes</span> catalogados.</p>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-8">
        {[
          { n: DASH.total, l: 'depoimentos', g: false },
          { n: DASH.ticketLabel, l: 'ticket médio', g: false },
          { n: DASH.nichoTop, l: 'nicho mais comum', g: false },
          { n: DASH.fortesPct, l: 'provas fortes', g: true },
        ].map((c, i) => (
          <div key={i} className="rounded-xl border border-white/[0.07] px-4 py-4">
            <div className={'text-[17px] sm:text-[19px] font-semibold num leading-tight ' + (c.g ? 'text-red' : 'text-ink')}>{c.n}</div>
            <div className="text-[11.5px] text-ink-mute mt-2 leading-snug">{c.l}</div>
          </div>
        ))}
      </div>

      {featured && (
        <>
          <Eyebrow>Prova em destaque</Eyebrow>
          <button onClick={() => navigate('detalhe', featured.id)} className="w-full text-left card card-hover p-4 flex items-center gap-4">
            <div className="w-20 h-16 rounded-lg overflow-hidden shrink-0"><Media media={featured.midiaWeb} name={featured.nome} compact className="w-full h-full" /></div>
            <div className="min-w-0 flex-1">
              <div className="text-[16px] font-semibold text-ink leading-snug line-clamp-2">{featured.headline}</div>
              <div className="text-[12px] text-ink-mute mt-1.5 truncate">{featured.nome}{featured.mercado ? ' · ' + featured.mercado : ''} · {featured.midiaLabel.toLowerCase()}</div>
            </div>
            <div className="shrink-0"><Money t={featured} size="18px" w="auto" /></div>
          </button>
        </>
      )}

      <div className="mt-12"><Eyebrow right={<button onClick={() => navigate('banco')} className="text-[12px] text-ink-sub hover:text-ink flex items-center gap-1.5">Ver banco <ArrowRight size={13} /></button>}>Adicionados recentemente</Eyebrow></div>
      <div>
        {RECENTES.slice(0, 5).map((t, i) => (
          <button key={t.id} onClick={() => navigate('detalhe', t.id)} className={'w-full text-left grid items-center gap-4 py-3.5 ' + (i ? 'border-t border-white/[0.06]' : '')} style={{ gridTemplateColumns: '44px 1fr 5em' }}>
            <div className="w-11 h-11 rounded-lg overflow-hidden"><Media media={t.midiaWeb} name={t.nome} compact className="w-full h-full" /></div>
            <div className="min-w-0">
              <div className="text-[13.5px] font-medium text-ink leading-snug line-clamp-1">{t.headline}</div>
              <div className="text-[11.5px] text-ink-mute mt-1 truncate">{t.nome}{t.mercado ? ' · ' + t.mercado : ''}</div>
            </div>
            <div className="justify-self-end"><Money t={t} size="14px" w="5em" color={t.valorRS ? '#3ECF8E' : '#9AA29D'} /></div>
          </button>
        ))}
      </div>

      <div className="mt-12"><Eyebrow right={<span className="text-[11px] text-ink-mute num">{DASH.total} casos</span>}>Classes de resultado</Eyebrow></div>
      <div className="card p-6 space-y-4">
        {CLASSES_DIST.map(ph => {
          const pct = DASH.total ? (ph.count / DASH.total * 100) : 0;
          return (
            <div key={ph.name} className="grid items-center gap-3 sm:gap-5" style={{ gridTemplateColumns: '140px 1fr 32px' }}>
              <div className="flex items-center gap-2 min-w-0"><span className="w-2 h-2 rounded-full shrink-0 bg-red"></span><span className="text-[12px] font-medium text-ink truncate">{ph.name}</span></div>
              <div className="h-1.5 bg-white/[0.06] rounded-full overflow-hidden"><div className="h-full rounded-full grow bg-red" style={{ '--w': pct + '%' }}></div></div>
              <div className="text-right num font-semibold text-ink text-[13px]">{ph.count}</div>
            </div>
          );
        })}
      </div>
    </PageWrap>
  );
}

/* ───────── Banco (mosaico — preservado) ───────── */

function ProvaCard({ t, onOpen }) {
  return (
    <button onClick={onOpen} className="card lift text-left flex flex-col overflow-hidden">
      <div className="h-40 shrink-0 border-b border-white/[0.05]"><Media media={t.midiaWeb} compact quote={t.citacao || t.headline} className="w-full h-full" /></div>
      <div className="p-5 flex flex-col flex-1">
        <div className="text-[15.5px] font-bold text-ink leading-snug line-clamp-2" style={{ minHeight: '2.6em' }}>{t.headline}</div>
        <div className="flex items-center gap-1.5 flex-wrap mt-3" style={{ minHeight: 24 }}><ClassBadges t={t} />{t.forte && <ForteTag />}</div>
        <div className="mt-auto pt-4 flex items-end justify-between gap-3 border-t border-white/[0.05]">
          <div className="min-w-0">
            <div className="text-[13px] font-medium text-ink truncate">{t.nome}</div>
            <div className="text-[11px] text-ink-mute truncate mt-1">{t.mercado || 'Nicho não informado'} · {t.midiaLabel}</div>
          </div>
          <div className="shrink-0 self-end"><Money t={t} size="16px" w="auto" /></div>
        </div>
      </div>
    </button>
  );
}

function Banco({ navigate, filters, toggleFilter, clearFilters, update }) {
  const f = filters || { search: '', nicho: '', objecao: '', classes: [] };
  const ql = norm(f.search || '');
  const filtered = DEPS.filter(t => {
    if (f.nicho && t.nichoCanon !== f.nicho) return false;
    if (f.objecao && !(t.objecoesCanon || []).includes(f.objecao)) return false;
    if (f.classes.length && !(t.classes || []).some(c => f.classes.includes(c))) return false;
    if (ql) {
      const blob = norm([t.headline, t.nome, t.mercado, t.resumo, t.kill, t.objecoes.join(' '), t.objecoesCanon.join(' '), t.classes.join(' ')].join(' '));
      if (!blob.includes(ql)) return false;
    }
    return true;
  });
  const active = (f.nicho ? 1 : 0) + (f.objecao ? 1 : 0) + f.classes.length + (f.search ? 1 : 0);
  const sel = 'field rounded-lg text-[12.5px] h-9 px-3 w-full sm:w-[210px]';
  // contagem REATIVA: o número de cada opção reflete os outros filtros já ativos
  const facets = facetOptions(f);

  return (
    <PageWrap max="1200px">
      <Eyebrow right={<span className="text-[12px] text-ink-mute num">{filtered.length} de {DEPS.length}</span>}>Banco de depoimentos</Eyebrow>
      <div className="flex flex-col gap-3 mb-8">
        <label className="relative block">
          <span className="absolute left-4 top-1/2 -translate-y-1/2 text-ink-mute"><Search size={16} /></span>
          <input type="text" value={f.search || ''} onChange={e => update({ search: e.target.value })} placeholder="Buscar por resultado, nome, nicho ou objeção…" className="field w-full h-11 pl-11 pr-10 rounded-xl text-[14px]" />
          {f.search && <button onClick={() => update({ search: '' })} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-mute hover:text-ink"><X size={15} /></button>}
        </label>
        <div className="flex flex-wrap items-center gap-2">
          <FilterSelect value={f.nicho} onChange={v => update({ nicho: v })} placeholder="Escolher nicho" options={facets.nicho} />
          <FilterSelect value={f.objecao} onChange={v => update({ objecao: v })} placeholder="Escolher objeção" options={facets.obj} />
          <span className="hidden sm:block w-px h-5 bg-white/10 mx-1"></span>
          {CLASSES_LIST.map(c => <button key={c} onClick={() => toggleFilter('classes', c)} className={'pill text-[12px] px-3 py-1.5 rounded-full ' + (f.classes.includes(c) ? 'on' : '')}>{c}</button>)}
          {active > 0 && <button onClick={clearFilters} className="text-[12px] text-ink-mute hover:text-red ml-1">limpar</button>}
        </div>
      </div>
      {filtered.length === 0 ? (
        <div className="card p-14 text-center text-[14px] text-ink-sub">Nenhum depoimento bate com esses filtros. <button onClick={clearFilters} className="text-red hover:underline">Limpar</button>.</div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 lg:gap-5">
          {filtered.map(t => <ProvaCard key={t.id} t={t} onOpen={() => navigate('detalhe', t.id)} />)}
        </div>
      )}
    </PageWrap>
  );
}

/* ───────── Ranking ───────── */

function Ranking({ navigate }) {
  const list = rankFinanceiro();
  return (
    <PageWrap max="900px">
      <Eyebrow>Maiores resultados financeiros</Eyebrow>
      <h1 className="text-[1.7rem] sm:text-[2rem] font-bold tracking-tight text-ink leading-tight">Ranking de resultados</h1>
      <p className="text-ink-sub text-[13.5px] mt-2 mb-7">{list.length} depoimentos com resultado financeiro, do maior para o menor.</p>
      <div>
        {list.map((t, i) => (
          <button key={t.id} onClick={() => navigate('detalhe', t.id)} className="w-full text-left grid items-center gap-3 sm:gap-5 border-t border-white/[0.06] py-3.5" style={{ gridTemplateColumns: '28px 1fr auto', minHeight: 64 }}>
            <span className="text-[24px] font-bold text-center num" style={{ color: i < 3 ? '#3ECF8E' : '#565B53' }}>{i + 1}</span>
            <span className="min-w-0">
              <span className="block text-[14px] font-medium text-ink leading-snug line-clamp-1">{t.headline}</span>
              <span className="block text-[11.5px] text-ink-mute mt-1 truncate">{t.nome}{t.mercado ? ' · ' + t.mercado : ''}</span>
            </span>
            <span className="justify-self-end"><Money t={t} size="15px" w="5.4em" color={i < 3 ? '#3ECF8E' : '#C9CEC6'} /></span>
          </button>
        ))}
      </div>
    </PageWrap>
  );
}

/* ───────── Detalhe ───────── */

function DetalheMedia({ t }) {
  const m = t.midiaWeb;
  if (!m) return null;
  if (m.kind === 'imagem') return <div className="space-y-3">{m.files.map((src, i) => <img key={i} src={src} alt="" className="w-full rounded-xl border border-white/[0.06]" />)}</div>;
  if (m.kind === 'video') return <video src={m.files[0]} poster={m.poster || undefined} controls preload="metadata" playsInline className="w-full max-h-[68vh] rounded-xl border border-white/[0.06] bg-black" />;
  if (m.kind === 'audio') return <div className="card px-5 py-6"><audio src={m.files[0]} controls preload="metadata" className="w-full" /></div>;
  return null;
}

function Detalhe({ navigate, id }) {
  const t = DEPS.find(x => x.id === id) || DEPS[0];
  if (!t) return null;
  return (
    <PageWrap max="760px">
      <div className="flex items-center justify-between gap-4 mb-7">
        <button onClick={() => navigate('banco')} className="flex items-center gap-2 text-[13px] text-ink-sub hover:text-ink group"><ArrowLeft size={15} className="group-hover:-translate-x-0.5 transition-transform" /> Voltar ao banco</button>
        {t.midiaWeb && t.midiaWeb.download && <a href={t.midiaWeb.download} download className="btn-primary rounded-xl px-4 py-2.5 inline-flex items-center gap-2 text-[13px] shrink-0"><Download size={15} strokeWidth={2.25} /> Baixar mídia</a>}
      </div>

      <div className="flex items-center gap-1.5 mb-4 flex-wrap"><ClassBadges t={t} />{t.forte && <ForteTag />}</div>
      <h1 className="text-[1.85rem] sm:text-[2.3rem] font-bold tracking-tight leading-[1.12] text-ink">{t.headline}</h1>
      <div className="flex items-center gap-2.5 mt-4 flex-wrap text-[13px] text-ink-sub">
        <span className="font-medium text-ink">{t.nome}</span>
        {t.mercado && <><span className="text-ink-mute">·</span><span>{t.mercado}{t.nichoInferido && <span className="text-ink-mute"> (inferido)</span>}</span></>}
        {t.data && <><span className="text-ink-mute">·</span><span>{t.data}</span></>}
        {t.valorCurto && <span className="ml-auto"><Money t={t} size="20px" w="auto" /></span>}
      </div>

      <div className="mt-8"><DetalheMedia t={t} /></div>

      {t.citacao && (
        <div className="mt-8 pl-5" style={{ borderLeft: '2px solid #3ECF8E' }}>
          <div className="eyebrow mb-3">Na voz do cliente</div>
          <p className="text-[17px] sm:text-[18px] text-ink leading-relaxed">“{t.citacao}”</p>
        </div>
      )}

      {(t.antes || t.depois) && (
        <div className="grid grid-cols-1 sm:[grid-template-columns:1fr_40px_1fr] items-stretch mt-8 border border-white/[0.07] rounded-xl overflow-hidden">
          <div className="p-5"><div className="eyebrow mb-2">Antes</div><div className="text-[14px] text-ink-sub leading-relaxed">{t.antes || '—'}</div></div>
          <div className="hidden sm:flex items-center justify-center text-red"><ArrowRight size={17} /></div>
          <div className="p-5 border-t sm:border-t-0 sm:border-l border-white/[0.07]"><div className="eyebrow mb-2">Depois</div><div className="text-[14px] text-ink leading-relaxed">{t.depois || '—'}</div></div>
        </div>
      )}
      {t.transformacao && <div className="mt-3 card p-5"><div className="eyebrow mb-2">Transformação</div><div className="text-[14px] text-ink leading-relaxed">{t.transformacao}</div></div>}

      {t.objecoesCanon.length > 0 && (
        <div className="mt-8">
          <div className="eyebrow mb-3.5">Objeções que contorna</div>
          <div className="flex flex-wrap gap-2">{t.objecoesCanon.map((o, i) => <span key={i} className="text-[12px] px-2.5 py-1 rounded-md text-red-soft" style={{ background: hexA('#3ECF8E', 0.10) }}>{o}</span>)}</div>
        </div>
      )}

      <div className="mt-8 pt-6 border-t border-white/[0.06]">
        <span className="text-[12px] text-ink-mute">Fonte: <span className="text-ink-sub">{t.fonte}</span></span>
      </div>
    </PageWrap>
  );
}

/* ───────── Matador de Objeção ───────── */

function MatadorItem({ rank, t, navigate }) {
  const [copied, setCopied] = React.useState(false);
  const copy = () => {
    const txt = [t.citacao ? '“' + t.citacao + '”' : '', t.nome + (t.mercado ? ' — ' + t.mercado : ''), t.valorCurto, '', 'Por que contorna: ' + t.kill].filter(Boolean).join('\n');
    if (navigator.clipboard) navigator.clipboard.writeText(txt);
    setCopied(true); setTimeout(() => setCopied(false), 1400);
  };
  const chipIcon = t.midia === 'video' ? <Play size={13} className="text-red" strokeWidth={2.5} /> : t.midia === 'audio' ? <Headphones size={13} className="text-red" /> : <ImageIcon size={13} className="text-ink-sub" />;
  return (
    <div className="card p-4 sm:p-5 grid gap-4 sm:gap-5" style={{ gridTemplateColumns: '32px 1fr 5.4em' }}>
      <span className="text-[28px] font-bold text-center num" style={{ color: '#3ECF8E' }}>{rank}</span>
      <div className="min-w-0">
        <div className="text-[15.5px] font-semibold text-ink leading-snug">{t.headline}</div>
        <div className="text-[11.5px] text-ink-mute mt-1">{t.nome}{t.mercado ? ' · ' + t.mercado : ''}</div>
        {t.citacao && <p className="mt-2.5 pl-3 text-[13px] text-ink-sub leading-relaxed line-clamp-3" style={{ borderLeft: '2px solid #3ECF8E' }}>“{t.citacao}”</p>}
        <button onClick={() => navigate('detalhe', t.id)} className="inline-flex items-center gap-2 mt-3 text-[11px] text-ink-sub bg-bg-elev rounded-lg px-2.5 py-1.5 hover:text-ink">{chipIcon} {t.midiaLabel} · abrir</button>
        <div className="flex gap-2 mt-3 text-[12.5px] leading-relaxed text-red-soft"><span className="text-red shrink-0 mt-0.5"><CornerDownRight size={14} strokeWidth={2.5} /></span><span><span className="text-ink font-medium">Por que contorna:</span> {t.kill}</span></div>
      </div>
      <div className="flex flex-col items-end gap-3">
        <Money t={t} size="15px" w="5.4em" />
        <span className="flex gap-1.5">
          <button onClick={copy} title={copied ? 'Copiado' : 'Copiar prova'} className={'w-8 h-8 rounded-lg border flex items-center justify-center transition ' + (copied ? 'border-red bg-red text-bg' : 'border-white/10 text-ink-sub hover:text-ink hover:border-white/20')}>{copied ? <CheckIcon size={14} strokeWidth={3} /> : <Copy size={14} />}</button>
          <button onClick={() => navigate('detalhe', t.id)} title="Abrir" className="w-8 h-8 rounded-lg border border-white/10 text-ink-sub hover:text-ink hover:border-white/20 flex items-center justify-center"><ExternalLink size={14} /></button>
        </span>
      </div>
    </div>
  );
}

function Matador({ navigate }) {
  const [query, setQuery] = React.useState('');
  const [results, setResults] = React.useState(() => rankObjecao(''));
  const [searched, setSearched] = React.useState(false);
  const run = () => { setResults(rankObjecao(query)); setSearched(query.trim().length > 0); };
  const onKey = e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); run(); } };

  return (
    <PageWrap max="860px">
      <div className="text-center pt-4">
        <div className="eyebrow mb-5">Ferramenta de vendas</div>
        <h1 className="text-[2rem] sm:text-[2.6rem] font-bold tracking-tight text-ink leading-tight">Contornar Objeções</h1>
        <p className="text-[14px] text-ink-sub mt-4 max-w-lg mx-auto leading-relaxed">Escreva a objeção do cliente e receba os depoimentos que a contornam, do mais aderente ao menos.</p>
      </div>

      <div className="card p-2 mt-9 focus-within:border-white/20 transition">
        <textarea rows={3} value={query} onChange={e => setQuery(e.target.value)} onKeyDown={onKey} placeholder="Exemplo: ele acha que não vai funcionar no mercado dele…" className="w-full resize-none bg-transparent p-4 text-[15px] text-ink placeholder:text-ink-mute leading-relaxed" />
        <div className="flex items-center justify-between gap-3 px-3 pb-2 pt-1">
          <span className="text-[11px] text-ink-mute hidden sm:block">Aperte Enter para buscar</span>
          <button onClick={run} className="btn-primary rounded-xl px-5 py-2.5 text-[13px] inline-flex items-center gap-2 ml-auto">Buscar provas <ArrowRight size={14} strokeWidth={2.5} /></button>
        </div>
      </div>

      <section className="mt-12">
        <Eyebrow>{searched ? results.length + ' provas · por aderência' : 'Provas mais fortes do banco'}</Eyebrow>
        {results.length === 0 ? (
          <div className="card p-14 text-center text-[14px] text-ink-sub">Nenhum depoimento do banco bate com essa objeção. Tente outras palavras.</div>
        ) : (
          <div className="flex flex-col gap-4">{results.map((t, i) => <MatadorItem key={t.id} t={t} rank={i + 1} navigate={navigate} />)}</div>
        )}
      </section>
    </PageWrap>
  );
}

Object.assign(window, { Painel, Banco, Ranking, Detalhe, Matador });
