// DemoReplay.jsx — scroll-triggered, looping, <1 second alert latency demo
// Left: source site with car thumbnails scrolling past. Right: AutoViz picking matches in real time.

const { useState, useEffect, useRef } = React;

// SVG car silhouette — gradient-colored, looks like a real thumbnail at small sizes
function carThumb(hue, sat = 60, light = 45) {
  const bg = `hsl(${hue}, ${sat}%, ${Math.max(8, light - 30)}%)`;
  const body = `hsl(${hue}, ${sat}%, ${light}%)`;
  const hl   = `hsl(${hue}, ${Math.min(90, sat + 20)}%, ${Math.min(85, light + 25)}%)`;
  const shad = `hsl(${hue}, ${sat}%, ${Math.max(5, light - 35)}%)`;
  const svg = `
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 56' preserveAspectRatio='xMidYMid slice'>
      <defs>
        <linearGradient id='g' x1='0' y1='0' x2='0' y2='1'>
          <stop offset='0' stop-color='${body}' stop-opacity='1'/>
          <stop offset='1' stop-color='${shad}' stop-opacity='1'/>
        </linearGradient>
        <linearGradient id='sky' x1='0' y1='0' x2='0' y2='1'>
          <stop offset='0' stop-color='${bg}' stop-opacity='1'/>
          <stop offset='1' stop-color='#0a0a0a' stop-opacity='1'/>
        </linearGradient>
      </defs>
      <rect width='80' height='56' fill='url(#sky)'/>
      <path d='M8 40 L14 30 Q18 25 26 24 L52 24 Q60 25 64 30 L72 40 L72 46 L8 46 Z' fill='url(#g)' stroke='${shad}' stroke-width='0.5'/>
      <path d='M20 30 Q24 26 28 26 L50 26 Q55 26 58 30 L58 34 L20 34 Z' fill='${hl}' opacity='0.5'/>
      <circle cx='22' cy='44' r='5' fill='#0a0a0a'/>
      <circle cx='22' cy='44' r='2.5' fill='${shad}'/>
      <circle cx='58' cy='44' r='5' fill='#0a0a0a'/>
      <circle cx='58' cy='44' r='2.5' fill='${shad}'/>
      <rect x='10' y='38' width='3' height='2' fill='${hl}' opacity='0.8'/>
      <rect x='67' y='38' width='3' height='2' fill='#ff5555' opacity='0.9'/>
    </svg>
  `;
  return `url("data:image/svg+xml;utf8,${encodeURIComponent(svg)}")`;
}

// Sample feed with colored car "thumbnails"
const SOURCE_FEED = [
  { id: 1,  img: carThumb(220, 20, 35), title: 'VW Golf 1.6 TDI, 120k, 2014', meta: 'Wien · 38s · €8,900', match: false },
  { id: 2,  img: carThumb(210, 70, 35), title: 'BMW 320d xDrive Touring, 2018', meta: 'München · 12s · €18,400', match: true },
  { id: 3,  img: carThumb(0,   70, 55), title: 'Fiat 500 1.2, 98k, 2016', meta: 'Milano · 42s · €6,200', match: false },
  { id: 4,  img: carThumb(200, 10, 20), title: 'Audi A4 Avant 2.0 TDI, 2019', meta: 'Graz · 8s · €22,800', match: true, quote: false },
  { id: 5,  img: carThumb(30,  60, 50), title: 'Opel Corsa 1.4, 62k, 2017', meta: 'Berlin · 51s · €7,400', match: false },
  { id: 6,  img: carThumb(200, 5,  92), title: 'Mercedes C220d T-Modell, 2020', meta: 'Hamburg · 15s · on request', match: true, quote: true },
  { id: 7,  img: carThumb(330, 50, 30), title: 'Renault Clio dCi, 145k, 2013', meta: 'Lyon · 56s · €4,800', match: false },
  { id: 8,  img: carThumb(215, 60, 25), title: 'BMW 530d xDrive, 88k, 2021', meta: 'Zürich · 4s · CHF 41,200', match: true },
  { id: 9,  img: carThumb(200, 8,  75), title: 'Hyundai i10, 78k, 2018', meta: 'Roma · 48s · €5,900', match: false },
  { id: 10, img: carThumb(145, 35, 30), title: 'Volvo V60 D4, 74k, 2020', meta: 'Göteborg · 22s · €24,300', match: true },
  { id: 11, img: carThumb(0,   80, 40), title: 'Porsche Macan S, 52k, 2019', meta: 'Salzburg · 6s · on request', match: true, quote: true },
  { id: 12, img: carThumb(270, 40, 30), title: 'Skoda Fabia 1.0, 2017', meta: 'Praha · 58s · €7,100', match: false },
];

// Timeline (seconds) — fast & punchy, ~14s loop showing 5 matches
const TIMELINE = [
  { at: 0.3, ev: 'src',  row: 0 },
  { at: 0.9, ev: 'src',  row: 1 },
  { at: 1.4, ev: 'pick', row: 1 }, // BMW 320d
  { at: 1.6, ev: 'app',  row: 1 },
  { at: 2.3, ev: 'src',  row: 2 },
  { at: 2.9, ev: 'src',  row: 3 },
  { at: 3.4, ev: 'pick', row: 3 }, // Audi A4
  { at: 3.6, ev: 'app',  row: 3 },
  { at: 4.4, ev: 'src',  row: 4 },
  { at: 5.1, ev: 'src',  row: 5 },
  { at: 5.6, ev: 'pick', row: 5 }, // Mercedes
  { at: 5.8, ev: 'app',  row: 5 },
  { at: 6.6, ev: 'src',  row: 6 },
  { at: 7.2, ev: 'src',  row: 7 },
  { at: 7.7, ev: 'pick', row: 7 }, // BMW 530d
  { at: 7.9, ev: 'app',  row: 7 },
  { at: 8.7, ev: 'src',  row: 8 },
  { at: 9.3, ev: 'src',  row: 9 },
  { at: 9.8, ev: 'pick', row: 9 }, // Volvo V60
  { at: 10.0, ev: 'app', row: 9 },
  { at: 10.8, ev: 'src', row: 10 },
  { at: 11.3, ev: 'pick',row: 10 }, // Porsche Macan
  { at: 11.5, ev: 'app', row: 10 },
];

const WALL_DURATION = 13; // seconds of real playback — fast
const CLOCK_MAX_MS = 900;  // "sub-second" displayed latency

function DemoReplay() {
  const [t, setT] = useState(0);
  const [started, setStarted] = useState(false);
  const [loopCount, setLoopCount] = useState(0);
  const rafRef = useRef(null);
  const startRef = useRef(null);
  const containerRef = useRef(null);

  // Scroll-trigger: start only when in view
  useEffect(() => {
    if (!containerRef.current) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !started) {
            setStarted(true);
          }
        });
      },
      { threshold: 0.35 }
    );
    observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, [started]);

  // Run animation — loops on completion
  useEffect(() => {
    if (!started) return;
    startRef.current = performance.now();
    const tick = (now) => {
      const elapsed = (now - startRef.current) / 1000;
      if (elapsed >= WALL_DURATION) {
        // pause briefly then loop
        setT(WALL_DURATION);
        setTimeout(() => {
          startRef.current = performance.now();
          setT(0);
          setLoopCount((c) => c + 1);
          rafRef.current = requestAnimationFrame(tick);
        }, 1200);
        return;
      }
      setT(elapsed);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [started, loopCount]);

  // Timeline progress is already in wall-clock
  const progressSec = t;

  const visibleSrcIdx = TIMELINE.filter((e) => e.ev === 'src' && e.at <= progressSec).map((e) => e.row);
  const pickedRows = new Set(TIMELINE.filter((e) => e.ev === 'pick' && e.at <= progressSec).map((e) => e.row));
  const appEvents = TIMELINE.filter((e) => e.ev === 'app' && e.at <= progressSec);
  const appRows = appEvents.map((e) => ({ ...SOURCE_FEED[e.row], addedAt: e.at }));
  const flashIds = new Set(
    TIMELINE.filter((e) => e.ev === 'app' && e.at <= progressSec && progressSec - e.at < 1.2).map((e) => e.row)
  );

  // Sub-second "latency" display pulses between 180–920ms to feel alive
  const latencyMs = 180 + Math.round((Math.sin(t * 6) + 1) * 350);
  const pct = Math.min(100, (t / WALL_DURATION) * 100);

  return (
    <div className="hero__demo" ref={containerRef} data-demo-replay>
      {/* Header */}
      <div className="demo-head">
        <div className="demo-dots">
          <span /><span /><span />
        </div>
        <div className="demo-title">autoviz.live · live feed</div>
        <div className="demo-timer">
          <span className="lv" />
          LATENCY {String(latencyMs).padStart(3, '0')}ms
        </div>
      </div>

      {/* Split body */}
      <div className="demo-split">
        {/* Left: source site */}
        <div className="demo-pane">
          <div className="demo-pane__label" style={{ color: '#F97316' }}>
            AutoScout24.de · new listings
          </div>
          <div className="src-rows">
            {SOURCE_FEED.slice(0, Math.max(visibleSrcIdx.length, 1)).map((row, i) => {
              const isVisible = visibleSrcIdx.includes(i);
              const isPicked = pickedRows.has(i);
              const isFiltered = isVisible && !row.match;
              if (!isVisible) return null;
              return (
                <div
                  key={`${loopCount}-${i}`}
                  className={`src-row ${isPicked ? 'is-picked' : ''} ${isFiltered ? 'is-filtered' : ''}`}
                >
                  <div className="src-row__thumb" style={{ backgroundImage: row.img }} />
                  <div className="src-row__body">
                    <div className="src-row__title">{row.title}</div>
                    <div className="src-row__meta">{row.meta}</div>
                  </div>
                  <div className="src-row__flag">
                    {isPicked ? '✓ MATCH' : isFiltered ? 'skip' : ''}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Right: AutoViz /app */}
        <div className="demo-pane">
          <div className="demo-pane__label" style={{ color: 'var(--accent)' }}>
            AutoViz /app · BMW &amp; Premium set
          </div>
          <div className="app-rows">
            {appRows.length === 0 && (
              <div className="app-empty">
                <div className="app-empty__pulse" />
                Monitoring 4 sources…
              </div>
            )}
            {appRows.map((row, i) => (
              <div
                key={`${loopCount}-a-${row.id}`}
                className={`app-row ${flashIds.has(row.id - 1) ? 'is-flash' : ''}`}
                style={{ animationDelay: `${i * 0.03}s` }}
              >
                <div className="app-row__thumb" style={{ backgroundImage: row.img }} />
                <div className="app-row__body">
                  <div className="app-row__title">{row.title}</div>
                  <div className="app-row__meta">
                    {row.meta.split(' · ').slice(0, 2).join(' · ')}
                    <span className="app-row__verify"> · ✓ AI verified</span>
                  </div>
                </div>
                {row.quote ? (
                  <div className="app-row__price app-row__price--quote">
                    <span>On request</span>
                    <button className="app-row__quote-btn" type="button">Ask price</button>
                  </div>
                ) : (
                  <div className="app-row__price">{row.meta.split('·').pop().trim()}</div>
                )}
                {flashIds.has(row.id - 1) && <span className="app-row__new">NEW</span>}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Footer */}
      <div className="demo-foot">
        <span>
          Scanned <b>{visibleSrcIdx.length}</b> · Matched <b>{appRows.length}</b> · First alert in <b>1.4s</b>
        </span>
        <div className="demo-progress">
          <div className="demo-progress__fill" style={{ width: `${pct}%` }} />
        </div>
        <span className="demo-loop">
          {!started ? 'PAUSED' : 'LIVE · LOOPING'}
        </span>
      </div>
    </div>
  );
}

Object.assign(window, { DemoReplay });
