/* global React, fmtViews, ytThumb, fullTextSearch */

// ============================================================
// TUCHO RESULTS PAGE — "Análise do Tucho"
// Página de resultado quando o usuário faz uma busca via Tucho.
// Aceita `data` como prop — não lê mais window.__TUCHO_RESULT__
// ============================================================

// ---------- ÍCONES AUXILIARES (placeholders neutros) ----------
const TR_Icon = {
  Video: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8">
      <rect x="2" y="6" width="14" height="12" rx="1"/>
      <path d="M16 10l5-2v8l-5-2z"/>
    </svg>
  ),
  Wrench: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a4 4 0 1 0-5 5l-7.4 7.4 2.5 2.5 7.4-7.4a4 4 0 0 0 5-5l-2 2-1.6-1.6 2-2z"/>
    </svg>
  ),
  Bulb: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 18h6"/>
      <path d="M10 21h4"/>
      <path d="M12 3a6 6 0 0 0-4 10.5c1 .8 1.5 1.5 2 3h4c.5-1.5 1-2.2 2-3A6 6 0 0 0 12 3z"/>
    </svg>
  ),
  Cog: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round">
      <circle cx="12" cy="12" r="3"/>
      <path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1l2.1-2.1M17 7l2.1-2.1"/>
    </svg>
  ),
  Cause: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round">
      <path d="M12 3l9 16H3z"/>
      <path d="M12 10v4M12 17v.5"/>
    </svg>
  ),
  Box: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round">
      <path d="M3 7l9-4 9 4-9 4z"/>
      <path d="M3 7v10l9 4 9-4V7"/>
      <path d="M12 11v10"/>
    </svg>
  ),
  Time: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <circle cx="12" cy="12" r="9"/>
      <path d="M12 7v5l3 2"/>
    </svg>
  ),
  Difficulty: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 17l4-4 3 3 5-6 6 7"/>
    </svg>
  ),
  CarTiny: () => (
    <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round">
      <path d="M3 13l2-5h14l2 5v5H3z"/>
      <circle cx="7" cy="17" r="1.5"/>
      <circle cx="17" cy="17" r="1.5"/>
    </svg>
  ),
  Check: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12l5 5 9-11"/>
    </svg>
  ),
  Crown: () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
      <path d="M3 6l4 4 5-6 5 6 4-4v12H3z"/>
    </svg>
  ),
  Arrow: () => (
    <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 6l6 6-6 6"/>
    </svg>
  ),
};

// ---------- TRADUÇÃO DIFICULDADE ----------
const DIFFICULTY_PT = {
  'beginner': 'Iniciante',
  'beginner/intermediate': 'Inic./Interm.',
  'intermediate': 'Intermediário',
  'intermediate/advanced': 'Interm./Avançado',
  'advanced': 'Avançado',
};
const diffPt = (d) => d ? (DIFFICULTY_PT[(d || '').toLowerCase()] || d) : '–';

// ---------- LATERAIS — barras de proporção ----------
function TrBarRow({ name, value, max = 100 }) {
  const w = Math.max(2, Math.min(100, (value / max) * 100));
  return (
    <div className="tr-bar">
      <div className="tr-bar__top">
        <span className="tr-bar__name">{name}</span>
        <span className="tr-bar__val">{value}%</span>
      </div>
      <div className="tr-bar__track">
        <div className="tr-bar__fill" style={{ width: w + "%" }} />
      </div>
    </div>
  );
}

function TrSideBlock({ icon, title, children, footer }) {
  const Ico = icon;
  return (
    <section className="tr-side">
      <header className="tr-side__head">
        {Ico && <span className="tr-side__ico"><Ico /></span>}
        <h3 className="tr-side__title">{title}</h3>
      </header>
      <div className="tr-side__body">{children}</div>
      {footer && <div className="tr-side__footer">{footer}</div>}
    </section>
  );
}

// ---------- CARD DO VÍDEO — bloco grande (seção "Melhor para o seu carro") ----------
function TrBigVideoCard({ video, onOpen }) {
  const cap = video.thumbCaption || {};
  return (
    <article className="tr-card" onClick={() => onOpen && onOpen(video)}>
      <div className="tr-card__thumb">
        <img src={ytThumb(video.ytId)} alt="" />
        {(cap.line1 || cap.line2) && (
          <div className="tr-card__thumb-overlay">
            <div className="tr-card__thumb-line tr-card__thumb-line--1">{cap.line1}</div>
            <div className="tr-card__thumb-line tr-card__thumb-line--2">{cap.line2}</div>
          </div>
        )}
        <span className="tr-card__duration">{video.duration}</span>
        <span className="tr-card__play">▶</span>
      </div>

      <div className="tr-card__main">
        <div className="tr-card__title-row">
          <span className="tr-card__rank">{video.rank}</span>
          <h4 className="tr-card__title">{video.title}</h4>
        </div>

        <div className="tr-card__match">
          <span className="tr-card__match-label">{video.matchLabel}</span>
          <span className="tr-card__match-pct">{video.matchPercent}%</span>
        </div>

        <p className="tr-card__what">{video.whatYouWillLearn}</p>

        <dl className="tr-card__meta">
          <div className="tr-card__meta-row">
            <dt><TR_Icon.CarTiny /> Aplicável a</dt>
            <dd>{video.applicableTo.join(" · ")}</dd>
          </div>
          <div className="tr-card__meta-row">
            <dt><TR_Icon.Difficulty /> Nível</dt>
            <dd>{diffPt(video.difficulty)}</dd>
          </div>
          <div className="tr-card__meta-row">
            <dt><TR_Icon.Time /> Tempo médio</dt>
            <dd>{video.estimatedTime}</dd>
          </div>
        </dl>
      </div>

      <aside className="tr-card__side">
        <div className="tr-card__chips">
          <div className="tr-card__chip-label">Ferramentas usadas</div>
          <div className="tr-card__chip-list">
            {video.tools.length > 0
              ? video.tools.map((t) => <span key={t.label} className="tr-chip">{t.label}</span>)
              : <span className="tr-chip tr-chip--empty">–</span>}
            {video.toolsExtra > 0 && <span className="tr-chip tr-chip--more">+{video.toolsExtra}</span>}
          </div>
        </div>

        <div className="tr-card__chips">
          <div className="tr-card__chip-label">Peças relacionadas</div>
          <div className="tr-card__chip-list">
            {video.parts.length > 0
              ? video.parts.map((p) => <span key={p.label} className="tr-chip tr-chip--part">{p.label}</span>)
              : <span className="tr-chip tr-chip--empty">–</span>}
            {video.partsExtra > 0 && <span className="tr-chip tr-chip--more">+{video.partsExtra}</span>}
          </div>
        </div>

        {video.usefulTimestamp && (
          <div className="tr-card__timestamp">
            <span className="tr-card__timestamp-label">{video.usefulTimestamp.label}</span>
            <span className="tr-card__timestamp-time">{video.usefulTimestamp.time}</span>
          </div>
        )}
      </aside>
    </article>
  );
}

// ---------- CARD DO VÍDEO — bloco médio (outras seções) ----------
function TrMidVideoCard({ video, onOpen }) {
  return (
    <article className="tr-midcard" onClick={() => onOpen && onOpen(video)}>
      <div className="tr-midcard__thumb">
        <img src={ytThumb(video.ytId)} alt="" />
        <span className="tr-midcard__duration">{video.duration}</span>
        {video.carBadge && <span className="tr-midcard__badge">{video.carBadge}</span>}
      </div>
      <div className="tr-midcard__body">
        <div className="tr-midcard__match">
          <span className="tr-card__match-label">{video.matchLabel}</span>
          <span className="tr-card__match-pct">{video.matchPercent}%</span>
        </div>
        <h4 className="tr-midcard__title">{video.title}</h4>
        <p className="tr-midcard__what">{video.whatYouWillLearn}</p>
        <div className="tr-midcard__foot">
          <span><TR_Icon.Difficulty /> {diffPt(video.difficulty)}</span>
          {video.estimatedTime && <span><TR_Icon.Time /> {video.estimatedTime}</span>}
          {video.usefulTimestamp && (
            <span className="tr-midcard__ts">
              {video.usefulTimestamp.label} <strong>{video.usefulTimestamp.time}</strong>
            </span>
          )}
        </div>
      </div>
    </article>
  );
}

// ---------- HEADER da busca + resumo do Tucho ----------
function TrSearchSummary({ data }) {
  return (
    <div className="tr-summary">
      <div className="tr-summary__main">
        <div className="tr-summary__label">SUA BUSCA</div>
        <div className="tr-summary__row">
          <img className="tr-summary__tucho" src="assets/tucho_mascote.png" alt="Tucho" />
          <div className="tr-summary__qwrap">
            <h1 className="tr-summary__query">&ldquo;{data.query}&rdquo;</h1>
            <div className="tr-summary__context">
              Buscando em: <strong>{data.context.label}</strong>
            </div>
            <dl className="tr-summary__stats">
              <div>
                <dt><TR_Icon.Video /></dt>
                <dd><span className="n">{data.stats.videosFound}</span><span className="k">vídeos encontrados</span></dd>
              </div>
              {data.stats.topMatchPercent > 0 && (
                <div>
                  <dt><TR_Icon.Bulb /></dt>
                  <dd>
                    <span className="n">{data.stats.topMatchPercent}%</span>
                    <span className="k">melhor resultado</span>
                  </dd>
                </div>
              )}
            </dl>
          </div>
        </div>
      </div>

      <aside className="tr-summary__resumo">
        <div className="tr-summary__resumo-head">RESUMO DO TUCHO</div>
        <p className="tr-summary__resumo-text">{data.tuchoSummary}</p>
        <details className="tr-summary__details">
          <summary>Ver mais detalhes <TR_Icon.Arrow /></summary>
          <ul>
            {data.tuchoSummaryDetails.map((d) => <li key={d}>{d}</li>)}
          </ul>
        </details>
      </aside>
    </div>
  );
}

// ---------- BARRA DE NAVEGAÇÃO INTERNA (voltar + modo) ----------
function TrTopNav({ onBack, breadcrumb }) {
  return (
    <>
      <div className="tr-topbar">
        <button className="tr-topbar__back" onClick={onBack}>
          <span className="tr-topbar__arrow">◂</span> VOLTAR
        </button>
        {/* #8: removidos os botões "Visão rápida/Análise completa" e os links
            "Dashboard/Todos os dados" — não tinham ação. */}
      </div>

      <nav className="tr-breadcrumb">
        {breadcrumb.map((b, i) => (
          <React.Fragment key={b}>
            {i > 0 && <span className="tr-breadcrumb__sep">/</span>}
            <span className={i === breadcrumb.length - 1 ? "tr-breadcrumb__here" : ""}>{b}</span>
          </React.Fragment>
        ))}
      </nav>
    </>
  );
}

// ---------- BLOCOS INFERIORES (4 colunas) ----------
function TrFooterBlocks({ data, onAskAgain }) {
  return (
    <div className="tr-foot">
      {/* Antes de assistir */}
      <section className="tr-foot__cell tr-foot__cell--check">
        <h4>Antes de assistir</h4>
        <ul>
          {data.beforeWatchingChecklist.map((c) => (
            <li key={c}><span className="tr-foot__check"><TR_Icon.Check /></span>{c}</li>
          ))}
        </ul>
      </section>

      {/* Dificuldade */}
      <section className="tr-foot__cell tr-foot__cell--diff">
        <h4>Dificuldade estimada</h4>
        <div className="tr-gauge">
          <svg viewBox="0 0 100 60" className="tr-gauge__svg">
            <path d="M10 55 A40 40 0 0 1 90 55" fill="none" stroke="#D8D8D8" strokeWidth="9" strokeLinecap="butt"/>
            <path d="M10 55 A40 40 0 0 1 90 55" fill="none" stroke="var(--pg-gold)" strokeWidth="9" strokeDasharray="125.6" strokeDashoffset={125.6 * (1 - (data.estimatedDifficulty.level + 1) / 4)} strokeLinecap="butt"/>
            <line x1="50" y1="55" x2={50 + 38 * Math.cos(Math.PI - (Math.PI * (data.estimatedDifficulty.level + 0.5)) / 4)} y2={55 - 38 * Math.sin(Math.PI - (Math.PI * (data.estimatedDifficulty.level + 0.5)) / 4)} stroke="var(--pg-black)" strokeWidth="2.5" strokeLinecap="round"/>
            <circle cx="50" cy="55" r="3.5" fill="var(--pg-black)"/>
          </svg>
          <div className="tr-gauge__label">{data.estimatedDifficulty.label.toUpperCase()}</div>
        </div>
        <p>{data.estimatedDifficulty.description}</p>
      </section>

      {/* Tempo médio */}
      <section className="tr-foot__cell tr-foot__cell--time">
        <h4>Tempo médio para resolver</h4>
        <div className="tr-foot__time">
          <span className="tr-foot__clock">
            <svg viewBox="0 0 64 64" width="56" height="56" fill="none" stroke="currentColor" strokeWidth="2.4">
              <circle cx="32" cy="32" r="26"/>
              <path d="M32 16v17l11 7" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </span>
          <div>
            <div className="tr-foot__time-val">{data.averageTimeToSolve.label}</div>
            <div className="tr-foot__time-desc">{data.averageTimeToSolve.description}</div>
          </div>
        </div>
      </section>

      {/* Precisa de mais ajuda? */}
      <section className="tr-foot__cell tr-foot__cell--ask">
        <h4>Precisa de mais ajuda?</h4>
        <p>Pergunte ao Tucho com detalhes específicos do sintoma.</p>
        <ul className="tr-foot__suggestions">
          {data.followUpSuggestions.map((s) => (
            <li key={s}>&ldquo;{s}&rdquo;</li>
          ))}
        </ul>
        <button className="tr-foot__ask" onClick={onAskAgain}>FAZER NOVA PERGUNTA <TR_Icon.Arrow /></button>
        <img className="tr-foot__tucho" src="assets/tucho_mascote.png" alt="" />
      </section>
    </div>
  );
}

// ---------- CARD COMPACTO para sidebar ----------
function TrSideVideoCard({ video, onOpen }) {
  return (
    <div className="tr-side-vid" onClick={() => onOpen && onOpen(video)}>
      <div className="tr-side-vid__thumb">
        <img src={ytThumb(video.ytId)} alt="" />
        <span className="tr-side-vid__dur">{video.duration}</span>
      </div>
      <div className="tr-side-vid__body">
        <span className="tr-side-vid__title">{video.title}</span>
        <span className="tr-side-vid__meta">
          <span className="tr-card__match-label" style={{fontSize:10}}>{video.matchLabel}</span>
          {' '}{video.matchPercent}%
          {video.applicableTo && video.applicableTo[0] && (
            <> · <span style={{opacity:.7}}>{video.applicableTo[0]}</span></>
          )}
        </span>
      </div>
    </div>
  );
}

// ---------- PAINEL LATERAL TÉCNICO ----------
function TrSidePanel({ data, sec3, onOpen }) {
  const hasSec3   = sec3 && sec3.length > 0;
  const hasCauses = !hasSec3 && data.probableCauses && data.probableCauses.length > 0;

  return (
    <aside className="tr-rail">
      {hasSec3 && (
        <TrSideBlock icon={TR_Icon.Bulb} title="Conhecimento relacionado">
          {sec3.map((v) => <TrSideVideoCard key={v.id} video={v} onOpen={onOpen} />)}
        </TrSideBlock>
      )}
      {hasCauses && (
        <TrSideBlock icon={TR_Icon.Cause} title="Assuntos relacionados">
          {data.probableCauses.map((c) => <TrBarRow key={c.name} name={c.name} value={c.score} />)}
        </TrSideBlock>
      )}
    </aside>
  );
}

// ============================================================
// MAIN COMPONENT
// Recebe `data` como prop (estrutura buildTuchoData() do app.jsx)
// ============================================================
// ---------- BUSCA NAS FALAS (full-text nas transcrições) ----------
function fmtTsLabel(s) {
  const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
  if (h > 0) return `${h}:${String(m).padStart(2,'0')}:${String(sec).padStart(2,'0')}`;
  return `${m}:${String(sec).padStart(2,'0')}`;
}

// Destaca os termos da query no snippet
function highlightSnippet(text, query) {
  const terms = (query || '').toLowerCase()
    .normalize('NFD').replace(/[̀-ͯ]/g, '')
    .split(/\s+/).filter(w => w.length > 2);
  if (terms.length === 0) return text;
  const norm = text.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
  // marca posições que casam algum termo
  const marks = new Array(text.length).fill(false);
  for (const t of terms) {
    let i = 0;
    while ((i = norm.indexOf(t, i)) !== -1) {
      for (let k = i; k < i + t.length; k++) marks[k] = true;
      i += t.length;
    }
  }
  const out = []; let buf = ''; let cur = false;
  for (let i = 0; i < text.length; i++) {
    if (marks[i] !== cur) {
      if (buf) out.push(cur ? <mark key={i} className="tr-fx__mark">{buf}</mark> : buf);
      buf = ''; cur = marks[i];
    }
    buf += text[i];
  }
  if (buf) out.push(cur ? <mark key="end" className="tr-fx__mark">{buf}</mark> : buf);
  return out;
}

function TrTranscriptMatches({ query, onOpen, contextCarId, contextLabel }) {
  // L2#1/#7 (rev. 15.2): se a busca tem contexto de carro, retorna até 60 e
  // filtra pelo carId no cliente. Sem contexto (busca geral) traz mais resultados
  // e oferece "ver mais" incremental.
  const [state, setState] = React.useState({ loading: true, results: [] });
  const [showCount, setShowCount] = React.useState(8);
  React.useEffect(() => {
    let alive = true;
    setState({ loading: true, results: [] });
    setShowCount(8);
    if (typeof fullTextSearch !== 'function' || !query) {
      setState({ loading: false, results: [] });
      return;
    }
    // Pede mais quando precisa filtrar por carro (pra ainda sobrar resultados)
    const limit = contextCarId ? 120 : 40;
    fullTextSearch(query, limit).then(res => {
      if (alive) setState({ loading: false, results: res });
    }).catch(() => { if (alive) setState({ loading: false, results: [] }); });
    return () => { alive = false; };
  }, [query, contextCarId]);

  const vmap = ((window.__PG_DATA__ || {}));
  const allV = {};
  [...(vmap.top || []), ...(vmap.recent || []),
   ...Object.values(vmap.byTopic || {}).flat()].forEach(v => { allV[v.id] = v; });

  // Filtra por carro quando o contexto da busca é um carro específico
  const filtered = contextCarId
    ? state.results.filter(r => (allV[r.id] || {}).carId === contextCarId)
    : state.results;

  if (state.loading) {
    return (
      <section className="tr-section">
        <header className="tr-section__head">
          <span className="tr-section__num">📝</span>
          <h2>Encontrado nas falas dos vídeos</h2>
          <span className="tr-section__sub">buscando nas transcrições…</span>
        </header>
      </section>
    );
  }
  if (filtered.length === 0) return null;

  const visible = filtered.slice(0, showCount);
  const subLabel = contextCarId
    ? `falas em vídeos de ${contextLabel || contextCarId}`
    : 'o Paulo menciona isso nesses momentos';

  return (
    <section className="tr-section">
      <header className="tr-section__head">
        <span className="tr-section__num">📝</span>
        <h2>Encontrado nas falas dos vídeos</h2>
        <span className="tr-section__sub">{subLabel}</span>
      </header>
      <div className="tr-fx__list">
        {visible.map(r => {
          const v = allV[r.id] || {};
          const title = v.title || r.id;
          const ytUrl = `https://www.youtube.com/watch?v=${r.id}&t=${r.timestamp_s}s`;
          return (
            <div key={r.id} className="tr-fx__row">
              <div className="tr-fx__thumb" onClick={() => onOpen && onOpen(v.id ? v : { id: r.id, title })}>
                <img src={ytThumb(r.id)} alt="" loading="lazy" />
              </div>
              <div className="tr-fx__body">
                <div className="tr-fx__title" onClick={() => onOpen && onOpen(v.id ? v : { id: r.id, title })}>
                  {title}
                </div>
                <div className="tr-fx__snippet">“…{highlightSnippet(r.snippet, query)}…”</div>
                <a className="tr-fx__ts" href={ytUrl} target="_blank" rel="noopener noreferrer">
                  ▶ ouvir em {fmtTsLabel(r.timestamp_s)}
                </a>
              </div>
            </div>
          );
        })}
      </div>
      {/* L2#7 (rev. 15.2): paginação incremental dentro da seção */}
      {filtered.length > showCount && (
        <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <button className="back-link" style={{fontFamily:'var(--font-mono)',fontSize:11}}
            onClick={() => setShowCount(c => c + 8)}>
            ▾ Ver mais 8 trechos
          </button>
          <span style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--pg-gray-2)',textTransform:'uppercase',letterSpacing:'0.1em'}}>
            Mostrando {showCount} de {filtered.length}
          </span>
        </div>
      )}
    </section>
  );
}

function TuchoResultsPage({ onBack, onOpen, data }) {
  if (!data) return null;

  const sec = data.sections || {};
  const sec1 = sec.bestForCurrentVehicle   || [];
  const sec2 = sec.sameProblemOtherVehicles || [];
  const sec3 = sec.relatedKnowledge        || [];
  const section1Title = data.section1Label || 'Vídeos mais relevantes';
  const hasSidebar = sec3.length > 0 || (data.probableCauses && data.probableCauses.length > 0);

  // Mapeia o vídeo enriquecido de volta para o formato do VideoPage
  const handleOpen = (v) => {
    if (!onOpen) return;
    // _source é o objeto original do allVideos; usa-o se disponível
    onOpen(v._source || {
      id: v.ytId || v.id,
      title: v.title,
      duration: v.duration,
    });
  };

  return (
    <div className="tr-page">
      <TrTopNav onBack={onBack} breadcrumb={data.breadcrumb || ['Início', 'Resultado da Busca']} />

      <div className={hasSidebar ? "tr-grid" : "tr-grid tr-grid--full"}>
        <div className="tr-grid__main">
          <TrSearchSummary data={data} />

          {/* Seção 1 — Vídeos mais relevantes / Melhor para o seu carro */}
          {sec1.length > 0 && (
            <section className="tr-section">
              <header className="tr-section__head">
                <span className="tr-section__crown"><TR_Icon.Crown /></span>
                <h2>{section1Title}</h2>
                {data.context && data.context.label && (
                  <span className="tr-section__ctx">({data.context.label})</span>
                )}
              </header>
              <div className="tr-section__list">
                {sec1.map((v) => (
                  <TrBigVideoCard key={v.id} video={v} onOpen={handleOpen} />
                ))}
              </div>
            </section>
          )}

          {/* Seção 2 — Outros veículos / mais vídeos */}
          {sec2.length > 0 && (
            <section className="tr-section">
              <header className="tr-section__head">
                <span className="tr-section__num">02</span>
                <h2>{data.section2Label || 'Mais vídeos relacionados'}</h2>
                <span className="tr-section__sub">
                  {data.section2Sub || 'outros vídeos que podem ajudar'}
                </span>
              </header>
              <div className="tr-section__midgrid">
                {sec2.map((v) => (
                  <TrMidVideoCard key={v.id} video={v} onOpen={handleOpen} />
                ))}
              </div>
            </section>
          )}

          {/* Busca full-text nas transcrições (rev. 14) */}
          <TrTranscriptMatches
            query={data.query}
            onOpen={handleOpen}
            contextCarId={data.context && data.context.carId}
            contextLabel={data.context && data.context.label}
          />

          <TrFooterBlocks data={data} onAskAgain={onBack} />

          <div className="tr-fineprint">
            <span className="tr-fineprint__mascot">
              <img src="assets/tucho_mascote.png" alt="" />
            </span>
            <span>Resultados gerados com base na análise de {(((window.__PG_DATA__ || {}).channel || {}).totalVideos) || '760+'} vídeos do canal Paulo's Garage</span>
            <span className="tr-fineprint__dot">·</span>
            <span>O Tucho está sempre aprendendo para te ajudar melhor!</span>
          </div>
        </div>

        {hasSidebar && (
          <div className="tr-grid__rail">
            <TrSidePanel data={data} sec3={sec3} onOpen={handleOpen} />
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TuchoResultsPage });
