# Recreate this section as a single HTML file: Paceline Customer Stories

## What it is

A warm, editorial **customer-stories section** for *Paceline*, a fictional appointment-scheduling tool for clinics. It sits on a paper-coloured ground. A large Instrument Serif headline ("Fewer gaps in the diary. *More time* with patients.") sits next to a **rating summary card** (average 4.8, five animated distribution bars). Below are two rows of **filter chips**, Specialty and Team size, each chip with a live count. Then comes a full-bleed **story rail** of eight cards that runs off the right edge. Each card has a clinic mark, a star rating, a serif quote and one **key phrase that draws its highlighter swipe** when the card comes fully into view. Under the quote is a big result figure ("−38% no-shows in one quarter") and the person. **Signature:** the rail is native scroll-snap with a **momentum mouse drag** (velocity projection, then an eased settle onto a card), and it is mirrored by a **draggable progress scrubber** with one tick per story. Filtering re-flows the cards with **FLIP**, and the rating summary re-counts and re-animates for that specialty. One card is a dark **voice-note** card. Pressing play drives a 46-bar waveform playhead and a word-by-word transcript, and reads the note aloud where the browser supports speech. Long quotes have a "Read the full story" expand. The section **advances on its own every 7 s**, with a visible pause button and a progress ring, and it pauses on hover, on focus, off-screen, in a hidden tab, during voice playback and while the dialog is open (WCAG 2.2.2). A "Share your story" dialog holds a validated form with a star rating.

## Page shell & libraries

- One `index.html` with inline CSS and one inline IIFE script. No frameworks and no JS libraries.
- The only remote dependency is Google Fonts: `https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter+Tight:wght@400;500;600;700&display=swap` (preconnect to fonts.googleapis.com and fonts.gstatic.com).
- Structure: `a.skip` → `section#stories.stories` → `.wrap` (brand row, `header.head` with copy | `aside.summary`, `.filters`) → `div#carousel[role=region][aria-roledescription=carousel]` (`.rail#rail` [tabindex=0], `.empty#empty`, `.wrap > .controls`) → `div#live[aria-live=polite]`. After the section come `#after-stories` (skip-link target) and `dialog#dlg`.
- The cards, chips, bars, ticks and star radios are all generated from data arrays (`STORIES`, `STATS`, `IND`, `SIZE`), so the counts always agree.

## Tokens

- **Colour:** paper `#f4f1ea` (ground), paper-2 `#ece7dc` (bar tracks, tags), card `#fbfaf6`, ink `#14201b`, ink-2 `#2b3832`, muted `#56625c` (≥ 5.5:1 on paper), line `#dcd5c6`, sage `#dce5d9` (monogram fill), accent `#e2552a` (stars, quote glyph, 5★ bar, autoplay ring), accent-ink `#a8380f` (accent text, eyebrow, results, links), highlighter `rgba(255,190,92,.62)`, focus `#1f6feb`.
- **Voice card:** night `#16231d`, night-2 `#22332b`, idle waveform `#5b6e64`, played waveform and play button `#ff9a6b`, unsaid transcript words `#90a198`, said words `#f4f6f3`.
- **Type:** Instrument Serif 400 / italic for display. The h2 is `clamp(44px, 6.4vw, 92px)` with line-height .96 and tracking −.02em, and *More time* is italic in accent-ink. Quotes are 29px / 1.14 (26px ≤ 1100, 24px ≤ 600). The average is 76px, results 44px and facts 30px. Inter Tight 400–700 for UI: body 16px, eyebrow 12px / .18em uppercase, chip 14px, meta 13px.
- **Radii:** cards 22px (18px on phones), chips and tags 999px, dialog 24px, fields 12px.
- **Spacing:** gutter `max(24px, (100vw − 1280px) / 2)`, 16px on phones. Card width 400px (360px ≤ 1100, `min(86vw, 340px)` ≤ 600). Rail gap 20px (12px on phones).
- **Easing:** `--ease: cubic-bezier(.2,.8,.2,1)` and `--ease-out: cubic-bezier(.22,.61,.36,1)`.

## Layout & structure

1. **Brand row:** a 26px rounded-square ink logo (a white stroke wave with an accent dot), "Paceline", and a muted "Scheduling for clinics" after a hairline divider (hidden on phones).
2. **Head** (grid `1.35fr / .65fr`, min 300px, gap `clamp(32px, 5vw, 88px)`, aligned to the bottom):
   - Left: an eyebrow "Customer stories" with a 22px rule before it, the h2, a lead paragraph (max 46ch, muted), then a facts list: "−38% no-shows · 6.2 h saved per desk, weekly · 2,400 clinics". The numbers are 30px serif.
   - Right: `aside.summary`, a card with a 1px line border and 24px padding. It holds the big average, five stars, "4.8 out of 5" and "1,186 verified reviews", then a `ul.bars` of five rows (`28px | bar | 38px`). Each bar track is 8px high, with an ink fill; the 5★ fill is accent. A scope line ("All clinic types" / "Showing Dental clinics") closes it.
3. **Filters:** a 1px top rule with 22px of padding above, holding two `.fgroup`s. Each has an uppercase label and `.chips[role=group]` of `button.chip[aria-pressed]`, each with a `.n` count.
   - Specialty: All, Physio & osteo, Dental, Veterinary, General practice, Dermatology, Paediatrics.
   - Team: Any size, 1–10, 11–50, 50+.
   - A pressed chip is ink with paper text. A chip whose count is 0 under the other filter gets a dashed border, but it stays clickable and leads to the empty state.
4. **Rail:** `display:flex; overflow-x:auto; scroll-snap-type:x mandatory`, padding `8px gutter 48px`, `scroll-padding-inline: gutter`, scrollbar hidden. A trailing `span.spacer` is sized so that the last card can also snap to the start. Each `article.card[role=group][aria-roledescription=slide][aria-label="Name, Clinic"]` has `scroll-snap-align:start` and min-height 440px, and stretches to the tallest card (top-aligned on phones). A card contains, in order:
   - a row with the clinic mark (a 26px inline SVG plus the name) and the stars (`role=img`, "5 out of 5 stars");
   - a `.clamp` wrapper whose `::before` is the 64px accent opening quote;
   - `blockquote.quote` with a `<mark>` key phrase;
   - for multi-paragraph quotes, `button.more[aria-expanded][aria-controls]`;
   - `p.result` (a 44px serif figure in accent-ink plus a 13px label);
   - `.who` (a 54px round photo with `alt=""`, since the name sits next to it; monogram cards use a sage circle with serif initials);
   - `.tags` (specialty and team-size pills) above a hairline.
5. **Voice card** (`.card.voice`, night ground): the label "● Voice note · 0:21", then a player row (52px round play/pause button, a `.wave` of 46 flex bars with heights from a seeded pseudo-random sequence times a sine envelope, and a countdown), then `blockquote.transcript` (24px serif, each word in a `span.w`) and a 12px note saying that playback reads the transcript aloud.
6. **Controls** (grid `auto 1fr auto`, margin-top −14px):
   - Prev (ghost) and next (ink) 52px round buttons, with a `01 / 08` counter.
   - The scrubber `#scrub[role=slider]`: a 44px hit area with a 2px line track, an ink fill, 6px tick dots (ink once passed) and a 28px paper thumb with a 2px ink ring and a name tooltip that shows while dragging or focused.
   - Then the pause button (52px, with a 62px SVG ring whose `pathLength=100` stroke fills over the 7 s interval) and "+ Share your story".
7. **Empty state:** a dashed card saying "No stories match that combination yet." with a "Clear filters" pill.
8. **Dialog:** "Share your story", with fields for name, clinic, work email, a 1–5 star radio group and "What changed for you?" (at least 20 characters), plus Cancel / Send. The success view has a check icon, "Thank you" (focused) and Close.

## Behaviour & interaction

- **Snap and index:** touch and trackpad use native scroll with snap. On each scroll frame (throttled with rAF), the current index is the visible card whose `offsetLeft − paddingLeft` is nearest to `scrollLeft`. The current card gets `.is-current`: a darker border and the shadow `0 22px 44px -26px rgba(20,32,27,.35)`.
- **Programmatic moves** (buttons, keys, scrubber, autoplay) use one animator. It switches snap off (`.is-free`), tweens `scrollLeft` with easeOutQuart over `clamp(380, 300 + distance × .35, 900)` ms, lands exactly on the snap point and turns snap back on next frame. With reduced motion it jumps instantly.
- **Momentum drag** (mouse and pen only; touch stays native): drag starts after 5px of movement. Snap is off while dragging, and `scrollLeft` follows the pointer. The script keeps samples from the last 90ms, and on release:
  - velocity `v` in px/ms comes from those samples;
  - the projected position is `scrollLeft − v × 260`, and the nearest card to it wins;
  - if that is still the same card and `|v| > .35`, a flick moves at least one card;
  - the settle lasts `clamp(420, 380 + |v| × 120, 900)` ms;
  - the click that follows a drag is suppressed.
- **Scrubber:** pointer-down jumps to the pointer and dragging maps x linearly onto `scrollLeft` (snap off); release settles on the nearest card. The thumb and fill track `scrollLeft / maxScroll` continuously, and ticks sit at each card's snap position over maxScroll. Keys: ←/↓ −1, →/↑ +1, PageUp/PageDown ±2, Home/End. `aria-valuenow`/`valuemax`, with valuetext "Story 3 of 8: Name, Clinic".
- **Rail keys** (rail focused): ←/→ step one card, Home/End go to the first/last.
- **Highlighter:** an IntersectionObserver (root = rail, threshold .82) adds `.is-seen` the first time a card is 82% visible. The `mark` background (`linear-gradient(hi,hi)` at `0 88% / 0% 42%`, `box-decoration-break:clone`) then grows to `100% 42%` over 900ms `--ease`, after a 150ms delay.
- **Expand:** long quotes clamp to `--clamp-def` (10.4em, 7.2em on phones) with a mask fade (`#000 62% → transparent`).
  - Opening sets `--clamp-h` to `scrollHeight` px, transitions max-height over 600ms, then sets it to `none`, and switches the label to "Show less".
  - Closing reverses this.
  - Expanding a card that is not current also moves to it.
- **Filtering (FLIP):**
  1. Cards that leave fade to `opacity 0, scale(.94) translateY(8px)` over 200ms ease-in.
  2. Hidden cards get `hidden`, the empty state toggles, the spacer is resized and the rail resets to 0.
  3. Cards that stay animate from their old rect delta to `none` over 560ms `cubic-bezier(.2,.8,.2,1)`.
  4. Entering cards come in from `translateX(40px) scale(.96)`, opacity 0, over 520ms with a stagger of `80 + i × 55` ms.
  5. Chip counts update for the cross-filter.
  6. The live region announces "2 stories for Dental."
  7. The summary switches to that specialty's numbers: the average counts up over 800ms (easeOutCubic) and the bars re-scale over 1s `--ease`.
- **Rating bars:** they start at `scaleX(0)` and animate once when the summary is 40% in view.
- **Voice note:**
  - Play animates the progress over 21s. Bars before the playhead turn `#ff9a6b`, the 3 bars at the head pulse (`scaleY 1 → 1.35`, 0.5s alternate), words up to the matching index turn bright, and the countdown runs.
  - If `speechSynthesis` exists, the transcript is spoken at rate .98, and `onboundary` word events override the timed word index.
  - Pause keeps the position. Clicking the waveform seeks. Playback stops when the story ends or a filter changes.
- **Auto-advance:** every 7000ms it goes to the next story and loops at the end, and the ring shows the elapsed time. The timer resets on every manual move.
  - It holds while: paused by the user, hovered (mouse), focus is inside the carousel (except the pause button), the tab is hidden, the rail is less than 35% on screen, a drag is in progress, voice is playing, the dialog is open, a filter is animating, or fewer than 2 stories show.
  - With reduced motion it starts paused.
  - The pause button toggles `aria-pressed` and its label (Pause / Resume auto-advance) and announces the change.
- **Announcements:** the polite live region speaks "Story N of M: Name, Role at Clinic." only within 1.5s of user navigation, never on auto-advance. It also announces filter results.
- **Dialog:** opens with `showModal()` and focuses the name field. Closing returns focus to Share. Clicking the backdrop closes it.
  - Validation runs on submit. Errors appear inline under each field, set `aria-invalid`, and are linked with `aria-describedby`; focus goes to the first invalid field.
  - Rules: name ≥ 2 characters, clinic ≥ 2, email `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`, rating required, message ≥ 20 (the error counts the characters still needed).
  - Stars light up on hover and on selection.

## Responsive

- **1440:** the head is two columns; three cards show fully, and the fourth bleeds off the right edge.
- **≤1100:** cards are 360px and quotes 26px.
- **≤860 (768 checked):** the head stacks to one column, with the summary full width. The controls become two rows: the scrubber spans the full width on top, with nav + counter on the left and pause + Share on the right below it.
- **≤600 (390 checked):**
  - The gutter is 16px and cards are `min(86vw, 340px)`, so the next card peeks in. Cards are top-aligned and the clamp is 7.2em.
  - The filter groups stack, and each chip row scrolls sideways on its own with edge masks; the page itself never scrolls sideways.
  - The h2 is `clamp(40px, 11.5vw, 52px)`, buttons are 46px and the Share label shortens to "Share".
- Check that `document.documentElement.scrollWidth === innerWidth` at 390, 768 and 1440.

## Accessibility & reduced motion

- Carousel semantics: a region with `aria-roledescription="carousel"`, each slide a group with `aria-roledescription="slide"`, and a labelled slider for position. Prev and next use `aria-controls="rail"`.
- Everything is reachable by keyboard: chips, rail arrows, the slider, play, expand, pause and the dialog. A 2px `#1f6feb` focus ring appears on all of them, and on the rail as an inset ring.
- Stars are `role=img` with text, and decorative SVGs are `aria-hidden`. Headshots use empty alt, because the name and role sit right next to them.
- There is a skip link past the stories.
- All text meets AA contrast, including the dashed zero-count chip text `#626a65`.
- `prefers-reduced-motion: reduce`: all transitions and animations are effectively off, highlighter marks show fully drawn, scroll moves jump, and auto-advance starts paused (and pauses if the setting changes live).

## Fallbacks

- No WebGL anywhere. Without IntersectionObserver, every card is marked seen and the bars show immediately. Without WAAPI (`Element.animate`), filters swap instantly. Without `speechSynthesis`, the voice note still plays visually with the timed transcript. Without `dialog.showModal`, it falls back to the `open` attribute.
- `document.fonts.ready` and `load` re-run the layout (spacer, ticks, snap position). Resize is debounced with rAF.

## Assets

Six square 160×160 `.webp` headshots (about 3 KB each). They are fictional people, shot in the same warm window light on a cream backdrop and cropped head-and-shoulders:

- `assets/margaret.webp`: a woman in her fifties with short silver hair and a navy knit top.
- `assets/daniel.webp`: a man in his thirties with a short beard and a light-blue oxford shirt.
- `assets/nia.webp`: a woman in her late twenties with curly dark hair tied back and olive scrubs.
- `assets/tom.webp`: a man in his sixties with white hair, round tortoiseshell glasses and a charcoal cardigan.
- `assets/grace.webp`: a woman in her forties with straight black hair and a rust blouse.
- `assets/mateo.webp`: a man in his late thirties with short dark hair, stubble and a mustard sweater.

The voice-note card (Priya Shah) and Owen Price use serif monogram circles. All eight clinic marks are inline SVG drawn on a 26×26 grid: Harbour (waves and a sun), Brightside (a tooth), Fernlea (a fern), Oakmere (a medical cross on a disc), Lumen (a sun), Little Steps (footprints), Saltmarsh (an arch) and Northgate (an N).

## Make it yours

This prompt rebuilds one exact design. If everyone ships it unchanged, the sites will look alike.
Before you paste it, change these lines so the result is yours. Each change is one edit to the
prompt; the structure and the interactions stay intact.

1. **Brand and audience.** Swap Paceline and its clinics for your own product and the people
   who use it, such as a field-service app for plumbers, accounting software for agencies, or a
   booking tool for salons. Rewrite `IND` as your 4–7 customer segments and `SIZE` as 3 team
   sizes. Keep 6–10 stories so the scrubber ticks stay readable and the cross-filter counts
   never leave every chip empty.
2. **The highlighter.** The key phrase that draws itself is the signature. Re-theme the
   `mark` and keep the trigger (82% in view) and the 900ms draw: a hand-drawn SVG underline
   squiggle that strokes in with `stroke-dashoffset`, a solid ink box that wipes in behind
   inverted text, a circled number, or a strike-through on the "before" and a highlight on the
   "after".
3. **The voice card.** Turn it into another kind of story: a 6-second "screen recording" card
   with a scrubbable frame strip, a handwritten note card that writes itself in, or a
   before/after metric card where the bars race. Keep the play button, the progress and the
   pause-on-play rule for auto-advance.
4. **Palette.** Replace paper, ink, accent, accent-ink, highlighter and the night tokens with your
   brand colours. Keep muted text and accent-ink at ≥ 4.5:1 on paper, and keep the highlighter
   pale enough that ink text over it stays ≥ 4.5:1.
5. **Type pairing.** Swap Instrument Serif + Inter Tight for another pairing, such as Fraunces +
   Geist, Newsreader + Manrope, or a grotesk-only pairing (Bricolage Grotesque + Inter) if your
   brand is not editorial. Re-tune the quote size so the longest short quote fits in 7 lines.
6. **Photos.** Replace the six `assets/*.webp` headshots with your real customers (with their
   permission), or generate new fictional ones in one batch with an identical prompt tail:
   same light direction, backdrop and lens. Then crop all of them to the same head size. Redraw
   the eight clinic marks as simple 26px SVGs of your customers' logos only if you have the
   rights.
7. **Results and copy.** Replace each `result` with a real, specific number your customer
   would sign off on, and rewrite the quotes in their own words. Use one concrete detail per
   quote ("before the kettle has boiled") rather than adjectives ("amazing", "seamless").

Tell your AI: *"Build exactly as specified, but with these changes: …"*, then list your edits.

---

## Reference implementation (use verbatim)

The complete working `index.html`. Every number in the spec above is in this file; if the two ever seem to differ, the code wins. Images and models referenced as `assets/...` can be downloaded from https://copytheprompt.design/demos/customer-stories-testimonials/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paceline Stories</title>
<meta name="description" content="Customer stories from clinics using Paceline, a fictional appointment scheduling tool.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter+Tight:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
  --paper:#f4f1ea;
  --paper-2:#ece7dc;
  --card:#fbfaf6;
  --ink:#14201b;
  --ink-2:#2b3832;
  --muted:#56625c;
  --line:#dcd5c6;
  --sage:#dce5d9;
  --accent:#e2552a;
  --accent-ink:#a8380f;
  --hi:rgba(255,190,92,.62);
  --night:#16231d;
  --night-2:#22332b;
  --wave:#5b6e64;
  --wave-on:#ff9a6b;
  --focus:#1f6feb;
  --gutter:max(24px, calc((100vw - 1280px) / 2));
  --card-w:400px;
  --gap:20px;
  --r:22px;
  --clamp-def:10.4em;
  --ease:cubic-bezier(.2,.8,.2,1);
  --ease-out:cubic-bezier(.22,.61,.36,1);
}
*,*::before,*::after{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{
  margin:0;background:var(--paper);color:var(--ink);
  font:400 16px/1.5 "Inter Tight",ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;
  -webkit-font-smoothing:antialiased;overflow-x:hidden;
}
button,input,textarea{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--focus);outline-offset:3px;border-radius:6px}
.sr{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
.skip{position:absolute;left:12px;top:-60px;background:var(--ink);color:#fff;padding:10px 14px;border-radius:10px;z-index:10;text-decoration:none}
.skip:focus{top:12px}

/* ------------------------------------------------ section shell */
.stories{position:relative;padding:clamp(56px,8vw,112px) 0 clamp(56px,7vw,96px);overflow:hidden}
.wrap{padding-inline:var(--gutter)}
.brand{display:flex;align-items:center;gap:10px;font-weight:600;letter-spacing:-.01em;font-size:15px;margin-bottom:clamp(28px,4vw,48px)}
.brand svg{width:26px;height:26px;flex:none}
.brand small{font-weight:500;color:var(--muted);font-size:13px;padding-left:10px;border-left:1px solid var(--line)}

.head{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(300px,.65fr);gap:clamp(32px,5vw,88px);align-items:end}
.eyebrow{margin:0 0 18px;font-size:12px;font-weight:600;letter-spacing:.18em;text-transform:uppercase;color:var(--accent-ink);display:flex;align-items:center;gap:10px}
.eyebrow::before{content:"";width:22px;height:1.5px;background:currentColor}
h2{
  margin:0;font-family:"Instrument Serif",Georgia,serif;font-weight:400;
  font-size:clamp(44px,6.4vw,92px);line-height:.96;letter-spacing:-.02em;text-wrap:balance;
}
h2 em{font-style:italic;color:var(--accent-ink)}
.lead{margin:22px 0 0;max-width:46ch;color:var(--muted);font-size:clamp(16px,1.3vw,18px);line-height:1.55}
.facts{display:flex;flex-wrap:wrap;gap:10px 28px;margin:26px 0 0;padding:0;list-style:none}
.facts li{display:flex;align-items:baseline;gap:8px;font-size:14px;color:var(--muted)}
.facts b{font-family:"Instrument Serif",Georgia,serif;font-weight:400;font-size:30px;color:var(--ink);letter-spacing:-.01em}

/* rating summary */
.summary{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:24px 24px 22px}
.summary .top{display:flex;align-items:flex-end;gap:16px;margin-bottom:18px}
.avg{font-family:"Instrument Serif",Georgia,serif;font-size:76px;line-height:.8;letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.summary .top p{margin:0;font-size:13px;color:var(--muted);line-height:1.4}
.summary .top p strong{display:block;color:var(--ink);font-weight:600;font-size:14px}
.stars{display:inline-flex;gap:2px;color:var(--accent)}
.stars svg{width:15px;height:15px;display:block}
.bars{margin:0;padding:0;list-style:none;display:grid;gap:8px}
.bars li{display:grid;grid-template-columns:28px 1fr 38px;align-items:center;gap:10px;font-size:13px;color:var(--muted);font-variant-numeric:tabular-nums}
.bar{height:8px;border-radius:99px;background:var(--paper-2);overflow:hidden}
.bar i{display:block;height:100%;width:100%;border-radius:inherit;background:var(--ink);transform-origin:left;transform:scaleX(0);transition:transform 1s var(--ease)}
.bars li:first-child .bar i{background:var(--accent)}
.bars li span:last-child{text-align:right}
.summary .scope{margin:14px 0 0;font-size:12px;color:var(--muted)}

/* ------------------------------------------------ filters */
.filters{display:flex;flex-wrap:wrap;gap:14px 28px;align-items:center;margin-top:clamp(36px,5vw,64px);padding-top:22px;border-top:1px solid var(--line)}
.fgroup{display:flex;align-items:flex-start;gap:12px;min-width:0}
.flabel{padding-top:10px;font-size:12px;font-weight:600;letter-spacing:.12em;text-transform:uppercase;color:var(--muted);flex:none}
.chips{display:flex;gap:6px;flex-wrap:wrap;min-width:0}
.chip{
  appearance:none;border:1px solid var(--line);background:transparent;border-radius:99px;
  padding:7px 13px 7px 14px;font-size:14px;font-weight:500;cursor:pointer;white-space:nowrap;
  display:inline-flex;align-items:center;gap:7px;min-height:36px;
  transition:background .25s var(--ease-out),border-color .25s,color .25s;
}
.chip .n{font-size:11px;font-weight:600;color:var(--muted);font-variant-numeric:tabular-nums;min-width:1ch}
.chip:hover{border-color:var(--ink-2)}
.chip[aria-pressed="true"]{background:var(--ink);border-color:var(--ink);color:var(--paper)}
.chip[aria-pressed="true"] .n{color:#b9c6bf}
.chip[data-empty="true"]:not([aria-pressed="true"]){color:#626a65;border-style:dashed}

/* ------------------------------------------------ rail */
.carousel{position:relative;margin-top:28px}
.rail{
  display:flex;gap:var(--gap);align-items:stretch;
  overflow-x:auto;overflow-y:hidden;scroll-snap-type:x mandatory;
  padding:8px var(--gutter) 48px;scroll-padding-inline:var(--gutter);
  scrollbar-width:none;overscroll-behavior-x:contain;
  cursor:grab;outline:none;position:relative;
}
.rail::-webkit-scrollbar{display:none}
.rail.is-free{scroll-snap-type:none}
.rail.is-dragging{cursor:grabbing;user-select:none}
.rail.is-dragging .card{pointer-events:none}
.rail:focus-visible{box-shadow:inset 0 0 0 2px var(--focus);border-radius:4px}
.spacer{flex:0 0 1px;margin-left:calc(var(--gap) * -1)}

.card{
  flex:0 0 var(--card-w);scroll-snap-align:start;
  position:relative;display:flex;flex-direction:column;
  background:var(--card);border:1px solid var(--line);border-radius:var(--r);
  padding:24px 24px 22px;min-height:440px;
  transition:border-color .35s,box-shadow .5s var(--ease),transform .5s var(--ease);
}
.card[hidden]{display:none}
.card.is-current{border-color:#c6bca8;box-shadow:0 1px 0 rgba(20,32,27,.04),0 22px 44px -26px rgba(20,32,27,.35)}
.card .row{display:flex;align-items:center;justify-content:space-between;gap:12px}
.org{display:inline-flex;align-items:center;gap:9px;font-size:13px;font-weight:600;letter-spacing:-.005em;min-width:0}
.org svg{width:26px;height:26px;flex:none}
.org span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.quote{
  margin:0;font-family:"Instrument Serif",Georgia,serif;font-size:29px;line-height:1.14;letter-spacing:-.008em;
  color:var(--ink);text-wrap:pretty;
}
.quote p{margin:0}
.clamp::before{content:"\201C";display:block;font-family:"Instrument Serif",Georgia,serif;font-size:64px;line-height:1;height:30px;color:var(--accent);margin:22px 0 4px}
mark{
  color:inherit;background:linear-gradient(var(--hi),var(--hi)) no-repeat 0 88%/0% 42%;
  -webkit-box-decoration-break:clone;box-decoration-break:clone;padding:0 .06em;
  transition:background-size .9s var(--ease) .15s;
}
.card.is-seen mark{background-size:100% 42%}

.clamp{position:relative}
.clamp.is-clamped .quote{max-height:var(--clamp-h,var(--clamp-def));overflow:hidden;-webkit-mask-image:linear-gradient(#000 62%,transparent);mask-image:linear-gradient(#000 62%,transparent)}
.clamp .quote{transition:max-height .6s var(--ease)}
.more{
  appearance:none;border:0;background:none;padding:6px 0;margin-top:10px;cursor:pointer;
  font-size:14px;font-weight:600;color:var(--accent-ink);display:inline-flex;align-items:center;gap:6px;
  text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:4px;
}
.more svg{width:14px;height:14px;transition:transform .35s var(--ease)}
.more[aria-expanded="true"] svg{transform:rotate(180deg)}

.result{margin:auto 0 0;padding-top:28px;display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}
.result b{font-family:"Instrument Serif",Georgia,serif;font-weight:400;font-size:44px;line-height:1;letter-spacing:-.02em;color:var(--accent-ink)}
.result span{font-size:13px;color:var(--muted);max-width:18ch;line-height:1.3}
.result+.who{margin-top:0;padding-top:18px}
.who{margin-top:auto;padding-top:26px;display:flex;align-items:center;gap:14px}
.who img,.mono{width:54px;height:54px;border-radius:50%;object-fit:cover;flex:none;background:var(--sage)}
.mono{display:grid;place-items:center;font-family:"Instrument Serif",Georgia,serif;font-size:24px;color:var(--ink)}
.who b{display:block;font-weight:600;font-size:15px;letter-spacing:-.01em}
.who div span{display:block;font-size:13px;color:var(--muted);line-height:1.35}
.tags{display:flex;gap:6px;margin-top:16px;padding-top:14px;border-top:1px solid var(--line);flex-wrap:wrap}
.tag{font-size:12px;font-weight:500;color:var(--ink-2);background:var(--paper-2);border-radius:99px;padding:3px 10px}

/* voice note variant */
.card.voice{background:var(--night);border-color:var(--night);color:#eef2ee}
.card.voice .org{color:#eef2ee}
.card.voice .stars{color:var(--wave-on)}
.card.voice .tags{border-color:#34463d}
.card.voice .tag{background:var(--night-2);color:#d7e0da}
.card.voice .who div span{color:#b5c2bb}
.card.voice .mono{background:#2d4237;color:#eef2ee}
.card.voice.is-current{box-shadow:0 22px 44px -22px rgba(20,32,27,.6)}
.vlabel{margin:26px 0 12px;font-size:12px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:#b5c2bb;display:flex;align-items:center;gap:8px}
.vlabel i{width:7px;height:7px;border-radius:50%;background:var(--wave-on);display:block}
.player{display:flex;align-items:center;gap:14px}
.play{
  width:52px;height:52px;border-radius:50%;border:0;flex:none;cursor:pointer;
  background:var(--wave-on);color:var(--night);display:grid;place-items:center;
  transition:transform .3s var(--ease),background .3s;
}
.play:hover{transform:scale(1.06)}
.play svg{width:20px;height:20px}
.play .i-pause{display:none}
.voice.is-playing .play .i-play{display:none}
.voice.is-playing .play .i-pause{display:block}
.wave{flex:1;height:52px;display:flex;align-items:center;gap:2px;min-width:0;cursor:pointer}
.wave i{flex:1;min-width:2px;border-radius:2px;background:var(--wave);height:calc(var(--h) * 100%);transform-origin:center;transition:background .2s}
.wave i.on{background:var(--wave-on)}
.voice.is-playing .wave i.live{animation:pulse .5s ease-in-out infinite alternate}
@keyframes pulse{to{transform:scaleY(1.35)}}
.time{font-size:12px;color:#b5c2bb;font-variant-numeric:tabular-nums;width:34px;text-align:right;flex:none}
.transcript{margin:18px 0 0;font-family:"Instrument Serif",Georgia,serif;font-size:24px;line-height:1.2;color:#90a198}
.transcript .w{transition:color .2s}
.transcript .w.said{color:#f4f6f3}
.transcript mark{background-image:linear-gradient(rgba(255,154,107,.38),rgba(255,154,107,.38))}
.vnote{font-size:12px;color:#93a39a;margin:12px 0 0}

/* empty state */
.empty{display:none;margin:8px var(--gutter) 28px;padding:40px 28px;border:1px dashed var(--line);border-radius:var(--r);text-align:center;color:var(--muted)}
.empty.show{display:block}
.empty p{margin:0 0 14px;font-family:"Instrument Serif",Georgia,serif;font-size:28px;color:var(--ink)}

/* ------------------------------------------------ controls */
.controls{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:clamp(16px,3vw,40px);margin-top:-14px}
.nav{display:flex;align-items:center;gap:10px}
.btn-round{
  width:52px;height:52px;border-radius:50%;border:1px solid var(--ink);background:var(--ink);color:var(--paper);
  display:grid;place-items:center;cursor:pointer;flex:none;
  transition:transform .3s var(--ease),background .3s,opacity .3s,color .3s;
}
.btn-round svg{width:20px;height:20px}
.btn-round:hover{transform:translateY(-2px)}
.btn-round.ghost{background:transparent;color:var(--ink)}
.btn-round[disabled]{opacity:.28;cursor:default;transform:none}
.count{font-size:14px;font-weight:500;color:var(--muted);font-variant-numeric:tabular-nums;margin-left:8px;white-space:nowrap}
.count b{color:var(--ink);font-weight:600}

.scrub{position:relative;height:44px;margin-inline:14px;cursor:pointer;touch-action:none;display:flex;align-items:center}
.scrub .trk{position:absolute;left:0;right:0;height:2px;background:var(--line);border-radius:2px}
.scrub .fill{position:absolute;left:0;height:2px;background:var(--ink);border-radius:2px;width:0}
.scrub .ticks{position:absolute;inset:0;pointer-events:none}
.scrub .ticks i{position:absolute;top:50%;width:6px;height:6px;margin:-3px 0 0 -3px;border-radius:50%;background:var(--line);transition:background .3s}
.scrub .ticks i.past{background:var(--ink)}
.scrub .thumb{
  position:absolute;top:50%;left:0;width:28px;height:28px;margin:-14px 0 0 -14px;border-radius:50%;
  background:var(--paper);border:2px solid var(--ink);box-shadow:0 2px 8px rgba(20,32,27,.18);
  transition:transform .25s var(--ease);
}
.scrub:hover .thumb,.scrub.is-grab .thumb{transform:scale(1.12)}
.scrub:focus-visible{outline:none}
.scrub:focus-visible .thumb{outline:2px solid var(--focus);outline-offset:3px}
.scrub .tip{position:absolute;bottom:100%;transform:translateX(-50%);font-size:12px;font-weight:600;background:var(--ink);color:var(--paper);padding:4px 8px;border-radius:6px;white-space:nowrap;opacity:0;transition:opacity .2s;pointer-events:none}
.scrub.is-grab .tip,.scrub:focus-visible .tip{opacity:1}

.auto{display:flex;align-items:center;gap:14px}
.pause{position:relative}
.pause .ring{position:absolute;inset:-5px;width:62px;height:62px;transform:rotate(-90deg);pointer-events:none}
.pause .ring circle{fill:none;stroke:var(--accent);stroke-width:2;stroke-linecap:round}
.pause .i-play{display:none}
.pause[aria-pressed="true"] .i-play{display:block}
.pause[aria-pressed="true"] .i-pause{display:none}
.share{
  appearance:none;border:0;background:none;cursor:pointer;padding:8px 0;font-size:15px;font-weight:600;
  display:inline-flex;align-items:center;gap:8px;white-space:nowrap;
  text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:5px;
}
.share svg{width:16px;height:16px}

/* ------------------------------------------------ dialog */
dialog{border:0;padding:0;border-radius:24px;background:var(--card);color:var(--ink);width:min(520px,calc(100vw - 32px));max-height:calc(100vh - 32px);box-shadow:0 40px 80px -30px rgba(20,32,27,.5)}
dialog::backdrop{background:rgba(20,32,27,.45);backdrop-filter:blur(3px)}
.dlg{padding:28px}
.dlg h3{margin:0 0 6px;font-family:"Instrument Serif",Georgia,serif;font-weight:400;font-size:36px;line-height:1}
.dlg>p{margin:0 0 20px;color:var(--muted);font-size:14px}
.field{display:grid;gap:6px;margin-bottom:14px}
.field label,.field legend{font-size:13px;font-weight:600}
.field input,.field textarea{width:100%;border:1px solid var(--line);border-radius:12px;background:#fff;padding:11px 13px;font-size:15px}
.field textarea{min-height:96px;resize:vertical}
.field input:focus-visible,.field textarea:focus-visible{outline:2px solid var(--focus);outline-offset:1px}
.field [aria-invalid="true"]{border-color:#b3261e}
.err{font-size:12px;color:#b3261e;min-height:0}
fieldset.field{border:0;padding:0;margin:0 0 14px}
.rate{display:flex;gap:4px}
.rate input{position:absolute;opacity:0;width:1px;height:1px}
.rate label{cursor:pointer;color:#c9c1b0;padding:2px}
.rate label svg{width:28px;height:28px;display:block}
.rate label.lit{color:var(--accent)}
.rate input:focus-visible+label{outline:2px solid var(--focus);border-radius:6px}
.dlg .acts{display:flex;justify-content:flex-end;gap:10px;margin-top:8px}
.pill{appearance:none;border:1px solid var(--ink);border-radius:99px;padding:11px 20px;font-weight:600;font-size:15px;cursor:pointer;background:var(--ink);color:var(--paper)}
.pill.ghost{background:transparent;color:var(--ink)}
.thanks{text-align:center;padding:16px 0 6px}
.thanks svg{width:52px;height:52px;color:var(--accent)}

/* live region */
#live{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}

/* ------------------------------------------------ responsive */
@media (max-width:1100px){
  :root{--card-w:360px}
  .quote{font-size:26px}
}
@media (max-width:860px){
  .head{grid-template-columns:1fr;align-items:start}
  .controls{grid-template-columns:1fr auto;grid-template-areas:"scrub scrub" "nav auto";row-gap:14px}
  .scrub{grid-area:scrub}.nav{grid-area:nav}.auto{grid-area:auto}
}
@media (max-width:600px){
  :root{--clamp-def:7.2em;--gutter:16px;--card-w:min(86vw,340px);--gap:12px;--r:18px}
  .brand small{display:none}
  h2{font-size:clamp(40px,11.5vw,52px)}
  .facts b{font-size:26px}
  .summary{padding:20px}
  .avg{font-size:64px}
  .filters{flex-direction:column;align-items:stretch;gap:12px}
  .fgroup{flex-direction:column;align-items:flex-start;gap:8px}
  .flabel{padding-top:0}
  .chips{flex-wrap:nowrap;overflow-x:auto;max-width:100%;scrollbar-width:none;margin-inline:calc(var(--gutter) * -1);padding-inline:var(--gutter);width:calc(100% + var(--gutter) * 2);
    -webkit-mask-image:linear-gradient(90deg,transparent,#000 16px,#000 calc(100% - 28px),transparent);mask-image:linear-gradient(90deg,transparent,#000 16px,#000 calc(100% - 28px),transparent)}
  .chips::-webkit-scrollbar{display:none}
  .rail{align-items:flex-start}
  .card{padding:20px 20px 18px;min-height:0}
  .quote{font-size:24px}
  .clamp::before{margin-top:16px}
  .transcript{font-size:21px}
  .btn-round{width:46px;height:46px}
  .pause .ring{width:56px;height:56px}
  .share .lbl-long{display:none}
}
@media (prefers-reduced-motion:reduce){
  *,*::before,*::after{transition-duration:.01ms!important;animation:none!important}
  mark{background-size:100% 42%!important}
}
</style>
</head>
<body>
<a class="skip" href="#after-stories">Skip customer stories</a>

<section class="stories" id="stories" aria-labelledby="stories-title">
  <div class="wrap">
    <div class="brand">
      <svg viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="9" fill="#14201b"/><path d="M9 21.5c2.4-6.6 4.6-9.6 7-9.6s3.2 4.3 7 4.3" fill="none" stroke="#f4f1ea" stroke-width="2.4" stroke-linecap="round"/><circle cx="23" cy="10.5" r="2.4" fill="#e2552a"/></svg>
      Paceline <small>Scheduling for clinics</small>
    </div>

    <header class="head">
      <div>
        <p class="eyebrow">Customer stories</p>
        <h2 id="stories-title">Fewer gaps in the diary. <em>More time</em> with patients.</h2>
        <p class="lead">Front desks, practice managers and clinicians on what changed after they moved their booking, reminders and waitlists to Paceline.</p>
        <ul class="facts" aria-label="Results across customers">
          <li><b>&minus;38%</b> no-shows</li>
          <li><b>6.2 h</b> saved per desk, weekly</li>
          <li><b>2,400</b> clinics</li>
        </ul>
      </div>

      <aside class="summary" aria-labelledby="sum-title">
        <h3 class="sr" id="sum-title">Rating summary</h3>
        <div class="top">
          <span class="avg" id="avg" aria-hidden="true">4.8</span>
          <p><span class="stars" id="avg-stars" aria-hidden="true"></span><strong id="avg-text">4.8 out of 5</strong><span id="avg-n">1,186 verified reviews</span></p>
        </div>
        <ul class="bars" id="bars" aria-label="Distribution of star ratings"></ul>
        <p class="scope" id="scope">All clinic types</p>
      </aside>
    </header>

    <div class="filters" role="group" aria-label="Filter stories">
      <div class="fgroup">
        <span class="flabel" id="lab-ind">Specialty</span>
        <div class="chips" id="chips-ind" role="group" aria-labelledby="lab-ind"></div>
      </div>
      <div class="fgroup">
        <span class="flabel" id="lab-size">Team</span>
        <div class="chips" id="chips-size" role="group" aria-labelledby="lab-size"></div>
      </div>
    </div>
  </div>

  <div class="carousel" id="carousel" aria-roledescription="carousel" aria-label="Customer stories" role="region">
    <div class="rail" id="rail" tabindex="0" aria-label="Stories, use left and right arrow keys to move between them"></div>
    <div class="empty" id="empty" role="status">
      <p>No stories match that combination yet.</p>
      <button type="button" class="pill ghost" id="clear">Clear filters</button>
    </div>

    <div class="wrap">
      <div class="controls">
        <div class="nav">
          <button type="button" class="btn-round ghost" id="prev" aria-controls="rail" aria-label="Previous story">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
          </button>
          <button type="button" class="btn-round" id="next" aria-controls="rail" aria-label="Next story">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </button>
          <span class="count" id="count" aria-hidden="true"><b>01</b> / 08</span>
        </div>

        <div class="scrub" id="scrub" role="slider" tabindex="0" aria-label="Story position" aria-controls="rail" aria-valuemin="1" aria-valuemax="8" aria-valuenow="1">
          <span class="trk"></span><span class="fill" id="fill"></span>
          <span class="ticks" id="ticks"></span>
          <span class="thumb" id="thumb"><span class="tip" id="tip"></span></span>
        </div>

        <div class="auto">
          <button type="button" class="btn-round ghost pause" id="pause" aria-pressed="false" aria-label="Pause auto-advance">
            <svg class="ring" viewBox="0 0 62 62" aria-hidden="true"><circle id="ring" cx="31" cy="31" r="29" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100"/></svg>
            <svg class="i-pause" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6.5" y="5" width="3.6" height="14" rx="1"/><rect x="13.9" y="5" width="3.6" height="14" rx="1"/></svg>
            <svg class="i-play" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.5v13a1 1 0 0 0 1.5.86l10.2-6.5a1 1 0 0 0 0-1.72L9.5 4.64A1 1 0 0 0 8 5.5Z"/></svg>
          </button>
          <button type="button" class="share" id="share">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>
            <span>Share<span class="lbl-long"> your story</span></span>
          </button>
        </div>
      </div>
    </div>
  </div>
  <div id="live" aria-live="polite" aria-atomic="true"></div>
</section>
<div id="after-stories" tabindex="-1"></div>

<dialog id="dlg" aria-labelledby="dlg-title">
  <div class="dlg">
    <form id="form" novalidate>
      <h3 id="dlg-title">Share your story</h3>
      <p>Tell other clinics how Paceline works for your team. We read every one.</p>
      <div class="field"><label for="f-name">Your name</label><input id="f-name" name="name" autocomplete="name" aria-describedby="e-name"><span class="err" id="e-name"></span></div>
      <div class="field"><label for="f-clinic">Clinic</label><input id="f-clinic" name="clinic" autocomplete="organization" aria-describedby="e-clinic"><span class="err" id="e-clinic"></span></div>
      <div class="field"><label for="f-email">Work email</label><input id="f-email" name="email" type="email" autocomplete="email" aria-describedby="e-email"><span class="err" id="e-email"></span></div>
      <fieldset class="field" aria-describedby="e-rate"><legend>Rating</legend><div class="rate" id="rate"></div><span class="err" id="e-rate"></span></fieldset>
      <div class="field"><label for="f-msg">What changed for you?</label><textarea id="f-msg" name="msg" aria-describedby="e-msg"></textarea><span class="err" id="e-msg"></span></div>
      <div class="acts"><button type="button" class="pill ghost" id="cancel">Cancel</button><button type="submit" class="pill">Send story</button></div>
    </form>
    <div class="thanks" id="thanks" hidden>
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="m7.5 12.5 3 3 6-7"/></svg>
      <h3 tabindex="-1" id="thanks-title">Thank you</h3>
      <p>Your story is with our team. We will email you before anything is published.</p>
      <div class="acts" style="justify-content:center"><button type="button" class="pill" id="done">Close</button></div>
    </div>
  </div>
</dialog>

<script>
(() => {
'use strict';
const $ = s => document.querySelector(s);
const reduced = matchMedia('(prefers-reduced-motion: reduce)');
const STAR = '<svg viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path d="m10 1.6 2.6 5.3 5.8.8-4.2 4.1 1 5.8L10 14.9l-5.2 2.7 1-5.8L1.6 7.7l5.8-.8z"/></svg>';
const stars = n => Array.from({length:5},(_,i)=>i<n?STAR:STAR.replace('currentColor','currentColor" opacity=".25')).join('');

/* fictional clinic marks, inline SVG */
const MARKS = {
  harbour:'<rect width="26" height="26" rx="8" fill="#1d4f5c"/><path d="M5 15.5c2 0 2-1.6 4-1.6s2 1.6 4 1.6 2-1.6 4-1.6 2 1.6 4 1.6M5 19.5c2 0 2-1.6 4-1.6s2 1.6 4 1.6 2-1.6 4-1.6 2 1.6 4 1.6" fill="none" stroke="#e8f2ef" stroke-width="1.6" stroke-linecap="round"/><circle cx="13" cy="8.5" r="2.6" fill="#ffb347"/>',
  bright:'<rect width="26" height="26" rx="13" fill="#e9e3f7"/><path d="M8.2 8.8c1.6-1.3 3.2-.8 4.8.2 1.6-1 3.2-1.5 4.8-.2 1.6 1.5.6 5-.4 8.4-.4 1.4-1.6 1.4-2 0L14.4 14c-.4-1-2.4-1-2.8 0l-1 3.2c-.4 1.4-1.6 1.4-2 0-1-3.4-2-6.9-.4-8.4Z" fill="#4b2f8f"/>',
  fern:'<rect width="26" height="26" rx="8" fill="#e3ecd6"/><path d="M13 21V7" stroke="#2f5a2a" stroke-width="1.6" stroke-linecap="round"/><path d="M13 9c-2-.2-3.6-1.2-4.4-2.8M13 12.5c-2.6-.2-4.6-1.4-5.6-3.4M13 16c-2.6 0-4.8-1.2-6-3.2M13 9c2-.2 3.6-1.2 4.4-2.8M13 12.5c2.6-.2 4.6-1.4 5.6-3.4M13 16c2.6 0 4.8-1.2 6-3.2" fill="none" stroke="#2f5a2a" stroke-width="1.5" stroke-linecap="round"/>',
  oak:'<rect width="26" height="26" rx="8" fill="#7a4a24"/><circle cx="13" cy="11" r="5.6" fill="#f2d9b8"/><path d="M13 16.6V21M10.4 21h5.2" stroke="#f2d9b8" stroke-width="1.8" stroke-linecap="round"/><path d="M13 7.8v6.4M9.8 11h6.4" stroke="#7a4a24" stroke-width="1.8" stroke-linecap="round"/>',
  lumen:'<rect width="26" height="26" rx="13" fill="#f6e2d6"/><circle cx="13" cy="13" r="4" fill="#c2542d"/><path d="M13 3.8v2.6M13 19.6v2.6M3.8 13h2.6M19.6 13h2.6M6.5 6.5l1.8 1.8M17.7 17.7l1.8 1.8M6.5 19.5l1.8-1.8M17.7 8.3l1.8-1.8" stroke="#c2542d" stroke-width="1.6" stroke-linecap="round"/>',
  steps:'<rect width="26" height="26" rx="8" fill="#fde7a1"/><ellipse cx="10" cy="15.5" rx="2.6" ry="4" fill="#6a4b00" transform="rotate(-12 10 15.5)"/><ellipse cx="16.4" cy="10.5" rx="2.6" ry="4" fill="#6a4b00" transform="rotate(12 16.4 10.5)"/>',
  salt:'<rect width="26" height="26" rx="8" fill="#2d4237"/><path d="M5 18h16M7 18c0-4.4 2.6-8 6-8s6 3.6 6 8" fill="none" stroke="#ff9a6b" stroke-width="1.8" stroke-linecap="round"/><path d="M13 6.2v2" stroke="#ff9a6b" stroke-width="1.8" stroke-linecap="round"/>',
  north:'<rect width="26" height="26" rx="8" fill="#14201b"/><path d="M7 19V7l12 12V7" fill="none" stroke="#f4f1ea" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>'
};

const IND = {physio:'Physio & osteo',dental:'Dental',vet:'Veterinary',gp:'General practice',derm:'Dermatology',paeds:'Paediatrics'};
const SIZE = {s:'1–10',m:'11–50',l:'50+'};

/* stories: [[...]] marks the key phrase */
const STORIES = [
  {id:'margaret',result:['0','double bookings since March'],name:'Margaret Hale',role:'Clinic Director',org:'Harbour Physio',mark:'harbour',ind:'physio',size:'m',rating:5,img:'assets/margaret.webp',
   alt:'Margaret Hale, a woman in her fifties with short silver hair, smiling',
   quote:['We used to spend Monday mornings untangling double bookings across four treatment rooms. Now [[the diary sorts itself out before the kettle has boiled]].']},
  {id:'daniel',result:['&minus;38%','no-shows in one quarter'],name:'Daniel Reeve',role:'Operations Manager',org:'Brightside Dental',mark:'bright',ind:'dental',size:'m',rating:5,img:'assets/daniel.webp',
   alt:'Daniel Reeve, a man in his thirties with a short beard and a light blue shirt',
   quote:['Recall appointments were our blind spot. Patients meant to come back every six months and simply drifted. Paceline sends the nudge, offers three slots and books whichever one they tap.',
          'Within one quarter [[our no-show rate fell from 11% to under 7%]], and the front desk stopped spending afternoons on the phone chasing people who were never going to pick up. The hygienists noticed first: their columns were finally full.']},
  {id:'nia',result:['71%','of clients rebook from the reminder'],name:'Nia Adeyemi',role:'Head Nurse',org:'Fernlea Veterinary',mark:'fern',ind:'vet',size:'s',rating:5,img:'assets/nia.webp',
   alt:'Nia Adeyemi, a young woman with curly hair tied back, wearing green scrubs',
   quote:['Pet owners are busy people. [[They rebook straight from the text reminder]] instead of ringing us at nine on a Monday, which is when we are busiest.']},
  {id:'priya',voice:true,name:'Priya Shah',role:'Osteopath and owner',org:'Saltmarsh Osteopathy',mark:'salt',ind:'physio',size:'s',rating:5,dur:21,
   quote:['Honestly, the waitlist is the bit I would not give up. Someone cancels at eight, [[the slot is filled by half past]], and I never touched my phone.']},
  {id:'tom',result:['3 in 4','patients over 70 book online'],name:'Dr Tom Whitlock',role:'GP Partner',org:'Oakmere Family Practice',mark:'oak',ind:'gp',size:'s',rating:4,img:'assets/tom.webp',
   alt:'Dr Tom Whitlock, an older man with white hair and round glasses, in a dark cardigan',
   quote:['I was sceptical about yet another system. What won me over was that [[patients over seventy use it without help]]. The large-text booking page was a small thing that mattered.']},
  {id:'grace',result:['9 sites','on one shared diary'],name:'Grace Lin',role:'Group Practice Manager',org:'Lumen Skin Clinics',mark:'lumen',ind:'derm',size:'l',rating:5,img:'assets/grace.webp',
   alt:'Grace Lin, a woman in her forties with straight black hair and a rust blouse',
   quote:['We run nine sites and every one of them had its own spreadsheet, its own habits and its own reasons why the other eight were doing it wrong.',
          'Moving to one shared diary took a fortnight. Now [[I can see every free chair across the group on one screen]], and when a laser room sits empty in Leeds we can offer it to the waitlist in York the same morning. That alone paid for the year.']},
  {id:'mateo',result:['52%','of bookings made after hours'],name:'Mateo Ruiz',role:'Front Desk Lead',org:'Little Steps Paediatrics',mark:'steps',ind:'paeds',size:'m',rating:5,img:'assets/mateo.webp',
   alt:'Mateo Ruiz, a smiling man with short dark hair wearing a mustard sweater',
   quote:['Parents book at eleven at night, when the kids are finally asleep. [[Half our appointments now arrive while we are closed]], and the morning queue at the desk has all but gone.']},
  {id:'owen',result:['23','practices live in six weeks'],name:'Owen Price',role:'Regional Lead',org:'Northgate Dental Group',mark:'north',ind:'dental',size:'l',rating:4,
   quote:['Rolling out to 23 practices, I expected a revolt. Instead [[the training took one lunchtime per site]]. Our only wish is for deeper payroll reporting, which they tell us is coming.']}
];

const STATS = {
  all:{avg:4.8,n:1186,d:[84,11,3,1,1]}, physio:{avg:4.9,n:312,d:[89,8,2,1,0]}, dental:{avg:4.7,n:405,d:[79,14,4,2,1]},
  vet:{avg:4.8,n:141,d:[83,13,3,1,0]}, gp:{avg:4.6,n:166,d:[72,19,6,2,1]}, derm:{avg:4.8,n:97,d:[85,10,3,1,1]}, paeds:{avg:4.9,n:65,d:[90,7,2,1,0]}
};

const esc = s => String(s).replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m]));
const rich = s => esc(s).replace(/\[\[(.+?)\]\]/g,'<mark>$1</mark>');
const plain = s => s.replace(/\[\[|\]\]/g,'');
const pad2 = n => String(n).padStart(2,'0');

/* ------------------------------------------------ render cards */
const rail = $('#rail');
function waveBars(seed){
  let x = seed, out = '';
  for(let i=0;i<46;i++){ x = (x*9301+49297)%233280; const r = x/233280; const env = .35+.65*Math.sin(Math.PI*(i+1)/47); out += `<i style="--h:${(.16+r*.84*env).toFixed(2)}"></i>`; }
  return out;
}
function cardHTML(s,i){
  const who = s.img
    ? `<img src="${s.img}" alt="" width="54" height="54" loading="lazy" decoding="async">`
    : `<span class="mono" aria-hidden="true">${esc(s.name.split(' ').map(w=>w[0]).join('').slice(0,2))}</span>`;
  const head = `<div class="row"><span class="org"><svg viewBox="0 0 26 26" aria-hidden="true">${MARKS[s.mark]}</svg><span>${esc(s.org)}</span></span><span class="stars" role="img" aria-label="${s.rating} out of 5 stars">${stars(s.rating)}</span></div>`;
  const result = s.result ? `<p class="result"><b>${s.result[0]}</b><span>${s.result[1]}</span></p>` : '';
  const foot = `${result}<div class="who">${who}<div><b>${esc(s.name)}</b><span>${esc(s.role)}, ${esc(s.org)}</span></div></div>
    <div class="tags"><span class="tag">${IND[s.ind]}</span><span class="tag">${SIZE[s.size]} staff</span></div>`;
  let body;
  if(s.voice){
    const words = plain(s.quote.join(' ')).split(' ');
    let k = 0;
    const tx = rich(s.quote.join(' ')).replace(/(<mark>)|(<\/mark>)|([^\s<>]+)/g,(m,a,b,w)=> a||b ? m : `<span class="w" data-k="${k++}">${w}</span>`);
    body = `<p class="vlabel"><i></i>Voice note &middot; 0:${pad2(s.dur)}</p>
      <div class="player"><button type="button" class="play" aria-label="Play voice note from ${esc(s.name)}">
        <svg class="i-play" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5.5v13a1 1 0 0 0 1.5.86l10.2-6.5a1 1 0 0 0 0-1.72L9.5 4.64A1 1 0 0 0 8 5.5Z"/></svg>
        <svg class="i-pause" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6.5" y="5" width="3.6" height="14" rx="1"/><rect x="13.9" y="5" width="3.6" height="14" rx="1"/></svg></button>
        <div class="wave" aria-hidden="true">${waveBars(7)}</div><span class="time" aria-hidden="true">0:${pad2(s.dur)}</span></div>
      <blockquote class="transcript" data-words="${words.length}"><p>${tx}</p></blockquote>
      <p class="vnote">Transcript shown; playback reads it aloud where your browser supports speech.</p>`;
  } else {
    const long = s.quote.length > 1;
    body = `<div class="clamp${long?' is-clamped':''}"><blockquote class="quote" id="q-${s.id}">${s.quote.map(p=>`<p>${rich(p)}</p>`).join('<p style="height:.5em"></p>')}</blockquote>
      ${long?`<button type="button" class="more" aria-expanded="false" aria-controls="q-${s.id}">Read the full story<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></button>`:''}</div>`;
  }
  return `<article class="card${s.voice?' voice':''}" data-id="${s.id}" data-ind="${s.ind}" data-size="${s.size}" role="group" aria-roledescription="slide" aria-label="${esc(s.name)}, ${esc(s.org)}">${head}${body}${foot}</article>`;
}
rail.innerHTML = STORIES.map(cardHTML).join('') + '<span class="spacer" aria-hidden="true"></span>';
const cards = [...rail.querySelectorAll('.card')];
const spacer = rail.querySelector('.spacer');

/* ------------------------------------------------ live announcements */
const live = $('#live');
let liveT;
function announce(msg){ clearTimeout(liveT); live.textContent=''; liveT=setTimeout(()=>{ live.textContent = msg; },60); }

/* ------------------------------------------------ carousel core */
const state = {ind:'all', size:'any', index:0, userPaused:reduced.matches, hover:false, focus:false, hidden:document.hidden, offscreen:false, dragging:false, voice:false, dialog:false};
const visible = () => cards.filter(c=>!c.hidden);
const padStart = () => parseFloat(getComputedStyle(rail).paddingLeft)||0;
const targetOf = c => c.offsetLeft - padStart();
const maxScroll = () => Math.max(0, rail.scrollWidth - rail.clientWidth);

function sizeSpacer(){
  const v = visible(); if(!v.length) return;
  const last = v[v.length-1];
  const w = Math.max(1, rail.clientWidth - last.offsetWidth - padStart()*2 + 2);
  spacer.style.flexBasis = w + 'px';
}
function nearest(pos){
  const v = visible(); let best=0, bd=Infinity;
  v.forEach((c,i)=>{ const d=Math.abs(targetOf(c)-pos); if(d<bd){bd=d;best=i} });
  return best;
}

let anim = null;
function animateTo(x, dur){
  cancelAnimationFrame(anim);
  x = Math.max(0, Math.min(maxScroll(), x));
  if(reduced.matches || dur===0){ rail.classList.add('is-free'); rail.scrollLeft = x; requestAnimationFrame(()=>rail.classList.remove('is-free')); onScroll(); return; }
  const from = rail.scrollLeft, dist = x-from;
  if(Math.abs(dist) < 1){ rail.classList.remove('is-free'); return; }
  dur = dur || Math.min(900, Math.max(380, 300 + Math.abs(dist)*.35));
  const t0 = performance.now();
  rail.classList.add('is-free');
  const step = now => {
    const t = Math.min(1,(now-t0)/dur), e = 1-Math.pow(1-t,4); // easeOutQuart
    rail.scrollLeft = from + dist*e;
    if(t<1) anim = requestAnimationFrame(step);
    else { rail.scrollLeft = x; anim = null; requestAnimationFrame(()=>rail.classList.remove('is-free')); }
  };
  anim = requestAnimationFrame(step);
}
let userNavAt = 0;
function go(i, opts={}){
  const v = visible(); if(!v.length) return;
  if(opts.loop) i = (i + v.length) % v.length;
  i = Math.max(0, Math.min(v.length-1, i));
  if(!opts.auto) userNavAt = performance.now();
  state.index = i; restartTimer();
  animateTo(targetOf(v[i]), opts.dur);
  paint(true);
}

/* paint: counter, scrubber, current card, buttons */
const prev=$('#prev'), next=$('#next'), count=$('#count'), scrub=$('#scrub'), thumb=$('#thumb'), fill=$('#fill'), tip=$('#tip'), ticks=$('#ticks');
let lastAnnounced = -1;
function paint(fromGo){
  const v = visible(), n = v.length, i = state.index;
  prev.disabled = i<=0 || !n; next.disabled = i>=n-1 || !n;
  count.innerHTML = n ? `<b>${pad2(i+1)}</b> / ${pad2(n)}` : '<b>00</b> / 00';
  cards.forEach(c=>c.classList.toggle('is-current', c===v[i]));
  const s = v[i] && STORIES.find(x=>x.id===v[i].dataset.id);
  scrub.setAttribute('aria-valuemax', Math.max(1,n));
  scrub.setAttribute('aria-valuenow', i+1);
  scrub.setAttribute('aria-valuetext', s ? `Story ${i+1} of ${n}: ${s.name}, ${s.org}` : 'No stories');
  tip.textContent = s ? s.name : '';
  [...ticks.children].forEach((t,k)=>t.classList.toggle('past', k<=i));
  if(s && performance.now()-userNavAt < 1500 && lastAnnounced !== i+'|'+n){
    lastAnnounced = i+'|'+n;
    announce(`Story ${i+1} of ${n}: ${s.name}, ${s.role} at ${s.org}.`);
  }
}
function paintThumb(){
  const m = maxScroll(), p = m ? Math.min(1, rail.scrollLeft/m) : 0;
  const w = scrub.clientWidth;
  thumb.style.left = (p*w)+'px'; fill.style.width = (p*w)+'px';
}
function buildTicks(){
  const v = visible(), m = maxScroll();
  ticks.innerHTML = v.map(c=>`<i style="left:${m? Math.min(100, targetOf(c)/m*100):0}%"></i>`).join('');
}

let sraf = 0;
function onScroll(){
  if(sraf) return;
  sraf = requestAnimationFrame(()=>{
    sraf = 0; paintThumb();
    if(!anim){ const i = nearest(rail.scrollLeft); if(i!==state.index){ state.index=i; restartTimer(); paint(); } }
  });
}
rail.addEventListener('scroll', onScroll, {passive:true});

prev.addEventListener('click',()=>go(state.index-1));
next.addEventListener('click',()=>go(state.index+1));
rail.addEventListener('keydown',e=>{
  if(e.target!==rail) return;
  if(e.key==='ArrowRight'){e.preventDefault();go(state.index+1)}
  else if(e.key==='ArrowLeft'){e.preventDefault();go(state.index-1)}
  else if(e.key==='Home'){e.preventDefault();go(0)}
  else if(e.key==='End'){e.preventDefault();go(visible().length-1)}
});

/* momentum drag for mouse / pen (touch uses native scroll + snap) */
let drag = null, suppressClick = false;
rail.addEventListener('pointerdown',e=>{
  if(e.pointerType==='touch' || e.button!==0 || e.target.closest('button,a,input,.wave')) return;
  cancelAnimationFrame(anim); anim=null;
  drag = {x:e.clientX, s:rail.scrollLeft, id:e.pointerId, moved:false, samples:[[performance.now(),e.clientX]]};
});
rail.addEventListener('pointermove',e=>{
  if(!drag || e.pointerId!==drag.id) return;
  const dx = e.clientX - drag.x;
  if(!drag.moved){
    if(Math.abs(dx)<5) return;
    drag.moved = true; state.dragging = true;
    rail.classList.add('is-free','is-dragging');
    try{rail.setPointerCapture(e.pointerId)}catch(_){}
  }
  rail.scrollLeft = drag.s - dx;
  const now = performance.now();
  drag.samples.push([now,e.clientX]);
  while(drag.samples.length>2 && now - drag.samples[0][0] > 90) drag.samples.shift();
});
function endDrag(e){
  if(!drag) return;
  const d = drag; drag = null;
  if(!d.moved) return;
  state.dragging = false; suppressClick = true; setTimeout(()=>suppressClick=false,0);
  rail.classList.remove('is-dragging');
  const a = d.samples[0], b = d.samples[d.samples.length-1];
  const v = (b[0]-a[0]) > 0 ? (b[1]-a[1])/(b[0]-a[0]) : 0; // px per ms
  const projected = rail.scrollLeft - v*260;                 // momentum projection
  let i = nearest(projected);
  if(i===state.index && Math.abs(v)>.35) i += v<0 ? 1 : -1;  // a quick flick always moves at least one card
  userNavAt = performance.now();
  go(i, {dur: Math.min(900, Math.max(420, 380 + Math.abs(v)*120))});
}
rail.addEventListener('pointerup',endDrag);
rail.addEventListener('pointercancel',endDrag);
rail.addEventListener('lostpointercapture',endDrag);
rail.addEventListener('click',e=>{ if(suppressClick){e.preventDefault();e.stopPropagation()} },true);
rail.addEventListener('dragstart',e=>e.preventDefault());

/* scrubber: drag, click, keyboard */
let sdrag = false;
function scrubTo(clientX){
  const r = scrub.getBoundingClientRect(); const p = Math.max(0,Math.min(1,(clientX-r.left)/r.width));
  rail.classList.add('is-free'); cancelAnimationFrame(anim); anim=null;
  rail.scrollLeft = p*maxScroll();
}
scrub.addEventListener('pointerdown',e=>{
  if(e.button!==0) return;
  sdrag = true; state.dragging = true; scrub.classList.add('is-grab');
  try{scrub.setPointerCapture(e.pointerId)}catch(_){}
  userNavAt = performance.now(); scrubTo(e.clientX); e.preventDefault(); scrub.focus({preventScroll:true});
});
scrub.addEventListener('pointermove',e=>{ if(sdrag){ userNavAt = performance.now(); scrubTo(e.clientX) } });
function endScrub(){ if(!sdrag) return; sdrag=false; state.dragging=false; scrub.classList.remove('is-grab'); go(nearest(rail.scrollLeft)); }
scrub.addEventListener('pointerup',endScrub); scrub.addEventListener('pointercancel',endScrub);
scrub.addEventListener('keydown',e=>{
  const n = visible().length, map = {ArrowRight:1,ArrowUp:1,ArrowLeft:-1,ArrowDown:-1,PageUp:2,PageDown:-2};
  if(e.key in map){ e.preventDefault(); go(state.index+map[e.key]); }
  else if(e.key==='Home'){ e.preventDefault(); go(0) }
  else if(e.key==='End'){ e.preventDefault(); go(n-1) }
});

/* ------------------------------------------------ highlight draws when a card is fully in view */
const seenIO = 'IntersectionObserver' in window ? new IntersectionObserver(es=>{
  es.forEach(en=>{ if(en.intersectionRatio>.82) en.target.classList.add('is-seen') });
},{root:rail, threshold:[.82]}) : null;
cards.forEach(c=> seenIO ? seenIO.observe(c) : c.classList.add('is-seen'));

/* ------------------------------------------------ expand long quotes */
function measureClamp(){
  rail.querySelectorAll('.clamp.is-clamped .quote').forEach(q=>{ q.style.removeProperty('--clamp-h') });
}
rail.addEventListener('click',e=>{
  const b = e.target.closest('.more'); if(!b) return;
  const wrap = b.parentElement, q = wrap.querySelector('.quote'), open = b.getAttribute('aria-expanded')==='true';
  if(!open){
    q.style.setProperty('--clamp-h', q.scrollHeight+'px');
    b.setAttribute('aria-expanded','true'); b.firstChild.textContent = 'Show less';
    requestAnimationFrame(()=>wrap.classList.remove('is-clamped'));
    setTimeout(()=>{ q.style.maxHeight='none' },620);
  } else {
    q.style.maxHeight=''; q.style.setProperty('--clamp-h', q.scrollHeight+'px');
    wrap.classList.add('is-clamped');
    requestAnimationFrame(()=>requestAnimationFrame(()=>q.style.removeProperty('--clamp-h')));
    b.setAttribute('aria-expanded','false'); b.firstChild.textContent = 'Read the full story';
  }
  const card = b.closest('.card'), i = visible().indexOf(card);
  if(i>-1 && i!==state.index) go(i);
});

/* ------------------------------------------------ voice note */
const vcard = rail.querySelector('.card.voice');
if(vcard){
  const s = STORIES.find(x=>x.voice), bars = [...vcard.querySelectorAll('.wave i')], words = [...vcard.querySelectorAll('.transcript .w')];
  const btn = vcard.querySelector('.play'), time = vcard.querySelector('.time');
  const text = plain(s.quote.join(' '));
  const speech = 'speechSynthesis' in window && typeof SpeechSynthesisUtterance !== 'undefined';
  let t0=0, p0=0, raf=0, boundaryWord=-1, utter=null;
  const DUR = s.dur*1000;
  function setProgress(p){
    const on = Math.floor(p*bars.length);
    bars.forEach((b,k)=>{ b.classList.toggle('on',k<on); b.classList.toggle('live',k>=on-2&&k<on+1&&p<1&&p>0) });
    const wk = boundaryWord>=0 ? boundaryWord : Math.floor(p*words.length);
    words.forEach((w,k)=>w.classList.toggle('said',k<=wk && p>0));
    const left = Math.max(0, Math.round(s.dur*(1-p)));
    time.textContent = '0:'+pad2(p>0&&p<1?left:s.dur);
  }
  function tick(now){
    let p = p0 + (now-t0)/DUR;
    if(boundaryWord>=0) p = Math.max(p, (boundaryWord+1)/words.length);
    if(p>=1){ stop(true); return; }
    setProgress(p); raf = requestAnimationFrame(tick);
  }
  function play(){
    state.voice = true; vcard.classList.add('is-playing'); btn.setAttribute('aria-label',`Pause voice note from ${s.name}`);
    if(p0>=1) p0=0;
    boundaryWord = -1; t0 = performance.now(); raf = requestAnimationFrame(tick);
    if(speech){
      try{
        speechSynthesis.cancel();
        const spoken = words.slice(Math.floor(p0*words.length)).map(w=>w.textContent).join(' ');
        const offset = Math.floor(p0*words.length);
        utter = new SpeechSynthesisUtterance(spoken); utter.rate = .98;
        utter.onboundary = ev => { if(ev.name && ev.name!=='word') return; const idx = spoken.slice(0, ev.charIndex).split(' ').length - 1; boundaryWord = offset + idx; };
        speechSynthesis.speak(utter);
      }catch(_){}
    }
  }
  function stop(done){
    cancelAnimationFrame(raf); state.voice=false; vcard.classList.remove('is-playing');
    btn.setAttribute('aria-label',`Play voice note from ${s.name}`);
    if(done){ p0=0; setProgress(0); words.forEach(w=>w.classList.add('said')); }
    else { p0 = Math.min(1, p0 + (performance.now()-t0)/DUR); }
    if(speech) try{ speechSynthesis.cancel() }catch(_){}
    restartTimer();
  }
  btn.addEventListener('click',()=>{ vcard.classList.contains('is-playing') ? stop(false) : play(); const i=visible().indexOf(vcard); if(i>-1&&i!==state.index) go(i); });
  vcard.querySelector('.wave').addEventListener('click',e=>{
    const r = e.currentTarget.getBoundingClientRect(); const was = vcard.classList.contains('is-playing');
    if(was) stop(false);
    p0 = Math.max(0,Math.min(.99,(e.clientX-r.left)/r.width)); boundaryWord=-1; setProgress(p0); play();
  });
  words.forEach(w=>w.classList.add('said'));
  vcard._stop = () => { if(vcard.classList.contains('is-playing')) stop(false) };
}

/* ------------------------------------------------ rating summary */
const barsEl = $('#bars');
barsEl.innerHTML = [5,4,3,2,1].map(k=>`<li><span>${k}&#9733;</span><span class="bar"><i></i></span><span>0%</span></li>`).join('');
$('#avg-stars').innerHTML = stars(5);
let sumShown = false, avgRaf = 0;
function paintSummary(animate){
  const st = STATS[state.ind];
  [...barsEl.children].forEach((li,k)=>{
    li.querySelector('i').style.transform = `scaleX(${sumShown? st.d[k]/100 : 0})`;
    li.lastElementChild.textContent = st.d[k]+'%';
    li.setAttribute('aria-label', `${5-k} stars: ${st.d[k]} percent`);
  });
  $('#avg-text').textContent = `${st.avg.toFixed(1)} out of 5`;
  $('#avg-n').textContent = `${st.n.toLocaleString('en-GB')} verified reviews`;
  $('#scope').textContent = state.ind==='all' ? 'All clinic types' : `Showing ${IND[state.ind]} clinics`;
  const el = $('#avg'), from = parseFloat(el.textContent)||0, to = st.avg;
  cancelAnimationFrame(avgRaf);
  if(!animate || reduced.matches){ el.textContent = to.toFixed(1); return; }
  const t0 = performance.now();
  const f = now => { const t=Math.min(1,(now-t0)/800), e=1-Math.pow(1-t,3); el.textContent=(from+(to-from)*e).toFixed(1); if(t<1) avgRaf=requestAnimationFrame(f) };
  avgRaf = requestAnimationFrame(f);
}
paintSummary(false);
const sumIO = 'IntersectionObserver' in window ? new IntersectionObserver(es=>{
  if(es.some(e=>e.isIntersecting)){ sumShown = true; $('#avg').textContent='0.0'; paintSummary(true); sumIO.disconnect(); }
},{threshold:.4}) : null;
sumIO ? sumIO.observe($('.summary')) : (sumShown=true, paintSummary(false));

/* ------------------------------------------------ filters with FLIP */
function counts(){
  const ci = {all:0}, cs = {any:0};
  STORIES.forEach(s=>{
    if(state.size==='any'||s.size===state.size){ ci.all++; ci[s.ind]=(ci[s.ind]||0)+1 }
    if(state.ind==='all'||s.ind===state.ind){ cs.any++; cs[s.size]=(cs[s.size]||0)+1 }
  });
  return {ci,cs};
}
function renderChips(){
  const {ci,cs} = counts();
  $('#chips-ind').innerHTML = [['all','All'],...Object.entries(IND)].map(([k,l])=>
    `<button type="button" class="chip" data-g="ind" data-v="${k}" aria-pressed="${state.ind===k}" data-empty="${!ci[k]}">${l}<span class="n" aria-label="${ci[k]||0} stories">${ci[k]||0}</span></button>`).join('');
  $('#chips-size').innerHTML = [['any','Any size'],...Object.entries(SIZE).map(([k,l])=>[k,l])].map(([k,l])=>
    `<button type="button" class="chip" data-g="size" data-v="${k}" aria-pressed="${state.size===k}" data-empty="${!cs[k]}">${l}<span class="n" aria-label="${cs[k]||0} stories">${cs[k]||0}</span></button>`).join('');
}
function updateChips(){
  const {ci,cs} = counts();
  document.querySelectorAll('.chip').forEach(b=>{
    const g=b.dataset.g, v=b.dataset.v, n = (g==='ind'?ci:cs)[v]||0;
    b.setAttribute('aria-pressed', String(state[g]===v)); b.dataset.empty = String(!n);
    const span=b.querySelector('.n'); span.textContent=n; span.setAttribute('aria-label', n+' stories');
  });
}
renderChips();

let filtering = false;
function applyFilter(){
  if(filtering) return; filtering = true;
  vcard && vcard._stop && vcard._stop();
  const match = c => (state.ind==='all'||c.dataset.ind===state.ind) && (state.size==='any'||c.dataset.size===state.size);
  const leaving = cards.filter(c=>!c.hidden && !match(c));
  const entering = cards.filter(c=>c.hidden && match(c));
  const staying = cards.filter(c=>!c.hidden && match(c));
  const first = new Map(staying.map(c=>[c, c.getBoundingClientRect()]));
  const fast = reduced.matches || !Element.prototype.animate;
  const outs = fast ? [] : leaving.map(c=>c.animate([{opacity:1,transform:'none'},{opacity:0,transform:'scale(.94) translateY(8px)'}],{duration:200,easing:'ease-in',fill:'forwards'}).finished.catch(()=>{}));
  Promise.all(outs).then(()=>{
    leaving.forEach(c=>{ c.hidden = true; c.getAnimations && c.getAnimations().forEach(a=>a.cancel()) });
    entering.forEach(c=>{ c.hidden = false });
    const v = visible();
    $('#empty').classList.toggle('show', !v.length);
    rail.style.display = v.length ? '' : 'none';
    sizeSpacer();
    rail.classList.add('is-free'); rail.scrollLeft = 0; state.index = 0;
    if(!fast){
      staying.forEach(c=>{
        const a = first.get(c), b = c.getBoundingClientRect(), dx = a.left-b.left, dy = a.top-b.top;
        if(Math.abs(dx)>1||Math.abs(dy)>1) c.animate([{transform:`translate(${dx}px,${dy}px)`},{transform:'none'}],{duration:560,easing:'cubic-bezier(.2,.8,.2,1)'});
      });
      entering.forEach(c=>{
        const k = v.indexOf(c);
        c.animate([{opacity:0,transform:'translateX(40px) scale(.96)'},{opacity:1,transform:'none'}],{duration:520,delay:80+k*55,easing:'cubic-bezier(.2,.8,.2,1)',fill:'backwards'});
      });
    }
    requestAnimationFrame(()=>rail.classList.remove('is-free'));
    buildTicks(); paintThumb();
    userNavAt = 0; paint();
    const label = [state.ind!=='all'?IND[state.ind]:null, state.size!=='any'?SIZE[state.size]+' staff':null].filter(Boolean).join(', ') || 'all clinics';
    announce(v.length ? `${v.length} ${v.length===1?'story':'stories'} for ${label}.` : `No stories for ${label}.`);
    paintSummary(true); restartTimer();
    filtering = false;
  });
}
document.querySelector('.filters').addEventListener('click',e=>{
  const b = e.target.closest('.chip'); if(!b || filtering) return;
  const g = b.dataset.g, v = b.dataset.v;
  if(state[g]===v) return;
  state[g]=v; updateChips(); applyFilter();
});
$('#clear').addEventListener('click',()=>{ state.ind='all'; state.size='any'; updateChips(); applyFilter(); $('#chips-ind .chip').focus(); });

/* ------------------------------------------------ auto-advance (WCAG 2.2.2) */
const AUTO_MS = 7000;
const pauseBtn = $('#pause'), ring = $('#ring'), carousel = $('#carousel');
let elapsed = 0, lastT = 0;
function blocked(){ return state.userPaused||state.hover||state.focus||state.hidden||state.offscreen||state.dragging||state.voice||state.dialog||filtering||visible().length<2 }
function restartTimer(){ elapsed = 0; ring.style.strokeDashoffset = 100; }
function loop(now){
  const dt = lastT ? Math.min(100, now-lastT) : 0; lastT = now;
  if(!blocked()){
    elapsed += dt;
    ring.style.strokeDashoffset = 100 - Math.min(100, elapsed/AUTO_MS*100);
    if(elapsed >= AUTO_MS){ go(state.index+1, {loop:true, auto:true}); }
  }
  requestAnimationFrame(loop);
}
function setPaused(p){
  state.userPaused = p;
  pauseBtn.setAttribute('aria-pressed', String(p));
  pauseBtn.setAttribute('aria-label', p ? 'Resume auto-advance' : 'Pause auto-advance');
  if(p) restartTimer();
}
setPaused(state.userPaused);
pauseBtn.addEventListener('click',()=>{ setPaused(!state.userPaused); announce(state.userPaused?'Auto-advance paused.':'Auto-advance on. Stories change every 7 seconds.'); });
carousel.addEventListener('pointerenter',e=>{ if(e.pointerType==='mouse') state.hover=true });
carousel.addEventListener('pointerleave',()=>{ state.hover=false });
carousel.addEventListener('focusin',e=>{ if(e.target!==pauseBtn) state.focus=true });
carousel.addEventListener('focusout',()=>{ setTimeout(()=>{ const a=document.activeElement; state.focus = carousel.contains(a) && a!==pauseBtn },0) });
document.addEventListener('visibilitychange',()=>{ state.hidden = document.hidden; lastT = 0; });
if('IntersectionObserver' in window) new IntersectionObserver(es=>{ state.offscreen = !es[0].isIntersecting },{threshold:.35}).observe(rail);
reduced.addEventListener && reduced.addEventListener('change',()=>{ if(reduced.matches) setPaused(true) });
requestAnimationFrame(loop);

/* ------------------------------------------------ share dialog */
const dlg = $('#dlg'), form = $('#form'), thanks = $('#thanks');
const rate = $('#rate'); let rating = 0;
rate.innerHTML = [1,2,3,4,5].map(k=>`<input type="radio" name="rating" id="r${k}" value="${k}"><label for="r${k}" aria-label="${k} star${k>1?'s':''}">${STAR}</label>`).join('');
const lightUp = n => rate.querySelectorAll('label').forEach((l,k)=>l.classList.toggle('lit',k<n));
rate.addEventListener('change',e=>{ rating=+e.target.value; lightUp(rating); setErr('rate','') });
rate.addEventListener('mouseover',e=>{ const l=e.target.closest('label'); if(l) lightUp(+l.htmlFor.slice(1)) });
rate.addEventListener('mouseleave',()=>lightUp(rating));
function setErr(k,msg){
  $('#e-'+k).textContent = msg;
  const f = k==='rate' ? null : $('#f-'+k); if(f) f.setAttribute('aria-invalid', msg?'true':'false');
}
$('#share').addEventListener('click',()=>{
  form.hidden=false; thanks.hidden=true; state.dialog=true;
  if(dlg.showModal) dlg.showModal(); else dlg.setAttribute('open','');
  $('#f-name').focus();
});
const closeDlg = () => { dlg.close ? dlg.close() : dlg.removeAttribute('open') };
dlg.addEventListener('close',()=>{ state.dialog=false; $('#share').focus() });
$('#cancel').addEventListener('click',closeDlg); $('#done').addEventListener('click',closeDlg);
dlg.addEventListener('click',e=>{ if(e.target===dlg) closeDlg() });
form.addEventListener('submit',e=>{
  e.preventDefault();
  const v = k => $('#f-'+k).value.trim(); let first=null;
  const chk = (k,ok,msg) => { setErr(k, ok?'':msg); if(!ok && !first) first = k };
  chk('name', v('name').length>=2, 'Please add your name.');
  chk('clinic', v('clinic').length>=2, 'Which clinic do you work at?');
  chk('email', /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v('email')), 'Enter an email like name@clinic.com.');
  chk('rate', rating>0, 'Choose a rating from 1 to 5.');
  chk('msg', v('msg').length>=20, `A few more words, please (${Math.max(0,20-v('msg').length)} to go).`);
  if(first){ (first==='rate' ? rate.querySelector('input') : $('#f-'+first)).focus(); return; }
  form.reset(); rating=0; lightUp(0);
  form.hidden = true; thanks.hidden = false; $('#thanks-title').focus();
});
form.addEventListener('input',e=>{ const k=e.target.id&&e.target.id.slice(2); if(k && $('#e-'+k) && $('#e-'+k).textContent) setErr(k,'') });

/* ------------------------------------------------ boot + resize */
function layout(){ sizeSpacer(); buildTicks(); paintThumb(); const v=visible(); if(v[state.index]) { rail.classList.add('is-free'); rail.scrollLeft = targetOf(v[state.index]); requestAnimationFrame(()=>rail.classList.remove('is-free')); } paint(); }
let rz; addEventListener('resize',()=>{ cancelAnimationFrame(rz); rz=requestAnimationFrame(layout) });
measureClamp(); layout();
if(document.fonts && document.fonts.ready) document.fonts.ready.then(layout);
addEventListener('load', layout);
})();
</script>
</body>
</html>

````
