// searching.jsx — live web-search animation theatre (dynamic per-topic)

const SEARCH_LINES_BY_PROFILE = {
  travel: [
    { host: "condenasttraveler.com", title: (a,b) => `${a} Travel Guide 2026` },
    { host: "monocle.com", title: (a,b) => `${b}: The City Issue` },
    { host: "lonelyplanet.com", title: (a,b) => `Best Time to Visit ${a} & ${b}` },
    { host: "michelin.com", title: (a,b) => `Michelin Guide — ${a}` },
    { host: "theinfatuation.com", title: (a,b) => `${b} vs ${a}: A Local Take` },
    { host: "nomadlist.com", title: (a,b) => `Cost of Travel: ${a} vs ${b}` },
    { host: "tripadvisor.com", title: (a,b) => `${b} 7-Day Itineraries` },
    { host: "cntraveller.com", title: (a,b) => `${a} Neighborhood Guide` },
    { host: "reuters.com", title: (a,b) => `${b} Tourism Reaches Decade High` },
    { host: "japan-guide.com", title: (a,b) => `${a} Transit Map 2026` },
  ],
  phone: [
    { host: "theverge.com", title: (a,b) => `${a} Review: A New Form Factor` },
    { host: "marquesbrownlee.com", title: (a,b) => `${a} vs ${b} — One Month Later` },
    { host: "dxomark.com", title: (a,b) => `${b} Camera Score` },
    { host: "ifixit.com", title: (a,b) => `${a} Teardown & Repairability` },
    { host: "anandtech.com", title: (a,b) => `${a} Performance Deep Dive` },
    { host: "wired.com", title: (a,b) => `${a}: The Bet on Thinness` },
    { host: "9to5mac.com", title: (a,b) => `${b} Battery Life Real-World` },
    { host: "consumerreports.org", title: (a,b) => `${a} & ${b} Reliability` },
    { host: "rtings.com", title: (a,b) => `${b} Display Lab Test` },
    { host: "engadget.com", title: (a,b) => `${a} vs ${b} Buyer's Guide` },
  ],
  ai: [
    { host: "anthropic.com", title: (a,b) => `${a} Model Card` },
    { host: "openai.com", title: (a,b) => `${b} System Card` },
    { host: "lmsys.org", title: (a,b) => `${a} vs ${b} on Chatbot Arena` },
    { host: "swebench.com", title: (a,b) => `${a} SWE-bench Verified` },
    { host: "simonwillison.net", title: (a,b) => `Notes on ${a} after a week` },
    { host: "huggingface.co", title: (a,b) => `${b} on Open LLM Leaderboard` },
    { host: "every.to", title: (a,b) => `Living with ${a} for daily work` },
    { host: "interconnects.ai", title: (a,b) => `${a} vs ${b}: Reasoning Teardown` },
    { host: "latent.space", title: (a,b) => `${b}: Context Window Tests` },
    { host: "artificialanalysis.ai", title: (a,b) => `${a} vs ${b} Pricing` },
  ],
  car: [
    { host: "caranddriver.com", title: (a,b) => `${a} Long-Term Test` },
    { host: "motortrend.com", title: (a,b) => `${a} vs ${b}: Head-to-Head` },
    { host: "edmunds.com", title: (a,b) => `${b} Review` },
    { host: "iihs.org", title: (a,b) => `${a} & ${b} Safety Ratings` },
    { host: "insideevs.com", title: (a,b) => `${a} Real-World Range` },
    { host: "consumerreports.org", title: (a,b) => `${b} Owner Survey` },
    { host: "topgear.com", title: (a,b) => `${a} on track` },
    { host: "kbb.com", title: (a,b) => `${a} & ${b} Resale Value` },
    { host: "cleantechnica.com", title: (a,b) => `${a} Charging Network Review` },
    { host: "autoblog.com", title: (a,b) => `${b} First Drive` },
  ],
  laptop: [
    { host: "theverge.com", title: (a,b) => `${a} Review` },
    { host: "wired.com", title: (a,b) => `${b}: The Repairable Future` },
    { host: "anandtech.com", title: (a,b) => `${a} Performance` },
    { host: "notebookcheck.net", title: (a,b) => `${b} Deep Review` },
    { host: "ifixit.com", title: (a,b) => `${b} Repairability Score` },
    { host: "rtings.com", title: (a,b) => `${a} Display Test` },
    { host: "consumerreports.org", title: (a,b) => `${a} & ${b} Reliability` },
    { host: "marquesbrownlee.com", title: (a,b) => `${a} vs ${b}` },
    { host: "tomshardware.com", title: (a,b) => `${b} Benchmarks` },
    { host: "laptopmag.com", title: (a,b) => `${a} Battery Real-World` },
  ],
  watch: [
    { host: "hodinkee.com", title: (a,b) => `${a}: The Long Read` },
    { host: "abtw.com", title: (a,b) => `${a} vs ${b} hands-on` },
    { host: "watchesbysjx.com", title: (a,b) => `${b} review` },
    { host: "fratellowatches.com", title: (a,b) => `${a} on the wrist` },
    { host: "chrono24.com", title: (a,b) => `${a} & ${b} market data` },
    { host: "monochrome-watches.com", title: (a,b) => `${b} value analysis` },
    { host: "watchpro.com", title: (a,b) => `${a} resale tracker` },
    { host: "timeandtidewatches.com", title: (a,b) => `${b} review` },
    { host: "wornandwound.com", title: (a,b) => `${a} long-term` },
    { host: "revolution.watch", title: (a,b) => `${b} feature` },
  ],
  app: [
    { host: "theverge.com", title: (a,b) => `${a} Review` },
    { host: "wired.com", title: (a,b) => `${b}: The Local-First Movement` },
    { host: "techcrunch.com", title: (a,b) => `${a} crosses 100M users` },
    { host: "every.to", title: (a,b) => `Switching from ${a} to ${b}` },
    { host: "reddit.com", title: (a,b) => `${a} vs ${b}: r/productivity` },
    { host: "ben-evans.com", title: (a,b) => `Notes on ${a}` },
    { host: "ycombinator.com", title: (a,b) => `${b}: HN discussion` },
    { host: "producthunt.com", title: (a,b) => `${a} Launch Page` },
    { host: "fastcompany.com", title: (a,b) => `${b} pricing changes` },
    { host: "g2.com", title: (a,b) => `${a} vs ${b} reviews` },
  ],
  wearable: [
    { host: "wired.com", title: (a,b) => `${a} Review` },
    { host: "theverge.com", title: (a,b) => `${b}: A Week on the Wrist` },
    { host: "dcrainmaker.com", title: (a,b) => `${a} vs ${b} Accuracy Test` },
    { host: "tomsguide.com", title: (a,b) => `${a} sleep tracking review` },
    { host: "outsideonline.com", title: (a,b) => `${b} for athletes` },
    { host: "androidcentral.com", title: (a,b) => `${a} & ${b} compatibility` },
    { host: "9to5mac.com", title: (a,b) => `${a} iOS integration` },
    { host: "androidauthority.com", title: (a,b) => `${b} long-term` },
    { host: "engadget.com", title: (a,b) => `${a} battery test` },
    { host: "cnet.com", title: (a,b) => `${a} vs ${b} buyer guide` },
  ],
  generic: [
    { host: "wikipedia.org", title: (a,b) => `${a}` },
    { host: "wikipedia.org", title: (a,b) => `${b}` },
    { host: "reddit.com", title: (a,b) => `${a} vs ${b}: discussion` },
    { host: "youtube.com", title: (a,b) => `${a} vs ${b} compared` },
    { host: "consumerreports.org", title: (a,b) => `${a} review` },
    { host: "consumerreports.org", title: (a,b) => `${b} review` },
    { host: "theverge.com", title: (a,b) => `${a} hands-on` },
    { host: "wired.com", title: (a,b) => `${b} feature` },
    { host: "nytimes.com", title: (a,b) => `${a} & ${b}: An Overview` },
    { host: "bloomberg.com", title: (a,b) => `${a} vs ${b} market data` },
  ],
};

const STEPS = [
  { label: "Reading your priorities", duration: 800 },
  { label: "Searching the web", duration: 4500 },
  { label: "Cross-checking sources", duration: 1800 },
  { label: "Weighing what you care about", duration: 1500 },
  { label: "Drafting the verdict", duration: 1200 },
];

const Searching = ({ answers, onComplete }) => {
  const [elapsed, setElapsed] = React.useState(0);
  const [activeStep, setActiveStep] = React.useState(0);

  const totalDuration = STEPS.reduce((s, x) => s + x.duration, 0);
  const a = answers?.what?.a || 'Item A';
  const b = answers?.what?.b || 'Item B';

  // Build dynamic search lines
  const searchLines = React.useMemo(() => {
    const profileKey = window.detectProfile ? window.detectProfile(a, b) : 'generic';
    const tmpl = SEARCH_LINES_BY_PROFILE[profileKey] || SEARCH_LINES_BY_PROFILE.generic;
    return tmpl.map((line, i) => ({
      host: line.host,
      title: line.title(a, b),
      delay: 200 + i * 520,
    }));
  }, [a, b]);

  // Build dynamic priorities ticker
  const priorityList = (answers?.priorities || []).slice(0, 4).join(', ').toLowerCase() || 'your priorities';

  React.useEffect(() => {
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const ms = now - start;
      setElapsed(ms);
      let acc = 0;
      let s = 0;
      for (let i = 0; i < STEPS.length; i++) {
        if (ms < acc + STEPS[i].duration) { s = i; break; }
        acc += STEPS[i].duration;
        s = i + 1;
      }
      setActiveStep(s);
      if (ms < totalDuration) raf = requestAnimationFrame(tick);
      else setTimeout(onComplete, 400);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const progress = Math.min(1, elapsed / totalDuration);
  const visibleLines = searchLines.filter(l => elapsed > l.delay);

  const tickerLines = [
    `Reading your priorities — ${priorityList}.`,
    `Found ${searchLines.length * 4 + 7} sources. Filtering for recency and quality.`,
    `Cross-referencing claims about ${a} and ${b} across multiple outlets.`,
    `Weighting categories against what you said matters.`,
    `Drafting a verdict you can actually use…`,
  ];

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <TopBar onHome={() => {}} />

      <div className="container" style={{ maxWidth: 900, padding: '60px 32px', flex: 1 }}>

        <div className="fade-in eyebrow" style={{ marginBottom: 24 }}>
          Working on it
        </div>

        <div className="fade-up" style={{ marginBottom: 8 }}>
          <h1 className="h1" style={{ margin: 0 }}>
            <span style={{ color: 'var(--a)' }}>{a}</span>
            <span className="mono" style={{ fontSize: '0.4em', color: 'var(--ink-4)', margin: '0 18px', verticalAlign: 'middle', letterSpacing: '0.2em' }}>VS</span>
            <span style={{ color: 'var(--b)' }}>{b}</span>
          </h1>
        </div>

        <div className="fade-up delay-1 lede" style={{ marginBottom: 48, maxWidth: 600 }}>
          Reading the latest from across the web. This usually takes about thirty seconds.
        </div>

        <div style={{ position: 'relative', height: 2, background: 'var(--rule)', marginBottom: 48, overflow: 'hidden' }}>
          <div style={{
            position: 'absolute', inset: 0,
            width: `${progress * 100}%`,
            background: 'var(--ink)',
            transition: 'width 0.1s linear',
          }} />
          <div style={{
            position: 'absolute', top: 0, bottom: 0,
            left: `${progress * 100}%`,
            width: 80,
            background: 'linear-gradient(to right, var(--accent), transparent)',
            opacity: progress < 1 ? 1 : 0,
          }} />
        </div>

        <div className="g-search">

          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Process</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {STEPS.map((s, i) => {
                const done = i < activeStep;
                const active = i === activeStep;
                return (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, opacity: done || active ? 1 : 0.35, transition: 'opacity 0.4s' }}>
                    <div style={{
                      width: 18, height: 18, borderRadius: '50%',
                      border: `1.5px solid ${done ? 'var(--ink)' : active ? 'var(--accent)' : 'var(--rule)'}`,
                      background: done ? 'var(--ink)' : 'transparent',
                      color: 'var(--paper)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 10,
                      flexShrink: 0,
                      position: 'relative',
                    }}>
                      {done && '✓'}
                      {active && (
                        <div style={{
                          position: 'absolute', inset: -3,
                          borderRadius: '50%',
                          border: '1.5px solid var(--accent)',
                          animation: 'pulse-dot 1.2s ease-in-out infinite',
                        }} />
                      )}
                    </div>
                    <div style={{ fontSize: 14, fontWeight: active ? 500 : 400 }}>
                      {s.label}{active && <span className="caret" />}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 18, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span>Sources <span className="mono" style={{ color: 'var(--ink-4)', marginLeft: 8 }}>{visibleLines.length} / {searchLines.length}</span></span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ink-3)', textTransform: 'none', letterSpacing: 'normal' }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'pulse-dot 1s ease-in-out infinite' }} />
                <span style={{ fontSize: 11 }}>LIVE</span>
              </span>
            </div>
            <div style={{ borderTop: '1px solid var(--rule-soft)' }}>
              {searchLines.map((line, i) => {
                const visible = elapsed > line.delay;
                return (
                  <div key={i} style={{
                    padding: '10px 0',
                    borderBottom: '1px solid var(--rule-soft)',
                    display: 'flex',
                    alignItems: 'center',
                    gap: 14,
                    opacity: visible ? 1 : 0,
                    transform: visible ? 'translateY(0)' : 'translateY(6px)',
                    transition: 'opacity 0.4s ease, transform 0.4s ease',
                  }}>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', width: 24 }}>
                      {String(i + 1).padStart(2, '0')}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {line.title}
                      </div>
                      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
                        {line.host}
                      </div>
                    </div>
                    <div style={{ flexShrink: 0, fontSize: 12, color: 'var(--accent)' }}>
                      ✓
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div className="fade-in" style={{ marginTop: 60, padding: '20px 24px', background: 'var(--paper-2)', borderRadius: 'var(--r-lg)', display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <div className="serif italic" style={{ color: 'var(--paper)', fontSize: 18 }}>v.</div>
          </div>
          <div className="serif italic" style={{ fontSize: 18, color: 'var(--ink-2)', minHeight: 24 }}>
            <Typewriter
              key={activeStep}
              text={tickerLines[Math.min(activeStep, 4)]}
              speed={18}
              showCaret={true}
            />
          </div>
        </div>
      </div>

    </div>
  );
};

window.Searching = Searching;
