#101 ui light mobile: native-first Sheets & Drawers

Multi-Detent Draggable Bottom Sheet

Pointer-draggable sheet that snaps smoothly between peek, half, and full detents over live spatial context.

Inspired by Citymapper ↗

Download .html
Fullscreen ↗

WHY THIS AESTHETIC IS UNIQUE

Preserves background spatial context while letting one-handed thumb drags reveal progressively richer detail without jarring route transitions.

BEST FOR

Transit & navigation appsMap-backed discovery feedsContextual detail drawersOne-handed mobile workflows

TAGS

COLOR PALETTE (CLICK TO COPY HEX)

TYPOGRAPHY

Display
Plus Jakarta Sans
Body
Inter
Mono
JetBrains Mono
Scale
Bold tabular arrival countdowns paired with compact 13-15px route metadata and 18-22px sheet headers.

Google Fonts Stylesheet ↗

ARCHITECTURE & MOBILE NOTES

LAYOUT

Full-bleed spatial canvas behind a bottom-anchored sheet on mobile (18%/52%/88% detents) that converts into a docked left side drawer on desktop viewports.

INTERACTION

Pointer drag on the top grabber tracks velocity and distance to snap cleanly to the nearest detent, supplemented by accessible detent buttons and keyboard shortcuts.

MOBILE

Uses touch-action: none on the grabber handle to prevent rubber-band viewport scroll fighting, with >=44px tap targets and safe-area bottom padding.

AI AGENT GUARDRAILS

DO

  • Provide explicit detent snap buttons alongside drag gestures for accessibility and desktop mouse users
  • Lock internal scroll until the sheet reaches its full detent so drags never fight list scrolling
  • Convert the bottom sheet into a docked side panel above 900px so wide screens stay balanced

DON'T

  • Do not trap users in a full-height sheet without a visible collapse handle or Escape key handler
  • Do not rely solely on hover tooltips to explain drag affordances
STANDALONE SOURCE · demos/multi-detent-bottom-sheet.html (32.5 KB)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MetroPulse — Multi-Detent Bottom Sheet Transit Planner</title>
<style>
  :root {
    --canvas: #F7FAF8;
    --surface: #FFFFFF;
    --surface-2: #EEF5F0;
    --ink: #0F2419;
    --muted: #5A7063;
    --accent: #16A34A;
    --accent-dark: #15803D;
    --accent-soft: #DCFCE7;
    --border: #D9E6DE;
    --shadow-sm: 0 2px 8px rgba(15, 36, 25, 0.08);
    --shadow-lg: 0 -8px 32px rgba(15, 36, 25, 0.14);
    --line-green: #16A34A;
    --line-blue: #2563EB;
    --line-amber: #D97706;
    --line-teal: #0D9488;
    --radius-xl: 24px;
    --radius-md: 14px;
    --sheet-h: 52vh;
  }

  * {
    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;
    line-height: 1.4;
  }

  .app {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  /* Interactive Transit Map Backdrop */
  .map-stage {
    position: absolute;
    inset: 0;
    background: #EAF2EC;
    overflow: hidden;
    user-select: none;
  }

  .map-svg {
    width: 100%;
    height: 100%;
    display: block;
    transition: transform 0.35s cubic-bezier(0.22, 1, 0.36, 1);
    transform-origin: center center;
  }

  .route-path {
    fill: none;
    stroke-linecap: round;
    stroke-linejoin: round;
    transition: opacity 0.25s ease, stroke-width 0.25s ease;
  }

  .route-path.dimmed {
    opacity: 0.22;
  }

  .route-path.active {
    opacity: 1;
    filter: drop-shadow(0 3px 6px rgba(15, 36, 25, 0.22));
  }

  .pulse-ring {
    transform-origin: center;
    transform-box: fill-box;
    animation: pulseRing 2.2s ease-out infinite;
  }

  @keyframes pulseRing {
    0% { transform: scale(0.8); opacity: 0.85; }
    100% { transform: scale(2.4); opacity: 0; }
  }

  /* Floating Top Search Bar */
  .top-bar {
    position: absolute;
    top: 12px;
    left: 12px;
    right: 12px;
    z-index: 20;
    display: flex;
    flex-direction: column;
    gap: 8px;
    pointer-events: none;
  }

  .route-card-top {
    pointer-events: auto;
    background: rgba(255, 255, 255, 0.96);
    backdrop-filter: blur(12px);
    border: 1px solid var(--border);
    border-radius: 18px;
    padding: 10px 12px;
    box-shadow: var(--shadow-sm);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .trip-dots {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 3px;
    padding: 2px 0;
  }

  .dot-origin {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 2.5px solid var(--accent);
    background: #fff;
  }

  .dot-line {
    width: 2px;
    height: 14px;
    background: #B9CEC1;
    border-radius: 2px;
  }

  .dot-dest {
    width: 10px;
    height: 10px;
    border-radius: 3px;
    background: var(--ink);
  }

  .trip-endpoints {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .endpoint-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13.5px;
    font-weight: 600;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .endpoint-row span.tag {
    font-size: 11px;
    font-weight: 600;
    color: var(--muted);
    margin-left: 8px;
    flex-shrink: 0;
  }

  .endpoint-divider {
    height: 1px;
    background: var(--border);
  }

  .icon-btn {
    width: 44px;
    height: 44px;
    min-width: 44px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--ink);
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background 0.15s ease, transform 0.15s ease, border-color 0.15s ease;
  }

  .icon-btn:hover {
    background: var(--surface-2);
    border-color: #B7CFC0;
  }

  .icon-btn:active {
    transform: scale(0.95);
  }

  .status-strip {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    pointer-events: none;
  }

  .live-pill {
    pointer-events: auto;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(15, 36, 25, 0.88);
    color: #fff;
    font-size: 12px;
    font-weight: 600;
    padding: 6px 11px;
    border-radius: 999px;
    box-shadow: var(--shadow-sm);
  }

  .live-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #4ADE80;
    box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.28);
  }

  .map-controls {
    position: absolute;
    right: 12px;
    top: 132px;
    z-index: 15;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .map-controls .icon-btn {
    box-shadow: var(--shadow-sm);
    background: rgba(255, 255, 255, 0.95);
  }

  /* Bottom Sheet (Mobile Default) */
  .sheet {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: var(--sheet-h);
    background: var(--surface);
    border-top-left-radius: var(--radius-xl);
    border-top-right-radius: var(--radius-xl);
    box-shadow: var(--shadow-lg);
    border-top: 1px solid var(--border);
    z-index: 30;
    display: flex;
    flex-direction: column;
    transition: height 0.34s cubic-bezier(0.22, 1, 0.36, 1);
    will-change: height;
  }

  .sheet.dragging {
    transition: none;
  }

  .sheet-grab-zone {
    padding: 10px 16px 10px;
    cursor: grab;
    touch-action: none;
    user-select: none;
    flex-shrink: 0;
    border-bottom: 1px solid #ECF2EE;
  }

  .sheet-grab-zone:active {
    cursor: grabbing;
  }

  .grab-handle {
    width: 44px;
    height: 5px;
    border-radius: 999px;
    background: #C4D4CA;
    margin: 0 auto 10px;
    transition: background 0.15s ease, width 0.15s ease;
  }

  .sheet.dragging .grab-handle {
    background: var(--accent);
    width: 56px;
  }

  .sheet-header-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }

  .sheet-title-wrap h1 {
    font-size: 16px;
    font-weight: 700;
    letter-spacing: -0.01em;
  }

  .sheet-subtitle {
    font-size: 12.5px;
    color: var(--muted);
    font-variant-numeric: tabular-nums;
  }

  .detent-group {
    display: inline-flex;
    background: var(--surface-2);
    border-radius: 11px;
    padding: 3px;
    gap: 2px;
  }

  .detent-btn {
    min-height: 38px;
    min-width: 48px;
    padding: 0 9px;
    border: none;
    background: transparent;
    color: var(--muted);
    font-size: 12px;
    font-weight: 600;
    border-radius: 8px;
    cursor: pointer;
    transition: background 0.15s ease, color 0.15s ease, box-shadow 0.15s ease;
  }

  .detent-btn[aria-pressed="true"] {
    background: var(--surface);
    color: var(--ink);
    box-shadow: 0 1px 3px rgba(15, 36, 25, 0.12);
  }

  /* Filter Chips */
  .filter-bar {
    display: flex;
    gap: 8px;
    padding: 10px 16px;
    overflow-x: auto;
    scrollbar-width: none;
    flex-shrink: 0;
    border-bottom: 1px solid #F0F5F2;
  }

  .filter-bar::-webkit-scrollbar {
    display: none;
  }

  .chip {
    min-height: 36px;
    padding: 0 14px;
    border-radius: 999px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--muted);
    font-size: 13px;
    font-weight: 600;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.15s ease;
  }

  .chip.active {
    background: var(--ink);
    border-color: var(--ink);
    color: #fff;
  }

  /* Route List */
  .sheet-body {
    flex: 1;
    overflow-y: auto;
    overscroll-behavior: contain;
    padding: 12px 16px 24px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .route-item {
    border: 1.5px solid var(--border);
    border-radius: 16px;
    background: var(--surface);
    padding: 13px 14px;
    cursor: pointer;
    transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.15s ease;
    text-align: left;
    width: 100%;
    color: inherit;
    font: inherit;
  }

  .route-item:hover {
    border-color: #A7CBB5;
  }

  .route-item.selected {
    border-color: var(--accent);
    background: #FAFFFC;
    box-shadow: 0 4px 16px rgba(22, 163, 74, 0.12);
  }

  .route-top {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 8px;
  }

  .line-badges {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 6px;
  }

  .badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 8px;
    border-radius: 7px;
    font-size: 12px;
    font-weight: 700;
    color: #fff;
  }

  .badge.walk {
    background: var(--surface-2);
    color: var(--muted);
    font-weight: 600;
  }

  .route-eta {
    text-align: right;
    flex-shrink: 0;
  }

  .eta-mins {
    font-size: 19px;
    font-weight: 800;
    letter-spacing: -0.02em;
    font-variant-numeric: tabular-nums;
    line-height: 1.1;
  }

  .eta-mins small {
    font-size: 12px;
    font-weight: 600;
    color: var(--muted);
  }

  .route-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12.5px;
    color: var(--muted);
    gap: 8px;
    font-variant-numeric: tabular-nums;
  }

  .dep-live {
    color: var(--accent-dark);
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    gap: 5px;
  }

  .dep-live::before {
    content: "";
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--accent);
    display: inline-block;
  }

  /* Expanded Legs */
  .route-legs {
    display: none;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px dashed var(--border);
    flex-direction: column;
    gap: 10px;
  }

  .route-item.selected .route-legs {
    display: flex;
  }

  .leg-step {
    display: grid;
    grid-template-columns: 18px 1fr auto;
    gap: 10px;
    align-items: start;
    font-size: 13px;
  }

  .leg-node {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-top: 3px;
    border: 3px solid var(--accent);
    background: #fff;
  }

  .leg-title {
    font-weight: 600;
    color: var(--ink);
  }

  .leg-sub {
    font-size: 12px;
    color: var(--muted);
  }

  .leg-dur {
    font-size: 12px;
    font-weight: 700;
    color: var(--muted);
    font-variant-numeric: tabular-nums;
  }

  .go-btn {
    margin-top: 4px;
    min-height: 44px;
    width: 100%;
    border: none;
    border-radius: 12px;
    background: var(--accent);
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: background 0.15s ease;
  }

  .go-btn:hover {
    background: var(--accent-dark);
  }

  /* Peek state hides extra chrome cleanly */
  .sheet[data-detent="peek"] .filter-bar,
  .sheet[data-detent="peek"] .sheet-body {
    opacity: 0.35;
    pointer-events: none;
  }

  /* Toast Banner */
  .toast {
    position: fixed;
    left: 50%;
    bottom: 20px;
    transform: translate(-50%, 80px);
    background: var(--ink);
    color: #fff;
    padding: 11px 18px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 600;
    box-shadow: 0 10px 28px rgba(15, 36, 25, 0.25);
    z-index: 60;
    opacity: 0;
    transition: transform 0.28s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.25s ease;
    pointer-events: none;
    white-space: nowrap;
  }

  .toast.show {
    transform: translate(-50%, 0);
    opacity: 1;
  }

  /* Desktop Side-Drawer Adaptation */
  @media (min-width: 900px) {
    .top-bar {
      left: 448px;
      right: auto;
      width: 400px;
      top: 18px;
    }

    .map-controls {
      top: 18px;
      right: 18px;
    }

    .sheet {
      top: 18px;
      left: 18px;
      bottom: 18px;
      right: auto;
      width: 412px;
      height: auto !important;
      border-radius: 22px;
      border: 1px solid var(--border);
      box-shadow: 0 12px 40px rgba(15, 36, 25, 0.14);
      transition: width 0.28s cubic-bezier(0.22, 1, 0.36, 1);
    }

    .sheet[data-detent="peek"] {
      width: 340px;
    }

    .sheet[data-detent="peek"] .filter-bar,
    .sheet[data-detent="peek"] .sheet-body {
      opacity: 1;
      pointer-events: auto;
    }

    .sheet[data-detent="full"] {
      width: 470px;
    }

    .grab-handle {
      display: none;
    }

    .sheet-grab-zone {
      cursor: default;
      padding-top: 16px;
    }
  }
</style>
</head>
<body>
<div class="app">
  <!-- Interactive SVG Transit Map -->
  <div class="map-stage" aria-label="Interactive city transit map">
    <svg id="mapSvg" class="map-svg" viewBox="0 0 900 720" preserveAspectRatio="xMidYMid slice">
      <defs>
        <pattern id="grid" width="48" height="48" patternUnits="userSpaceOnUse">
          <path d="M 48 0 L 0 0 0 48" fill="none" stroke="#DCE8DF" stroke-width="1"/>
        </pattern>
      </defs>

      <!-- Base land & street grid -->
      <rect width="900" height="720" fill="#EDF4EF"/>
      <rect width="900" height="720" fill="url(#grid)"/>

      <!-- Parks -->
      <path d="M90 120 Q150 90 210 130 Q245 180 180 225 Q110 220 80 170 Z" fill="#D5EBD9"/>
      <path d="M580 70 Q680 55 725 130 Q700 200 615 185 Q555 150 580 70 Z" fill="#D5EBD9"/>
      <path d="M355 460 Q430 430 480 485 Q455 565 370 550 Z" fill="#D5EBD9"/>

      <!-- Harbor River -->
      <path d="M-20 410 C150 385, 290 455, 470 390 C630 330, 740 365, 920 315 L920 420 C750 460, 620 435, 465 485 C295 540, 150 470, -20 495 Z" fill="#C9E4F5"/>
      <path d="M-20 432 C150 407, 290 475, 470 410 C630 350, 740 385, 920 335" fill="none" stroke="#E4F3FC" stroke-width="5" stroke-dasharray="18 14" opacity="0.7"/>

      <!-- Major avenues -->
      <g stroke="#FFFFFF" stroke-width="6" stroke-linecap="round" opacity="0.85">
        <line x1="160" y1="0" x2="210" y2="720"/>
        <line x1="450" y1="0" x2="430" y2="720"/>
        <line x1="700" y1="0" x2="660" y2="720"/>
        <line x1="0" y1="220" x2="900" y2="255"/>
        <line x1="0" y1="540" x2="900" y2="510"/>
      </g>

      <!-- Transit Routes -->
      <!-- Route 1: M4 Green Metro (fastest) -->
      <path id="path-m4" class="route-path active" d="M210 210 L355 215 L445 265 L560 275 L695 295" stroke="#16A34A" stroke-width="7"/>
      <!-- Route 2: Bus 72 Express -->
      <path id="path-b72" class="route-path dimmed" d="M210 210 L245 315 L410 345 L555 340 L695 295" stroke="#2563EB" stroke-width="6" stroke-dasharray="14 6"/>
      <!-- Route 3: Ferry F2 + Walk -->
      <path id="path-f2" class="route-path dimmed" d="M210 210 L290 420 C420 445, 550 385, 675 375 L695 295" stroke="#0D9488" stroke-width="6" stroke-dasharray="4 10"/>
      <!-- Route 4: Tram T8 + Bike -->
      <path id="path-t8" class="route-path dimmed" d="M210 210 L320 140 L515 155 L640 215 L695 295" stroke="#D97706" stroke-width="6"/>

      <!-- Intermediate Stations -->
      <g fill="#FFFFFF" stroke="#0F2419" stroke-width="2.5">
        <circle cx="355" cy="215" r="5"/>
        <circle cx="445" cy="265" r="5"/>
        <circle cx="560" cy="275" r="5"/>
        <circle cx="410" cy="345" r="5"/>
        <circle cx="515" cy="155" r="5"/>
        <circle cx="290" cy="420" r="5"/>
      </g>

      <!-- Live Moving Train Dot -->
      <circle id="liveVehicle" cx="355" cy="215" r="7" fill="#16A34A" stroke="#FFFFFF" stroke-width="2.5"/>

      <!-- Origin Pin: Union Sq -->
      <g transform="translate(210, 210)">
        <circle class="pulse-ring" r="11" fill="#16A34A" opacity="0.45"/>
        <circle r="9" fill="#FFFFFF" stroke="#16A34A" stroke-width="4"/>
        <rect x="-42" y="-34" width="84" height="22" rx="11" fill="#0F2419"/>
        <text x="0" y="-19" text-anchor="middle" fill="#FFFFFF" font-size="11" font-weight="700">Union Sq</text>
      </g>

      <!-- Destination Pin: Harbor Pier 14 -->
      <g transform="translate(695, 295)">
        <circle r="10" fill="#0F2419" stroke="#FFFFFF" stroke-width="3"/>
        <rect x="-54" y="-36" width="108" height="22" rx="11" fill="#16A34A"/>
        <text x="0" y="-21" text-anchor="middle" fill="#FFFFFF" font-size="11" font-weight="700">Harbor Pier 14</text>
      </g>
    </svg>
  </div>

  <!-- Floating Top Origin/Destination Bar -->
  <header class="top-bar">
    <div class="route-card-top">
      <div class="trip-dots" aria-hidden="true">
        <span class="dot-origin"></span>
        <span class="dot-line"></span>
        <span class="dot-dest"></span>
      </div>
      <div class="trip-endpoints">
        <div class="endpoint-row"><span id="originLabel">Union Sq Station</span><span class="tag">Now</span></div>
        <div class="endpoint-divider"></div>
        <div class="endpoint-row"><span id="destLabel">Harbor Pier 14</span><span class="tag">6.4 km</span></div>
      </div>
      <button id="swapBtn" class="icon-btn" type="button" aria-label="Swap origin and destination" title="Swap endpoints">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M7 16V4m0 0L3 8m4-4l4 4M17 8v12m0 0l4-4m-4 4l-4-4"/>
        </svg>
      </button>
    </div>
    <div class="status-strip">
      <div class="live-pill"><span class="live-dot"></span>Live transit feed &middot; Normal service</div>
    </div>
  </header>

  <!-- Map Controls -->
  <div class="map-controls" aria-label="Map zoom controls">
    <button id="zoomInBtn" class="icon-btn" type="button" aria-label="Zoom in map">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
    </button>
    <button id="zoomOutBtn" class="icon-btn" type="button" aria-label="Zoom out map">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round"><path d="M5 12h14"/></svg>
    </button>
    <button id="recenterBtn" class="icon-btn" type="button" aria-label="Recenter map">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round"><circle cx="12" cy="12" r="3"/><path d="M12 2v3m0 14v3M2 12h3m14 0h3"/></svg>
    </button>
  </div>

  <!-- Multi-Detent Bottom Sheet / Desktop Side Drawer -->
  <section id="sheet" class="sheet" data-detent="half" aria-label="Route options">
    <div id="grabZone" class="sheet-grab-zone" tabindex="0" role="slider" aria-label="Sheet height detent" aria-valuemin="1" aria-valuemax="3" aria-valuenow="2" aria-valuetext="Half">
      <div class="grab-handle"></div>
      <div class="sheet-header-row">
        <div class="sheet-title-wrap">
          <h1>Suggested Routes</h1>
          <div class="sheet-subtitle" id="activeSummary">Fastest: 18 min via M4 Metro</div>
        </div>
        <div class="detent-group" role="group" aria-label="Sheet detents">
          <button class="detent-btn" data-set-detent="peek" aria-pressed="false" type="button">Peek</button>
          <button class="detent-btn" data-set-detent="half" aria-pressed="true" type="button">Half</button>
          <button class="detent-btn" data-set-detent="full" aria-pressed="false" type="button">Full</button>
        </div>
      </div>
    </div>

    <div class="filter-bar" role="tablist" aria-label="Filter routes by mode">
      <button class="chip active" data-filter="all" type="button">All (4)</button>
      <button class="chip" data-filter="rail" type="button">Rail &amp; Tram</button>
      <button class="chip" data-filter="bus" type="button">Bus</button>
      <button class="chip" data-filter="ferry" type="button">Ferry</button>
    </div>

    <div id="routeList" class="sheet-body"></div>
  </section>

  <div id="toast" class="toast" role="status" aria-live="polite"></div>
</div>

<script>
(() => {
  const DETENTS = { peek: 18, half: 52, full: 88 };
  const DETENT_ORDER = ['peek', 'half', 'full'];

  const ROUTES = [
    {
      id: 'm4',
      mode: 'rail',
      pathId: 'path-m4',
      color: '#16A34A',
      duration: 18,
      depSeconds: 135,
      fare: '$2.75',
      walkMins: 4,
      co2: '1.1 kg CO2 saved',
      badges: [
        { label: 'Walk 2m', type: 'walk' },
        { label: 'M4 Metro', color: '#16A34A' },
        { label: 'Walk 2m', type: 'walk' }
      ],
      legs: [
        { title: 'Walk to Union Sq North Entrance', sub: '180 m · Flat', dur: '2 min', color: '#5A7063' },
        { title: 'Board M4 Green Line toward East Pier', sub: '4 stops · Platform 2 · Low crowding', dur: '14 min', color: '#16A34A' },
        { title: 'Exit at Pier 14 Promenade', sub: '150 m to main terminal', dur: '2 min', color: '#5A7063' }
      ],
      track: [[210,210],[355,215],[445,265],[560,275],[695,295]]
    },
    {
      id: 'b72',
      mode: 'bus',
      pathId: 'path-b72',
      color: '#2563EB',
      duration: 24,
      depSeconds: 290,
      fare: '$2.25',
      walkMins: 5,
      co2: '0.8 kg CO2 saved',
      badges: [
        { label: 'Walk 3m', type: 'walk' },
        { label: 'Bus 72X', color: '#2563EB' },
        { label: 'Walk 2m', type: 'walk' }
      ],
      legs: [
        { title: 'Walk to Market & 4th Bus Bay', sub: '240 m · Crosswalk signal', dur: '3 min', color: '#5A7063' },
        { title: 'Ride 72X Waterfront Express', sub: '6 stops · Dedicated bus lane', dur: '19 min', color: '#2563EB' },
        { title: 'Walk to Harbor Pier 14', sub: '140 m along Embarcadero', dur: '2 min', color: '#5A7063' }
      ],
      track: [[210,210],[245,315],[410,345],[555,340],[695,295]]
    },
    {
      id: 'f2',
      mode: 'ferry',
      pathId: 'path-f2',
      color: '#0D9488',
      duration: 27,
      depSeconds: 410,
      fare: '$4.50',
      walkMins: 6,
      co2: 'Scenic bay crossing',
      badges: [
        { label: 'Walk 5m', type: 'walk' },
        { label: 'Ferry F2', color: '#0D9488' }
      ],
      legs: [
        { title: 'Walk to South Basin Slip B', sub: '410 m · Waterfront path', dur: '5 min', color: '#5A7063' },
        { title: 'F2 Harbor Shuttle Catamaran', sub: 'Direct crossing · Open deck seats', dur: '21 min', color: '#0D9488' },
        { title: 'Disembark directly at Pier 14', sub: 'Gate A · Step-free', dur: '1 min', color: '#5A7063' }
      ],
      track: [[210,210],[290,420],[480,410],[675,375],[695,295]]
    },
    {
      id: 't8',
      mode: 'rail',
      pathId: 'path-t8',
      color: '#D97706',
      duration: 22,
      depSeconds: 195,
      fare: '$2.75',
      walkMins: 3,
      co2: '1.0 kg CO2 saved',
      badges: [
        { label: 'Tram T8', color: '#D97706' },
        { label: 'Walk 3m', type: 'walk' }
      ],
      legs: [
        { title: 'Board Tram T8 at Union Plaza', sub: 'Street-level boarding · Every 6 min', dur: '19 min', color: '#D97706' },
        { title: 'Walk down North Dock Steps', sub: '220 m to Harbor Pier 14', dur: '3 min', color: '#5A7063' }
      ],
      track: [[210,210],[320,140],[515,155],[640,215],[695,295]]
    }
  ];

  const sheet = document.getElementById('sheet');
  const grabZone = document.getElementById('grabZone');
  const routeList = document.getElementById('routeList');
  const activeSummary = document.getElementById('activeSummary');
  const mapSvg = document.getElementById('mapSvg');
  const liveVehicle = document.getElementById('liveVehicle');
  const toast = document.getElementById('toast');

  let currentDetent = 'half';
  let currentFilter = 'all';
  let selectedId = 'm4';
  let mapScale = 1;
  let swapped = false;
  let toastTimer = null;

  function showToast(msg) {
    toast.textContent = msg;
    toast.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => toast.classList.remove('show'), 2200);
  }

  function formatCountdown(sec) {
    if (sec <= 45) return `Due (${sec}s)`;
    const mins = Math.floor(sec / 60);
    const rem = sec % 60;
    return `in ${mins}m ${String(rem).padStart(2, '0')}s`;
  }

  function setDetent(name) {
    currentDetent = name;
    sheet.dataset.detent = name;
    sheet.style.setProperty('--sheet-h', DETENTS[name] + 'vh');
    grabZone.setAttribute('aria-valuenow', String(DETENT_ORDER.indexOf(name) + 1));
    grabZone.setAttribute('aria-valuetext', name[0].toUpperCase() + name.slice(1));
    document.querySelectorAll('.detent-btn').forEach(btn => {
      btn.setAttribute('aria-pressed', String(btn.dataset.setDetent === name));
    });
  }

  function highlightMapRoute(id) {
    ROUTES.forEach(r => {
      const el = document.getElementById(r.pathId);
      if (!el) return;
      el.classList.toggle('active', r.id === id);
      el.classList.toggle('dimmed', r.id !== id);
    });
    const active = ROUTES.find(r => r.id === id);
    if (active) {
      liveVehicle.setAttribute('fill', active.color);
      activeSummary.textContent = `Selected: ${active.duration} min · Departs ${formatCountdown(active.depSeconds)}`;
    }
  }

  function renderRoutes() {
    const filtered = currentFilter === 'all'
      ? ROUTES
      : ROUTES.filter(r => r.mode === currentFilter);

    routeList.innerHTML = filtered.map(r => {
      const isSelected = r.id === selectedId;
      const badgesHtml = r.badges.map(b =>
        b.type === 'walk'
          ? `<span class="badge walk">${b.label}</span>`
          : `<span class="badge" style="background:${b.color}">${b.label}</span>`
      ).join('');

      const legsHtml = r.legs.map(l => `
        <div class="leg-step">
          <span class="leg-node" style="border-color:${l.color}"></span>
          <div>
            <div class="leg-title">${l.title}</div>
            <div class="leg-sub">${l.sub}</div>
          </div>
          <span class="leg-dur">${l.dur}</span>
        </div>
      `).join('');

      return `
        <div class="route-item ${isSelected ? 'selected' : ''}" data-route-id="${r.id}" role="button" tabindex="0" aria-expanded="${isSelected}">
          <div class="route-top">
            <div class="line-badges">${badgesHtml}</div>
            <div class="route-eta">
              <div class="eta-mins">${r.duration} <small>min</small></div>
            </div>
          </div>
          <div class="route-meta">
            <span class="dep-live" data-dep="${r.id}">${formatCountdown(r.depSeconds)}</span>
            <span>${r.fare} &middot; ${r.co2}</span>
          </div>
          <div class="route-legs">
            ${legsHtml}
            <button type="button" class="go-btn" data-go="${r.id}">
              Start Live Guidance
            </button>
          </div>
        </div>
      `;
    }).join('');
  }

  // Click / keyboard selection on routes
  routeList.addEventListener('click', (e) => {
    const goBtn = e.target.closest('[data-go]');
    if (goBtn) {
      e.stopPropagation();
      const route = ROUTES.find(r => r.id === goBtn.dataset.go);
      showToast(`Live guidance started for ${route.badges.find(b => !b.type).label}`);
      return;
    }
    const card = e.target.closest('.route-item');
    if (!card) return;
    selectedId = card.dataset.routeId;
    renderRoutes();
    highlightMapRoute(selectedId);
    if (currentDetent === 'peek' && window.innerWidth < 900) {
      setDetent('half');
    }
  });

  routeList.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      const card = e.target.closest('.route-item');
      if (card) {
        e.preventDefault();
        card.click();
      }
    }
  });

  // Detent buttons
  document.querySelectorAll('.detent-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      setDetent(btn.dataset.setDetent);
    });
  });

  // Filter chips
  document.querySelectorAll('.chip').forEach(chip => {
    chip.addEventListener('click', () => {
      currentFilter = chip.dataset.filter;
      document.querySelectorAll('.chip').forEach(c => c.classList.toggle('active', c === chip));
      const visible = currentFilter === 'all' ? ROUTES : ROUTES.filter(r => r.mode === currentFilter);
      if (visible.length && !visible.some(r => r.id === selectedId)) {
        selectedId = visible[0].id;
        highlightMapRoute(selectedId);
      }
      renderRoutes();
    });
  });

  // Pointer drag mechanics on mobile bottom sheet
  let dragging = false;
  let startY = 0;
  let startHeightPx = 0;
  let lastY = 0;
  let lastTime = 0;
  let velocityY = 0;

  grabZone.addEventListener('pointerdown', (e) => {
    if (window.innerWidth >= 900) return;
    if (e.target.closest('.detent-btn')) return;
    dragging = true;
    startY = lastY = e.clientY;
    lastTime = performance.now();
    velocityY = 0;
    startHeightPx = sheet.getBoundingClientRect().height;
    sheet.classList.add('dragging');
    grabZone.setPointerCapture(e.pointerId);
  });

  grabZone.addEventListener('pointermove', (e) => {
    if (!dragging) return;
    const now = performance.now();
    const dt = Math.max(1, now - lastTime);
    velocityY = (e.clientY - lastY) / dt; // px/ms, negative = dragging upward
    lastY = e.clientY;
    lastTime = now;

    const deltaY = startY - e.clientY;
    const vh = window.innerHeight;
    let nextH = startHeightPx + deltaY;
    const minPx = vh * 0.14;
    const maxPx = vh * 0.92;
    if (nextH < minPx) nextH = minPx - (minPx - nextH) * 0.25;
    if (nextH > maxPx) nextH = maxPx + (nextH - maxPx) * 0.25;
    sheet.style.setProperty('--sheet-h', `${(nextH / vh) * 100}vh`);
  });

  function finishDrag() {
    if (!dragging) return;
    dragging = false;
    sheet.classList.remove('dragging');
    const vh = window.innerHeight;
    const pct = (sheet.getBoundingClientRect().height / vh) * 100;

    // Velocity flick snapping
    let target = currentDetent;
    const idx = DETENT_ORDER.indexOf(currentDetent);
    if (velocityY < -0.45) {
      target = DETENT_ORDER[Math.min(2, idx + 1)];
    } else if (velocityY > 0.45) {
      target = DETENT_ORDER[Math.max(0, idx - 1)];
    } else {
      // Snap to nearest detent
      let bestDist = Infinity;
      for (const name of DETENT_ORDER) {
        const d = Math.abs(DETENTS[name] - pct);
        if (d < bestDist) {
          bestDist = d;
          target = name;
        }
      }
    }
    setDetent(target);
  }

  grabZone.addEventListener('pointerup', finishDrag);
  grabZone.addEventListener('pointercancel', finishDrag);

  // Keyboard support for detent slider
  grabZone.addEventListener('keydown', (e) => {
    const idx = DETENT_ORDER.indexOf(currentDetent);
    if (e.key === 'ArrowUp' && idx < 2) {
      e.preventDefault();
      setDetent(DETENT_ORDER[idx + 1]);
    } else if (e.key === 'ArrowDown' && idx > 0) {
      e.preventDefault();
      setDetent(DETENT_ORDER[idx - 1]);
    }
  });

  // Swap endpoints
  document.getElementById('swapBtn').addEventListener('click', () => {
    swapped = !swapped;
    document.getElementById('originLabel').textContent = swapped ? 'Harbor Pier 14' : 'Union Sq Station';
    document.getElementById('destLabel').textContent = swapped ? 'Union Sq Station' : 'Harbor Pier 14';
    showToast(swapped ? 'Reversed route: Pier 14 -> Union Sq' : 'Route: Union Sq -> Pier 14');
  });

  // Map zoom controls
  function applyZoom() {
    mapSvg.style.transform = `scale(${mapScale.toFixed(2)})`;
  }
  document.getElementById('zoomInBtn').addEventListener('click', () => {
    mapScale = Math.min(1.5, mapScale + 0.15);
    applyZoom();
  });
  document.getElementById('zoomOutBtn').addEventListener('click', () => {
    mapScale = Math.max(0.85, mapScale - 0.15);
    applyZoom();
  });
  document.getElementById('recenterBtn').addEventListener('click', () => {
    mapScale = 1;
    applyZoom();
    showToast('Map recentered on active route');
  });

  // Live countdown ticker & moving transit dot
  let animT = 0;
  setInterval(() => {
    ROUTES.forEach(r => {
      r.depSeconds = r.depSeconds > 15 ? r.depSeconds - 1 : 240 + Math.floor(Math.random() * 120);
      const depEl = routeList.querySelector(`[data-dep="${r.id}"]`);
      if (depEl) depEl.textContent = formatCountdown(r.depSeconds);
    });
    const active = ROUTES.find(r => r.id === selectedId);
    if (active) {
      activeSummary.textContent = `Selected: ${active.duration} min · Departs ${formatCountdown(active.depSeconds)}`;
    }
  }, 1000);

  function animateVehicle() {
    animT = (animT + 0.0022) % 1;
    const active = ROUTES.find(r => r.id === selectedId) || ROUTES[0];
    const pts = active.track;
    const segCount = pts.length - 1;
    const scaled = animT * segCount;
    const i = Math.min(segCount - 1, Math.floor(scaled));
    const localT = scaled - i;
    const x = pts[i][0] + (pts[i + 1][0] - pts[i][0]) * localT;
    const y = pts[i][1] + (pts[i + 1][1] - pts[i][1]) * localT;
    liveVehicle.setAttribute('cx', x.toFixed(1));
    liveVehicle.setAttribute('cy', y.toFixed(1));
    requestAnimationFrame(animateVehicle);
  }

  // Init
  setDetent('half');
  renderRoutes();
  highlightMapRoute(selectedId);
  requestAnimationFrame(animateVehicle);
})();
</script>
</body>
</html>