{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "geo-visitors",
  "title": "Live visitors",
  "description": "A live map of visits with a feed and an online-now count: each visit drops onto the map with a ring of light, and leaves an afterglow.",
  "registryDependencies": [
    "https://elements.lumesec.ai/r/lumesec-theme.json",
    "https://elements.lumesec.ai/r/lumesec-canvas.json",
    "https://elements.lumesec.ai/r/lumesec-color.json",
    "https://elements.lumesec.ai/r/lumesec-geo.json",
    "https://elements.lumesec.ai/r/lumesec-geo-countries.json",
    "https://elements.lumesec.ai/r/lumesec-geo-data.json",
    "https://elements.lumesec.ai/r/lumesec-math.json",
    "https://elements.lumesec.ai/r/lumesec-motion.json",
    "https://elements.lumesec.ai/r/lumesec-roll-text.json",
    "https://elements.lumesec.ai/r/lumesec-sparks.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/components/lumesec/geo-visitors.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { fillSquare, localPoint, useCanvas, type CanvasSurface } from \"@/lib/lumesec/canvas\";\nimport { usePalette } from \"@/lib/lumesec/color\";\nimport {\n  createDotBatch,\n  createProjection,\n  createScreenPoint,\n  easeInCubic,\n  GEO_TOKENS,\n  geoInk,\n  MAP_LAT_RANGE,\n  mapLattice,\n  nearestIndex,\n  projectionAspect,\n  projectionOutlineSvgPath,\n  ringFront,\n  wrapLongitude,\n  type DotBatch,\n  type DotLattice,\n  type GeoInk,\n  type MapProjection,\n} from \"@/lib/lumesec/geo\";\nimport { countryAt } from \"@/lib/lumesec/geo-countries\";\nimport {\n  createRandom,\n  DEMO_CITIES,\n  formatAgo,\n  formatLatLon,\n  formatNumber,\n  pickWeighted,\n  scatterAround,\n  useNow,\n} from \"@/lib/lumesec/geo-data\";\nimport { clamp, easeOutCubic, rgba, smoothstep } from \"@/lib/lumesec/math\";\nimport {\n  prefersReducedMotion,\n  settleSpring,\n  useAnimationLoop,\n  useInView,\n  useInterval,\n  useLazyRef,\n  useReducedMotion,\n  type Spring,\n} from \"@/lib/lumesec/motion\";\nimport { RollText } from \"@/lib/lumesec/roll-text\";\nimport { Sparks, type SparkOptions } from \"@/lib/lumesec/sparks\";\nimport { cn } from \"@/lib/utils\";\n\n/** One visit: where and when someone opened a page, and what the feed shows for it. */\nexport interface VisitorEvent {\n  /** Unique id. A new id drops onto the map; an id that is already shown is ignored. */\n  readonly id: string;\n  /** Latitude in degrees, −90 to 90. */\n  readonly lat: number;\n  /** Longitude in degrees, −180 to 180. */\n  readonly lon: number;\n  /** Place shown in the feed. Without it the feed shows the country at the point, or the coordinates. */\n  readonly city?: string;\n  /** What was visited, such as a path (`/pricing`). Shown in mono under the place; without it, the coordinates. */\n  readonly label?: string;\n  /** When the visit happened, in epoch ms. */\n  readonly time: number;\n}\n\n/** Map projection of the visitor map. */\nexport type GeoVisitorsProjection = \"equalEarth\" | \"equirectangular\";\n\n/** Imperative actions, exposed through `ref`. */\nexport interface GeoVisitorsHandle {\n  /**\n   * Adds a visit. It drops onto the map, adds to the afterglow and enters the feed like any new visit. Ids that are\n   * already shown are ignored.\n   */\n  push(event: VisitorEvent): void;\n}\n\n/** Props of `GeoVisitors`. Other `div` props go to the root; `ref` receives the `GeoVisitorsHandle`. */\nexport interface GeoVisitorsProps extends Omit<React.ComponentProps<\"div\">, \"ref\" | \"title\"> {\n  /**\n   * Your visits. Ids that appear after the first render drop onto the map; ids that leave the list leave the map and\n   * the feed. Without it a seeded demo stream runs. An empty array shows an empty feed.\n   */\n  events?: readonly VisitorEvent[];\n  /** Count shown as online now. Default: the visits of the last five minutes. */\n  online?: number;\n  /** Seconds until a visit's afterglow has faded. At least 5. */\n  decay?: number;\n  /** Rows in the feed, 1 to 24. */\n  maxFeed?: number;\n  /** Map projection. */\n  projection?: GeoVisitorsProjection;\n  /** Header text. */\n  title?: React.ReactNode;\n  /** Runs the demo stream while `events` is not given. The stream pauses while the panel is off screen. */\n  live?: boolean;\n  /** Called when a feed row is activated with a click, Enter or Space. */\n  onEventClick?: (event: VisitorEvent) => void;\n  /** Exposes `push(event)`. */\n  ref?: React.Ref<GeoVisitorsHandle>;\n}\n\n/**\n * A live map of visits with a feed beside it and an online-now count. Each visit falls onto the map as a short\n * streak, lands with an uneven ring of lit land dots and a few sparks that can fly past the map's edge, and its row\n * slides into the feed. Visits leave an afterglow on the land dots that fades over `decay` seconds, so busy regions\n * build up a soft density. Pointing at a row marks its point; pointing at the map marks the nearest visit's row.\n *\n * Without `events` a seeded demo stream runs. Pass your visits as `events` (new ids drop in), or add them one by one\n * with `push()` through `ref`.\n *\n * @example\n * <GeoVisitors events={visits} onEventClick={(visit) => openSession(visit.id)} />\n */\nexport function GeoVisitors(props: GeoVisitorsProps) {\n  // demo data and your data are separate timelines: switching between them starts the panel over\n  return <VisitorsPanel key={props.events === undefined ? \"demo\" : \"data\"} {...props} />;\n}\n\nfunction VisitorsPanel({\n  events,\n  online,\n  decay: decayProp = 300,\n  maxFeed: maxFeedProp = 6,\n  projection = \"equalEarth\",\n  title = \"Visitors\",\n  live = true,\n  onEventClick,\n  ref,\n  className,\n  ...props\n}: GeoVisitorsProps) {\n  const demo = events === undefined;\n  const decay = Number.isFinite(decayProp) ? Math.max(5, decayProp) : 300;\n  const maxFeed = Number.isFinite(maxFeedProp) ? clamp(Math.round(maxFeedProp), 1, 24) : 6;\n  const reducedMotion = useReducedMotion();\n\n  // The first timeline: the seeded demo history (times relative to 0) or your events. Server and client agree on it.\n  const [initial] = React.useState(() => {\n    const visits = demo ? demoHistory() : validEvents(events ?? []);\n    return { visits, reference: demo ? 0 : newestTime(visits) };\n  });\n\n  const [feed, setFeed] = React.useState<FeedState>(() => ({\n    limit: maxFeed,\n    rows: newestRows(initial.visits, maxFeed),\n  }));\n  if (feed.limit !== maxFeed) setFeed(resizeFeed(feed, maxFeed));\n\n  // The clock starts after mount, so the server and the first client render show the same relative times.\n  const [clock, setClock] = React.useState<number | null>(null);\n  const tick = useNow(15_000, clock !== null);\n  const now = clock === null ? initial.reference : Math.max(clock, tick ?? clock);\n\n  const [recent, setRecent] = React.useState(() => countRecent(initial.visits, initial.reference));\n  const count = online !== undefined && Number.isFinite(online) ? Math.max(0, Math.round(online)) : recent;\n  const [summary, setSummary] = React.useState(\"\");\n\n  const [rowActive, setRowActive] = React.useState<string | null>(null);\n  const [mapHover, setMapHover] = React.useState<MapHover | null>(null);\n  const activeId = rowActive ?? mapHover?.event.id ?? null;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const baseRef = React.useRef<HTMLCanvasElement>(null);\n  const heatRef = React.useRef<HTMLCanvasElement>(null);\n  const effectsRef = React.useRef<HTMLCanvasElement>(null);\n  // the map and the feed queue are created on first use (effects, handlers and the loop), never during a render\n  const mapRef = useLazyRef(() => new VisitorMap());\n  const queueRef = useLazyRef(createQueue);\n  /** Ids of `events` the map already knows, to tell new ids from removed ones. */\n  const knownIds = React.useRef<Set<string>>(new Set());\n  const feedLimit = React.useRef(maxFeed);\n  const streamCount = React.useRef(0);\n  const inView = useInView(rootRef, \"120px\");\n  /** Whether new visits may drop: only while the map is on screen and the page is visible, else they would pile up. */\n  const onScreen = React.useRef(false);\n\n  /**\n   * The feed queue, which writes the rows into state and reads the latest row limit. A function declaration rather than\n   * an inline arrow, so the React Compiler does not treat `feedLimit` as frozen by the hook call.\n   */\n  function createQueue() {\n    return createFeedQueue(\n      (change) =>\n        setFeed((state) =>\n          change.kind === \"add\"\n            ? insertRow(state, change.event, prefersReducedMotion())\n            : replaceRows(state, change.events),\n        ),\n      () => feedLimit.current,\n    );\n  }\n\n  /** Where the effects layer sits relative to the map, in CSS px (layout offsets are unaffected by a scaled preview). */\n  function measureEffects() {\n    const map = baseRef.current;\n    const layer = effectsRef.current;\n    if (map && layer)\n      mapRef.current.setEffectsOffset(map.offsetLeft - layer.offsetLeft, map.offsetTop - layer.offsetTop);\n  }\n\n  const loop = useAnimationLoop(rootRef, step);\n  const palette = usePalette(rootRef, GEO_TOKENS, applyTheme);\n  const base = useCanvas(\n    baseRef,\n    (surface) => {\n      mapRef.current.layout(surface.width, surface.height, surface.dpr);\n      measureEffects();\n      loop.kick();\n    },\n    MAP_CANVAS,\n  );\n  const heat = useCanvas(\n    heatRef,\n    () => {\n      mapRef.current.invalidate();\n      loop.kick();\n    },\n    MAP_CANVAS,\n  );\n  const effects = useCanvas(\n    effectsRef,\n    () => {\n      measureEffects();\n      loop.kick();\n    },\n    MAP_CANVAS,\n  );\n\n  function step(_time: number, delta: number) {\n    return mapRef.current.step(base.current, heat.current, effects.current, delta);\n  }\n\n  function applyTheme() {\n    const colors = palette.current;\n    if (!colors) return;\n    mapRef.current.setInk(geoInk(colors));\n    loop.kick();\n  }\n\n  React.useEffect(() => {\n    onScreen.current = inView;\n  }, [inView]);\n\n  React.useEffect(() => {\n    feedLimit.current = maxFeed;\n    if (mapRef.current.configure(projection, decay)) loop.kick();\n  }, [mapRef, projection, decay, loop, maxFeed]);\n\n  // A landed visit queues its row; the queue changes at most one row per 160 ms.\n  React.useEffect(() => {\n    const map = mapRef.current;\n    const queue = queueRef.current;\n    map.onLand = (event) => queue.add(event);\n    return () => queue.clear();\n  }, [mapRef, queueRef]);\n\n  // Start the clock: the demo history moves to now, your events are loaded as they are. No drops for these.\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => {\n      const start = Date.now();\n      const shift = demo ? start : 0;\n      const visits = shift ? initial.visits.map((visit) => ({ ...visit, time: visit.time + shift })) : initial.visits;\n      const map = mapRef.current;\n      map.addVisits(visits, { animate: false, announce: false }, start);\n      knownIds.current = new Set(visits.map((visit) => visit.id));\n      if (shift) setFeed((state) => shiftRows(state, shift));\n      setRecent(map.countRecent(start));\n      setClock(start);\n      loop.kick();\n    }, 0);\n    return () => window.clearTimeout(timer);\n  }, [demo, initial, mapRef, loop]);\n\n  // Your events: new ids drop in, removed ids leave the map and the feed.\n  React.useEffect(() => {\n    if (demo || clock === null) return;\n    const list = validEvents(events ?? []);\n    const ids = new Set(list.map((event) => event.id));\n    const known = knownIds.current;\n    knownIds.current = ids;\n    const removed = new Set([...known].filter((id) => !ids.has(id)));\n    const added = list.filter((event) => !known.has(event.id));\n    const map = mapRef.current;\n    if (removed.size > 0) {\n      map.removeVisits(removed);\n      queueRef.current.replace(map.newest(maxFeed), removed);\n    }\n    if (added.length > 0) map.addVisits(added, { animate: canDrop(onScreen.current), announce: true }, Date.now());\n    loop.kick();\n  }, [demo, clock, events, mapRef, queueRef, loop, maxFeed]);\n\n  // The demo stream: a visit every 0.6 to 2.2 s, weighted by city, while the panel is on screen.\n  React.useEffect(() => {\n    if (!demo || !live || !inView || clock === null) return;\n    const random = createRandom(Date.now());\n    let timer = 0;\n    const next = () => {\n      timer = window.setTimeout(\n        () => {\n          const visit = demoVisit(random, Date.now(), `v${streamCount.current++}`);\n          mapRef.current.addVisits([visit], { animate: canDrop(onScreen.current), announce: true }, visit.time);\n          loop.kick();\n          next();\n        },\n        600 + random() * 1600,\n      );\n    };\n    next();\n    return () => window.clearTimeout(timer);\n  }, [demo, live, inView, clock, mapRef, loop]);\n\n  // Rows mark their point: a ping and a lit ring, with the rest of the afterglow dimmed. The map hover only marks.\n  React.useEffect(() => {\n    mapRef.current.setActive(activeId, rowActive !== null);\n    loop.kick();\n  }, [activeId, rowActive, mapRef, loop]);\n\n  // The afterglow fades in steps of 250 ms; the online count follows.\n  useInterval(\n    () => {\n      const map = mapRef.current;\n      const time = Date.now();\n      map.tick(time);\n      setRecent(map.countRecent(time));\n      loop.kick();\n    },\n    HEAT_TICK_MS,\n    inView && clock !== null,\n  );\n\n  // One polite summary every 15 s instead of an announcement per visit, and none while the panel is off screen.\n  useInterval(\n    () => {\n      const text = mapRef.current.summary(Date.now());\n      if (text) setSummary(text);\n    },\n    SUMMARY_MS,\n    inView && clock !== null,\n  );\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      push(event: VisitorEvent) {\n        if (!isValidEvent(event)) return;\n        mapRef.current.addVisits([event], { animate: canDrop(onScreen.current), announce: true }, Date.now());\n        loop.kick();\n      },\n    }),\n    [mapRef, loop],\n  );\n\n  const removeRow = React.useCallback((id: string) => setFeed((state) => dropRow(state, id)), []);\n  const pointRow = React.useCallback((id: string | null) => setRowActive(id), []);\n  const activateRow = React.useCallback(\n    (event: VisitorEvent) => {\n      // a click pings the point again, even when the row is already marked\n      mapRef.current.ping(event.id);\n      loop.kick();\n      onEventClick?.(event);\n    },\n    [mapRef, loop, onEventClick],\n  );\n\n  function holdFeed(reason: \"pointer\" | \"focus\", held: boolean) {\n    queueRef.current.hold(reason, held);\n  }\n\n  function handleMapPointer(event: React.PointerEvent<HTMLDivElement>) {\n    const box = event.currentTarget;\n    // in CSS px of the map, which the gallery may show scaled\n    const point = localPoint(box, event.clientX, event.clientY);\n    const hit = mapRef.current.nearest(point.x, point.y, HOVER_RADIUS);\n    setMapHover((current) => {\n      if (!hit) return null;\n      if (current && current.event.id === hit.event.id && current.x === hit.x && current.y === hit.y) return current;\n      return { event: hit.event, x: hit.x, y: hit.y, width: box.offsetWidth };\n    });\n  }\n\n  function handleFeedKeyDown(event: React.KeyboardEvent<HTMLOListElement>) {\n    const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>(\"li:not([inert]) button\"));\n    const index = buttons.findIndex((button) => button === document.activeElement);\n    if (index < 0) return;\n    const target =\n      event.key === \"ArrowDown\"\n        ? Math.min(buttons.length - 1, index + 1)\n        : event.key === \"ArrowUp\"\n          ? Math.max(0, index - 1)\n          : event.key === \"Home\"\n            ? 0\n            : event.key === \"End\"\n              ? buttons.length - 1\n              : -1;\n    if (target < 0) return;\n    event.preventDefault();\n    buttons[target].focus();\n  }\n\n  const aspect = projectionAspect(projection, MAP_LAT_RANGE);\n  const outline = React.useMemo(\n    () =>\n      projectionOutlineSvgPath(\n        createProjection(projection, { width: NOMINAL_WIDTH, height: NOMINAL_WIDTH / aspect, latRange: MAP_LAT_RANGE }),\n      ),\n    [projection, aspect],\n  );\n  const streaming = !demo || live;\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"geo-visitors\"\n      className={cn(\n        \"@container w-full max-w-[660px] rounded-[14px] border border-border bg-card text-card-foreground shadow-[0_14px_34px_-20px_rgb(0_0_0/0.4)] [-webkit-tap-highlight-color:transparent]\",\n        className,\n      )}\n      {...props}\n    >\n      <div className=\"flex h-11 items-center gap-3 border-b border-border px-4\">\n        <div className=\"min-w-0 truncate text-[13.5px] leading-5 font-medium tracking-[-0.005em] text-foreground\">\n          {title}\n        </div>\n        <div className=\"ml-auto flex shrink-0 items-center gap-2 text-[12.5px] leading-5\">\n          <LiveDot paused={!streaming} />\n          <span className=\"font-mono text-[13px] text-foreground tabular-nums\">\n            <RollingCount value={count} animate={!reducedMotion} />\n          </span>\n          <span aria-hidden=\"true\" className=\"text-muted-foreground\">\n            online now\n          </span>\n          <span className=\"sr-only\">{`${formatNumber(count)} online now`}</span>\n        </div>\n      </div>\n      <div className=\"grid @min-[560px]:grid-cols-[minmax(0,1fr)_216px]\">\n        <div className=\"flex flex-col justify-center gap-2 p-3\">\n          <div\n            ref={boxRef}\n            className=\"relative w-full select-none\"\n            style={{ aspectRatio: aspect }}\n            onPointerMove={handleMapPointer}\n            onPointerDown={handleMapPointer}\n            onPointerLeave={(event) => {\n              // a tap keeps its tooltip until the next tap on the map\n              if (event.pointerType !== \"touch\") setMapHover(null);\n            }}\n          >\n            <svg\n              aria-hidden=\"true\"\n              viewBox={`0 0 ${NOMINAL_WIDTH} ${round2(NOMINAL_WIDTH / aspect)}`}\n              preserveAspectRatio=\"none\"\n              className=\"pointer-events-none absolute inset-0 block size-full overflow-visible\"\n            >\n              <path\n                d={outline}\n                vectorEffect=\"non-scaling-stroke\"\n                strokeWidth={1}\n                className=\"fill-muted/35 stroke-border\"\n              />\n            </svg>\n            <canvas ref={baseRef} aria-hidden=\"true\" className=\"absolute inset-0 block size-full\" />\n            <canvas ref={heatRef} aria-hidden=\"true\" className=\"absolute inset-0 block size-full\" />\n            <canvas\n              ref={effectsRef}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute -top-14 -left-4 z-[3] block h-[calc(100%+80px)] w-[calc(100%+32px)] @min-[560px]:-left-10 @min-[560px]:w-[calc(100%+80px)]\"\n            />\n            {mapHover ? <MapTooltip hover={mapHover} now={now} /> : null}\n          </div>\n          <Legend decay={decay} />\n        </div>\n        <div className=\"border-t border-border px-2 py-2 @min-[560px]:border-t-0 @min-[560px]:border-l\">\n          {feed.rows.length === 0 ? (\n            <p\n              className=\"m-0 grid place-items-center text-[12.5px] leading-5 text-muted-foreground\"\n              style={{ minHeight: feed.limit * ROW_HEIGHT }}\n            >\n              No visits yet\n            </p>\n          ) : (\n            <ol\n              aria-label=\"Recent visits\"\n              className=\"m-0 grid list-none content-start p-0\"\n              style={{ minHeight: feed.limit * ROW_HEIGHT }}\n              onKeyDown={handleFeedKeyDown}\n              onPointerEnter={() => holdFeed(\"pointer\", true)}\n              onPointerLeave={() => holdFeed(\"pointer\", false)}\n              onFocus={() => holdFeed(\"focus\", true)}\n              onBlur={(event) => {\n                if (!event.currentTarget.contains(event.relatedTarget)) holdFeed(\"focus\", false);\n              }}\n            >\n              {feed.rows.map((row) => (\n                <FeedRow\n                  key={row.event.id}\n                  row={row}\n                  now={now}\n                  active={row.event.id === activeId}\n                  onPoint={pointRow}\n                  onActivate={activateRow}\n                  onExited={removeRow}\n                />\n              ))}\n            </ol>\n          )}\n        </div>\n      </div>\n      <div aria-live=\"polite\" className=\"sr-only\">\n        {summary}\n      </div>\n    </div>\n  );\n}\n\n/* Feed ------------------------------------------------------------------------------------------------ */\n\ninterface FeedRowState {\n  readonly event: VisitorEvent;\n  /** `enter` slides in once, `exit` slides out and then leaves the list. */\n  readonly phase: \"idle\" | \"enter\" | \"exit\";\n}\n\ninterface FeedState {\n  readonly limit: number;\n  /** Newest first. Leaving rows stay until their animation ends. */\n  readonly rows: readonly FeedRowState[];\n}\n\ninterface FeedRowProps {\n  row: FeedRowState;\n  now: number;\n  active: boolean;\n  onPoint: (id: string | null) => void;\n  onActivate: (event: VisitorEvent) => void;\n  onExited: (id: string) => void;\n}\n\n/** One visit in the feed: the place and the relative time, the page in mono below. */\nfunction FeedRow({ row, now, active, onPoint, onActivate, onExited }: FeedRowProps) {\n  const itemRef = React.useRef<HTMLLIElement>(null);\n  const markerRef = React.useRef<HTMLSpanElement>(null);\n  const { event, phase } = row;\n  const id = event.id;\n  const place = React.useMemo(() => placeName(event), [event]);\n  const detail = event.label?.trim() || formatLatLon(event, \"decimal\", 1);\n\n  React.useLayoutEffect(() => {\n    const item = itemRef.current;\n    if (phase !== \"enter\" || !item || typeof item.animate !== \"function\" || prefersReducedMotion()) return;\n    const entering = item.animate(ROW_ENTER_KEYFRAMES, ROW_TIMING);\n    const flash = markerRef.current?.animate(MARKER_FLASH_KEYFRAMES, {\n      duration: 2400,\n      easing: \"cubic-bezier(.2,.8,.2,1)\",\n    });\n    return () => {\n      entering.cancel();\n      flash?.cancel();\n    };\n  }, [phase]);\n\n  React.useLayoutEffect(() => {\n    if (phase !== \"exit\") return;\n    const item = itemRef.current;\n    if (!item || typeof item.animate !== \"function\" || prefersReducedMotion()) {\n      onExited(id);\n      return;\n    }\n    const leaving = item.animate(ROW_EXIT_KEYFRAMES, { ...ROW_TIMING, fill: \"forwards\" });\n    leaving.onfinish = () => onExited(id);\n    return () => {\n      leaving.onfinish = null;\n      leaving.cancel();\n    };\n  }, [phase, id, onExited]);\n\n  const leaving = phase === \"exit\";\n  return (\n    <li ref={itemRef} inert={leaving} aria-hidden={leaving || undefined} className=\"grid grid-rows-[1fr]\">\n      <div className=\"min-h-0 overflow-hidden\">\n        <button\n          type=\"button\"\n          data-active={active ? \"\" : undefined}\n          onPointerEnter={() => onPoint(id)}\n          onPointerLeave={() => onPoint(null)}\n          onFocus={() => onPoint(id)}\n          onBlur={() => onPoint(null)}\n          onClick={() => onActivate(event)}\n          className=\"group/row flex h-[36px] w-full cursor-pointer items-center gap-2.5 rounded-md border-0 bg-transparent px-2 text-left font-[inherit] text-inherit transition-colors duration-150 outline-none hover:bg-muted focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-lumesec focus-visible:outline-solid data-[active]:bg-muted motion-reduce:transition-none\"\n        >\n          <span\n            ref={markerRef}\n            aria-hidden=\"true\"\n            className=\"[margin-top:9px] size-[5px] shrink-0 self-start rounded-[1px] bg-foreground/20 transition-colors duration-200 group-data-[active]/row:bg-lumesec motion-reduce:transition-none\"\n          />\n          <span className=\"grid min-w-0 flex-1\">\n            <span className=\"flex min-w-0 items-baseline gap-2\">\n              <span className=\"truncate text-[13px] leading-4 text-foreground\">{place}</span>\n              <span className=\"ml-auto shrink-0 text-[11.5px] leading-4 text-muted-foreground tabular-nums\">\n                <RollText text={formatAgo(event.time, now)} />\n              </span>\n            </span>\n            <span className=\"truncate font-mono text-[11.5px] leading-[15px] text-muted-foreground\">{detail}</span>\n          </span>\n        </button>\n      </div>\n    </li>\n  );\n}\n\n/* Header ---------------------------------------------------------------------------------------------- */\n\n/** The 6 px live dot: it pulses every 1.6 s while visits stream in. */\nfunction LiveDot({ paused }: { paused: boolean }) {\n  const dotRef = React.useRef<HTMLSpanElement>(null);\n  const haloRef = React.useRef<HTMLSpanElement>(null);\n  const reduced = useReducedMotion();\n\n  React.useEffect(() => {\n    const dot = dotRef.current;\n    const halo = haloRef.current;\n    if (paused || reduced || !dot || !halo || typeof dot.animate !== \"function\") return;\n    const timing: KeyframeAnimationOptions = { duration: 1600, iterations: Infinity, easing: \"ease-in-out\" };\n    const pulse = dot.animate(DOT_PULSE_KEYFRAMES, timing);\n    const ring = halo.animate(HALO_KEYFRAMES, { ...timing, easing: \"cubic-bezier(.2,.7,.3,1)\" });\n    return () => {\n      pulse.cancel();\n      ring.cancel();\n    };\n  }, [paused, reduced]);\n\n  return (\n    <span aria-hidden=\"true\" className=\"relative grid size-1.5 shrink-0 place-items-center\">\n      <span\n        ref={haloRef}\n        className={cn(\"absolute inset-0 rounded-full opacity-0\", paused ? \"bg-muted-foreground\" : \"bg-lumesec-success\")}\n      />\n      <span\n        ref={dotRef}\n        className={cn(\"size-1.5 rounded-full\", paused ? \"bg-muted-foreground/60\" : \"bg-lumesec-success\")}\n      />\n    </span>\n  );\n}\n\n/**\n * The online count as mechanical figures: each digit rolls on its own, in the direction of the change, so 214 → 215\n * turns only the last wheel.\n */\nfunction RollingCount({ value, animate }: { value: number; animate: boolean }) {\n  const [shown, setShown] = React.useState({ value, direction: 1 });\n  if (shown.value !== value) setShown({ value, direction: value >= shown.value ? 1 : -1 });\n  const characters = Array.from(formatNumber(value));\n  return (\n    <span aria-hidden=\"true\" className=\"inline-flex\">\n      {characters.map((character, i) => (\n        // keyed from the right, so the ones digit keeps its wheel when the number grows a digit\n        <RollText key={characters.length - i} text={character} direction={shown.direction} animate={animate} />\n      ))}\n    </span>\n  );\n}\n\n/* Map overlays ---------------------------------------------------------------------------------------- */\n\ninterface MapHover {\n  event: VisitorEvent;\n  /** The visit's point on the map in CSS px. */\n  x: number;\n  y: number;\n  /** Map width when it was measured, to keep the tooltip inside. */\n  width: number;\n}\n\n/** The colour scale of the afterglow and its time window, under the map. */\nfunction Legend({ decay }: { decay: number }) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"flex items-center gap-1.5 font-mono text-[10.5px] leading-3 text-muted-foreground\"\n    >\n      <span className=\"flex gap-[2px]\">\n        {LEGEND_SWATCHES.map((swatch) => (\n          <span key={swatch} className={cn(\"size-1 rounded-[0.5px]\", swatch)} />\n        ))}\n      </span>\n      <span>Last {formatWindow(decay)}</span>\n    </div>\n  );\n}\n\n/** Place, page and time of the visit under the pointer, above its point. Pointer only: the feed has the same data. */\nfunction MapTooltip({ hover, now }: { hover: MapHover; now: number }) {\n  const { event, x, y, width } = hover;\n  const align = x < 72 ? \"start\" : x > width - 72 ? \"end\" : \"center\";\n  const shiftX = align === \"start\" ? \"-14px\" : align === \"end\" ? \"calc(-100% + 14px)\" : \"-50%\";\n  const below = y < 46;\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute top-0 left-0 z-[4] w-max max-w-[220px] rounded-md border border-border bg-popover px-2 py-1 text-popover-foreground shadow-[0_6px_16px_-8px_rgb(0_0_0/0.35)]\"\n      style={{ transform: `translate(${x}px, ${y}px) translate(${shiftX}, ${below ? \"12px\" : \"calc(-100% - 12px)\"})` }}\n    >\n      <div className=\"flex items-baseline gap-2 text-[12px] leading-4\">\n        <span className=\"truncate font-medium\">{placeName(event)}</span>\n        <span className=\"shrink-0 text-[11px] text-muted-foreground tabular-nums\">{formatAgo(event.time, now)}</span>\n      </div>\n      <div className=\"truncate font-mono text-[11px] leading-[14px] text-muted-foreground\">\n        {event.label?.trim() || formatLatLon(event, \"decimal\", 1)}\n      </div>\n    </div>\n  );\n}\n\n/* Constants ------------------------------------------------------------------------------------------- */\n\nconst MAP_CANVAS = { maxDpr: 2 } as const;\n/** Width of the SVG outline's coordinate space. */\nconst NOMINAL_WIDTH = 1000;\n/** Lattice pitch and land dot size in CSS px. */\nconst PITCH = 4;\nconst DOT_SIZE = 1.5;\n/** A visit warms the land dots within 10 px by exp(−d² / 40). */\nconst HEAT_RADIUS = 10;\nconst HEAT_KERNEL = 40;\n/** Below `HEAT_MIN` the afterglow is not drawn; from `WARM` a dot is in the accent, from `HOT` at the shine. */\nconst HEAT_MIN = 0.012;\nconst WARM = 0.6;\nconst HOT = 4;\n/** How much a marked row dims the rest of the afterglow. */\nconst FOCUS_DIM = 0.5;\n/** The marker and focus levels, 0 to 1, follow a critically damped spring that settles within 0.002. */\nconst LEVEL_SPRING = { stiffness: 260, damping: 1, epsilon: 0.002, velocityEpsilon: 0.01 };\n/** The drop: a streak falls for 260 ms, the ring spreads for 700 ms, the landing dot settles for 1.2 s. */\nconst FALL_MS = 260;\nconst RING_MS = 700;\nconst SETTLE_MS = 1200;\nconst BLOOM_MS = 420;\nconst STREAK_DOTS = 6;\nconst STREAK_HEIGHT = 18;\nconst STREAK_SIZE = 1.5;\n/** At most 30 drops in flight; more visits only add to the afterglow. Drops arriving together fall in turn. */\nconst MAX_DROPS = 30;\nconst DROP_STAGGER_MS = 70;\nconst PING_MS = 900;\n/** The marked visit's reticle: 12 squares on a 7.5 px circle. */\nconst RETICLE_DOTS = 12;\nconst RETICLE_RADIUS = 7.5;\nconst PING_GAP_MS = 180;\nconst REVEAL_MS = 1300;\nconst REVEAL_BAND = 0.06;\nconst REVEAL_END = 1 + REVEAL_BAND * 1.5;\nconst HEAT_TICK_MS = 250;\nconst SUMMARY_MS = 15_000;\n/** Online now counts the visits of the last five minutes. */\nconst RECENT_MS = 300_000;\n/** Pointing at the map finds the nearest of the last 50 visits within 12 px. */\nconst HOVER_POOL = 50;\nconst HOVER_RADIUS = 12;\nconst FEED_STEP_MS = 160;\nconst ROW_HEIGHT = 36;\n/** Visits kept for the afterglow, the count and the hover, at most. */\nconst MAX_VISITS = 4000;\n\nconst LANDING_SPARKS: SparkOptions = {\n  angle: -Math.PI / 2,\n  spread: 2.4,\n  speed: [40, 170],\n  gravity: 260,\n  life: [0.35, 0.8],\n  size: [1.5, 2],\n  jitter: 1.5,\n};\n\nconst ROW_TIMING = { duration: 320, easing: \"cubic-bezier(.2,.9,.3,1)\" } as const;\nconst ROW_ENTER_KEYFRAMES: Keyframe[] = [\n  { gridTemplateRows: \"0fr\", opacity: 0, transform: \"translateY(-6px)\" },\n  { gridTemplateRows: \"1fr\", opacity: 1, transform: \"translateY(0)\" },\n];\nconst ROW_EXIT_KEYFRAMES: Keyframe[] = [\n  { gridTemplateRows: \"1fr\", opacity: 1, transform: \"translateY(0)\" },\n  { gridTemplateRows: \"0fr\", opacity: 0, transform: \"translateY(-6px)\" },\n];\n/** A new row's marker lands in the accent and cools to the resting grey. */\nconst MARKER_FLASH_KEYFRAMES: Keyframe[] = [\n  { backgroundColor: \"var(--lumesec)\", boxShadow: \"0 0 0 3px color-mix(in srgb, var(--lumesec) 22%, transparent)\" },\n  { backgroundColor: \"var(--lumesec)\", boxShadow: \"0 0 0 0 transparent\", offset: 0.4 },\n];\nconst DOT_PULSE_KEYFRAMES: Keyframe[] = [{ opacity: 1 }, { opacity: 0.4, offset: 0.5 }, { opacity: 1 }];\nconst HALO_KEYFRAMES: Keyframe[] = [\n  { opacity: 0.45, transform: \"scale(1)\" },\n  { opacity: 0, transform: \"scale(2.8)\", offset: 0.7 },\n  { opacity: 0, transform: \"scale(2.8)\" },\n];\n\n/** The afterglow ramp as the legend shows it: land grey → accent → shine. */\nconst LEGEND_SWATCHES = [\n  \"bg-[color-mix(in_srgb,var(--muted-foreground)_70%,var(--card))]\",\n  \"bg-[color-mix(in_srgb,var(--muted-foreground)_35%,var(--lumesec))]\",\n  \"bg-lumesec\",\n  \"bg-[color-mix(in_srgb,var(--lumesec)_50%,var(--lumesec-shine))]\",\n  \"bg-lumesec-shine\",\n] as const;\n\n/** Demo pages with invented weights. */\nconst DEMO_PAGES = [\n  { path: \"/\", weight: 3 },\n  { path: \"/pricing\", weight: 2.2 },\n  { path: \"/docs/install\", weight: 1.8 },\n  { path: \"/docs\", weight: 1.5 },\n  { path: \"/blog\", weight: 1.2 },\n  { path: \"/changelog\", weight: 0.9 },\n  { path: \"/docs/api\", weight: 0.8 },\n  { path: \"/signup\", weight: 0.7 },\n  { path: \"/blog/dot-maps\", weight: 0.5 },\n  { path: \"/careers\", weight: 0.3 },\n] as const;\n\n/* Map engine ------------------------------------------------------------------------------------------ */\n\ninterface Visit {\n  readonly event: VisitorEvent;\n  /** Point on the map in CSS px, updated when the map is resized. */\n  x: number;\n  y: number;\n  /** Whether its afterglow is in: after the drop landed, or at once. */\n  landed: boolean;\n}\n\ninterface Drop {\n  readonly visit: Visit;\n  /** performance.now() when the streak starts to fall. */\n  readonly start: number;\n  landed: boolean;\n}\n\ninterface Ping {\n  readonly visit: Visit;\n  readonly start: number;\n}\n\ninterface AddOptions {\n  /** Drop new visits onto the map (else their afterglow appears at once). */\n  animate: boolean;\n  /** Queue their rows for the feed. */\n  announce: boolean;\n}\n\n/**\n * Everything the map draws, outside React: visits and their points, the afterglow per land dot, drops, pings, the\n * marked visit and the sparks. Three canvases: the land lattice (baked, redrawn only on resize, theme change and the\n * first reveal), the afterglow and landings (redrawn on the 250 ms ticks and while something moves) and a larger\n * effects layer for streaks and sparks.\n */\nclass VisitorMap {\n  /** Called when a visit lands (or arrives without a drop), so its row can enter the feed. */\n  onLand: (event: VisitorEvent) => void = () => undefined;\n\n  private kind: GeoVisitorsProjection = \"equalEarth\";\n  private decay = 300;\n  private ink: GeoInk | null = null;\n  private colors = { land: \"\", accent: \"\", shine: \"\", card: \"\" };\n  private batch: DotBatch | null = null;\n  private box: { width: number; height: number; dpr: number } | null = null;\n  private projection: MapProjection | null = null;\n  private lattice: DotLattice | null = null;\n  /** Afterglow per lattice dot. */\n  private heat = new Float32Array(0);\n  /** Reveal threshold per lattice dot (distance from the origin, with jitter). */\n  private threshold = new Float32Array(0);\n  private heatClock = 0;\n  /** Oldest first. */\n  private visits: Visit[] = [];\n  private readonly ids = new Set<string>();\n  private drops: Drop[] = [];\n  private pings: Ping[] = [];\n  private readonly sparks = new Sparks();\n  private nextDrop = 0;\n  private dirty = true;\n  private baseDirty = true;\n  private effectsDirty = false;\n  private reveal: \"waiting\" | \"running\" | \"done\" = \"waiting\";\n  private revealStart = 0;\n  private marker: Visit | null = null;\n  private activeId: string | null = null;\n  private readonly markerLevel: Spring = { position: 0, velocity: 0 };\n  private markerTarget = 0;\n  private readonly focusLevel: Spring = { position: 0, velocity: 0 };\n  private focusTarget = 0;\n  private effectsX = 0;\n  private effectsY = 0;\n  private readonly point = createScreenPoint();\n  private readonly hoverX = new Float32Array(HOVER_POOL);\n  private readonly hoverY = new Float32Array(HOVER_POOL);\n  private readonly hoverVisits: Visit[] = [];\n\n  /** Applies the projection and the decay. Returns whether anything changed. */\n  configure(kind: GeoVisitorsProjection, decay: number) {\n    let changed = false;\n    if (decay !== this.decay) {\n      this.decay = decay;\n      this.rebuildHeat(Date.now());\n      changed = true;\n    }\n    if (kind !== this.kind) {\n      this.kind = kind;\n      if (this.box) this.layout(this.box.width, this.box.height, this.box.dpr);\n      changed = true;\n    }\n    return changed;\n  }\n\n  /** New theme colours: the ramp and the baked land follow. */\n  setInk(ink: GeoInk) {\n    this.ink = ink;\n    this.colors = { land: rgba(ink.land), accent: rgba(ink.accent), shine: rgba(ink.shine), card: rgba(ink.card) };\n    // land → accent → shine: the hottest dots read as the most intense in both themes\n    const ramp = [ink.land, ink.accent, ink.shine];\n    if (this.batch) this.batch.setRamp(ramp);\n    else this.batch = createDotBatch(4096, ramp, { tones: 32, levels: 16 });\n    this.baseDirty = true;\n    this.dirty = true;\n  }\n\n  /** New map size: projection, lattice and points follow, and the afterglow is rebuilt from the visits. */\n  layout(width: number, height: number, dpr: number) {\n    this.box = { width, height, dpr };\n    const projection = createProjection(this.kind, { width, height, latRange: MAP_LAT_RANGE });\n    const lattice = mapLattice(projection, { pitch: PITCH });\n    this.projection = projection;\n    this.lattice = lattice;\n    this.heat = new Float32Array(lattice.count);\n    this.threshold = new Float32Array(lattice.count);\n    for (const visit of this.visits) this.place(visit);\n    if (this.reveal === \"running\") this.prepareReveal();\n    this.rebuildHeat(Date.now());\n    this.baseDirty = true;\n  }\n\n  /** The afterglow canvas was cleared (resized): draw it again on the next frame. */\n  invalidate() {\n    this.dirty = true;\n  }\n\n  /** Position of the map's top-left corner on the effects layer. */\n  setEffectsOffset(x: number, y: number) {\n    this.effectsX = x;\n    this.effectsY = y;\n  }\n\n  /** Adds visits (any order; ids already known are skipped). `now` is the epoch time their age is measured from. */\n  addVisits(events: readonly VisitorEvent[], options: AddOptions, now: number) {\n    const reduced = prefersReducedMotion();\n    const started = performance.now();\n    let inFlight = 0;\n    for (const drop of this.drops) if (!drop.landed) inFlight++;\n    const sorted = [...events].sort((a, b) => a.time - b.time);\n    for (const event of sorted) {\n      if (this.ids.has(event.id)) continue;\n      this.ids.add(event.id);\n      const visit: Visit = { event, x: 0, y: 0, landed: false };\n      this.place(visit);\n      this.insert(visit);\n      const age = Math.max(0, now - event.time);\n      // events older than the decay add no afterglow and do not drop\n      const warm = age < this.decay * 1000;\n      if (options.animate && warm && !reduced && this.projection && inFlight < MAX_DROPS) {\n        const start = Math.max(started, this.nextDrop);\n        this.nextDrop = start + DROP_STAGGER_MS * (0.6 + 0.8 * Math.random());\n        this.drops.push({ visit, start, landed: false });\n        inFlight++;\n        continue;\n      }\n      visit.landed = true;\n      if (warm) this.addHeat(visit, this.decayFactor(age));\n      if (options.announce) this.onLand(event);\n    }\n    this.trim();\n    this.dirty = true;\n  }\n\n  /** Removes visits by id and rebuilds the afterglow without them. */\n  removeVisits(ids: ReadonlySet<string>) {\n    this.visits = this.visits.filter((visit) => !ids.has(visit.event.id));\n    this.drops = this.drops.filter((drop) => !ids.has(drop.visit.event.id));\n    this.pings = this.pings.filter((ping) => !ids.has(ping.visit.event.id));\n    if (this.marker && ids.has(this.marker.event.id)) this.marker = null;\n    for (const id of ids) this.ids.delete(id);\n    this.rebuildHeat(Date.now());\n  }\n\n  /** The newest landed visits, newest first. */\n  newest(count: number) {\n    const list: VisitorEvent[] = [];\n    for (let i = this.visits.length - 1; i >= 0 && list.length < count; i--) {\n      if (this.visits[i].landed) list.push(this.visits[i].event);\n    }\n    return list;\n  }\n\n  /** Landed visits of the last five minutes. */\n  countRecent(now: number) {\n    let count = 0;\n    for (let i = this.visits.length - 1; i >= 0; i--) {\n      const visit = this.visits[i];\n      if (now - visit.event.time >= RECENT_MS) break;\n      if (visit.landed) count++;\n    }\n    return count;\n  }\n\n  /** \"12 visits in the last 15 seconds, most from São Paulo.\" or \"\" when there were none. */\n  summary(now: number) {\n    const places = new Map<string, number>();\n    let total = 0;\n    for (let i = this.visits.length - 1; i >= 0; i--) {\n      const visit = this.visits[i];\n      if (now - visit.event.time > SUMMARY_MS) break;\n      if (!visit.landed) continue;\n      total++;\n      const place = placeName(visit.event);\n      places.set(place, (places.get(place) ?? 0) + 1);\n    }\n    if (total === 0) return \"\";\n    let top = \"\";\n    let most = 0;\n    for (const [place, visits] of places) {\n      if (visits > most) {\n        most = visits;\n        top = place;\n      }\n    }\n    return total === 1\n      ? `1 visit in the last 15 seconds, from ${top}.`\n      : `${total} visits in the last 15 seconds, most from ${top}.`;\n  }\n\n  /** The 250 ms tick: fades the afterglow by the time since the last tick and lets go of visits nobody needs. */\n  tick(now: number) {\n    const elapsed = now - this.heatClock;\n    this.heatClock = now;\n    if (elapsed > 0) {\n      const factor = this.decayFactor(elapsed);\n      const heat = this.heat;\n      for (let i = 0; i < heat.length; i++) {\n        if (heat[i] === 0) continue;\n        heat[i] *= factor;\n        if (heat[i] < HEAT_MIN * 0.25) heat[i] = 0;\n      }\n      this.dirty = true;\n    }\n    this.trim(now);\n  }\n\n  /** Marks a visit (or none). A marked row also pings once and dims the rest of the afterglow. */\n  setActive(id: string | null, fromRow: boolean) {\n    const visit = id ? this.find(id) : undefined;\n    if (visit) this.marker = visit;\n    this.markerTarget = visit ? 1 : 0;\n    this.focusTarget = visit && fromRow ? 1 : 0;\n    if (visit && fromRow && id !== this.activeId) this.ping(visit.event.id);\n    this.activeId = id;\n  }\n\n  /** Two uneven rings of lit dots spread from the visit's point. No sparks. */\n  ping(id: string) {\n    const visit = this.find(id);\n    if (!visit || prefersReducedMotion()) return;\n    this.pings.push({ visit, start: performance.now() });\n  }\n\n  /** The nearest of the last 50 landed visits within `radius` px of (x, y). */\n  nearest(x: number, y: number, radius: number) {\n    const pool = this.hoverVisits;\n    pool.length = 0;\n    for (let i = this.visits.length - 1; i >= 0 && pool.length < HOVER_POOL; i--) {\n      const visit = this.visits[i];\n      if (!visit.landed) continue;\n      this.hoverX[pool.length] = visit.x;\n      this.hoverY[pool.length] = visit.y;\n      pool.push(visit);\n    }\n    const index = nearestIndex(this.hoverX, this.hoverY, pool.length, x, y, radius);\n    return index >= 0 ? pool[index] : null;\n  }\n\n  /** One frame: reveal, landings, springs, then the afterglow and the effects. Returns whether to keep going. */\n  step(base: CanvasSurface | null, heat: CanvasSurface | null, effects: CanvasSurface | null, delta: number) {\n    if (!this.lattice || !this.ink || !this.batch || !base || !heat) return false;\n    const now = performance.now();\n    const reduced = prefersReducedMotion();\n    let moving = false;\n\n    // The land prints itself once, outward from the newest visit, the first time the map is on screen.\n    let front = Infinity;\n    if (this.reveal !== \"done\") {\n      if (reduced) {\n        this.reveal = \"done\";\n      } else {\n        if (this.reveal === \"waiting\") {\n          this.reveal = \"running\";\n          this.revealStart = now;\n          this.prepareReveal();\n        }\n        const t = (now - this.revealStart) / REVEAL_MS;\n        if (t >= 1) {\n          this.reveal = \"done\";\n          this.baseDirty = true;\n          this.dirty = true;\n        } else {\n          front = easeOutCubic(t) * REVEAL_END;\n          this.drawReveal(base, front);\n          moving = true;\n        }\n      }\n    }\n    if (this.reveal === \"done\" && this.baseDirty) {\n      this.bake(base);\n      this.baseDirty = false;\n    }\n\n    const epoch = Date.now();\n    for (const drop of this.drops) if (!drop.landed && now >= drop.start + FALL_MS) this.land(drop, epoch);\n    if (this.drops.length) this.drops = this.drops.filter((drop) => now < drop.start + FALL_MS + SETTLE_MS);\n    if (this.pings.length) this.pings = this.pings.filter((ping) => now < ping.start + PING_GAP_MS + PING_MS);\n    if (settleSpring(this.markerLevel, this.markerTarget, delta, reduced, LEVEL_SPRING)) moving = true;\n    if (settleSpring(this.focusLevel, this.focusTarget, delta, reduced, LEVEL_SPRING)) moving = true;\n    if (this.drops.length || this.pings.length) moving = true;\n\n    if (this.dirty || moving) {\n      this.drawHeat(heat, now, front);\n      this.dirty = false;\n    }\n    const sparking = effects ? this.drawEffects(effects, now, delta) : false;\n    return moving || sparking;\n  }\n\n  /* internals */\n\n  private find(id: string) {\n    for (let i = this.visits.length - 1; i >= 0; i--) if (this.visits[i].event.id === id) return this.visits[i];\n    return undefined;\n  }\n\n  private place(visit: Visit) {\n    if (!this.projection) return;\n    const lat = clamp(visit.event.lat, MAP_LAT_RANGE[0], MAP_LAT_RANGE[1]);\n    this.projection.project(lat, wrapLongitude(visit.event.lon), this.point);\n    visit.x = this.point.x;\n    visit.y = this.point.y;\n  }\n\n  /** Keeps `visits` sorted by time; new visits are nearly always the newest. */\n  private insert(visit: Visit) {\n    const list = this.visits;\n    let index = list.length;\n    while (index > 0 && list[index - 1].event.time > visit.event.time) index--;\n    list.splice(index, 0, visit);\n  }\n\n  /** Drops visits older than the afterglow and the count need, keeping the last 50 for the hover. */\n  private trim(now = Date.now()) {\n    const keep = Math.max(this.decay * 1000, RECENT_MS);\n    let remove = Math.max(0, this.visits.length - MAX_VISITS);\n    while (remove < this.visits.length - HOVER_POOL) {\n      const visit = this.visits[remove];\n      if (now - visit.event.time <= keep || !visit.landed) break;\n      remove++;\n    }\n    if (remove === 0) return;\n    for (const visit of this.visits.slice(0, remove)) this.ids.delete(visit.event.id);\n    this.visits = this.visits.slice(remove);\n  }\n\n  private decayFactor(ms: number) {\n    // half-life of a quarter of the decay: after `decay` seconds 1/16 is left\n    return Math.exp(((-ms / 1000) * Math.LN2) / (this.decay / 4));\n  }\n\n  private addHeat(visit: Visit, amount: number) {\n    const lattice = this.lattice;\n    if (!lattice || !(amount > 0)) return;\n    const heat = this.heat;\n    lattice.grid.query(visit.x, visit.y, HEAT_RADIUS, (i, distanceSquared) => {\n      heat[i] += amount * Math.exp(-distanceSquared / HEAT_KERNEL);\n    });\n  }\n\n  private rebuildHeat(now: number) {\n    this.heat.fill(0);\n    this.heatClock = now;\n    const limit = this.decay * 1000;\n    for (const visit of this.visits) {\n      if (!visit.landed) continue;\n      const age = Math.max(0, now - visit.event.time);\n      if (age < limit) this.addHeat(visit, this.decayFactor(age));\n    }\n    this.dirty = true;\n  }\n\n  /** The streak has arrived: afterglow in, sparks out, the row may enter the feed. */\n  private land(drop: Drop, now: number) {\n    drop.landed = true;\n    const visit = drop.visit;\n    visit.landed = true;\n    this.addHeat(visit, this.decayFactor(Math.max(0, now - visit.event.time)));\n    this.dirty = true;\n    const ink = this.ink;\n    if (ink) {\n      // the glint is near white: on a light card the soft accent carries the third tone instead\n      const third = ink.dark ? ink.glint : ink.soft;\n      this.sparks.add(\n        visit.x + this.effectsX,\n        visit.y + this.effectsY,\n        12,\n        [ink.accent, ink.shine, third],\n        LANDING_SPARKS,\n      );\n    }\n    this.onLand(visit.event);\n  }\n\n  /** Reveal thresholds: distance from the newest visit (or the middle), plus the dot's jitter for an uneven front. */\n  private prepareReveal() {\n    const lattice = this.lattice;\n    const box = this.box;\n    if (!lattice || !box) return;\n    let ox = box.width / 2;\n    let oy = box.height / 2;\n    for (let i = this.visits.length - 1; i >= 0; i--) {\n      if (this.visits[i].landed) {\n        ox = this.visits[i].x;\n        oy = this.visits[i].y;\n        break;\n      }\n    }\n    const reach = Math.max(\n      Math.hypot(ox, oy),\n      Math.hypot(box.width - ox, oy),\n      Math.hypot(ox, box.height - oy),\n      Math.hypot(box.width - ox, box.height - oy),\n    );\n    for (let i = 0; i < lattice.count; i++) {\n      const n = Math.hypot(lattice.x[i] - ox, lattice.y[i] - oy) / reach;\n      this.threshold[i] = n * 0.82 + lattice.jitter[i] * 0.18;\n    }\n  }\n\n  /** Queues a lattice dot on the batch, snapped to device pixels so 1.5 px squares stay crisp. */\n  private addDot(i: number, size: number, tone: number, alpha: number) {\n    const lattice = this.lattice;\n    const batch = this.batch;\n    const dpr = this.box?.dpr ?? 1;\n    if (!lattice || !batch) return;\n    const s = Math.max(1, Math.round(size * dpr)) / dpr;\n    const x = Math.round((lattice.x[i] - s / 2) * dpr) / dpr + s / 2;\n    const y = Math.round((lattice.y[i] - s / 2) * dpr) / dpr + s / 2;\n    batch.add(x, y, s, tone, alpha);\n  }\n\n  private bake(surface: CanvasSurface) {\n    const { context, width, height } = surface;\n    const lattice = this.lattice;\n    context.clearRect(0, 0, width, height);\n    if (!lattice) return;\n    const dpr = this.box?.dpr ?? surface.dpr;\n    const s = Math.max(1, Math.round(DOT_SIZE * dpr)) / dpr;\n    context.fillStyle = this.colors.land;\n    for (let i = 0; i < lattice.count; i++) {\n      context.fillRect(\n        Math.round((lattice.x[i] - s / 2) * dpr) / dpr,\n        Math.round((lattice.y[i] - s / 2) * dpr) / dpr,\n        s,\n        s,\n      );\n    }\n  }\n\n  /** The first reveal: dots appear behind an uneven front that flashes in the accent as it passes. */\n  private drawReveal(surface: CanvasSurface, front: number) {\n    const { context, width, height } = surface;\n    const lattice = this.lattice;\n    const batch = this.batch;\n    context.clearRect(0, 0, width, height);\n    if (!lattice || !batch) return;\n    for (let i = 0; i < lattice.count; i++) {\n      const passed = front - this.threshold[i];\n      const appear = clamp(passed / REVEAL_BAND, 0, 1);\n      if (appear <= 0) continue;\n      const flash = Math.exp(-passed / 0.05);\n      this.addDot(i, DOT_SIZE + 0.6 * flash, 0.5 * flash, appear);\n    }\n    batch.flush(context);\n  }\n\n  private drawHeat(surface: CanvasSurface, now: number, front: number) {\n    const { context, width, height } = surface;\n    const lattice = this.lattice;\n    const batch = this.batch;\n    context.clearRect(0, 0, width, height);\n    if (!lattice || !batch) return;\n    const heat = this.heat;\n    const dim = 1 - FOCUS_DIM * clamp(this.focusLevel.position, 0, 1);\n    const revealing = Number.isFinite(front);\n\n    // the afterglow: even a faint trace reads as accent; only busy places climb toward the shine\n    for (let i = 0; i < lattice.count; i++) {\n      const h = heat[i];\n      if (h < HEAT_MIN) continue;\n      let alpha = (0.3 + 0.7 * (1 - Math.exp(-2 * h))) * smoothstep(HEAT_MIN, 0.06, h) * dim;\n      if (revealing) alpha *= clamp((front - this.threshold[i]) / REVEAL_BAND, 0, 1);\n      const tone = 0.5 * Math.min(1, Math.pow(h / WARM, 0.7)) + 0.5 * smoothstep(1, HOT, h);\n      this.addDot(i, DOT_SIZE + 0.5 * smoothstep(1, HOT, h), tone, alpha);\n    }\n\n    // landing rings: an uneven front of lit dots that spreads 24 px and fades\n    for (const drop of this.drops) {\n      if (!drop.landed) continue;\n      const t = (now - drop.start - FALL_MS) / RING_MS;\n      if (t < 1) this.ring(drop.visit, 2 + 22 * easeOutCubic(t), 4, 4, Math.pow(1 - t, 1.2), 0.55);\n    }\n    // pings: two thinner rings, the second a little later and weaker\n    for (const ping of this.pings) {\n      for (let k = 0; k < 2; k++) {\n        const t = (now - ping.start - k * PING_GAP_MS) / PING_MS;\n        if (t >= 0 && t < 1)\n          this.ring(ping.visit, 3 + 28 * easeOutCubic(t), 3.5, 3, Math.pow(1 - t, 1.2) * (k ? 0.75 : 1), 0.55);\n      }\n    }\n    // the marked visit: a still, uneven ring around its point\n    const level = clamp(this.markerLevel.position, 0, 1);\n    if (this.marker && level > 0.01) this.ring(this.marker, 6, 2.2, 2.5, level * 0.95, 0.6);\n    batch.flush(context);\n\n    const dpr = this.box?.dpr ?? surface.dpr;\n    for (const drop of this.drops) {\n      if (!drop.landed) continue;\n      const since = now - drop.start - FALL_MS;\n      const { x, y } = drop.visit;\n      if (since < BLOOM_MS && this.ink) {\n        // a short splash of light under the ring\n        const t = since / BLOOM_MS;\n        const radius = 5 + 13 * easeOutCubic(t);\n        const glow = context.createRadialGradient(x, y, 0, x, y, radius);\n        glow.addColorStop(0, rgba(this.ink.accent, 0.36 * Math.pow(1 - t, 1.5)));\n        glow.addColorStop(1, rgba(this.ink.accent, 0));\n        context.fillStyle = glow;\n        context.fillRect(x - radius, y - radius, radius * 2, radius * 2);\n      }\n      if (since < SETTLE_MS) {\n        // the landing dot: 3 px, shrinking into the afterglow\n        const t = since / SETTLE_MS;\n        context.globalAlpha = 1 - smoothstep(0.3, 1, t);\n        context.fillStyle = t < 0.12 ? this.colors.shine : this.colors.accent;\n        fillSquare(context, x, y, 3.2 - 1.7 * easeOutCubic(t), dpr);\n      }\n    }\n    if (this.marker && level > 0.01) {\n      // a dotted reticle that closes in on the point, legible over land and sea alike\n      const { x, y } = this.marker;\n      const radius = RETICLE_RADIUS + 5 * (1 - level);\n      context.globalAlpha = level;\n      context.fillStyle = this.colors.accent;\n      for (let k = 0; k < RETICLE_DOTS; k++) {\n        const angle = (k / RETICLE_DOTS) * Math.PI * 2;\n        fillSquare(context, x + Math.cos(angle) * radius, y + Math.sin(angle) * radius, 1.5, dpr);\n      }\n      context.fillStyle = this.colors.card;\n      fillSquare(context, x, y, 5, dpr);\n      context.fillStyle = this.colors.shine;\n      fillSquare(context, x, y, 3, dpr);\n    }\n    context.globalAlpha = 1;\n  }\n\n  /** Lattice dots on a ring around a visit, `strength` 0..1, toned from `tone` up to the shine where brightest. */\n  private ring(visit: Visit, radius: number, width: number, unevenness: number, strength: number, tone: number) {\n    const lattice = this.lattice;\n    if (!lattice) return;\n    lattice.grid.query(visit.x, visit.y, radius + unevenness + width * 2.5, (i, distanceSquared) => {\n      const b = ringFront(Math.sqrt(distanceSquared), radius, width, lattice.jitter[i], unevenness) * strength;\n      if (b > 0.05) this.addDot(i, DOT_SIZE + 0.6 * b, tone + (1 - tone) * b, Math.min(1, b));\n    });\n  }\n\n  /** Falling streaks and sparks on the layer that reaches past the map. Returns whether anything is alive. */\n  private drawEffects(surface: CanvasSurface, now: number, delta: number) {\n    const { context, width, height } = surface;\n    let falling = false;\n    for (const drop of this.drops) if (!drop.landed) falling = true;\n    if (!falling && !this.sparks.active) {\n      if (this.effectsDirty) {\n        context.clearRect(0, 0, width, height);\n        this.effectsDirty = false;\n      }\n      return false;\n    }\n    this.effectsDirty = true;\n    context.clearRect(0, 0, width, height);\n    const dpr = surface.dpr;\n    for (const drop of this.drops) {\n      if (drop.landed) continue;\n      const t = (now - drop.start) / FALL_MS;\n      if (t < 0) continue;\n      // a streak of six squares falls from 18 px above the point, speeding up and stretching as it goes\n      const fall = easeInCubic(t);\n      const x = drop.visit.x + this.effectsX;\n      const head = drop.visit.y + this.effectsY - STREAK_HEIGHT * (1 - fall);\n      const gap = 1.4 + 2.6 * fall;\n      const fadeIn = smoothstep(0, 0.3, t);\n      for (let k = 0; k < STREAK_DOTS; k++) {\n        context.globalAlpha = fadeIn * Math.pow(1 - k / STREAK_DOTS, 1.3);\n        context.fillStyle = k === 0 ? this.colors.shine : this.colors.accent;\n        fillSquare(context, x, head - k * gap, STREAK_SIZE, dpr);\n      }\n    }\n    context.globalAlpha = 1;\n    this.sparks.step(context, delta);\n    return true;\n  }\n}\n\n/* Feed queue and rows --------------------------------------------------------------------------------- */\n\ntype FeedChange = { kind: \"add\"; event: VisitorEvent } | { kind: \"replace\"; events: readonly VisitorEvent[] };\n\ninterface FeedQueue {\n  /** Queues a visit's row. Only the newest `limit` queued rows are kept: older ones would leave at once anyway. */\n  add(event: VisitorEvent): void;\n  /** Replaces the rows with `events` after the visits in `removed` left, on the next turn. */\n  replace(events: readonly VisitorEvent[], removed: ReadonlySet<string>): void;\n  /** Holds row changes while the feed is pointed at or focused, so rows do not move under the reader. */\n  hold(reason: string, held: boolean): void;\n  clear(): void;\n}\n\n/** Applies row changes one at a time, at most one per 160 ms, so bursts cascade instead of jumping. */\nfunction createFeedQueue(apply: (change: FeedChange) => void, limit: () => number): FeedQueue {\n  let pending: VisitorEvent[] = [];\n  let timer = 0;\n  let replaceTimer = 0;\n  let last = -Infinity;\n  const holds = new Set<string>();\n\n  const flush = () => {\n    timer = 0;\n    if (holds.size > 0) return;\n    const event = pending.shift();\n    if (!event) return;\n    last = performance.now();\n    apply({ kind: \"add\", event });\n    schedule();\n  };\n  const schedule = () => {\n    if (timer || holds.size > 0 || pending.length === 0) return;\n    timer = window.setTimeout(flush, Math.max(0, last + FEED_STEP_MS - performance.now()));\n  };\n\n  return {\n    add(event) {\n      let index = pending.length;\n      while (index > 0 && pending[index - 1].time > event.time) index--;\n      pending.splice(index, 0, event);\n      if (pending.length > limit()) pending = pending.slice(-limit());\n      schedule();\n    },\n    replace(events, removed) {\n      pending = pending.filter((event) => !removed.has(event.id));\n      window.clearTimeout(replaceTimer);\n      replaceTimer = window.setTimeout(() => {\n        replaceTimer = 0;\n        apply({ kind: \"replace\", events });\n      }, 0);\n    },\n    hold(reason, held) {\n      if (held) holds.add(reason);\n      else holds.delete(reason);\n      if (holds.size > 0) {\n        window.clearTimeout(timer);\n        timer = 0;\n      } else {\n        schedule();\n      }\n    },\n    clear() {\n      window.clearTimeout(timer);\n      window.clearTimeout(replaceTimer);\n      timer = 0;\n      replaceTimer = 0;\n      pending = [];\n    },\n  };\n}\n\nfunction newestRows(visits: readonly VisitorEvent[], limit: number): FeedRowState[] {\n  return [...visits]\n    .sort((a, b) => b.time - a.time)\n    .slice(0, limit)\n    .map((event) => ({ event, phase: \"idle\" as const }));\n}\n\n/** A new row at its place by time; the oldest rows past the limit slide out. */\nfunction insertRow(state: FeedState, event: VisitorEvent, reduced: boolean): FeedState {\n  if (state.rows.some((row) => row.event.id === event.id)) return state;\n  const live = state.rows.filter((row) => row.phase !== \"exit\");\n  // every slot holds a newer visit: this one would leave at once\n  if (live.length >= state.limit && live.every((row) => row.event.time >= event.time)) return state;\n  const rows = [...state.rows];\n  const index = rows.findIndex((row) => row.event.time < event.time);\n  rows.splice(index < 0 ? rows.length : index, 0, { event, phase: reduced ? \"idle\" : \"enter\" });\n  let excess = live.length + 1 - state.limit;\n  for (let i = rows.length - 1; i >= 0 && excess > 0; i--) {\n    if (rows[i].phase === \"exit\") continue;\n    if (reduced) rows.splice(i, 1);\n    else rows[i] = { event: rows[i].event, phase: \"exit\" };\n    excess--;\n  }\n  return { ...state, rows };\n}\n\nfunction dropRow(state: FeedState, id: string): FeedState {\n  return state.rows.some((row) => row.event.id === id)\n    ? { ...state, rows: state.rows.filter((row) => row.event.id !== id) }\n    : state;\n}\n\n/** Rows for a new list of newest visits, without animation. */\nfunction replaceRows(state: FeedState, events: readonly VisitorEvent[]): FeedState {\n  return { ...state, rows: events.slice(0, state.limit).map((event) => ({ event, phase: \"idle\" as const })) };\n}\n\n/** A new `maxFeed`: extra rows go at once; a larger feed fills up as visits arrive. */\nfunction resizeFeed(state: FeedState, limit: number): FeedState {\n  return { limit, rows: state.rows.filter((row) => row.phase !== \"exit\").slice(0, limit) };\n}\n\n/** Moves the demo history's relative times to the clock. */\nfunction shiftRows(state: FeedState, shift: number): FeedState {\n  return {\n    ...state,\n    rows: state.rows.map((row) => ({ ...row, event: { ...row.event, time: row.event.time + shift } })),\n  };\n}\n\n/* Data helpers ---------------------------------------------------------------------------------------- */\n\n/** Drops only play on screen in a visible page; otherwise the visit's afterglow appears at once. */\nfunction canDrop(onScreen: boolean) {\n  return onScreen && document.visibilityState !== \"hidden\";\n}\n\nfunction isValidEvent(event: VisitorEvent) {\n  return (\n    typeof event.id === \"string\" &&\n    event.id !== \"\" &&\n    Number.isFinite(event.lat) &&\n    Number.isFinite(event.lon) &&\n    Number.isFinite(event.time)\n  );\n}\n\n/** Valid events, first of each id, oldest first. */\nfunction validEvents(events: readonly VisitorEvent[]): VisitorEvent[] {\n  const seen = new Set<string>();\n  const list: VisitorEvent[] = [];\n  for (const event of events) {\n    if (!isValidEvent(event) || seen.has(event.id)) continue;\n    seen.add(event.id);\n    list.push(event);\n  }\n  return list.sort((a, b) => a.time - b.time);\n}\n\nfunction newestTime(events: readonly VisitorEvent[]) {\n  let newest = 0;\n  for (const event of events) newest = Math.max(newest, event.time);\n  return newest;\n}\n\nfunction countRecent(events: readonly VisitorEvent[], now: number) {\n  let count = 0;\n  for (const event of events) if (now - event.time < RECENT_MS) count++;\n  return count;\n}\n\n/** The place a row shows: the event's city, else the country at its point, else its coordinates. */\nfunction placeName(event: VisitorEvent) {\n  const city = event.city?.trim();\n  if (city) return city;\n  return countryAt(clamp(event.lat, -90, 90), wrapLongitude(event.lon))?.name ?? formatLatLon(event, \"decimal\", 1);\n}\n\n/** \"5 min\", \"45 s\", \"2 h\". */\nfunction formatWindow(seconds: number) {\n  if (seconds < 90) return `${Math.round(seconds)} s`;\n  if (seconds < 90 * 60) return `${Math.round(seconds / 60)} min`;\n  return `${Math.round(seconds / 3600)} h`;\n}\n\nconst round2 = (value: number) => Math.round(value * 100) / 100;\n\n/** A demo visit: a city picked by its weight, a point near it and a page. */\nfunction demoVisit(random: () => number, time: number, id: string): VisitorEvent {\n  const city = pickWeighted(random, DEMO_CITIES, (item) => item.weight);\n  const point = scatterAround(random, city, 30 + 90 * city.weight, true);\n  const page = pickWeighted(random, DEMO_PAGES, (item) => item.weight);\n  return { id, lat: point.lat, lon: point.lon, city: city.name, label: page.path, time };\n}\n\n/**\n * Five minutes of seeded demo history at the stream's own pace (a visit every 0.6 to 2.2 s), with times relative to\n * 0. The same on the server and the client; the clock moves it to now after mount.\n */\nfunction demoHistory(): VisitorEvent[] {\n  const random = createRandom(\"geo-visitors\");\n  const visits: VisitorEvent[] = [];\n  let ago = 0;\n  for (let i = 0; ; i++) {\n    ago += 600 + random() * 1600;\n    if (ago >= RECENT_MS) break;\n    visits.push(demoVisit(random, -Math.round(ago), `h${i}`));\n  }\n  return visits.reverse();\n}\n",
      "type": "registry:component",
      "target": "@components/lumesec/geo-visitors.tsx"
    }
  ],
  "meta": {
    "tag": "geo-visitors",
    "collection": "location",
    "react": "GeoVisitors",
    "kind": "react",
    "data": "input"
  },
  "docs": "Live visitors docs: https://elements.lumesec.ai/components/location/visitors",
  "categories": [
    "location",
    "maps-traffic"
  ],
  "type": "registry:component"
}