"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";/* ───────────────────────────────────────────────────────── * SEAT MAP: pick seats while other people are picking too * * pick tap a seat and it rises a little as your initials * drop into it; the seat list and the total roll * live when someone else takes a seat while you look, it * turns over to taken and a ripple runs out from it * through the seats around, so you notice where it went * lost if it was one of yours, it shakes, lets go of your * initials, and the nearest free seats in the same tier * pulse once as the next best * limit past the most seats you can hold, the count shakes * * Seats and their status are yours: pass rows of seats (null for an * aisle) and tiers with prices; the map tells you what's picked and * calls onContinue. Arrow keys move between seats. * ───────────────────────────────────────────────────────── */export interface Seat { id: string; /** The seat's number in its row. */ label: string; status: "free" | "taken"; /** A tier id; seats without one use the first tier. */ tier?: string;}export interface SeatRow { /** The row's letter. */ id: string; /** Seats left to right; null leaves an aisle. */ seats: (Seat | null)[];}export interface SeatTier { id: string; name: string; price: number; /** Any CSS colour. Defaults to your chart colours in turn. */ color?: string;}export interface SeatMapProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "title"> { rows: SeatRow[]; tiers: SeatTier[]; selected?: string[]; defaultSelected?: string[]; onSelectedChange?: (ids: string[]) => void; /** The most seats one person can hold. */ max?: number; /** Shown in your seats. */ initials?: string; /** What the seats face, e.g. "Screen" or "Stage". */ stage?: string; title?: string; subtitle?: string; currency?: string; locale?: string; onContinue?: (ids: string[]) => void;}const EASE = "cubic-bezier(0.16,1,0.3,1)";const FOCUS = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background";const NONE: string[] = [];const SHAKE: Keyframe[] = [{ translate: "0 0" }, { translate: "-3px 0" }, { translate: "3px 0" }, { translate: "-1.5px 0" }, { translate: "0 0" }];const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(reducedQuery); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const subscribeNothing = () => () => {};const useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);const mix = (color: string, amount: number, into = "transparent") => `color-mix(in oklab, ${color} ${amount}%, ${into})`;export function SeatMap({ rows, tiers, selected: selectedProp, defaultSelected = NONE, onSelectedChange, max = 6, initials = "You", stage = "Screen", title, subtitle, currency = "USD", locale, onContinue, className = "", ...props}: SeatMapProps) { const reduced = useReducedMotion(); const hydrated = useHydrated(); const loc = locale ?? (hydrated ? undefined : "en-US"); const [own, setOwn] = React.useState(defaultSelected); const selected = selectedProp ?? own; const [width, setWidth] = React.useState(0); const [active, setActive] = React.useState<string | null>(null); const [said, setSaid] = React.useState(""); const boxRef = React.useRef<HTMLDivElement>(null); const countRef = React.useRef<HTMLParagraphElement>(null); const seatRefs = React.useRef(new Map<string, HTMLButtonElement>()); const before = React.useRef<Map<string, Seat["status"]> | null>(null); const tierOf = React.useMemo(() => { const map = new Map(tiers.map((t, i) => [t.id, { ...t, color: t.color ?? `var(--chart-${(i % 5) + 1}, var(--primary))` }])); return (seat: Seat) => map.get(seat.tier ?? tiers[0]?.id) ?? { id: "", name: "", price: 0, color: "var(--primary)" }; }, [tiers]); const all = React.useMemo(() => { const out = new Map<string, { seat: Seat; row: string; r: number; c: number }>(); rows.forEach((row, r) => row.seats.forEach((s, c) => s && out.set(s.id, { seat: s, row: row.id, r, c }))); return out; }, [rows]); const set = (ids: string[]) => { if (selectedProp === undefined) setOwn(ids); onSelectedChange?.(ids); }; React.useLayoutEffect(() => { const box = boxRef.current; if (!box) return; const measure = () => setWidth((w) => (w === box.offsetWidth ? w : box.offsetWidth)); measure(); const observer = new ResizeObserver(measure); observer.observe(box); return () => observer.disconnect(); }, []); const cols = Math.max(...rows.map((r) => r.seats.length)); // Narrow maps keep the row letters on one side only and pack the seats a little closer. const narrow = (width || 360) < 340; const label = 16; const gap = narrow ? 3 : 4; const size = Math.max(13, Math.min(28, Math.floor(((width || 360) - label * (narrow ? 1 : 2) - 8 - gap * (cols - 1)) / cols))); const live = React.useRef({ selected, set: (ids: string[]) => void ids }); React.useLayoutEffect(() => { live.current.selected = selected; live.current.set = (ids: string[]) => { if (selectedProp === undefined) setOwn(ids); onSelectedChange?.(ids); }; }); // Seats other people took while you were looking: turn them over and ripple out; if it was yours, let it go. React.useLayoutEffect(() => { const selected = live.current.selected; const ripple = (from: { r: number; c: number }, delay = 0) => { if (reduced) return; all.forEach((p, id) => { const d = Math.hypot(p.r - from.r, p.c - from.c); if (d === 0 || d > 3.6) return; seatRefs.current.get(id)?.animate([{ scale: "1", filter: "brightness(1)" }, { scale: "1.08", filter: "brightness(1.18)" }, { scale: "1", filter: "brightness(1)" }], { duration: 420, delay: delay + d * 55, easing: "ease-in-out", }); }); }; const now = new Map([...all].map(([id, p]) => [id, p.seat.status])); const prev = before.current; before.current = now; if (!prev) return; const lost: string[] = []; now.forEach((status, id) => { if (prev.get(id) !== "free" || status !== "taken") return; const p = all.get(id)!; const el = seatRefs.current.get(id); if (!reduced) el?.animate([{ transform: "rotateX(0)" }, { transform: "rotateX(90deg)", offset: 0.5 }, { transform: "rotateX(0)" }], { duration: 460, easing: "ease-in-out" }); ripple(p, 120); if (selected.includes(id)) lost.push(id); }); if (!lost.length) return; lost.forEach((id) => { const p = all.get(id)!; if (!reduced) seatRefs.current.get(id)?.animate(SHAKE, { duration: 380, easing: "ease-out" }); // The next best: the nearest free seats in the same tier. const tier = tierOf(p.seat).id; [...all.values()] .filter((q) => q.seat.status === "free" && tierOf(q.seat).id === tier && !selected.includes(q.seat.id)) .sort((a, b) => Math.hypot(a.r - p.r, a.c - p.c) - Math.hypot(b.r - p.r, b.c - p.c)) .slice(0, 2) .forEach((q, i) => { if (reduced) return; seatRefs.current.get(q.seat.id)?.animate( [{ boxShadow: `0 0 0 0px ${mix(tierOf(q.seat).color, 60)}` }, { boxShadow: `0 0 0 4px ${mix(tierOf(q.seat).color, 0)}` }], { duration: 900, delay: 420 + i * 120, easing: EASE, iterations: 2 }, ); }); }); const next = selected.filter((id) => !lost.includes(id)); // Hand the change back on the next frame, outside this layout pass. requestAnimationFrame(() => live.current.set(next)); setSaid(`${lost.map((id) => `${all.get(id)!.row}${all.get(id)!.seat.label}`).join(", ")} was just taken. Pick another seat.`); }, [all, reduced, tierOf]); const toggle = (seat: Seat) => { if (seat.status === "taken") return; const p = all.get(seat.id)!; if (selected.includes(seat.id)) { set(selected.filter((id) => id !== seat.id)); setSaid(`Row ${p.row} seat ${seat.label} removed.`); return; } if (selected.length >= max) { if (!reduced) countRef.current?.animate(SHAKE, { duration: 380, easing: "ease-out" }); setSaid(`You can hold up to ${max} seats.`); return; } set([...selected, seat.id]); setSaid(`Row ${p.row} seat ${seat.label} added, ${fmt(tierOf(seat).price)}.`); }; // Arrow keys move between seats; a roving tab stop keeps the map one stop in the tab order. const first = [...all.values()].find((p) => p.seat.status === "free")?.seat.id ?? [...all.keys()][0]; const stop = active && all.has(active) ? active : first; const key = (e: React.KeyboardEvent, id: string) => { const p = all.get(id); if (!p) return; const dir = { ArrowLeft: [0, -1], ArrowRight: [0, 1], ArrowUp: [-1, 0], ArrowDown: [1, 0] }[e.key]; if (!dir) return; e.preventDefault(); let best: string | null = null; let bestD = Infinity; all.forEach((q, qid) => { const dr = q.r - p.r; const dc = q.c - p.c; if ((dir[0] && Math.sign(dr) !== dir[0]) || (dir[1] && Math.sign(dc) !== dir[1])) return; const d = dir[0] ? Math.abs(dr) * 10 + Math.abs(dc) : Math.abs(dc) * 10 + Math.abs(dr); if (d < bestD) { bestD = d; best = qid; } }); if (best) { setActive(best); seatRefs.current.get(best)?.focus(); } }; const fmt = (v: number) => new Intl.NumberFormat(loc, { style: "currency", currency, maximumFractionDigits: v % 1 ? 2 : 0 }).format(v); const picked = selected.map((id) => all.get(id)).filter(Boolean) as { seat: Seat; row: string }[]; const total = picked.reduce((s, p) => s + tierOf(p.seat).price, 0); const list = picked.length ? picked.map((p) => `${p.row}${p.seat.label}`).join(", ") : "No seats yet"; const onSeat = (c: string) => `oklch(from ${c} clamp(0.2, (0.7 - l) * 100, 0.99) 0 h)`; return ( <div className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}> <div aria-hidden="true" data-natural-width className="grid h-0" style={{ gridTemplateColumns: "minmax(0, 460px)" }} /> <div className="p-4 sm:p-5"> {(title || subtitle) && ( <div className="mb-3"> {title && <p className="text-[15px] font-medium tracking-[-0.01em] text-foreground">{title}</p>} {subtitle && <p className="mt-0.5 text-[12px] text-muted-foreground">{subtitle}</p>} </div> )} <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11.5px] text-muted-foreground"> {tiers.map((t, i) => { const color = t.color ?? `var(--chart-${(i % 5) + 1}, var(--primary))`; return ( <span key={t.id} className="inline-flex items-center gap-1.5"> <span className="size-2.5 rounded-[3px]" style={{ background: mix(color, 16), boxShadow: `inset 0 0 0 1px ${mix(color, 60)}` }} /> {t.name} <span className="tabular-nums text-foreground">{fmt(t.price)}</span> </span> ); })} <span className="inline-flex items-center gap-1.5"> <span className="size-2.5 rounded-[3px]" style={{ background: mix("var(--foreground)", 12) }} /> Taken </span> </div> {/* What the seats face. */} <div aria-hidden="true" className="mt-4 flex flex-col items-center"> <svg viewBox="0 0 200 16" className="h-4 w-[72%]" preserveAspectRatio="none"> <path d="M2 14 Q100 -6 198 14" fill="none" stroke="color-mix(in oklab, var(--foreground) 35%, transparent)" strokeWidth="1.5" vectorEffect="non-scaling-stroke" strokeLinecap="round" /> </svg> <span className="mt-0.5 text-[10.5px] uppercase tracking-[0.12em] text-muted-foreground">{stage}</span> </div> <div ref={boxRef} role="grid" aria-label="Seats" className="mt-3 flex w-full flex-col items-center" style={{ gap, perspective: 600 }}> {width > 0 && rows.map((row) => ( <div key={row.id} role="row" className="flex items-center" style={{ gap }}> <span aria-hidden="true" className="text-center text-[10.5px] tabular-nums text-muted-foreground" style={{ width: label }}> {row.id} </span> {row.seats.map((seat, c) => seat ? ( <SeatButton key={seat.id} seat={seat} row={row.id} size={size} color={tierOf(seat).color} price={fmt(tierOf(seat).price)} mine={selected.includes(seat.id)} initials={initials} ink={onSeat(tierOf(seat).color)} tabStop={seat.id === stop} reduced={reduced} onToggle={toggle} onKey={key} onFocusSeat={setActive} register={(el) => { if (el) seatRefs.current.set(seat.id, el); else seatRefs.current.delete(seat.id); }} /> ) : ( <span key={`aisle-${c}`} aria-hidden="true" style={{ width: size * 0.6 }} /> ), )} {!narrow && ( <span aria-hidden="true" className="text-center text-[10.5px] tabular-nums text-muted-foreground" style={{ width: label }}> {row.id} </span> )} </div> ))} </div> </div> <div className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 sm:px-5"> <div className="min-w-0"> <p ref={countRef} className="text-[12px] text-muted-foreground tabular-nums"> <TextMorph>{picked.length ? `${picked.length} of ${max} seats` : `Up to ${max} seats`}</TextMorph> </p> <p className="truncate text-[13px] font-medium text-foreground"> <TextMorph>{list}</TextMorph> </p> </div> <div className="flex shrink-0 items-center gap-3"> <p className="text-[17px] font-medium tracking-[-0.02em] text-foreground tabular-nums"> <NumberRoll value={total} format={{ style: "currency", currency, maximumFractionDigits: 0 }} locales={loc} duration={700} /> </p> <button type="button" disabled={!picked.length} onClick={() => onContinue?.(selected)} className={`h-9 cursor-pointer rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground transition-[opacity,scale] duration-200 active:scale-[0.97] disabled:cursor-default disabled:opacity-40 disabled:active:scale-100 ${FOCUS}`} > Continue </button> </div> </div> <p className="sr-only" aria-live="polite"> {said} </p> </div> );}interface SeatButtonProps { seat: Seat; row: string; size: number; color: string; price: string; mine: boolean; initials: string; ink: string; tabStop: boolean; reduced: boolean; onToggle: (seat: Seat) => void; onKey: (e: React.KeyboardEvent, id: string) => void; onFocusSeat: (id: string) => void; register: (el: HTMLButtonElement | null) => void;}const SeatButton = React.memo(function SeatButton({ seat, row, size, color, price, mine, initials, ink, tabStop, reduced, onToggle, onKey, onFocusSeat, register }: SeatButtonProps) { const taken = seat.status === "taken"; const letters = initials.slice(0, 2).toUpperCase(); return ( <button ref={register} type="button" role="gridcell" aria-selected={mine} aria-disabled={taken} aria-label={`Row ${row}, seat ${seat.label}, ${taken ? "taken" : mine ? "yours" : price}`} tabIndex={tabStop ? 0 : -1} onClick={() => onToggle(seat)} onKeyDown={(e) => onKey(e, seat.id)} onFocus={() => onFocusSeat(seat.id)} className={`relative flex shrink-0 items-center justify-center overflow-hidden rounded-b-[4px] rounded-t-[8px] transition-[background-color,box-shadow,translate] duration-300 ${taken ? "cursor-default" : "cursor-pointer"} ${FOCUS}`} style={{ width: size, height: size, background: taken ? mix("var(--foreground)", 12) : mine ? color : mix(color, 14), boxShadow: taken ? "none" : mine ? `inset 0 -2px 0 ${mix("black", 18)}` : `inset 0 0 0 1px ${mix(color, 55)}`, translate: mine ? "0 -2px" : "0 0", transitionTimingFunction: EASE, }} > <span aria-hidden="true" className="text-[9px] font-semibold leading-none" style={{ color: ink, opacity: mine ? 1 : 0, transform: mine ? "none" : "translateY(-8px)", transition: reduced ? "none" : `transform 380ms cubic-bezier(0.34,1.36,0.64,1) 60ms, opacity 200ms ${EASE} 60ms`, fontSize: Math.max(8, size * 0.36), }} > {size >= 20 ? letters : letters.slice(0, 1)} </span> </button> );});