# #106 — Segmented Scroll-Snap Story/Chapter Scrubber

> Multi-chapter visual story viewer with animated segmented progress bars, tap zones, hold-to-pause, and swipe navigation.

## Metadata

- **Index**: #106
- **Slug**: `segmented-story-scrubber`
- **Kind**: `ui`
- **Family**: Media & Stories
- **Theme**: `dark`
- **Mobile Strength**: `native-first`
- **Tags**: `story-scrubber`, `segmented-progress`, `chapter-viewer`, `data-story`, `tap-zones`
- **Best For**: Year-in-review data recaps, Visual product onboarding, Editorial photo essays, Fitness & activity highlights
- **Real-World Inspiration**: [Strava](https://www.strava.com)
- **Detail Page**: https://templates.michaelpitts.net/t/segmented-story-scrubber
- **Live Demo**: https://templates.michaelpitts.net/demos/segmented-story-scrubber.html
- **JSON API**: https://templates.michaelpitts.net/api/templates/segmented-story-scrubber

## Why This Aesthetic Is Unique

Packages data recaps, onboarding narratives, or editorial chapters into bite-sized full-bleed frames with instant temporal orientation at the top edge.

## Color Palette

| Role | Name | Hex |
|------|------|-----|
| `canvas` | Volcanic Slate | `#101216` |
| `surface` | Track Charcoal | `#1B1F27` |
| `ink` | Finish Line White | `#F8FAFC` |
| `accent` | Blaze Orange | `#FC4C02` |
| `muted` | Pacer Silver | `#94A3B8` |

## Typography

- **Display**: `Barlow Condensed`
- **Body**: `Inter`
- **Mono**: `JetBrains Mono`
- **Scale Notes**: Hero condensed athletic numerals (48-68px) anchored over clean 14px narrative captions.
- **Google Fonts**: https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@700;800&family=Inter:wght@400;600&family=JetBrains+Mono:wght@600&display=swap
  ```html
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@700;800&family=Inter:wght@400;600&family=JetBrains+Mono:wght@600&display=swap">
  ```

## Layout Architecture

Full-height vertical story frame on mobile that centers as a sleek 9:16 theatre card with side Prev/Next arrows and chapter dots on desktop.

## Interaction & Micro-Motion Rules

Auto-advancing timer fills the active top progress segment; tapping left/right thirds jumps chapters, pressing and holding pauses playback, and clicking any top bar jumps directly.

## Mobile & Responsive Rules

Generous edge tap zones avoid accidental misses while bottom controls remain safely clear of interactive content.

## Agent Guardrails

### DO
- Provide an explicit Pause/Play toggle in addition to press-and-hold for accessibility and reduced-motion comfort
- Make each segmented progress bar directly clickable so users can jump to any chapter
- Keep text concise enough to read comfortably within a 5-7 second story interval

### DON'T
- Do not auto-advance while a user is actively interacting with buttons inside a story slide
- Do not stretch portrait story frames uncomfortably across 1280px desktop screens without framing

## Complete Standalone Starter Code

File: `demos/segmented-story-scrubber.html`

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PaceReplay — Segmented Story Chapter Scrubber</title>
<style>
  :root {
    --canvas: #101216;
    --surface: #1B1F27;
    --ink: #F8FAFC;
    --muted: #94A3B8;
    --accent: #FC4C02;
    --accent-soft: rgba(252, 76, 2, 0.22);
    --border: rgba(255, 255, 255, 0.1);
  }

  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    -webkit-tap-highlight-color: transparent;
  }

  html, body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: var(--canvas);
    color: var(--ink);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;
    user-select: none;
  }

  .shell {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 28px;
    padding: 0;
  }

  /* Desktop Chapter Sidebar (hidden on mobile) */
  .desktop-nav {
    display: none;
    flex-direction: column;
    gap: 10px;
    width: 240px;
  }

  .desktop-nav h2 {
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.09em;
    color: var(--muted);
    margin-bottom: 4px;
  }

  .chap-pill {
    min-height: 48px;
    padding: 10px 14px;
    border-radius: 14px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--muted);
    text-align: left;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font: inherit;
    font-size: 13.5px;
    font-weight: 600;
    transition: all 0.18s ease;
  }

  .chap-pill.active {
    border-color: var(--accent);
    background: rgba(252, 76, 2, 0.14);
    color: var(--ink);
  }

  .chap-num {
    font-size: 11px;
    font-weight: 800;
    color: var(--accent);
  }

  /* Story Viewer Frame */
  .story-frame {
    position: relative;
    width: 100%;
    height: 100%;
    background: var(--surface);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    touch-action: pan-y;
  }

  /* Ambient chapter glow */
  .ambient-glow {
    position: absolute;
    inset: -20%;
    background: radial-gradient(circle at 50% 18%, rgba(252, 76, 2, 0.28), transparent 58%);
    transition: background 0.45s ease;
    pointer-events: none;
  }

  /* Top Segmented Scrubber Bars */
  .scrubber-top {
    position: relative;
    z-index: 20;
    padding: max(14px, env(safe-area-inset-top)) 14px 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .segments {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 6px;
  }

  .seg-btn {
    height: 22px;
    display: flex;
    align-items: center;
    background: transparent;
    border: none;
    cursor: pointer;
    padding: 0;
  }

  .seg-track {
    width: 100%;
    height: 4px;
    border-radius: 999px;
    background: rgba(255, 255, 255, 0.2);
    overflow: hidden;
  }

  .seg-fill {
    height: 100%;
    width: 0%;
    background: var(--accent);
    border-radius: 999px;
  }

  .story-meta-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }

  .athlete-id {
    display: flex;
    align-items: center;
    gap: 9px;
  }

  .avatar {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    background: linear-gradient(135deg, #FC4C02, #FB923C);
    display: grid;
    place-items: center;
    font-weight: 900;
    font-size: 13px;
    color: #fff;
  }

  .athlete-name {
    font-size: 13.5px;
    font-weight: 700;
    line-height: 1.2;
  }

  .athlete-sub {
    font-size: 11.5px;
    color: var(--muted);
  }

  .top-controls {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .ctrl-btn {
    min-width: 44px;
    min-height: 44px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: rgba(16, 18, 22, 0.55);
    color: var(--ink);
    display: grid;
    place-items: center;
    cursor: pointer;
    font-size: 12px;
    font-weight: 700;
    padding: 0 10px;
  }

  .pause-pill {
    position: absolute;
    top: 86px;
    left: 50%;
    transform: translateX(-50%) scale(0.9);
    background: rgba(16, 18, 22, 0.85);
    border: 1px solid var(--border);
    color: var(--ink);
    font-size: 11px;
    font-weight: 800;
    letter-spacing: 0.1em;
    padding: 5px 12px;
    border-radius: 999px;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.18s ease, transform 0.18s ease;
    z-index: 25;
  }

  .story-frame.paused .pause-pill {
    opacity: 1;
    transform: translateX(-50%) scale(1);
  }

  /* Chapter Slide Content */
  .story-stage {
    position: relative;
    z-index: 10;
    flex: 1;
    padding: 12px 20px 24px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    cursor: pointer;
  }

  .kicker {
    font-size: 12px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: 0.1em;
    color: var(--accent);
    margin-bottom: 6px;
  }

  .hero-stat {
    font-size: clamp(44px, 11vw, 62px);
    font-weight: 900;
    letter-spacing: -0.04em;
    line-height: 0.98;
    font-variant-numeric: tabular-nums;
  }

  .hero-stat small {
    font-size: 20px;
    font-weight: 700;
    color: var(--muted);
    margin-left: 4px;
  }

  .hero-caption {
    margin-top: 10px;
    font-size: 15px;
    line-height: 1.5;
    color: #CBD5E1;
    max-width: 340px;
  }

  /* Visualization Card */
  .viz-card {
    background: rgba(16, 18, 22, 0.72);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 16px;
    margin: 14px 0;
  }

  .viz-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    color: var(--muted);
    font-weight: 600;
    margin-bottom: 10px;
  }

  .viz-svg {
    width: 100%;
    height: 168px;
    display: block;
  }

  /* Bottom Telemetry Grid */
  .metrics-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }

  .metric-box {
    background: rgba(255, 255, 255, 0.04);
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 11px 10px;
  }

  .metric-val {
    font-size: 16px;
    font-weight: 800;
    font-variant-numeric: tabular-nums;
  }

  .metric-lbl {
    font-size: 11px;
    color: var(--muted);
    margin-top: 2px;
  }

  .tap-hint {
    margin-top: 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 11.5px;
    color: var(--muted);
  }

  @media (min-width: 900px) {
    .shell {
      padding: 24px;
    }

    .desktop-nav {
      display: flex;
    }

    .story-frame {
      width: 410px;
      height: min(760px, calc(100vh - 48px));
      border-radius: 30px;
      border: 1px solid var(--border);
      box-shadow: 0 28px 72px rgba(0, 0, 0, 0.65);
    }
  }
</style>
</head>
<body>
<div class="shell">
  <!-- Desktop Chapter Index -->
  <aside class="desktop-nav" aria-label="Story chapters">
    <h2>2026 Season Recap</h2>
    <div id="desktopChapters"></div>
    <p style="font-size:12px;color:#94A3B8;margin-top:8px;line-height:1.5;">
      Tap left/right of the card, swipe horizontally, hold to pause, or use Arrow keys &amp; Space.
    </p>
  </aside>

  <!-- Main Story Viewer -->
  <section id="storyFrame" class="story-frame" aria-label="Season recap story viewer">
    <div id="ambientGlow" class="ambient-glow"></div>

    <header class="scrubber-top">
      <div id="segments" class="segments" role="tablist" aria-label="Chapter progress"></div>
      <div class="story-meta-bar">
        <div class="athlete-id">
          <div class="avatar">MR</div>
          <div>
            <div class="athlete-name">Maya Reyes</div>
            <div class="athlete-sub" id="chapterSubtitle">Chapter 1 of 5 &middot; Season Totals</div>
          </div>
        </div>
        <div class="top-controls">
          <button id="pauseBtn" class="ctrl-btn" type="button" aria-label="Pause or resume story">Pause</button>
        </div>
      </div>
    </header>

    <div class="pause-pill">PAUSED</div>

    <div id="storyStage" class="story-stage">
      <div>
        <div id="kicker" class="kicker"></div>
        <div id="heroStat" class="hero-stat"></div>
        <p id="heroCaption" class="hero-caption"></p>
      </div>

      <div class="viz-card">
        <div class="viz-head">
          <span id="vizTitle"></span>
          <span id="vizMeta" style="color:#FC4C02;"></span>
        </div>
        <div id="vizContainer"></div>
      </div>

      <div>
        <div id="metricsGrid" class="metrics-grid"></div>
        <div class="tap-hint">
          <span>&larr; Tap left for prev</span>
          <span>Hold to pause</span>
          <span>Tap right for next &rarr;</span>
        </div>
      </div>
    </div>
  </section>
</div>

<script>
(() => {
  const DURATION_MS = 6500;

  const CHAPTERS = [
    {
      name: 'Season Totals',
      kicker: '2026 Endurance Summary',
      stat: '1,482',
      unit: 'km',
      caption: 'Your highest-volume year on record—19% farther than last season across trail runs and tempo road blocks.',
      glow: 'radial-gradient(circle at 50% 16%, rgba(252, 76, 2, 0.30), transparent 60%)',
      vizTitle: 'Monthly Distance (km)',
      vizMeta: 'Peak: Oct (168 km)',
      metrics: [
        { val: '184h', lbl: 'Active Time' },
        { val: '214', lbl: 'Activities' },
        { val: '+24.6k m', lbl: 'Total Climb' }
      ],
      svg: () => {
        const vals = [92, 108, 124, 118, 136, 142, 128, 149, 152, 168, 134, 131];
        const bars = vals.map((v, i) => {
          const h = (v / 175) * 126;
          const x = 14 + i * 28;
          const y = 142 - h;
          const fill = i === 9 ? '#FC4C02' : '#334155';
          return `<rect x="${x}" y="${y.toFixed(1)}" width="18" height="${h.toFixed(1)}" rx="5" fill="${fill}"/>`;
        }).join('');
        return `<svg class="viz-svg" viewBox="0 0 360 160" aria-hidden="true">${bars}<line x1="10" y1="146" x2="350" y2="146" stroke="rgba(255,255,255,0.12)"/></svg>`;
      }
    },
    {
      name: 'Fastest 10K PR',
      kicker: 'Breakthrough Effort',
      stat: '41:18',
      unit: 'PR',
      caption: 'Negative split on the Bayfront Autumn 10K, closing the final two kilometers at 3:56 /km.',
      glow: 'radial-gradient(circle at 50% 16%, rgba(56, 189, 248, 0.25), transparent 60%)',
      vizTitle: 'Kilometer Split Pace',
      vizMeta: 'Avg 4:07 /km',
      metrics: [
        { val: '176 bpm', lbl: 'Avg HR' },
        { val: '184 spm', lbl: 'Cadence' },
        { val: '-1:14', lbl: 'vs Old PR' }
      ],
      svg: () => `
        <svg class="viz-svg" viewBox="0 0 360 160" aria-hidden="true">
          <defs>
            <linearGradient id="paceGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stop-color="#FC4C02" stop-opacity="0.45"/>
              <stop offset="100%" stop-color="#FC4C02" stop-opacity="0"/>
            </linearGradient>
          </defs>
          <path d="M16 112 L52 104 L88 98 L124 94 L160 88 L196 82 L232 72 L268 62 L304 44 L340 30 L340 145 L16 145 Z" fill="url(#paceGrad)"/>
          <path d="M16 112 L52 104 L88 98 L124 94 L160 88 L196 82 L232 72 L268 62 L304 44 L340 30" fill="none" stroke="#FC4C02" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
          <circle cx="340" cy="30" r="6" fill="#F8FAFC" stroke="#FC4C02" stroke-width="3"/>
          <text x="275" y="24" fill="#F8FAFC" font-size="11" font-weight="700">3:56 /km</text>
        </svg>
      `
    },
    {
      name: 'Biggest Climb',
      kicker: 'King of the Ridge',
      stat: '+1,340',
      unit: 'm',
      caption: 'Continuous coastal ascent up Mt. Tamalpais East Peak through morning marine fog.',
      glow: 'radial-gradient(circle at 50% 16%, rgba(245, 158, 11, 0.25), transparent 60%)',
      vizTitle: 'Summit Elevation Profile',
      vizMeta: 'Max Grade 14.2%',
      metrics: [
        { val: '784 m', lbl: 'High Point' },
        { val: '2h 48m', lbl: 'Moving Time' },
        { val: '1,620', lbl: 'Calories' }
      ],
      svg: () => `
        <svg class="viz-svg" viewBox="0 0 360 160" aria-hidden="true">
          <defs>
            <linearGradient id="climbGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stop-color="#FB923C" stop-opacity="0.5"/>
              <stop offset="100%" stop-color="#FB923C" stop-opacity="0.02"/>
            </linearGradient>
          </defs>
          <path d="M14 142 L68 124 L118 96 L165 72 L218 28 L272 68 L314 106 L346 132 L346 146 L14 146 Z" fill="url(#climbGrad)"/>
          <path d="M14 142 L68 124 L118 96 L165 72 L218 28 L272 68 L314 106 L346 132" fill="none" stroke="#FB923C" stroke-width="3.5" stroke-linejoin="round"/>
          <line x1="218" y1="28" x2="218" y2="146" stroke="rgba(255,255,255,0.22)" stroke-dasharray="4 4"/>
          <circle cx="218" cy="28" r="6" fill="#FC4C02" stroke="#fff" stroke-width="2.5"/>
          <text x="228" y="32" fill="#F8FAFC" font-size="11" font-weight="700">East Peak 784m</text>
        </svg>
      `
    },
    {
      name: 'Signature Route',
      kicker: 'Most-Run Loop',
      stat: '21.4',
      unit: 'km',
      caption: 'Golden Gate Dawn Loop—completed 14 times this year, mostly before 7:00 AM.',
      glow: 'radial-gradient(circle at 50% 16%, rgba(52, 211, 153, 0.24), transparent 60%)',
      vizTitle: 'GPS Trace Telemetry',
      vizMeta: '14x Logged',
      metrics: [
        { val: '6:12 AM', lbl: 'Avg Start' },
        { val: '4:42 /km', lbl: 'Route Avg' },
        { val: '382 m', lbl: 'Loop Gain' }
      ],
      svg: () => `
        <svg class="viz-svg" viewBox="0 0 360 160" aria-hidden="true">
          <g stroke="rgba(255,255,255,0.06)" stroke-width="1">
            <line x1="0" y1="40" x2="360" y2="40"/><line x1="0" y1="80" x2="360" y2="80"/><line x1="0" y1="120" x2="360" y2="120"/>
            <line x1="90" y1="0" x2="90" y2="160"/><line x1="180" y1="0" x2="180" y2="160"/><line x1="270" y1="0" x2="270" y2="160"/>
          </g>
          <path d="M58 112 C42 62, 108 26, 178 44 C236 58, 298 34, 312 86 C322 126, 224 138, 162 118 C118 104, 78 140, 58 112 Z" fill="none" stroke="rgba(252,76,2,0.28)" stroke-width="11"/>
          <path d="M58 112 C42 62, 108 26, 178 44 C236 58, 298 34, 312 86 C322 126, 224 138, 162 118 C118 104, 78 140, 58 112 Z" fill="none" stroke="#FC4C02" stroke-width="3.5" stroke-linecap="round"/>
          <circle cx="58" cy="112" r="6" fill="#34D399" stroke="#101216" stroke-width="2"/>
          <circle cx="312" cy="86" r="5" fill="#F8FAFC"/>
        </svg>
      `
    },
    {
      name: 'Consistency Streak',
      kicker: 'Unbroken Momentum',
      stat: '26',
      unit: 'wks',
      caption: 'Half a year without missing a weekly training block—putting you in the top 4% of club athletes.',
      glow: 'radial-gradient(circle at 50% 16%, rgba(252, 76, 2, 0.34), transparent 60%)',
      vizTitle: '12-Week Activity Heatmap',
      vizMeta: 'Top 4% Club',
      metrics: [
        { val: '5.1 /wk', lbl: 'Avg Days' },
        { val: '94%', lbl: 'Plan Hit' },
        { val: '1,240', lbl: 'Kudos' }
      ],
      svg: () => {
        const levels = [
          [1,2,0,3,2,1,3,2,3,1,2,3],
          [2,1,2,2,0,2,3,1,2,3,2,2],
          [0,2,3,1,2,3,1,2,3,2,1,3],
          [2,3,1,2,3,2,2,3,1,2,3,2],
          [1,0,2,3,2,1,3,2,2,3,2,1]
        ];
        const fills = ['#252A36', '#7C2D12', '#C2410C', '#FC4C02'];
        let cells = '';
        for (let r = 0; r < 5; r++) {
          for (let c = 0; c < 12; c++) {
            cells += `<rect x="${18 + c * 27}" y="${16 + r * 26}" width="20" height="20" rx="5" fill="${fills[levels[r][c]]}"/>`;
          }
        }
        return `<svg class="viz-svg" viewBox="0 0 360 160" aria-hidden="true">${cells}</svg>`;
      }
    }
  ];

  const storyFrame = document.getElementById('storyFrame');
  const storyStage = document.getElementById('storyStage');
  const segmentsEl = document.getElementById('segments');
  const desktopChapters = document.getElementById('desktopChapters');
  const pauseBtn = document.getElementById('pauseBtn');

  let currentIdx = 0;
  let elapsed = 0;
  let paused = false;
  let holdPaused = false;
  let lastTs = performance.now();

  // Build segment bars & desktop nav
  segmentsEl.innerHTML = CHAPTERS.map((c, i) => `
    <button class="seg-btn" data-seg="${i}" type="button" aria-label="Jump to chapter ${i + 1}: ${c.name}">
      <span class="seg-track"><span class="seg-fill" id="segFill-${i}"></span></span>
    </button>
  `).join('');

  desktopChapters.innerHTML = CHAPTERS.map((c, i) => `
    <button class="chap-pill" data-chap="${i}" type="button">
      <span>${c.name}</span>
      <span class="chap-num">0${i + 1}</span>
    </button>
  `).join('');

  function renderChapter() {
    const ch = CHAPTERS[currentIdx];
    document.getElementById('ambientGlow').style.background = ch.glow;
    document.getElementById('chapterSubtitle').textContent = `Chapter ${currentIdx + 1} of ${CHAPTERS.length} · ${ch.name}`;
    document.getElementById('kicker').textContent = ch.kicker;
    document.getElementById('heroStat').innerHTML = `${ch.stat}<small>${ch.unit}</small>`;
    document.getElementById('heroCaption').textContent = ch.caption;
    document.getElementById('vizTitle').textContent = ch.vizTitle;
    document.getElementById('vizMeta').textContent = ch.vizMeta;
    document.getElementById('vizContainer').innerHTML = ch.svg();
    document.getElementById('metricsGrid').innerHTML = ch.metrics.map(m => `
      <div class="metric-box">
        <div class="metric-val">${m.val}</div>
        <div class="metric-lbl">${m.lbl}</div>
      </div>
    `).join('');

    desktopChapters.querySelectorAll('.chap-pill').forEach((btn, i) => {
      btn.classList.toggle('active', i === currentIdx);
    });
    updateProgressBars();
  }

  function updateProgressBars() {
    for (let i = 0; i < CHAPTERS.length; i++) {
      const fill = document.getElementById(`segFill-${i}`);
      if (!fill) continue;
      if (i < currentIdx) fill.style.width = '100%';
      else if (i > currentIdx) fill.style.width = '0%';
      else fill.style.width = `${Math.min(100, (elapsed / DURATION_MS) * 100).toFixed(2)}%`;
    }
  }

  function goTo(idx) {
    currentIdx = (idx + CHAPTERS.length) % CHAPTERS.length;
    elapsed = 0;
    renderChapter();
  }

  function setPausedState(isPaused) {
    paused = isPaused;
    pauseBtn.textContent = paused ? 'Play' : 'Pause';
    storyFrame.classList.toggle('paused', paused || holdPaused);
  }

  // Scrubber segment click
  segmentsEl.addEventListener('click', (e) => {
    const btn = e.target.closest('[data-seg]');
    if (!btn) return;
    goTo(Number(btn.dataset.seg));
  });

  // Desktop nav click
  desktopChapters.addEventListener('click', (e) => {
    const btn = e.target.closest('[data-chap]');
    if (!btn) return;
    goTo(Number(btn.dataset.chap));
  });

  pauseBtn.addEventListener('click', () => setPausedState(!paused));

  // Tap left/right, press-and-hold to pause, and horizontal swipe
  let downX = 0;
  let downTime = 0;
  let holdTimer = null;

  storyStage.addEventListener('pointerdown', (e) => {
    downX = e.clientX;
    downTime = performance.now();
    holdTimer = setTimeout(() => {
      holdPaused = true;
      storyFrame.classList.add('paused');
    }, 180);
  });

  function finishPointer(e) {
    clearTimeout(holdTimer);
    const wasHold = holdPaused;
    holdPaused = false;
    storyFrame.classList.toggle('paused', paused);

    if (e.type === 'pointercancel' || wasHold) return;
    const dx = e.clientX - downX;
    const dt = performance.now() - downTime;

    if (Math.abs(dx) > 46) {
      goTo(dx < 0 ? currentIdx + 1 : currentIdx - 1);
    } else if (dt < 260) {
      const rect = storyStage.getBoundingClientRect();
      const relX = (e.clientX - rect.left) / rect.width;
      if (relX < 0.32) goTo(currentIdx - 1);
      else goTo(currentIdx + 1);
    }
  }

  storyStage.addEventListener('pointerup', finishPointer);
  storyStage.addEventListener('pointercancel', finishPointer);

  // Keyboard navigation
  window.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowRight') goTo(currentIdx + 1);
    else if (e.key === 'ArrowLeft') goTo(currentIdx - 1);
    else if (e.key === ' ') {
      e.preventDefault();
      setPausedState(!paused);
    }
  });

  // Animation loop
  function tick(ts) {
    const dt = Math.min(100, ts - lastTs);
    lastTs = ts;
    if (!paused && !holdPaused) {
      elapsed += dt;
      if (elapsed >= DURATION_MS) {
        goTo(currentIdx + 1);
      } else {
        updateProgressBars();
      }
    }
    requestAnimationFrame(tick);
  }

  renderChapter();
  requestAnimationFrame(tick);
})();
</script>
</body>
</html>
```
