/* global React, fmtViews, ytThumb */

// ============================================================
// 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>
  ),
};

// ---------- 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="" />
        <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>{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.slice(0, 3).map((t) => (
              <span key={t} className="tr-chip">{t}</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.slice(0, 3).map((p) => (
              <span key={p} className="tr-chip tr-chip--part">{p}</span>
            ))}
            {video.partsExtra > 0 && <span className="tr-chip tr-chip--more">+{video.partsExtra}</span>}
          </div>
        </div>

        <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 /> {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>
              <div>
                <dt><TR_Icon.Wrench /></dt>
                <dd><span className="n">{data.stats.causesIdentified}</span><span className="k">causas identificadas</span></dd>
              </div>
              <div>
                <dt><TR_Icon.Bulb /></dt>
                <dd>
                  <span className="n">{data.stats.overallMatchPercent}%</span>
                  <span className="k">compatibilidade média</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>

        <div className="tr-topbar__mode">
          <span className="tr-topbar__mode-label">MODO DE VISUALIZAÇÃO:</span>
          <div className="tr-topbar__seg">
            <button className="tr-topbar__seg-btn">VISÃO RÁPIDA</button>
            <button className="tr-topbar__seg-btn tr-topbar__seg-btn--active">
              ANÁLISE COMPLETA <TR_Icon.Arrow />
            </button>
          </div>
        </div>

        <div className="tr-topbar__right">
          <a href="#" onClick={(e)=>e.preventDefault()}>DASHBOARD COMPLETO</a>
          <span className="tr-topbar__sep">·</span>
          <a href="#" onClick={(e)=>e.preventDefault()}>TODOS OS DADOS</a>
        </div>
      </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>
  );
}

// ---------- PAINEL LATERAL TÉCNICO ----------
function TrSidePanel({ data }) {
  const hasCauses = data.probableCauses && data.probableCauses.length > 0;
  const hasTools  = data.mostUsedTools  && data.mostUsedTools.length  > 0;
  const hasParts  = data.relatedParts   && data.relatedParts.length   > 0;
  if (!hasCauses && !hasTools && !hasParts) return null;
  return (
    <aside className="tr-rail">
      {hasCauses && (
        <TrSideBlock icon={TR_Icon.Cause} title="Assuntos relacionados">
          {data.probableCauses.map((c) => <TrBarRow key={c.name} name={c.name} value={c.score} />)}
        </TrSideBlock>
      )}
      {hasTools && (
        <TrSideBlock
          icon={TR_Icon.Wrench}
          title="Ferramentas mais utilizadas"
          footer={<button className="tr-side__cta">VER FERRAMENTAS <TR_Icon.Arrow /></button>}
        >
          {data.mostUsedTools.map((t) => <TrBarRow key={t.name} name={t.name} value={t.frequency} />)}
        </TrSideBlock>
      )}
      {hasParts && (
        <TrSideBlock
          icon={TR_Icon.Box}
          title="Peças mais relacionadas"
          footer={<button className="tr-side__cta">VER PEÇAS RELACIONADAS <TR_Icon.Arrow /></button>}
        >
          {data.relatedParts.map((p) => <TrBarRow key={p.name} name={p.name} value={p.frequency} />)}
        </TrSideBlock>
      )}
    </aside>
  );
}

// ============================================================
// MAIN COMPONENT
// Recebe `data` como prop (estrutura buildTuchoData() do app.jsx)
// ============================================================
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 = 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>
          )}

          {/* Seção 3 — Conhecimento relacionado */}
          {sec3.length > 0 && (
            <section className="tr-section">
              <header className="tr-section__head">
                <span className="tr-section__num">03</span>
                <h2>Conhecimento relacionado</h2>
                <span className="tr-section__sub">para entender melhor o sistema antes de pôr a mão</span>
              </header>
              <div className="tr-section__midgrid">
                {sec3.map((v) => (
                  <TrMidVideoCard key={v.id} video={v} onOpen={handleOpen} />
                ))}
              </div>
            </section>
          )}

          <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 766+ 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} />
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TuchoResultsPage });
