/* global React, ReactDOM, TopBar, TipsBar, Header, Home, VideoPage, CarPage, TopicPage, AboutPage,
          SearchPage, TuchoResultsPage, hybridSearch,
          TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakSelect, TweakToggle */

// =============== DATA ====================================================
const CURATED = /*__DATA_PLACEHOLDER__*/ window.__PG_DATA__;

// =============== URL ROUTING =============================================
// Mapeamento slug ↔ carId (espelho do build_seo_pages.py)
const _CAR_SLUG_TO_ID = {
  'ford-ka': 'ka', 'volkswagen-gol': 'gol', 'volkswagen-brasilia': 'brasilia',
  'chevrolet-s10': 's10', 'honda-fit': 'fit', 'honda-crv': 'crv', 'fiat-palio': 'palio',
};
const _CAR_ID_TO_SLUG = {
  ka: 'ford-ka', gol: 'volkswagen-gol', brasilia: 'volkswagen-brasilia',
  s10: 'chevrolet-s10', fit: 'honda-fit', crv: 'honda-crv', palio: 'fiat-palio',
};

function _pgSlugify(text) {
  return (text || '')
    .normalize('NFD').replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, ' ')
    .replace(/[\s_-]+/g, '-')
    .trim()
    .slice(0, 80)
    .replace(/-+$/, '');
}

// Converte estado React → URL canônica
function _routeToUrl(route, currentVideo, currentCar, currentTopic, topicActiveCar) {
  if (route === 'video' && currentVideo) {
    const slug = _pgSlugify(currentVideo.title || currentVideo.id);
    return `/videos/${currentVideo.id}/${slug}/`;
  }
  if (route === 'car' && currentCar) {
    const carSlug = _CAR_ID_TO_SLUG[currentCar.carId] || currentCar.carId;
    return `/carros/${carSlug}/`;
  }
  if (route === 'topic' && currentTopic) {
    if (topicActiveCar) {
      const carSlug = _CAR_ID_TO_SLUG[topicActiveCar] || topicActiveCar;
      return `/carros/${carSlug}/${currentTopic.id}/`;
    }
    return `/sistemas/${currentTopic.id}/`;
  }
  return '/';
}

// Converte URL → { route, currentVideo?, currentCar? }
// Label legível por topic.id (espelha icons.jsx + build_seo_pages.py)
const _TOPIC_LABELS = {
  motor: 'MOTOR', freios: 'FREIOS', suspensao: 'SUSPENSÃO', eletrica: 'ELÉTRICA',
  funilaria: 'FUNILARIA & PINTURA', dicas: 'DICAS GERAIS', cambio: 'CÂMBIO',
  arrefecimento: 'ARREFECIMENTO', interior: 'INTERIOR', carroceria: 'CARROCERIA',
  combustivel: 'COMBUSTÍVEL', direcao: 'DIREÇÃO', pneus: 'PNEUS',
  escapamento: 'ESCAPAMENTO', transmissao: 'TRANSMISSÃO', ferramentas: 'FERRAMENTAS',
};

// Monta objeto de tópico compatível com TopicPage.
// Usa TOPICS global (icons.jsx) se disponível, senão constrói um mínimo.
function _topicById(topicId) {
  if (typeof TOPICS !== 'undefined') {
    const found = TOPICS.find(t => t.id === topicId);
    if (found) return found;
  }
  const label = _TOPIC_LABELS[topicId] || topicId.toUpperCase();
  return { id: topicId, label, count: 0, ico: null };
}

function _parseUrl(pathname, allVideos) {
  // /videos/{id}/[slug]/
  const vm = pathname.match(/^\/videos\/([^/]+)/);
  if (vm) {
    const vid = allVideos.find(v => v.id === vm[1]);
    if (vid) return { route: 'video', currentVideo: vid };
  }
  // /carros/{car-slug}/{topic-id}/  — tópico dentro de um carro (mais específico, vem primeiro)
  const ctm = pathname.match(/^\/carros\/([^/]+)\/([^/]+)\/?$/);
  if (ctm) {
    const carId   = _CAR_SLUG_TO_ID[ctm[1]];
    const topicId = ctm[2];
    if (carId && _TOPIC_LABELS[topicId]) {
      return { route: 'topic', currentTopic: _topicById(topicId), initialCar: carId };
    }
  }
  // /carros/{car-slug}/
  const cm = pathname.match(/^\/carros\/([^/]+)\/?$/);
  if (cm) {
    const carId  = _CAR_SLUG_TO_ID[cm[1]];
    if (carId) {
      const cars   = (CURATED.cars || []);
      const carObj = cars.find(c => c.id === carId) || { id: carId };
      return { route: 'car', currentCar: { car: carObj, carId } };
    }
  }
  // /sistemas/{topic-id}/
  const sm = pathname.match(/^\/sistemas\/([^/]+)\/?$/);
  if (sm && _TOPIC_LABELS[sm[1]]) {
    return { route: 'topic', currentTopic: _topicById(sm[1]) };
  }
  return { route: 'home' };
}

// =============== TUCHO DATA BUILDER ======================================
// Converte (query, scoredResults [{v,score}], context) no formato esperado
// pelo TuchoResultsPage. Chamado a cada busca via Tucho.
function buildTuchoData(query, scoredResults, context) {
  if (!scoredResults || scoredResults.length === 0) return null;

  const carId        = context && context.carId;
  const topicId      = context && context.topicId;
  const contextLabel = (context && context.label) || 'Todos os vídeos do canal';

  // Detecta se os scores são semânticos (floats 0–1) ou keyword (inteiros ≥ 1)
  // Scores semânticos sempre têm decimais (ex: 0.619); keyword são inteiros exatos
  const isSemantic = scoredResults.some(x => x.score > 0 && x.score % 1 !== 0);

  const matchPct = (score) => {
    if (isSemantic) return Math.round(score * 100);           // cosine similarity direto
    return score >= 3 ? 90 : score >= 2 ? 75 : score >= 1 ? 60 : 45;
  };

  const matchLabel = (score) => {
    if (isSemantic) {
      if (score >= 0.60) return 'Alta relevância';
      if (score >= 0.50) return 'Boa relação';
      if (score >= 0.40) return 'Relação aproximada';
      return 'Complementar';
    }
    if (score >= 3) return 'Alta relevância';
    if (score >= 2) return 'Boa relação';
    if (score >= 1) return 'Relação aproximada';
    return 'Complementar';
  };

  // Converte seconds → "mm:ss"
  const secToTime = (s) => {
    if (!s && s !== 0) return null;
    const m = Math.floor(s / 60), sec = s % 60;
    return `${m}:${String(sec).padStart(2, '0')}`;
  };

  const enrichVideo = (item, rank) => {
    const { v, score } = item;

    // Ferramentas e peças curadas (filtra placeholders vazios ou "-")
    const isValidName = (n) => typeof n === 'string' && n.trim().length > 1 && n.trim() !== '-';
    const truncLabel  = (s, max = 24) => s.length > max ? s.slice(0, max).trimEnd() + '…' : s;
    const curTools  = (v.curatedTools || []).filter(t => isValidName(t.name));
    const curParts  = [...(v.curatedParts || []), ...(v.curatedPartsReplaced || [])].filter(p => isValidName(p.name));
    const MAX_SHOW  = 3;
    const tools     = curTools.slice(0, MAX_SHOW).map(t => ({ label: truncLabel(t.name), time: secToTime(t.timestamp_s) }));
    const parts     = curParts.slice(0, MAX_SHOW).map(p => ({ label: truncLabel(p.name), time: secToTime(p.timestamp_s) }));

    // Primeiro timestamp útil: curated tools/parts → jumpPoints
    let usefulTimestamp = null;
    const allItemsWithTs = [...curTools, ...curParts].filter(i => i.timestamp_s);
    if (allItemsWithTs.length) {
      const first = allItemsWithTs.sort((a, b) => a.timestamp_s - b.timestamp_s)[0];
      usefulTimestamp = { label: first.name.split(' ').slice(0, 2).join(' '), time: secToTime(first.timestamp_s) };
    } else if ((v.jumpPoints || []).length) {
      const jp = v.jumpPoints.find(p => p.s > 30);
      if (jp) usefulTimestamp = { label: jp.l || 'Trecho relevante', time: jp.r || secToTime(jp.s) };
    }

    return {
      id:             v.id,
      rank:           rank + 1,
      title:          v.title,
      ytId:           v.id,
      duration:       v.duration || '--:--',
      matchPercent:   matchPct(score),
      matchLabel:     matchLabel(score),
      whatYouWillLearn: v.summaryCard || v.sintomaPrincipal || '',
      applicableTo:   v.carModel ? [v.carModel] : v.car ? [v.car] : [],
      difficulty:     v.difficulty || '–',
      estimatedTime:  v.estimatedTime || null,
      tools, toolsExtra: Math.max(0, curTools.length - MAX_SHOW),
      parts, partsExtra: Math.max(0, curParts.length - MAX_SHOW),
      usefulTimestamp,
      thumbCaption:   { line1: '', line2: '' },
      carBadge:       v.carModel || v.car || null,
      _source:        v,
    };
  };

  // Divisão em seções
  let sec1 = [], sec2 = [], sec3 = [];
  if (carId) {
    const forCar   = scoredResults.filter(x => x.v.carId === carId);
    const otherCar = scoredResults.filter(x => x.v.carId && x.v.carId !== carId);
    const generic  = scoredResults.filter(x => !x.v.carId);
    sec1 = forCar.slice(0, 3);
    sec2 = otherCar.slice(0, 4);
    sec3 = [...generic, ...otherCar.slice(4)].slice(0, 4);
  } else if (topicId) {
    // Contexto de assunto: sec1 = vídeos com esse tópico, sec2/sec3 = outros
    const inTopic  = scoredResults.filter(x => (x.v.topics || []).includes(topicId));
    const outTopic = scoredResults.filter(x => !(x.v.topics || []).includes(topicId));
    sec1 = inTopic.slice(0, 3);
    sec2 = outTopic.slice(0, 4);
    sec3 = [...inTopic.slice(3), ...outTopic.slice(4)].slice(0, 4);
  } else {
    sec1 = scoredResults.slice(0, 3);
    sec2 = scoredResults.slice(3, 7);
    sec3 = scoredResults.slice(7, 11);
  }

  // Frequência de tópicos nos top 20 resultados → barra lateral
  const topicFreq = new Map();
  scoredResults.slice(0, 20).forEach(({ v }) => {
    (v.topics || []).forEach(t => topicFreq.set(t, (topicFreq.get(t) || 0) + 1));
  });
  const topTopics = [...topicFreq.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, 6)
    .map(([name, n]) => ({
      name,
      score: Math.round((n / Math.min(20, scoredResults.length)) * 100),
    }));

  const videosFound = scoredResults.length;
  const topScore    = scoredResults[0] ? matchPct(scoredResults[0].score) : 0;

  return {
    query,
    context: { label: contextLabel, carId, topicId, make: context && context.make, model: context && context.model },
    breadcrumb: carId
      ? ['Início', 'Por Carro', contextLabel, 'Resultado da Busca']
      : topicId
        ? ['Início', 'Por Assunto', contextLabel, 'Resultado da Busca']
        : ['Início', 'Resultado da Busca'],
    stats: {
      videosFound,
      topMatchPercent: topScore,
    },
    tuchoSummary:
      `${isSemantic ? 'Busca semântica: ' : ''}Separei os ${Math.min(videosFound, 10)} vídeos mais relevantes para "${query}"` +
      ((carId || topicId) && contextLabel !== 'Todos os vídeos do canal' ? ` em ${contextLabel}` : '') +
      `.`,
    tuchoSummaryDetails: [
      isSemantic ? 'Relevância calculada por similaridade semântica (IA)' : 'Relevância calculada por palavras-chave',
      `${videosFound} vídeo${videosFound !== 1 ? 's' : ''} encontrado${videosFound !== 1 ? 's' : ''}`,
      'Esta orientação não substitui inspeção mecânica presencial',
    ],
    sections: {
      bestForCurrentVehicle:    sec1.map((item, i) => enrichVideo(item, i)),
      sameProblemOtherVehicles: sec2.map((item, i) => enrichVideo(item, sec1.length + i)),
      relatedKnowledge:         sec3.map((item, i) => enrichVideo(item, sec1.length + sec2.length + i)),
    },
    section1Label: carId ? 'Melhor para o seu carro'
                         : topicId ? `Vídeos em ${contextLabel}`
                         : 'Vídeos mais relevantes',
    section2Label: carId ? 'Mesmo problema em outros carros'
                         : topicId ? 'Outros vídeos relacionados'
                         : 'Mais vídeos sobre o tema',
    section2Sub:   carId ? 'vídeos que ajudam pelo mesmo princípio mecânico'
                         : 'outros vídeos relevantes',
    probableCauses: topTopics,
    mostUsedTools:  [],
    relatedParts:   [],
    beforeWatchingChecklist: [
      'Descreva o sintoma com o máximo de detalhes',
      'Observe em que condição o problema ocorre',
      'Verifique se há outros sintomas associados',
      'Consulte o manual do proprietário se disponível',
    ],
    estimatedDifficulty: { label: 'Variável', description: 'Depende da causa identificada.', level: 1 },
    averageTimeToSolve:  { label: 'Variável', description: 'Consulte os vídeos para estimativas.' },
    followUpSuggestions: [
      query + ' passo a passo',
      query + ' como diagnosticar',
      query + ' quais peças',
    ],
  };
}

// =============== APP =====================================================
const DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "default",
  "accent": "gold",
  "showStatStrip": true,
  "cardStyle": "flat",
  "heroLayout": "sidebar",
  "theme": "light"
}/*EDITMODE-END*/;

function App() {
  const tweaks = useTweaks ? useTweaks(DEFAULTS) : [DEFAULTS, () => {}];
  const [T, setT] = tweaks;

  // expose for external previews / screenshots
  React.useEffect(() => { window.__setHero = (v) => setT('heroLayout', v); }, [setT]);
  React.useEffect(() => { window.__goTucho = () => goHome('tucho'); }, []);

  const [route, setRoute] = React.useState('home'); // 'home' | 'video' | 'car' | 'topic' | 'about' | 'search'
  const [currentVideo, setCurrentVideo] = React.useState(null);
  const [currentCar, setCurrentCar] = React.useState(null); // { car, carId }
  const [carView, setCarView] = React.useState('light'); // 'light' | 'complete'
  const [currentTopic, setCurrentTopic] = React.useState(null);
  const [topicActiveCar, setTopicActiveCar] = React.useState(null); // carId ativo no TopicPage
  const [currentSearch, setCurrentSearch] = React.useState(null); // { query, scoredResults, context }
  const [search, setSearch] = React.useState('');
  const [homePanel, setHomePanel] = React.useState('cars');
  const [tuchoQuery, setTuchoQuery] = React.useState('');

  const allVideos = React.useMemo(() => {
    const map = new Map();
    [...CURATED.top, ...CURATED.recent, ...Object.values(CURATED.byTopic).flat()]
      .forEach(v => map.set(v.id, v));
    return [...map.values()];
  }, []);

  // (rev. 15) Faixa dourada de dicas removida — consolidada na barra superior
  // (TopBar), que agora rotaciona stats dinâmicos + banco de dicas (tipsDb).

  // ── Pilha de navegação (rev. 15) ───────────────────────────────────
  // Guarda snapshots para o "Voltar" retornar à página anterior real
  // (antes voltava sempre pro início e perdia o progresso).
  const [navStack, setNavStack] = React.useState([]);
  const stateRef = React.useRef({});
  stateRef.current = { route, currentVideo, currentCar, carView, currentTopic, topicActiveCar, currentSearch, homePanel };

  const pushNav = () => setNavStack(s => [...s, { ...stateRef.current }]);

  const applySnapshot = (snap) => {
    setRoute(snap.route);
    setCurrentVideo(snap.currentVideo);
    setCurrentCar(snap.currentCar);
    setCarView(snap.carView);
    setCurrentTopic(snap.currentTopic);
    setTopicActiveCar(snap.topicActiveCar || null);
    setCurrentSearch(snap.currentSearch);
    setHomePanel(snap.homePanel);
    // Sincroniza URL com o estado restaurado
    const url = _routeToUrl(snap.route, snap.currentVideo, snap.currentCar, snap.currentTopic, snap.topicActiveCar);
    history.replaceState({ pgRoute: snap.route }, '', url);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const goBack = () => {
    setNavStack(s => {
      if (s.length === 0) {
        setRoute('home');
        history.replaceState({ pgRoute: 'home' }, '', '/');
        window.scrollTo({ top: 0, behavior: 'instant' });
        return s;
      }
      applySnapshot(s[s.length - 1]);
      return s.slice(0, -1);
    });
  };

  const openVideo = (v) => {
    pushNav();
    // TuchoResultsPage passa objetos leves com _source apontando para o vídeo completo
    const full = v._source || allVideos.find(x => x.id === v.id) || v;
    setCurrentVideo(full);
    setRoute('video');
    const url = _routeToUrl('video', full, null);
    history.pushState({ pgRoute: 'video', id: full.id }, '', url);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const openCar = (car) => {
    pushNav();
    setCurrentCar({ car, carId: car.id });
    setCarView('light');
    setRoute('car');
    const url = _routeToUrl('car', null, { car, carId: car.id });
    history.pushState({ pgRoute: 'car', carId: car.id }, '', url);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const openTopic = (topic, initialCar = null) => {
    pushNav();
    setCurrentTopic(topic);
    setTopicActiveCar(initialCar || null);
    setRoute('topic');
    const url = _routeToUrl('topic', null, null, topic, initialCar);
    history.pushState({ pgRoute: 'topic', topicId: topic.id }, '', url);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // Chamado pelo TopicPage quando o filtro de carro muda — atualiza URL via replaceState
  const handleTopicCarFilter = (carId, topic) => {
    setTopicActiveCar(carId || null);
    const url = _routeToUrl('topic', null, null, topic, carId);
    history.replaceState({ pgRoute: 'topic', topicId: topic && topic.id }, '', url);
  };

  // scoredResults = [{v, score}], context = { label, carId, make, model } | null
  const openSearch = (query, scoredResults, context = null) => {
    pushNav();
    setCurrentSearch({ query, scoredResults, context });
    setRoute('search');
    // Busca não tem URL própria — mantém URL atual
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // goHome reseta a pilha (volta ao topo da jornada — clicar no logo/início)
  const goHome = (panel = null) => {
    if (panel) setHomePanel(panel);
    setNavStack([]);
    setRoute('home');
    history.pushState({ pgRoute: 'home' }, '', '/');
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // ── Leitura da URL inicial + popstate (botão voltar do navegador) ───────
  React.useEffect(() => {
    // Helper: aplica um resultado de _parseUrl ao estado React
    const applyParsed = (p) => {
      if (p.route === 'video' && p.currentVideo) {
        setCurrentVideo(p.currentVideo);
        setRoute('video');
      } else if (p.route === 'car' && p.currentCar) {
        setCurrentCar(p.currentCar);
        setCarView('light');
        setRoute('car');
      } else if (p.route === 'topic' && p.currentTopic) {
        setCurrentTopic(p.currentTopic);
        setTopicActiveCar(p.initialCar || null);
        setRoute('topic');
      } else {
        setRoute('home');
        setCurrentVideo(null);
        setCurrentCar(null);
        setCurrentTopic(null);
        setTopicActiveCar(null);
      }
    };

    // 1. Lê a URL atual ao montar
    const initial = _parseUrl(window.location.pathname, allVideos);
    if (initial.route !== 'home') {
      applyParsed(initial);
      history.replaceState({ pgRoute: initial.route }, '', window.location.pathname);
    } else {
      history.replaceState({ pgRoute: 'home' }, '', '/');
    }

    // 2. Listener para botão voltar/avançar do navegador
    const onPopState = (e) => {
      const parsed = _parseUrl(window.location.pathname, allVideos);
      applyParsed(parsed);
      setNavStack([]); // reseta pilha interna — browser history é o source of truth
      window.scrollTo({ top: 0, behavior: 'instant' });
    };

    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, [allVideos]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleHeaderNav = (target) => {
    if (target === 'home') return goHome();
    if (target === 'cars') return goHome('cars');
    if (target === 'topics') return goHome('topics');
    if (target === 'search') return goHome('tucho');
    if (target === 'about') { pushNav(); return setRoute('about'); }
  };

  const handleHeaderSearch = async (query) => {
    const text = (query || '').trim();
    if (!text) return;
    setSearch(text);

    // Usa a mesma busca híbrida do Tucho (Worker semântico + keyword)
    // hybridSearch é global (definido em pages.jsx); cai para keyword se o Worker
    // estiver indisponível.
    let results;
    try {
      results = await hybridSearch(text, allVideos, allVideos);
    } catch (_) {
      // Fallback puro keyword caso hybridSearch não esteja disponível
      const words = text.toLowerCase().split(/\s+/).filter(w => w.length > 2);
      const scored = allVideos.map(v => {
        const hay = [v.title, v.summaryCard, v.sintomaPrincipal]
          .filter(Boolean).join(' ').toLowerCase();
        let score = 0;
        words.forEach(w => { if (hay.includes(w)) score += 1; });
        return { v, score };
      }).filter(x => x.score > 0).sort((a, b) => b.score - a.score);
      results = scored.length > 0 ? scored : allVideos.slice(0, 20).map(v => ({ v, score: 0 }));
    }
    openSearch(text, results, null);
  };

  // density on body
  React.useEffect(() => {
    document.body.classList.remove('density-comfy','density-tight');
    if (T.density === 'comfy') document.body.classList.add('density-comfy');
    if (T.density === 'tight') document.body.classList.add('density-tight');
  }, [T.density]);

  // accent
  React.useEffect(() => {
    const map = {
      gold:   ['#F5A500', '#C78700'],
      red:    ['#E53935', '#B71C1C'],
      green:  ['#4CAF50', '#2E7D32'],
      cyan:   ['#00ACC1', '#00838F'],
    };
    const [a, b] = map[T.accent] || map.gold;
    document.documentElement.style.setProperty('--pg-gold', a);
    document.documentElement.style.setProperty('--pg-gold-deep', b);
  }, [T.accent]);

  // theme
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', T.theme === 'dark' ? 'dark' : 'light');
  }, [T.theme]);

  const toggleTheme = () => setT('theme', T.theme === 'dark' ? 'light' : 'dark');

  return (
    <>
      <TopBar theme={T.theme} onToggleTheme={toggleTheme} onOpen={openVideo} />
      <Header
        route={route}
        homePanel={homePanel}
        onNav={handleHeaderNav}
        search={search}
        setSearch={setSearch}
        onSearch={handleHeaderSearch}
      />
      {route === 'home' && (
        <Home
          data={CURATED}
          onOpen={openVideo}
          onOpenCar={openCar}
          onOpenTopic={openTopic}
          onSearch={openSearch}
          heroLayout={T.heroLayout}
          forcedPanel={homePanel}
          tuchoQuery={tuchoQuery}
        />
      )}
      {route === 'video' && (
        <div className="page">
          <VideoPage
            video={currentVideo}
            allVideos={allVideos}
            onBack={goBack}
            onOpen={openVideo}
            onOpenCar={openCar}
          />
        </div>
      )}
      {route === 'car' && currentCar && (
        <CarPage
          carId={currentCar.carId}
          allVideos={allVideos}
          onBack={goBack}
          onOpen={openVideo}
          onSearch={openSearch}
          view={carView}
          setView={(v) => { if (v === 'complete' && carView !== 'complete') pushNav(); setCarView(v); }}
        />
      )}
      {route === 'topic' && currentTopic && (
        <TopicPage
          topic={currentTopic}
          allVideos={allVideos}
          onBack={goBack}
          onOpen={openVideo}
          onOpenCar={openCar}
          onSearch={openSearch}
          initialCar={topicActiveCar}
          onCarFilter={handleTopicCarFilter}
        />
      )}
      {route === 'search' && currentSearch && (
        <div className="page">
          <TuchoResultsPage
            data={buildTuchoData(currentSearch.query, currentSearch.scoredResults, currentSearch.context)}
            onBack={goBack}
            onOpen={openVideo}
          />
        </div>
      )}
      {route === 'about' && <AboutPage />}

      <footer className="pg-footer">
        <div className="pg-footer__row">
          <div>
            <strong style={{color:'var(--pg-ink)'}}>PaulosGarage.com</strong> · portal de conhecimento automotivo DIY · conteúdo do canal {' '}
            <a href="https://youtube.com/PaulosGarage">youtube.com/PaulosGarage</a>
          </div>
          <div className="pg-footer__links">
            <a href="#">Sobre</a>
            <a href="#">Contato</a>
            <a href="#">RSS</a>
            <a href="#">Créditos</a>
          </div>
        </div>
        <div style={{maxWidth:1360,margin:'10px auto 0',fontFamily:'var(--font-mono)',fontSize:10,letterSpacing:'0.1em',textTransform:'uppercase',color:'var(--pg-gray-3)'}}>
          BUILD · DESKTOP-FIRST · PAGEFIND · TUCHO v0.1
        </div>
      </footer>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Layout do Hero">
          <TweakRadio
            value={T.heroLayout}
            options={[
              { value: 'sidebar',  label: 'Jornada dominante + lista lateral ★' },
              { value: 'carousel', label: 'Carrossel duplo' },
              { value: 'strip',    label: 'Faixa horizontal única' },
            ]}
            onChange={(v) => setT('heroLayout', v)}
          />
        </TweakSection>
        <TweakSection label="Tema">
          <TweakRadio
            value={T.theme}
            options={[
              { value: 'light', label: 'Claro (manual técnico)' },
              { value: 'dark',  label: 'Escuro (oficina noturna)' },
            ]}
            onChange={(v) => setT('theme', v)}
          />
        </TweakSection>
        <TweakSection label="Acento">
          <TweakRadio
            value={T.accent}
            options={[
              { value: 'gold',  label: 'Ouro (padrão)' },
              { value: 'red',   label: 'Vermelho' },
              { value: 'green', label: 'Verde' },
              { value: 'cyan',  label: 'Ciano' },
            ]}
            onChange={(v) => setT('accent', v)}
          />
        </TweakSection>
        <TweakSection label="Densidade">
          <TweakRadio
            value={T.density}
            options={[
              { value: 'tight',   label: 'Compacta (Yahoo 2005)' },
              { value: 'default', label: 'Padrão (manual técnico)' },
              { value: 'comfy',   label: 'Confortável' },
            ]}
            onChange={(v) => setT('density', v)}
          />
        </TweakSection>
        <TweakSection label="Faixa de estatísticas">
          <TweakToggle
            checked={T.showStatStrip}
            label="Mostrar"
            onChange={(v) => setT('showStatStrip', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
