/* ============================================================
   NeuralScout — Processing Timeline (How It Works)
   5 steps, horizontal, with active-step animation
   ============================================================ */

function Timeline() {
  const [active, setActive] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % 5), 3400);
    return () => clearInterval(id);
  }, []);

  const steps = [
    { n: '01', title: 'RTSP feed', sub: 'Paste your stream URL — we connect in seconds.', render: () => <StepRTSP active={active === 0} /> },
    { n: '02', title: 'Draw zones of interest', sub: 'Sketch polygons on any frame: lines, regions, counters.', render: () => <StepZones active={active === 1} /> },
    { n: '03', title: 'Vision AI processes Stream', sub: 'Streams are processed at 30 fps with sub-100ms latency with 95% accuracy.', render: () => <StepStream active={active === 2} /> },
    { n: '04', title: 'See it on the dashboard', sub: 'Charts, filters, alerts — grouped by camera, zone, time.', render: () => <StepDash active={active === 3} /> },
    { n: '05', title: 'Ask the VLM', sub: 'Type a question. The model applies it to every frame.', render: () => <StepQuery active={active === 4} /> },
  ];

  return (
    <div id="ns-timeline" style={tlStyles.wrap}>
      <div style={tlStyles.track}>
        {/* Connecting line */}
        <div style={tlStyles.line}>
          <div style={{
            ...tlStyles.lineFill,
            width: `${(active / 4) * 100}%`,
          }} />
        </div>

        {steps.map((s, i) => (
          <div key={i} style={tlStyles.step}>
            <div style={{
              ...tlStyles.dot,
              background: i <= active ? 'var(--ns-accent)' : 'var(--ns-bg-3)',
              borderColor: i <= active ? 'var(--ns-accent)' : 'var(--ns-line-2)',
              boxShadow: i === active ? '0 0 16px var(--ns-accent)' : 'none',
            }}>
              <span style={{
                fontFamily: 'var(--ns-mono)', fontSize: 10, fontWeight: 700,
                color: i <= active ? '#0a0a0a' : 'var(--ns-fg-dimmer)',
              }}>{s.n}</span>
            </div>
          </div>
        ))}
      </div>

      <div style={tlStyles.grid}>
        {steps.map((s, i) => (
          <div key={i} style={{
            ...tlStyles.card,
            borderColor: i === active ? 'var(--ns-accent)' : 'var(--ns-line)',
            background: i === active ? 'var(--ns-bg-2)' : 'var(--ns-bg-1)',
          }}>
            <div style={tlStyles.cardViz}>
              {s.render()}
            </div>
            <div style={{ padding: '14px 16px 18px' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 4 }}>
                <span className="ns-mono" style={{
                  fontSize: 10, color: i <= active ? 'var(--ns-accent)' : 'var(--ns-fg-dimmer)',
                  letterSpacing: '0.08em',
                }}>STEP_{s.n}</span>
              </div>
              <h4 style={tlStyles.cardTitle}>{s.title}</h4>
              <p style={tlStyles.cardSub}>{s.sub}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- step vizes ---- */

function StepRTSP({ active }) {
  const now = useTick();
  const t = (now % 2200) / 2200;
  const text = 'rtsp://10.0.1.44:554/stream1';
  const chars = active ? Math.floor(t * text.length * 1.3) : text.length;
  return (
    <div style={{ padding: 14, height: '100%', display: 'flex', flexDirection: 'column', gap: 8, justifyContent: 'center' }}>
      <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 9, color: 'var(--ns-fg-dimmer)', letterSpacing: '0.1em' }}>CAMERA URL</div>
      <div style={{
        padding: '10px 12px', border: '1px solid var(--ns-line-2)',
        background: 'var(--ns-bg)', fontFamily: 'var(--ns-mono)', fontSize: 12,
        color: 'var(--ns-fg)', letterSpacing: '0.02em',
      }}>
        {text.slice(0, chars)}
        {active && chars < text.length && <span style={{ display: 'inline-block', width: 6, height: 12, background: 'var(--ns-accent)', marginLeft: 2, verticalAlign: 'text-bottom', animation: 'ns-blink 1s steps(2) infinite' }} />}
      </div>
      <div style={{ display: 'flex', gap: 6, marginTop: 4, fontFamily: 'var(--ns-mono)', fontSize: 9 }}>
        <span style={{ padding: '2px 6px', background: 'var(--ns-lime-soft)', color: 'var(--ns-lime)', border: '1px solid var(--ns-lime)', letterSpacing: '0.06em' }}>● CONNECTED</span>
        <span style={{ padding: '2px 6px', color: 'var(--ns-fg-dimmer)' }}>30 FPS · 1080p</span>
      </div>
    </div>
  );
}

function StepZones({ active }) {
  const now = useTick();
  const t = active ? (now % 3000) / 3000 : 1;
  const pts1 = [[15, 45], [65, 38], [72, 82], [18, 88]];
  const pts2 = [[70, 20], [130, 25], [135, 62], [75, 60]];
  const drawLen1 = Math.min(1, t * 1.4);
  const drawLen2 = active ? Math.max(0, Math.min(1, (t - 0.35) * 1.4)) : 1;

  const makePath = (pts, frac) => {
    if (frac <= 0) return '';
    const n = pts.length;
    const total = n;
    const stop = frac * total;
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i <= stop && i <= n; i++) {
      const idx = i % n;
      d += ` L ${pts[idx][0]} ${pts[idx][1]}`;
    }
    return d;
  };

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', background: '#0c1018' }}>
      {/* mock feed */}
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg, #1a1f28 0%, #0c1018 100%)' }} />
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(90deg, var(--ns-line) 1px, transparent 1px)', backgroundSize: '16px 100%', opacity: 0.4 }} />
      <svg viewBox="0 0 160 100" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} preserveAspectRatio="none">
        <path d={makePath(pts1, drawLen1)} stroke="var(--ns-cyan)" strokeWidth="1.5" fill={drawLen1 >= 0.99 ? 'var(--ns-cyan-soft)' : 'none'} strokeDasharray="3 2" />
        <path d={makePath(pts2, drawLen2)} stroke="var(--ns-amber)" strokeWidth="1.5" fill={drawLen2 >= 0.99 ? 'var(--ns-amber-soft)' : 'none'} strokeDasharray="3 2" />
        {pts1.map(([x, y], i) => <circle key={i} cx={x} cy={y} r="1.5" fill="var(--ns-cyan)" />)}
        {pts2.map(([x, y], i) => <circle key={i} cx={x} cy={y} r="1.5" fill="var(--ns-amber)" />)}
        {/* cursor */}
        {active && drawLen1 < 1 && (
          <circle cx={pts1[Math.floor(drawLen1 * pts1.length) % pts1.length][0]} cy={pts1[Math.floor(drawLen1 * pts1.length) % pts1.length][1]} r="4" fill="none" stroke="var(--ns-cyan)" strokeWidth="1" />
        )}
      </svg>
    </div>
  );
}

function StepQuery({ active }) {
  const now = useTick();
  const q = 'flag anyone not wearing a hi-vis vest';
  const t = active ? (now % 4000) / 4000 : 1;
  const chars = active ? Math.floor(t * q.length * 1.6) : q.length;
  return (
    <div style={{ padding: 14, height: '100%', display: 'flex', flexDirection: 'column', gap: 8, justifyContent: 'center', background: '#0c1018' }}>
      <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 9, color: 'var(--ns-violet)', letterSpacing: '0.1em' }}>VLM · PROMPT</div>
      <div style={{
        padding: '10px 12px', border: '1px solid var(--ns-violet)', borderRadius: 2,
        background: 'var(--ns-violet-soft)', fontFamily: 'var(--ns-mono)', fontSize: 12,
        color: 'var(--ns-fg)',
      }}>
        › {q.slice(0, chars)}
        {active && chars < q.length && <span style={{ display: 'inline-block', width: 6, height: 12, background: 'var(--ns-violet)', marginLeft: 2, verticalAlign: 'text-bottom', animation: 'ns-blink 1s steps(2) infinite' }} />}
      </div>
      {chars >= q.length && (
        <div style={{ display: 'flex', gap: 6, fontFamily: 'var(--ns-mono)', fontSize: 9, animation: 'ns-lock .3s var(--ns-ease-snap)' }}>
          <span style={{ padding: '2px 6px', background: 'var(--ns-coral)', color: '#0a0a0a', fontWeight: 700, letterSpacing: '0.06em' }}>3 MATCHES</span>
          <span style={{ color: 'var(--ns-fg-dim)', padding: '2px 0' }}>active now</span>
        </div>
      )}
    </div>
  );
}

function StepStream({ active }) {
  const now = useTick();
  const t = (now % 1800) / 1800;
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', background: '#0c1018', padding: 14, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
      {/* Source */}
      <div style={{ textAlign: 'center' }}>
        <div style={{
          width: 46, height: 46, borderRadius: 4,
          background: 'var(--ns-bg-3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid var(--ns-line-2)',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ns-fg-dim)" strokeWidth="1.5">
            <rect x="2" y="7" width="14" height="10" rx="1" />
            <path d="M16 10l6-3v10l-6-3z" />
          </svg>
        </div>
        <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 8, marginTop: 6, color: 'var(--ns-fg-dim)' }}>FEED</div>
      </div>

      {/* Packets flowing */}
      <div style={{ flex: 1, position: 'relative', height: 30 }}>
        <div style={{ position: 'absolute', top: '50%', left: 0, right: 0, height: 1, background: 'var(--ns-line-2)' }} />
        {active && [0, 0.33, 0.66].map((offset, i) => {
          const p = ((t + offset) % 1);
          return (
            <div key={i} style={{
              position: 'absolute', top: '50%', left: `${p * 100}%`,
              width: 18, height: 8, transform: 'translate(-50%, -50%)',
              background: 'var(--ns-accent)',
              boxShadow: '0 0 10px var(--ns-accent)',
              borderRadius: 1,
            }}>
              <span style={{
                position: 'absolute', top: 10, left: '50%', transform: 'translateX(-50%)',
                fontFamily: 'var(--ns-mono)', fontSize: 7, color: 'var(--ns-accent)',
                whiteSpace: 'nowrap',
              }}>{Math.floor(p * 30)}ms</span>
            </div>
          );
        })}
      </div>

      {/* Server */}
      <div style={{ textAlign: 'center' }}>
        <div style={{
          width: 46, height: 46, borderRadius: 4,
          background: 'var(--ns-bg-3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: '1px solid var(--ns-line-2)',
          position: 'relative',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--ns-accent)" strokeWidth="1.5">
            <rect x="3" y="4" width="18" height="5" rx="1" />
            <rect x="3" y="11" width="18" height="5" rx="1" />
            <circle cx="7" cy="6.5" r="0.5" fill="var(--ns-lime)" />
            <circle cx="7" cy="13.5" r="0.5" fill="var(--ns-lime)" />
          </svg>
          {active && <div style={{
            position: 'absolute', inset: -4, border: '1px solid var(--ns-accent)',
            animation: 'ns-pulse 1.2s ease-in-out infinite',
          }} />}
        </div>
        <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 8, marginTop: 6, color: 'var(--ns-fg-dim)' }}>SERVER</div>
      </div>
    </div>
  );
}

function StepDash({ active }) {
  const now = useTick();
  const t = (now % 2500) / 2500;
  const bars = [0.3, 0.45, 0.6, 0.75, 0.85, 0.95, 0.7];
  return (
    <div style={{ padding: 14, height: '100%', background: '#0c1018', display: 'flex', flexDirection: 'column', gap: 8, justifyContent: 'center' }}>
      <div style={{ display: 'flex', gap: 6 }}>
        <div style={{ flex: 1, padding: '6px 8px', background: 'var(--ns-bg-2)', border: '1px solid var(--ns-line)' }}>
          <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 7, color: 'var(--ns-fg-dimmer)' }}>TODAY</div>
          <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 13, color: 'var(--ns-accent)', fontWeight: 600 }}>1,842</div>
        </div>
        <div style={{ flex: 1, padding: '6px 8px', background: 'var(--ns-bg-2)', border: '1px solid var(--ns-line)' }}>
          <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 7, color: 'var(--ns-fg-dimmer)' }}>DWELL</div>
          <div style={{ fontFamily: 'var(--ns-mono)', fontSize: 13, color: 'var(--ns-lime)', fontWeight: 600 }}>3m 42s</div>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 3, alignItems: 'flex-end', height: 36 }}>
        {bars.map((b, i) => (
          <div key={i} style={{
            flex: 1, height: `${b * 100}%`,
            background: active ? (i <= Math.floor(t * bars.length) ? 'var(--ns-accent)' : 'var(--ns-line-2)') : 'var(--ns-accent)',
            opacity: active ? 1 : 0.6,
            transition: 'all .3s',
          }} />
        ))}
      </div>
    </div>
  );
}

const tlStyles = {
  wrap: { display: 'flex', flexDirection: 'column', gap: 32 },
  track: {
    position: 'relative',
    display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
    padding: '0 20px',
  },
  line: {
    position: 'absolute', top: 14, left: 'calc(10% + 14px)', right: 'calc(10% + 14px)',
    height: 2, background: 'var(--ns-line)', borderRadius: 99, overflow: 'hidden',
  },
  lineFill: {
    height: '100%', background: 'var(--ns-accent)',
    transition: 'width 0.6s var(--ns-ease)',
    boxShadow: '0 0 12px var(--ns-accent)',
  },
  step: { display: 'flex', justifyContent: 'center', position: 'relative', zIndex: 1 },
  dot: {
    width: 30, height: 30, borderRadius: 99,
    border: '2px solid var(--ns-line-2)',
    background: 'var(--ns-bg-3)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    transition: 'all 0.4s var(--ns-ease)',
  },
  grid: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 },
  card: {
    border: '1px solid var(--ns-line)',
    background: 'var(--ns-bg-1)',
    borderRadius: 'var(--ns-r-3)',
    overflow: 'hidden',
    transition: 'all 0.4s var(--ns-ease)',
  },
  cardViz: {
    aspectRatio: '16/7',
    borderBottom: '1px solid var(--ns-line)',
    overflow: 'hidden',
    position: 'relative',
  },
  cardTitle: {
    fontSize: 17, margin: '2px 0 4px', fontWeight: 500,
    letterSpacing: '-0.01em',
  },
  cardSub: {
    fontSize: 13, color: 'var(--ns-fg-dim)', margin: 0, lineHeight: 1.5,
    textWrap: 'pretty',
  },
};

window.Timeline = Timeline;
