
function Timeline() {
  const [pos, setPos] = React.useState(72); // 0-100, scrub position
  const [playing, setPlaying] = React.useState(true);
  const cassetteRef = React.useRef(null);

  React.useEffect(() => {
    if (!playing) return;
    let raf;
    const tick = () => {
      setPos(p => p >= 100 ? 0 : p + 0.15);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing]);

  // Track for the scrub bar with simulated signal trace
  const ticks = 80;
  const sigData = React.useMemo(() => Array.from({length: ticks}, (_, i) => {
    const t = i / ticks;
    return 35 + 25 * Math.sin(t * 18) + 15 * Math.cos(t * 7) + (i > ticks * 0.5 ? 12 * Math.sin(t * 35) : 0);
  }), []);

  return (
    <section id="timeline" style={{ padding: "100px 2rem", background: "rgba(168,85,247,0.04)", position: "relative", overflow: "hidden" }}>
      {/* tape grain bg */}
      <div style={{ position: "absolute", inset: 0, opacity: 0.06, pointerEvents: "none",
        backgroundImage: "repeating-linear-gradient(90deg, rgba(168,85,247,0.4) 0 1px, transparent 1px 4px)" }} />

      <div style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>
        <SectionHeader
          tag="06 / Timeline · User Experience Focused"
          title="Rewind! What just happened?"
          subtitle="You never have to remember to start a recording. PECAN is always logging — every session, every lap. Quickly navigate through your data like a DJ spinning a record."
        />

        {/* Two-column: cassette visual + value props */}
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 48, marginTop: 56, alignItems: "center" }}>
          <div>
            {/* Cassette tape visual */}
            <div ref={cassetteRef} style={{
              background: "linear-gradient(135deg, #1a1820 0%, #0d0c11 100%)",
              border: "1px solid rgba(168,85,247,0.25)", borderRadius: 16, padding: "32px 28px",
              boxShadow: "0 0 60px rgba(168,85,247,0.15), inset 0 1px 0 rgba(255,255,255,0.05)",
            }}>
              {/* Reels */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
                {[0, 1].map(i => {
                  const C = 47, R_OUT = 42, R_HUB = 13, SPOKES = 5, SPOKE_W = 9;
                  const spokePaths = Array.from({length: SPOKES}, (_, s) => {
                    const a = (s / SPOKES) * Math.PI * 2 - Math.PI / 2;
                    const perp = a + Math.PI / 2;
                    const r0 = R_HUB, r1 = R_OUT - 3;
                    const hw0 = SPOKE_W / 2, hw1 = SPOKE_W * 0.45;
                    const x0a = C + r0 * Math.cos(a) + hw0 * Math.cos(perp);
                    const y0a = C + r0 * Math.sin(a) + hw0 * Math.sin(perp);
                    const x0b = C + r0 * Math.cos(a) - hw0 * Math.cos(perp);
                    const y0b = C + r0 * Math.sin(a) - hw0 * Math.sin(perp);
                    const x1a = C + r1 * Math.cos(a) + hw1 * Math.cos(perp);
                    const y1a = C + r1 * Math.sin(a) + hw1 * Math.sin(perp);
                    const x1b = C + r1 * Math.cos(a) - hw1 * Math.cos(perp);
                    const y1b = C + r1 * Math.sin(a) - hw1 * Math.sin(perp);
                    return `M${x0a.toFixed(1)},${y0a.toFixed(1)} L${x1a.toFixed(1)},${y1a.toFixed(1)} L${x1b.toFixed(1)},${y1b.toFixed(1)} L${x0b.toFixed(1)},${y0b.toFixed(1)}Z`;
                  });
                  // Outer rim arc segments (10 segments with small gaps)
                  const RIM_SEGS = 10;
                  const rimArcs = Array.from({length: RIM_SEGS}, (_, t) => {
                    const startA = (t / RIM_SEGS) * Math.PI * 2 - 0.15;
                    const endA = ((t + 0.75) / RIM_SEGS) * Math.PI * 2 - 0.15;
                    const x1 = C + R_OUT * Math.cos(startA), y1 = C + R_OUT * Math.sin(startA);
                    const x2 = C + R_OUT * Math.cos(endA), y2 = C + R_OUT * Math.sin(endA);
                    return `M${x1.toFixed(1)},${y1.toFixed(1)} A${R_OUT},${R_OUT} 0 0,1 ${x2.toFixed(1)},${y2.toFixed(1)}`;
                  });
                  return (
                    <svg key={i} width="94" height="94" viewBox="0 0 94 94"
                      style={{ animation: playing ? `${i ? "spinR" : "spinL"} 2.5s linear infinite` : "none", overflow: "visible" }}>
                      {/* 5 blade spokes — transparent gaps between them */}
                      {spokePaths.map((d, s) => (
                        <path key={s} d={d} fill="rgba(168,85,247,0.55)" />
                      ))}
                      {/* Outer rim — segmented arcs with gaps (= notches) */}
                      {rimArcs.map((d, t) => (
                        <path key={t} d={d} fill="none" stroke="rgba(168,85,247,0.75)" strokeWidth="5" strokeLinecap="butt" />
                      ))}
                      {/* Inner hub ring */}
                      <circle cx={C} cy={C} r={R_HUB} fill="rgba(26,24,38,0.9)" stroke="rgba(168,85,247,0.55)" strokeWidth="2" />
                      {/* Hub slots */}
                      {Array.from({length: 5}, (_, s) => {
                        const a = (s / 5) * Math.PI * 2 - Math.PI / 2;
                        const x = C + (R_HUB - 4) * Math.cos(a);
                        const y = C + (R_HUB - 4) * Math.sin(a);
                        return <circle key={s} cx={x.toFixed(1)} cy={y.toFixed(1)} r="2.5" fill="rgba(13,12,17,0.9)" />;
                      })}
                      {/* Center dot */}
                      <circle cx={C} cy={C} r={4.5} fill="rgba(214,171,57,0.95)" />
                    </svg>
                  );
                })}
              </div>

              {/* Tape window — signal scrub */}
              <div style={{
                background: "rgba(13,12,17,0.8)",
                border: "1px solid rgba(214,171,57,0.3)", borderRadius: 8,
                padding: "12px 14px", marginBottom: 18,
              }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, fontFamily: "'Space Mono', monospace", fontSize: 9, letterSpacing: 1 }}>
                  <span style={{ color: "#D6AB39" }}>● REC · ALWAYS</span>
                  <span style={{ color: "rgba(255,255,255,0.4)" }}>HOT 5min · COLD 1hr</span>
                </div>
                <svg viewBox="0 0 400 60" style={{ width: "100%", height: 60 }}>
                  {/* Scrub-position fill */}
                  <rect x="0" y="0" width={(pos / 100) * 400} height="60" fill="rgba(168,85,247,0.08)" />
                  {/* Signal trace */}
                  <polyline
                    points={sigData.map((v, i) => `${(i / (ticks - 1)) * 400},${v}`).join(" ")}
                    fill="none" stroke="#a855f7" strokeWidth="1.2" opacity="0.85"
                  />
                  <polyline
                    points={sigData.map((v, i) => `${(i / (ticks - 1)) * 400},${60 - (60 - v) * 0.6 + 5}`).join(" ")}
                    fill="none" stroke="#22d3ee" strokeWidth="1" opacity="0.6"
                  />
                  {/* Playhead */}
                  <line x1={(pos / 100) * 400} y1="0" x2={(pos / 100) * 400} y2="60" stroke="#D6AB39" strokeWidth="2" />
                  <circle cx={(pos / 100) * 400} cy="6" r="4" fill="#D6AB39" />
                </svg>

                {/* Scrubber */}
                <input type="range" min="0" max="100" step="0.1" value={pos}
                  onChange={e => { setPos(parseFloat(e.target.value)); setPlaying(false); }}
                  style={{ width: "100%", marginTop: 10, accentColor: "#D6AB39", cursor: "grab" }} />

                {/* Time markers */}
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontFamily: "'Space Mono', monospace", fontSize: 9, color: "rgba(255,255,255,0.3)" }}>
                  <span>-1:00:00</span>
                  <span>-30:00</span>
                  <span style={{ color: "#D6AB39" }}>● {Math.floor((pos / 100) * 60)}:{String(Math.floor(((pos / 100) * 60 * 60) % 60)).padStart(2, "0")}</span>
                  <span>NOW</span>
                </div>
              </div>

              {/* Controls */}
              <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
                {[
                  { l: "◀◀", a: () => { setPos(Math.max(0, pos - 10)); setPlaying(false); } },
                  { l: playing ? "❚❚" : "▶", a: () => setPlaying(!playing), prim: true },
                  { l: "▶▶", a: () => { setPos(Math.min(100, pos + 10)); setPlaying(false); } },
                  { l: "● LIVE", a: () => { setPos(100); setPlaying(true); } },
                ].map((b, i) => (
                  <button key={i} onClick={b.a} style={{
                    padding: "8px 16px", borderRadius: 6,
                    background: b.prim ? "rgba(214,171,57,0.2)" : "rgba(168,85,247,0.1)",
                    border: `1px solid ${b.prim ? "rgba(214,171,57,0.5)" : "rgba(168,85,247,0.3)"}`,
                    color: b.prim ? "#D6AB39" : "#c4b5fd",
                    fontFamily: "'Space Mono', monospace", fontSize: 11, fontWeight: 700, cursor: "pointer",
                    letterSpacing: 1, minWidth: 56,
                  }}>{b.l}</button>
                ))}
              </div>
            </div>

            <p style={{ fontFamily: "'Space Mono', monospace", fontSize: 10, color: "rgba(255,255,255,0.35)", textAlign: "center", marginTop: 14, letterSpacing: 1 }}>
              ↑ Live scrubber — drag to rewind through the session
            </p>
          </div>

          {/* Value props */}
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {[
              { color: "#D6AB39", title: "Always Recording", body: "No \"start recording\" button. Saves one hour of data and the buffer size is adjustable. By the time you realize something happened, it's already saved." },
              { color: "#a855f7", title: "Rewind at Any Time", body: "Drag the timeline like a DJ scratches a record. Every chart, sensor, and CAN message instantly jumps to that exact moment — no replay mode toggle." },
              { color: "#22d3ee", title: "Snapshot · Review", body: "Spot something interesting? Hit \"Add Checkpoint\" and come back later. You can also share .pecan file that saves your data, graph configurations, and checkpoints." },
              { color: "#ef4444", title: "Cold Storage in Browser", body: "Up to 500 MB of compressed binary frames live in OPFS. No server round-trip, no IT team, no SD card pull — your laptop is the recorder." },
            ].map(f => (
              <div key={f.title} style={{
                background: "rgba(32,32,47,0.6)", border: `1px solid ${f.color}25`,
                borderRadius: 12, padding: "20px 22px",
                borderLeft: `3px solid ${f.color}`,
              }}>
                <h3 style={{ fontWeight: 700, fontSize: 15, color: "#fff", marginBottom: 8, lineHeight: 1.3 }}>{f.title}</h3>
                <p style={{ fontSize: 13.5, color: "rgba(255,255,255,0.6)", lineHeight: 1.65 }}>{f.body}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes spinL { from { transform: rotate(0); } to { transform: rotate(-360deg); } }
        @keyframes spinR { from { transform: rotate(0); } to { transform: rotate(360deg); } }
      `}</style>
    </section>
  );
}

Object.assign(window, { Timeline });
