{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "geo-globe",
  "title": "Connection globe",
  "description": "A dotted globe with connections as dotted arcs. Each landing lights the land around the destination in an uneven ring and throws sparks past the edge.",
  "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-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",
    "https://elements.lumesec.ai/r/lumesec-use-controllable-state.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/components/lumesec/geo-globe.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { useCanvas, type CanvasSurface } from \"@/lib/lumesec/canvas\";\nimport { usePalette } from \"@/lib/lumesec/color\";\nimport {\n  angleDelta,\n  arcLift,\n  ARROW_DIRECTIONS,\n  buildArcLength,\n  centralAngle,\n  createDotBatch,\n  createGlobeMotion,\n  createScreenPoint,\n  cubicBezier,\n  DEG,\n  flyTo,\n  forEachDot,\n  GEO_TOKENS,\n  geoInk,\n  globeArc,\n  graticuleSvgPath,\n  isOccluded,\n  isValidLatLon,\n  latLonToVector,\n  nudgeGlobe,\n  placeLabels,\n  pointAtDistance,\n  projectLatLonGlobe,\n  ringFront,\n  rotationFromView,\n  spacingForRadius,\n  spatialNavigate,\n  sphereLattice,\n  stepGlobeMotion,\n  toneColor,\n  traceGlobeCoastlines,\n  useGlobeDrag,\n  wrapLongitude,\n  type ArcLengthTable,\n  type DotBatch,\n  type GeoInk,\n  type GlobeMotion,\n  type GlobeView,\n  type LabelAnchor,\n  type LabelPlacement,\n  type LatLon,\n  type ScreenPoint,\n  type SphereLattice,\n  type Vec3,\n} from \"@/lib/lumesec/geo\";\nimport { createRandom, DEMO_CITIES, DEMO_REGIONS, pickWeighted } from \"@/lib/lumesec/geo-data\";\nimport { clamp, easeOutCubic, mixRgb, rgba, smoothstep, TAU, type RGB } from \"@/lib/lumesec/math\";\nimport {\n  prefersReducedMotion,\n  springStep,\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 } from \"@/lib/lumesec/sparks\";\nimport { useControllableState } from \"@/lib/lumesec/use-controllable-state\";\nimport { cn } from \"@/lib/utils\";\n\n/** Colour of a connection: the accent, or one of the status colours. */\nexport type GlobeTone = \"accent\" | \"info\" | \"success\" | \"warning\" | \"destructive\";\n\n/** Land dot pitch: `fine` 3 px, `regular` 4 px, `coarse` 5 px between dots at the centre of the globe. */\nexport type GlobeDensity = \"fine\" | \"regular\" | \"coarse\";\n\n/** A place on the globe. Connections refer to it by `id`. */\nexport interface GlobeLocation {\n  /** Unique id. Connections use it in `from` and `to`, and it is the selection value. */\n  readonly id: string;\n  /** Name shown in the chip and used as the marker's accessible name. */\n  readonly label: string;\n  /** Latitude in degrees, -90 to 90. */\n  readonly lat: number;\n  /** Longitude in degrees, east positive. */\n  readonly lon: number;\n}\n\n/** One connection between two locations. Each `id` plays once. */\nexport interface GlobeConnection {\n  /** Unique id. A connection whose id has already played is ignored. */\n  readonly id: string;\n  /** Id of the location it leaves. */\n  readonly from: string;\n  /** Id of the location it lands at. */\n  readonly to: string;\n  /** Colour of the arc, packet and arrival. Default `accent`. */\n  readonly tone?: GlobeTone;\n}\n\n/** Imperative actions on the globe, exposed through `ref`. */\nexport interface GeoGlobeHandle {\n  /** Plays one connection (ignored when its id has already played). Works with or without `connections`. */\n  push(connection: GlobeConnection): void;\n  /** Turns the globe toward a location id or a point. */\n  flyTo(target: string | LatLon): void;\n}\n\n/** Props of GeoGlobe. The remaining props go to the root `<div>`. */\nexport interface GeoGlobeProps extends Omit<React.ComponentProps<\"div\">, \"ref\" | \"defaultValue\" | \"children\"> {\n  /** Points on the globe. Without it the globe shows 12 demo regions. An empty array shows the bare globe. */\n  locations?: readonly GlobeLocation[];\n  /**\n   * Connections to play, with location ids. Each new `id` plays once, so the array can grow or be replaced. Without\n   * it a seeded demo stream runs; pass an empty array to play only what you `push()`.\n   */\n  connections?: readonly GlobeConnection[];\n  /** Selected location id (controlled). Use with `onValueChange`. */\n  value?: string | null;\n  /** Selected location when uncontrolled. */\n  defaultValue?: string | null;\n  /** Called when a location is selected or the selection is cleared. */\n  onValueChange?: (value: string | null) => void;\n  /** Where the globe faces on mount, and where Home returns to. The latitude is limited to ±35°. */\n  defaultCenter?: LatLon;\n  /** Turns the globe slowly while idle, resuming 2.5 s after the last interaction. Off with reduced motion. */\n  autoRotate?: boolean;\n  /** Land dot pitch: 3, 4 or 5 px. */\n  density?: GlobeDensity;\n  /** Draws the hairline coastline. */\n  coastline?: boolean;\n  /** Arcs in flight at once. Further connections only add to the counts. */\n  maxArcs?: number;\n  /** Called when a connection's packet lands; at once for connections beyond `maxArcs`. */\n  onArrive?: (connection: GlobeConnection) => void;\n  /** Accessible name of the globe. */\n  label?: string;\n  /** Exposes `push()` and `flyTo()`. */\n  ref?: React.Ref<GeoGlobeHandle>;\n}\n\n/* Constants ------------------------------------------------------------------------------------------- */\n\nconst DEFAULT_CENTER: LatLon = { lat: 24, lon: 12 };\nconst LAT_LIMIT = 35;\nconst PITCH: Record<GlobeDensity, number> = { fine: 3, regular: 4, coarse: 5 };\n/** The globe's radius as a share of the stage's shorter side, leaving room for the arcs above it. */\nconst RADIUS_SHARE = 0.38;\n/** The effects canvas reaches this far above and below the stage, so sparks fly past its edge. */\nconst FX_Y = 40;\nconst LAND_DOT = 1.5;\n/** Dots closer to the limb than this (view z) are skipped: the foreshortened rows would moiré. */\nconst LIMB_CUTOFF = 0.06;\nconst MARKER_SIZE = 24;\n/** Zoomed in, the globe and its markers fade out over this many px at the stage edge. */\nconst EDGE_FADE = 20;\nconst EDGE_MASK = [\"bottom\", \"right\"]\n  .map(\n    (side) =>\n      `linear-gradient(to ${side}, transparent, #000 ${EDGE_FADE}px, #000 calc(100% - ${EDGE_FADE}px), transparent)`,\n  )\n  .join(\", \");\nconst MARKER_HIDE_Z = 0.12;\nconst AUTO_ROTATE_SPEED = 6;\nconst ZOOM_STEP = 0.2;\n\nconst ARC_SEGMENTS = 64;\nconst ARC_LIFT = 0.7;\nconst ARC_EASE = cubicBezier(0.45, 0, 0.25, 1);\n/** Seconds the full arc rests between drawing and erasing. */\nconst ARC_HOLD = 0.5;\nconst ARC_DOT_SPACING = 3.5;\nconst ARC_ALPHA = 0.7;\n/** Static arcs under reduced motion stay this long. */\nconst STILL_SECONDS = 2;\n/** Seconds between connections of a batch, so a burst arrives as a volley. */\nconst STAGGER = 0.12;\n/** A long volley still leaves within this many seconds. */\nconst MAX_STAGGER = 2.4;\n\nconst RIPPLE_SECONDS = 0.9;\nconst RIPPLE_REACH = 46;\nconst RIPPLE_WIDTH = 7;\nconst RIPPLE_COS = Math.cos(25 * DEG);\nconst GLOW_SECONDS = 2.4;\nconst SPARK_COUNT = 18;\n\nconst PLAYED_LIMIT = 2000;\nconst DEMO_INTERVAL_MS = 900;\nconst REPORT_INTERVAL_MS = 10_000;\n\nconst TONES: readonly GlobeTone[] = [\"accent\", \"info\", \"success\", \"warning\", \"destructive\"];\n\n/** The marker dot per tone; neutral markers use the land ink (the foreground 55 % over the card). */\nconst TONE_DOT: Record<GlobeTone, string> = {\n  accent: \"bg-lumesec\",\n  info: \"bg-lumesec-info\",\n  success: \"bg-lumesec-success\",\n  warning: \"bg-lumesec-warning\",\n  destructive: \"bg-destructive\",\n};\nconst NEUTRAL_DOT = \"bg-[color-mix(in_srgb,var(--foreground)_55%,var(--card))]\";\n\n/** The first 12 demo regions, from the shared Location demo set. */\nconst DEMO_LOCATIONS: readonly GlobeLocation[] = DEMO_REGIONS.slice(0, 12).map((region) => ({\n  id: region.id,\n  label: region.label,\n  lat: region.lat,\n  lon: region.lon,\n}));\n\n/** Demo traffic weights: each region takes the weight of its city in the demo city list. */\nconst DEMO_WEIGHTS = new Map<string, number>(\n  DEMO_REGIONS.map((region) => [region.id, DEMO_CITIES.find((city) => city.name === region.city)?.weight ?? 0.5]),\n);\n\nconst POP_KEYFRAMES: Keyframe[] = [\n  { transform: \"scale(1)\" },\n  { transform: \"scale(2.1)\", offset: 0.28 },\n  { transform: \"scale(1)\" },\n];\nconst CHIP_ENTER_KEYFRAMES: Keyframe[] = [\n  { scale: \"0.94\", filter: \"blur(2px)\" },\n  { scale: \"1\", filter: \"blur(0)\" },\n];\n\n/**\n * A dotted globe of the land masses with connections between locations. Each connection is a dotted arc that rises\n * higher the farther it travels, with a packet at its head; when the packet lands, the land dots around the\n * destination light up in an uneven ring and sparks fly off past the globe's edge. Drag to turn the globe (it coasts\n * and settles); locations are buttons in one tab stop, and selecting one keeps only its connections lit.\n *\n * @example\n * const globe = React.useRef<GeoGlobeHandle>(null);\n * <GeoGlobe ref={globe} locations={regions} connections={[]} onArrive={(c) => log(c)} />\n * // later: globe.current?.push({ id: \"c-1\", from: \"us-east\", to: \"eu-central\" });\n */\nexport function GeoGlobe({\n  locations,\n  connections,\n  value,\n  defaultValue = null,\n  onValueChange,\n  defaultCenter = DEFAULT_CENTER,\n  autoRotate = false,\n  density = \"regular\",\n  coastline = true,\n  maxArcs = 24,\n  onArrive,\n  label = \"Connections between locations\",\n  ref,\n  className,\n  ...props\n}: GeoGlobeProps) {\n  const [selected, setSelected] = useControllableState<string | null>({ value, defaultValue, onChange: onValueChange });\n  const places = React.useMemo(() => normalizeLocations(locations ?? DEMO_LOCATIONS), [locations]);\n  const placeById = React.useMemo(() => new Map(places.map((place) => [place.id, place])), [places]);\n  const demo = connections === undefined;\n  const reducedMotion = useReducedMotion();\n  const hintId = React.useId();\n\n  const centerLat = clamp(\n    Number.isFinite(defaultCenter.lat) ? defaultCenter.lat : DEFAULT_CENTER.lat,\n    -LAT_LIMIT,\n    LAT_LIMIT,\n  );\n  const centerLon = wrapLongitude(Number.isFinite(defaultCenter.lon) ? defaultCenter.lon : DEFAULT_CENTER.lon);\n\n  const [stats, setStats] = React.useState<StatsMap>(EMPTY_STATS);\n  // derived state: demo counts never mix with your data\n  const [statsDemo, setStatsDemo] = React.useState(demo);\n  if (statsDemo !== demo) {\n    setStatsDemo(demo);\n    setStats(EMPTY_STATS);\n  }\n  const [hoverId, setHoverId] = React.useState<string | null>(null);\n  const [focusId, setFocusId] = React.useState<string | null>(null);\n  const [tabStopId, setTabStopId] = React.useState<string | null>(null);\n  const [report, setReport] = React.useState(\"\");\n\n  const selectedPlace = selected !== null ? placeById.get(selected) : undefined;\n  const known = (id: string | null) => (id !== null && placeById.has(id) ? id : null);\n  const chipId = known(hoverId) ?? known(focusId) ?? selectedPlace?.id ?? null;\n  const chipPlace = chipId !== null ? placeById.get(chipId) : undefined;\n  const chipStats = (chipId !== null && stats[chipId]) || ZERO_STATS;\n  const tabStop = known(tabStopId) ?? selectedPlace?.id ?? places[0]?.id ?? null;\n\n  // Server markup: markers placed from the starting view, in container units, until the loop takes over.\n  const serverMarkers = React.useMemo(\n    () => serverMarkerStyles(places, centerLon, centerLat),\n    [places, centerLon, centerLat],\n  );\n  const graticule = React.useMemo(\n    () => graticuleSvgPath({ size: 200, centerLon, centerLat, step: 30 }),\n    [centerLon, centerLat],\n  );\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const surfaceRef = React.useRef<HTMLDivElement>(null);\n  const globeRef = React.useRef<HTMLCanvasElement>(null);\n  const effectsRef = React.useRef<HTMLCanvasElement>(null);\n  const placeholderRef = React.useRef<SVGSVGElement>(null);\n  const ringRef = React.useRef<HTMLDivElement>(null);\n  const chipRef = React.useRef<HTMLDivElement>(null);\n  const markerRefs = React.useRef(new Map<string, HTMLButtonElement>());\n  const dotRefs = React.useRef(new Map<string, HTMLSpanElement>());\n\n  const motionRef = useLazyRef(() =>\n    createGlobeMotion({ lon: centerLon, lat: centerLat, stiffness: 120, damping: 0.85, latLimit: LAT_LIMIT }),\n  );\n  /** Everything the loop mutates, created on first use (never during render). */\n  const runtimeRef = useLazyRef(createRuntime);\n  /** What the loop and the imperative handle read: the latest props and derived values. */\n  const latest = React.useRef<Latest>({ selected, chipId, places, placeById, maxArcs, onArrive, demo });\n  React.useEffect(() => {\n    latest.current = { selected, chipId, places, placeById, maxArcs, onArrive, demo };\n  });\n\n  const loop = useAnimationLoop(stageRef, step);\n  const palette = usePalette(rootRef, GEO_TOKENS, () => {\n    runtimeRef.current.inkStale = true;\n    loop.kick();\n  });\n  const globeSurface = useCanvas(\n    globeRef,\n    () => {\n      runtimeRef.current.globeDirty = true;\n      loop.kick();\n    },\n    { maxDpr: 2 },\n  );\n  const effectsSurface = useCanvas(effectsRef, () => loop.kick(), { maxDpr: 2 });\n\n  useGlobeDrag(surfaceRef, motionRef, {\n    radius: () => runtimeRef.current.view.radius,\n    axis: \"x\",\n    onChange: () => {\n      surfaceRef.current?.toggleAttribute(\"data-dragging\", motionRef.current.dragging);\n      loop.kick();\n    },\n    // a tap on the globe (not on a marker) clears the selection\n    onTap: () => setSelected(null),\n  });\n\n  /**\n   * Queues connections. Several in one go (an array, or `push()` calls in one handler) leave as a staggered volley\n   * rather than all in the same frame.\n   */\n  const play = React.useCallback(\n    (list: readonly GlobeConnection[], demoStream = false) => {\n      const run = runtimeRef.current;\n      let played = false;\n      for (const connection of list) {\n        if (!isConnection(connection) || run.played.has(connection.id)) continue;\n        enqueue(run, latest.current, connection, { delay: volleyDelay(run), demo: demoStream });\n        played = true;\n      }\n      if (played) loop.kick();\n    },\n    [runtimeRef, loop],\n  );\n\n  const flyToTarget = React.useCallback(\n    (target: string | LatLon) => {\n      const point = typeof target === \"string\" ? latest.current.placeById.get(target) : target;\n      if (!point || !Number.isFinite(point.lat) || !Number.isFinite(point.lon)) {\n        warnOnce(runtimeRef.current, `GeoGlobe: flyTo() got an unknown location \"${String(target)}\".`);\n        return;\n      }\n      flyTo(motionRef.current, point);\n      loop.kick();\n    },\n    [motionRef, runtimeRef, loop],\n  );\n\n  React.useImperativeHandle(ref, () => ({ push: (connection) => play([connection]), flyTo: flyToTarget }), [\n    play,\n    flyToTarget,\n  ]);\n\n  // Your connections: every id that has not played yet plays now.\n  React.useEffect(() => {\n    if (connections) play(connections);\n  }, [connections, play]);\n\n  // Demo stream: three arcs already in flight, then a connection every 0.9 s while the globe is in view.\n  const inView = useInView(rootRef, \"120px\");\n  React.useEffect(() => {\n    const run = runtimeRef.current;\n    if (!demo) {\n      // nothing invented stays once your data arrives\n      run.arcs = run.arcs.filter((arc) => !arc.demo);\n      run.stats = [];\n      run.arrivals = [];\n      loop.kick();\n      return;\n    }\n    if (run.seeded) return;\n    run.seeded = true;\n    for (const progress of [0.72, 0.46, 0.18]) {\n      const connection = nextDemoConnection(run, latest.current.places);\n      if (connection) enqueue(run, latest.current, connection, { progress, demo: true });\n    }\n    loop.kick();\n  }, [demo, runtimeRef, loop]);\n  useInterval(\n    () => {\n      if (document.hidden) return;\n      const connection = nextDemoConnection(runtimeRef.current, latest.current.places);\n      if (connection) play([connection], true);\n    },\n    DEMO_INTERVAL_MS,\n    demo && inView,\n  );\n\n  // Polite summary of the arrivals, at most every 10 s.\n  useInterval(() => {\n    const run = runtimeRef.current;\n    if (!run.arrivals.length) return;\n    setReport(arrivalReport(run.arrivals, latest.current.placeById));\n    run.arrivals = [];\n  }, REPORT_INTERVAL_MS);\n\n  // A new selection turns the globe toward it; the arcs re-spring their emphasis either way.\n  const selectedLat = selectedPlace?.lat;\n  const selectedLon = selectedPlace?.lon;\n  React.useEffect(() => {\n    if (selectedLat !== undefined && selectedLon !== undefined)\n      flyTo(motionRef.current, { lat: selectedLat, lon: selectedLon });\n    loop.kick();\n  }, [selectedLat, selectedLon, selected, motionRef, loop]);\n\n  React.useEffect(() => {\n    motionRef.current.autoRotate = autoRotate ? AUTO_ROTATE_SPEED : 0;\n    loop.kick();\n  }, [autoRotate, motionRef, loop]);\n\n  React.useEffect(() => {\n    runtimeRef.current.globeDirty = true;\n    loop.kick();\n  }, [coastline, density, places, reducedMotion, runtimeRef, loop]);\n\n  // Ctrl or Meta + wheel (and trackpad pinch) zooms; a plain wheel still scrolls the page.\n  React.useEffect(() => {\n    const surface = surfaceRef.current;\n    if (!surface) return;\n    const handleWheel = (event: WheelEvent) => {\n      if (!event.ctrlKey && !event.metaKey) return;\n      event.preventDefault();\n      const lines = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 400 : 1;\n      nudgeGlobe(motionRef.current, 0, 0, clamp(-event.deltaY * lines * 0.0025, -0.25, 0.25));\n      loop.kick();\n    };\n    surface.addEventListener(\"wheel\", handleWheel, { passive: false });\n    return () => surface.removeEventListener(\"wheel\", handleWheel);\n  }, [motionRef, loop]);\n\n  // The chip's size feeds its placement.\n  React.useEffect(() => {\n    const chip = chipRef.current;\n    if (!chip) return;\n    const run = runtimeRef.current;\n    const measure = () => {\n      run.chipWidth = chip.offsetWidth;\n      run.chipHeight = chip.offsetHeight;\n      loop.kick();\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(chip);\n    return () => observer.disconnect();\n  }, [runtimeRef, loop]);\n\n  // A chip for a new location eases in where it lands.\n  React.useEffect(() => {\n    const chip = chipRef.current;\n    runtimeRef.current.chipSide = null;\n    loop.kick();\n    if (chipId === null || !chip || reducedMotion || typeof chip.animate !== \"function\") return;\n    const animation = chip.animate(CHIP_ENTER_KEYFRAMES, { duration: 200, easing: \"cubic-bezier(.2,.8,.2,1)\" });\n    return () => animation.cancel();\n  }, [chipId, reducedMotion, runtimeRef, loop]);\n\n  // A new starting view makes React write the markers' server styles again; the loop puts them back on its next frame.\n  React.useLayoutEffect(() => {\n    runtimeRef.current.markers.clear();\n    loop.kick();\n  }, [serverMarkers, runtimeRef, loop]);\n\n  React.useEffect(() => {\n    const run = runtimeRef.current;\n    return () => {\n      window.clearTimeout(run.latticeTimer);\n      // a cancelled rebuild must be scheduled again when the effect re-runs\n      run.latticePending = 0;\n    };\n  }, [runtimeRef]);\n\n  function step(_time: number, delta: number) {\n    const run = runtimeRef.current;\n    const globe = globeSurface.current;\n    const colors = palette.current;\n    if (!globe || !colors) return false;\n    if (run.inkStale || !run.ink) applyInk(run, geoInk(colors));\n    const ink = run.ink;\n    if (!ink) return false;\n\n    const reduced = prefersReducedMotion();\n    const state = motionRef.current;\n    const moving = stepGlobeMotion(state, delta, reduced);\n    updateView(run, state, globe.width, globe.height);\n    ensureLattice(run, PITCH[density] ?? PITCH.regular, () => loop.kick());\n\n    const { selected: selection } = latest.current;\n    const springing = advanceArcs(\n      run,\n      selection,\n      delta,\n      reduced,\n      (arc) => arrive(arc, reduced),\n      (arc) => depart(arc),\n    );\n    advanceRipples(run, delta);\n\n    if (run.globeDirty || run.ripples.length) {\n      drawGlobe(globe, run, ink, coastline);\n      run.globeDirty = false;\n      if (!run.painted) {\n        run.painted = true;\n        // crossfade from the server placeholder to the first canvas frame\n        if (placeholderRef.current) placeholderRef.current.style.opacity = \"0\";\n      }\n    }\n    const effects = effectsSurface.current;\n    if (effects) drawEffects(effects, run, delta);\n\n    placeMarkers(run);\n    placeChip(run);\n    placeRing(run);\n\n    if (run.stats.length) {\n      const events = run.stats;\n      run.stats = [];\n      setStats((previous) => applyStats(previous, events));\n    }\n\n    return (\n      moving ||\n      springing ||\n      run.arcs.length > 0 ||\n      run.ripples.length > 0 ||\n      run.glows.length > 0 ||\n      run.sparks.active ||\n      run.fxDirty\n    );\n  }\n\n  function depart(arc: Arc) {\n    runtimeRef.current.stats.push({ id: arc.connection.from, kind: \"out\", tone: arc.tone });\n  }\n\n  /** The packet landed: ring, sparks and a pop on the marker; under reduced motion only the glow and the counts. */\n  function arrive(arc: Arc, reduced: boolean) {\n    const run = runtimeRef.current;\n    const { connection, tone } = arc;\n    const vector = latLonToVector(arc.to.lat, arc.to.lon);\n    run.glows.push({ vector, age: 0, tone });\n    run.stats.push({ id: connection.to, kind: \"in\", tone });\n    run.arrivals.push(connection.to);\n    if (!reduced) {\n      run.ripples.push({ vector, age: 0, tone, radius: 0, fade: 1 });\n      const point = run.point;\n      const { view } = run;\n      if (projectLatLonGlobe(view, arc.to.lat, arc.to.lon, point) && point.z > 0.05 && run.ink) {\n        // sparks leave away from the globe's centre, so near the limb they fly off the disc\n        const angle = Math.atan2(point.y - view.cy, point.x - view.cx);\n        run.sparks.add(point.x, point.y + FX_Y, SPARK_COUNT, [toneColor(run.ink, tone), run.hot], {\n          angle,\n          spread: 1.6,\n          speed: [60, 220],\n          life: [0.4, 0.9],\n        });\n      }\n      const dot = dotRefs.current.get(connection.to);\n      if (dot && point.z >= MARKER_HIDE_Z && typeof dot.animate === \"function\") {\n        dot.animate(POP_KEYFRAMES, { duration: 520, easing: \"cubic-bezier(.2,.8,.2,1)\" });\n      }\n    }\n    latest.current.onArrive?.(connection);\n  }\n\n  function placeMarkers(run: Runtime) {\n    const { places: list } = latest.current;\n    const point = run.point;\n    for (const place of list) {\n      const button = markerRefs.current.get(place.id);\n      if (!button) continue;\n      projectLatLonGlobe(run.view, place.lat, place.lon, point);\n      const x = point.x - MARKER_SIZE / 2;\n      const y = point.y - MARKER_SIZE / 2;\n      // zoomed in, markers fade out at the stage edge with the globe instead of floating past it\n      const edge = Math.min(point.x, run.width - point.x, point.y, run.height - point.y);\n      const opacity =\n        smoothstep(MARKER_HIDE_Z, MARKER_HIDE_Z + 0.12, point.z) * smoothstep(EDGE_FADE * 0.25, EDGE_FADE, edge);\n      const last = run.markers.get(place.id);\n      const unchanged = last?.element === button && Math.abs(last.x - x) < 0.01 && Math.abs(last.y - y) < 0.01;\n      if (unchanged && Math.abs(last.opacity - opacity) < 0.005) continue;\n      button.style.transform = `translate3d(${x.toFixed(2)}px,${y.toFixed(2)}px,0)`;\n      button.style.opacity = opacity.toFixed(3);\n      // back-side markers stay focusable; focusing one turns the globe toward it\n      button.style.pointerEvents = opacity > 0 ? \"\" : \"none\";\n      run.markers.set(place.id, { element: button, x, y, opacity });\n    }\n  }\n\n  function placeChip(run: Runtime) {\n    const chip = chipRef.current;\n    if (!chip) return;\n    const { chipId: id, placeById: lookup, places: list } = latest.current;\n    const place = id !== null ? lookup.get(id) : undefined;\n    const point = run.point;\n    const front = place ? projectLatLonGlobe(run.view, place.lat, place.lon, point) && point.z >= MARKER_HIDE_Z : false;\n    const marker = place ? run.markers.get(place.id) : undefined;\n    const shown = Boolean(place) && front && (marker?.opacity ?? 0) > 0.5 && run.chipWidth > 0;\n    if (shown !== run.chipShown) {\n      run.chipShown = shown;\n      chip.style.opacity = shown ? \"1\" : \"0\";\n    }\n    if (!shown || !place) return;\n    const anchor = { x: point.x, y: point.y };\n    const others: { x: number; y: number }[] = [];\n    for (const other of list) {\n      if (other.id === place.id) continue;\n      const marker = run.markers.get(other.id);\n      if (marker && marker.opacity > 0.5) others.push({ x: marker.x + MARKER_SIZE / 2, y: marker.y + MARKER_SIZE / 2 });\n    }\n    const box = chipBox(run, anchor, others);\n    chip.style.transform = `translate3d(${box.x.toFixed(1)}px,${box.y.toFixed(1)}px,0)`;\n  }\n\n  function placeRing(run: Runtime) {\n    const ring = ringRef.current;\n    if (!ring || Math.abs(run.ringRadius - run.view.radius) < 0.25) return;\n    run.ringRadius = run.view.radius;\n    const size = `${(run.view.radius * 2).toFixed(1)}px`;\n    ring.style.width = size;\n    ring.style.height = size;\n  }\n\n  function focusPlace(place: GlobeLocation) {\n    setFocusId(place.id);\n    setTabStopId(place.id);\n    flyTo(motionRef.current, place);\n    loop.kick();\n  }\n\n  function handleStageKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    const state = motionRef.current;\n    const degrees = event.shiftKey ? 30 : 10;\n    switch (event.key) {\n      case \"ArrowLeft\":\n        nudgeGlobe(state, -degrees, 0);\n        break;\n      case \"ArrowRight\":\n        nudgeGlobe(state, degrees, 0);\n        break;\n      case \"ArrowUp\":\n        nudgeGlobe(state, 0, degrees);\n        break;\n      case \"ArrowDown\":\n        nudgeGlobe(state, 0, -degrees);\n        break;\n      case \"+\":\n      case \"=\":\n        nudgeGlobe(state, 0, 0, ZOOM_STEP);\n        break;\n      case \"-\":\n      case \"_\":\n        nudgeGlobe(state, 0, 0, -ZOOM_STEP);\n        break;\n      case \"Home\":\n        flyTo(state, { lat: centerLat, lon: centerLon }, 1);\n        break;\n      case \"Escape\":\n        if (selected === null) return;\n        setSelected(null);\n        break;\n      default:\n        return;\n    }\n    event.preventDefault();\n    loop.kick();\n  }\n\n  function handleMarkerKeyDown(event: React.KeyboardEvent<HTMLButtonElement>, index: number) {\n    const direction = ARROW_DIRECTIONS[event.key];\n    if (!direction) return;\n    event.preventDefault();\n    event.stopPropagation();\n    // the globe unrolled around the view centre, so the arrows reach locations on the far side too\n    const state = motionRef.current;\n    const centre = state.target ?? state;\n    const points = places.map((place) => ({ x: angleDelta(centre.lon, place.lon), y: -place.lat }));\n    const next = spatialNavigate(points, index, direction);\n    if (next !== index) markerRefs.current.get(places[next].id)?.focus();\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"geo-globe\"\n      className={cn(\"@container relative w-full max-w-[660px] text-foreground\", className)}\n      {...props}\n    >\n      <div\n        ref={stageRef}\n        role=\"group\"\n        aria-roledescription=\"globe\"\n        aria-label={`${label}, ${places.length} ${places.length === 1 ? \"location\" : \"locations\"}`}\n        aria-describedby={hintId}\n        tabIndex={0}\n        onKeyDown={handleStageKeyDown}\n        className=\"group/globe relative aspect-square outline-none select-none [--globe-cy:50cqw] [--globe-r:38cqw] @[480px]:aspect-[16/11] @[480px]:[--globe-cy:34.375cqw] @[480px]:[--globe-r:26.125cqw]\"\n      >\n        <svg\n          ref={placeholderRef}\n          aria-hidden=\"true\"\n          viewBox=\"0 0 200 200\"\n          className=\"pointer-events-none absolute top-1/2 left-1/2 size-[calc(var(--globe-r)*2)] -translate-x-1/2 -translate-y-1/2 overflow-visible transition-opacity duration-300 motion-reduce:transition-none\"\n        >\n          <circle\n            cx=\"100\"\n            cy=\"100\"\n            r=\"100\"\n            className=\"fill-card stroke-border\"\n            strokeWidth={1}\n            vectorEffect=\"non-scaling-stroke\"\n          />\n          <path d={graticule} fill=\"none\" className=\"stroke-border\" strokeWidth={1} vectorEffect=\"non-scaling-stroke\" />\n        </svg>\n        <canvas\n          ref={globeRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-0 block size-full\"\n          style={{\n            maskImage: EDGE_MASK,\n            WebkitMaskImage: EDGE_MASK,\n            maskComposite: \"intersect\",\n            WebkitMaskComposite: \"source-in\",\n          }}\n        />\n        <div\n          ref={surfaceRef}\n          aria-hidden=\"true\"\n          className=\"absolute inset-0 cursor-grab touch-pan-y [-webkit-tap-highlight-color:transparent] data-[dragging]:cursor-grabbing\"\n        />\n        <canvas\n          ref={effectsRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 -top-10 z-[1] block h-[calc(100%+80px)] w-full\"\n        />\n        <div\n          ref={ringRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute top-1/2 left-1/2 size-[calc(var(--globe-r)*2)] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-0 outline-2 outline-offset-4 outline-lumesec outline-solid group-focus-visible/globe:opacity-100\"\n        />\n        <div className=\"pointer-events-none absolute inset-0 z-[2]\">\n          {places.map((place, index) => {\n            const placeStats = stats[place.id];\n            const tone = placeStats?.tone ?? null;\n            const pressed = place.id === selectedPlace?.id;\n            return (\n              <button\n                key={place.id}\n                ref={(node) => {\n                  if (node) markerRefs.current.set(place.id, node);\n                  else markerRefs.current.delete(place.id);\n                }}\n                type=\"button\"\n                tabIndex={place.id === tabStop ? 0 : -1}\n                aria-pressed={pressed}\n                aria-label={`${place.label}, ${placeStats?.incoming ?? 0} in, ${placeStats?.outgoing ?? 0} out`}\n                onClick={() => setSelected((current) => (current === place.id ? null : place.id))}\n                onFocus={() => focusPlace(place)}\n                onBlur={() => setFocusId((current) => (current === place.id ? null : current))}\n                onKeyDown={(event) => handleMarkerKeyDown(event, index)}\n                onPointerEnter={() => setHoverId(place.id)}\n                onPointerLeave={() => setHoverId((current) => (current === place.id ? null : current))}\n                className=\"group/marker pointer-events-auto absolute top-0 left-0 grid size-6 cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 outline-none [-webkit-tap-highlight-color:transparent] focus-visible:outline-2 focus-visible:outline-lumesec focus-visible:outline-solid\"\n                style={serverMarkers.get(place.id)}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className=\"absolute inset-[4px] scale-75 rounded-full border border-foreground/30 opacity-0 transition-[opacity,scale,border-color] duration-200 ease-out group-hover/marker:scale-100 group-hover/marker:opacity-100 group-aria-pressed/marker:scale-100 group-aria-pressed/marker:border-lumesec group-aria-pressed/marker:opacity-100 motion-reduce:transition-none\"\n                />\n                <span\n                  ref={(node) => {\n                    if (node) dotRefs.current.set(place.id, node);\n                    else dotRefs.current.delete(place.id);\n                  }}\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"relative size-1.5 rounded-full shadow-[0_0_0_1.5px_var(--card)] transition-colors duration-500\",\n                    tone ? TONE_DOT[tone] : NEUTRAL_DOT,\n                    pressed && !tone && \"bg-lumesec\",\n                  )}\n                />\n              </button>\n            );\n          })}\n        </div>\n        <div\n          ref={chipRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute top-0 left-0 z-[3] flex items-center gap-2 rounded-md border border-border bg-card px-2 py-[5px] text-[12px] leading-4 whitespace-nowrap opacity-0 shadow-[0_8px_20px_-12px_rgb(0_0_0/0.45)] transition-opacity duration-150 motion-reduce:transition-none\"\n        >\n          <span className=\"font-medium\">{chipPlace?.label ?? \"\"}</span>\n          <span className=\"h-3 w-px bg-border\" />\n          <span className=\"flex items-center gap-1 font-mono text-[11.5px] text-muted-foreground tabular-nums\">\n            In\n            <RollText key={`in:${chipId}`} text={String(chipStats.incoming)} className=\"text-foreground\" />\n            <span className=\"px-0.5\">·</span>\n            Out\n            <RollText key={`out:${chipId}`} text={String(chipStats.outgoing)} className=\"text-foreground\" />\n          </span>\n        </div>\n      </div>\n      <p id={hintId} className=\"sr-only\">\n        Arrow keys turn the globe, plus and minus zoom, Home resets the view. Each location is a button; arrow keys move\n        between locations.\n      </p>\n      <div aria-live=\"polite\" className=\"sr-only\">\n        {report}\n      </div>\n    </div>\n  );\n}\n\n/* Runtime state ----------------------------------------------------------------------------------------- */\n\ninterface LocationStats {\n  readonly incoming: number;\n  readonly outgoing: number;\n  /** Tone of the latest connection that left or reached the location. */\n  readonly tone: GlobeTone | null;\n}\n\ntype StatsMap = Readonly<Record<string, LocationStats>>;\n\nconst EMPTY_STATS: StatsMap = {};\nconst ZERO_STATS: LocationStats = { incoming: 0, outgoing: 0, tone: null };\n\ninterface StatEvent {\n  id: string;\n  kind: \"in\" | \"out\";\n  tone: GlobeTone;\n}\n\ninterface Latest {\n  selected: string | null;\n  chipId: string | null;\n  places: readonly GlobeLocation[];\n  placeById: ReadonlyMap<string, GlobeLocation>;\n  maxArcs: number;\n  onArrive: ((connection: GlobeConnection) => void) | undefined;\n  demo: boolean;\n}\n\n/** A connection in flight: its lifted arc in world space and the screen buffers it is redrawn from every frame. */\ninterface Arc {\n  readonly connection: GlobeConnection;\n  readonly tone: GlobeTone;\n  readonly to: LatLon;\n  readonly demo: boolean;\n  /** World xyz per sample, lifted by the arc's altitude. */\n  readonly samples: Float32Array;\n  /** Seconds to draw (and to erase) the arc: longer for longer arcs. */\n  readonly duration: number;\n  /** Seconds since departure; negative while waiting its turn in a volley. */\n  age: number;\n  departed: boolean;\n  arrived: boolean;\n  /** Reduced motion at departure: the arc shows complete and static, without a packet. */\n  still: boolean;\n  /** 1 when it touches the selection (or nothing is selected), else 0.15; sprung. */\n  readonly emphasis: Spring;\n  readonly xs: Float32Array;\n  readonly ys: Float32Array;\n  readonly zs: Float32Array;\n  readonly visible: Uint8Array;\n  readonly table: ArcLengthTable;\n}\n\ninterface Ripple {\n  readonly vector: Vec3;\n  readonly tone: GlobeTone;\n  age: number;\n  /** Ring radius in px this frame. */\n  radius: number;\n  /** Brightness left this frame, 1 to 0. */\n  fade: number;\n}\n\ninterface Glow {\n  readonly vector: Vec3;\n  readonly tone: GlobeTone;\n  age: number;\n}\n\ninterface MarkerPosition {\n  /** The button last written, so a remounted one is placed again. */\n  element: HTMLButtonElement;\n  x: number;\n  y: number;\n  opacity: number;\n}\n\n/** Shared state of the forEachDot visitor, so drawing an arc allocates nothing. */\ninterface DotCursor {\n  arc: Arc | null;\n  batch: DotBatch | null;\n  segment: number;\n  head: number;\n  tail: number;\n  flying: boolean;\n  emphasis: number;\n}\n\n/** Everything the animation loop mutates. Lives in a ref, never in React state. */\ninterface Runtime {\n  view: GlobeView;\n  width: number;\n  height: number;\n  lastLon: number;\n  lastLat: number;\n  lattice: SphereLattice | null;\n  latticeSpacing: number;\n  latticePending: number;\n  latticeTimer: number;\n  ink: GeoInk | null;\n  inkStale: boolean;\n  hot: RGB;\n  discFill: string;\n  limb: string;\n  coast: string;\n  /** Land dots in their resting shade. */\n  base: DotBatch | null;\n  /** Land dots lit by an arrival: land ink → tone → hot, per tone. */\n  lit: Record<GlobeTone, DotBatch> | null;\n  /** Arc dots and packets: tone → hot, per tone. */\n  trail: Record<GlobeTone, DotBatch> | null;\n  arcs: Arc[];\n  ripples: Ripple[];\n  glows: Glow[];\n  sparks: Sparks;\n  played: Set<string>;\n  playedOrder: string[];\n  stats: StatEvent[];\n  /** Destination ids since the last live-region report. */\n  arrivals: string[];\n  random: () => number;\n  demoCount: number;\n  /** When the last connection was queued (ms) and its place in the current volley. */\n  volleyTime: number;\n  volleyIndex: number;\n  seeded: boolean;\n  warned: boolean;\n  globeDirty: boolean;\n  fxDirty: boolean;\n  painted: boolean;\n  markers: Map<string, MarkerPosition>;\n  chipWidth: number;\n  chipHeight: number;\n  chipShown: boolean;\n  chipSide: LabelPlacement[\"side\"] | null;\n  /** Radius the focus ring was last sized to. */\n  ringRadius: number;\n  point: ScreenPoint;\n  cursor: DotCursor;\n  visitArcDot: (x: number, y: number, s: number) => void;\n  packet: { x: number; y: number; angle: number };\n}\n\nfunction createRuntime(): Runtime {\n  const run: Runtime = {\n    view: { cx: 0, cy: 0, radius: 0, rotation: new Float64Array(9) },\n    width: 0,\n    height: 0,\n    lastLon: Number.NaN,\n    lastLat: Number.NaN,\n    lattice: null,\n    latticeSpacing: 0,\n    latticePending: 0,\n    latticeTimer: 0,\n    ink: null,\n    inkStale: true,\n    hot: [255, 255, 255],\n    discFill: \"\",\n    limb: \"\",\n    coast: \"\",\n    base: null,\n    lit: null,\n    trail: null,\n    arcs: [],\n    ripples: [],\n    glows: [],\n    sparks: new Sparks(),\n    played: new Set(),\n    playedOrder: [],\n    stats: [],\n    arrivals: [],\n    random: createRandom(\"geo-globe\"),\n    demoCount: 0,\n    volleyTime: -Infinity,\n    volleyIndex: 0,\n    seeded: false,\n    warned: false,\n    globeDirty: true,\n    fxDirty: false,\n    painted: false,\n    markers: new Map(),\n    chipWidth: 0,\n    chipHeight: 0,\n    chipShown: false,\n    chipSide: null,\n    ringRadius: 0,\n    point: createScreenPoint(),\n    cursor: { arc: null, batch: null, segment: 0, head: 0, tail: 0, flying: false, emphasis: 1 },\n    visitArcDot: () => {},\n    packet: { x: 0, y: 0, angle: 0 },\n  };\n  run.visitArcDot = (x, y, s) => visitArcDot(run.cursor, x, y, s);\n  return run;\n}\n\n/* Data ---------------------------------------------------------------------------------------------------- */\n\nconst isTone = (tone: unknown): tone is GlobeTone =>\n  typeof tone === \"string\" && (TONES as readonly string[]).includes(tone);\n\nfunction isConnection(value: GlobeConnection | null | undefined): value is GlobeConnection {\n  return (\n    Boolean(value) && typeof value?.id === \"string\" && typeof value.from === \"string\" && typeof value.to === \"string\"\n  );\n}\n\n/** Valid, unique locations with wrapped longitudes. Invalid entries are skipped. */\nfunction normalizeLocations(list: readonly GlobeLocation[]): GlobeLocation[] {\n  const seen = new Set<string>();\n  const result: GlobeLocation[] = [];\n  for (const place of list) {\n    if (!place || typeof place.id !== \"string\" || seen.has(place.id)) continue;\n    if (!isValidLatLon(place)) continue;\n    seen.add(place.id);\n    result.push({\n      id: place.id,\n      label: String(place.label ?? place.id),\n      lat: place.lat,\n      lon: wrapLongitude(place.lon),\n    });\n  }\n  return result;\n}\n\n/** Server styles for the markers: positions from the starting view in container units, back-side ones hidden. */\nfunction serverMarkerStyles(places: readonly GlobeLocation[], centerLon: number, centerLat: number) {\n  const rotation = rotationFromView(centerLon, centerLat);\n  const view: GlobeView = { cx: 0, cy: 0, radius: 1, rotation };\n  const point = createScreenPoint();\n  const styles = new Map<string, React.CSSProperties>();\n  for (const place of places) {\n    projectLatLonGlobe(view, place.lat, place.lon, point);\n    const hidden = point.z < MARKER_HIDE_Z;\n    styles.set(place.id, {\n      transform: `translate3d(calc(50cqw + ${point.x.toFixed(4)} * var(--globe-r) - ${MARKER_SIZE / 2}px), calc(var(--globe-cy) + ${point.y.toFixed(4)} * var(--globe-r) - ${MARKER_SIZE / 2}px), 0)`,\n      opacity: hidden ? 0 : 1,\n      pointerEvents: hidden ? \"none\" : undefined,\n    });\n  }\n  return styles;\n}\n\nfunction warnOnce(run: Runtime, message: string) {\n  if (run.warned || process.env.NODE_ENV === \"production\") return;\n  run.warned = true;\n  console.warn(message);\n}\n\n/** Delay of the next connection: 0, unless others were queued in the same task, then one stagger step more each. */\nfunction volleyDelay(run: Runtime) {\n  const now = performance.now();\n  run.volleyIndex = now - run.volleyTime < 4 ? run.volleyIndex + 1 : 0;\n  run.volleyTime = now;\n  return Math.min(run.volleyIndex * STAGGER, MAX_STAGGER);\n}\n\n/** Remembers a played id; the oldest of the last 2,000 is forgotten. */\nfunction remember(run: Runtime, id: string) {\n  run.played.add(id);\n  run.playedOrder.push(id);\n  if (run.playedOrder.length > PLAYED_LIMIT) {\n    const forgotten = run.playedOrder.splice(0, run.playedOrder.length - PLAYED_LIMIT);\n    for (const old of forgotten) run.played.delete(old);\n  }\n}\n\n/** Adds a connection: an arc while fewer than `maxArcs` are in flight, else straight to the counts. */\nfunction enqueue(\n  run: Runtime,\n  latest: Latest,\n  connection: GlobeConnection,\n  options: { delay?: number; progress?: number; demo?: boolean },\n) {\n  const from = latest.placeById.get(connection.from);\n  const to = latest.placeById.get(connection.to);\n  remember(run, connection.id);\n  if (!from || !to) {\n    warnOnce(run, `GeoGlobe: connection \"${connection.id}\" refers to an unknown location and was skipped.`);\n    return;\n  }\n  const tone = isTone(connection.tone) ? connection.tone : \"accent\";\n  const angle = centralAngle(from, to);\n  if (run.arcs.length >= Math.max(0, latest.maxArcs) || angle < 1e-4) {\n    run.stats.push({ id: from.id, kind: \"out\", tone }, { id: to.id, kind: \"in\", tone });\n    latest.onArrive?.(connection);\n    return;\n  }\n  const count = ARC_SEGMENTS + 1;\n  const duration = 0.7 + (0.9 * angle) / Math.PI;\n  const xs = new Float32Array(count);\n  const ys = new Float32Array(count);\n  const selected = latest.selected;\n  const emphasis = selected === null || connection.from === selected || connection.to === selected ? 1 : 0.15;\n  run.arcs.push({\n    connection,\n    tone,\n    to: { lat: to.lat, lon: to.lon },\n    demo: options.demo ?? false,\n    samples: globeArc(from, to, { segments: ARC_SEGMENTS, lift: arcLift(angle, ARC_LIFT) }),\n    duration,\n    age: options.progress !== undefined ? options.progress * duration : -(options.delay ?? 0),\n    departed: false,\n    // seeded demo arcs already past their landing do not land again\n    arrived: options.progress !== undefined && options.progress >= 1,\n    still: false,\n    emphasis: { position: emphasis, velocity: 0 },\n    xs,\n    ys,\n    zs: new Float32Array(count),\n    visible: new Uint8Array(count),\n    table: buildArcLength(xs, ys, count),\n  });\n}\n\n/** The next demo connection: two different locations, weighted by the traffic of their cities. */\nfunction nextDemoConnection(run: Runtime, places: readonly GlobeLocation[]): GlobeConnection | null {\n  if (places.length < 2) return null;\n  const weight = (place: GlobeLocation) => DEMO_WEIGHTS.get(place.id) ?? 0.5;\n  const from = pickWeighted(run.random, places, weight);\n  let to = pickWeighted(run.random, places, weight);\n  for (let attempt = 0; attempt < 6 && to.id === from.id; attempt++) to = pickWeighted(run.random, places, weight);\n  if (to.id === from.id) return null;\n  return { id: `demo-${run.demoCount++}`, from: from.id, to: to.id };\n}\n\nfunction applyStats(previous: StatsMap, events: readonly StatEvent[]): StatsMap {\n  const next: Record<string, LocationStats> = { ...previous };\n  for (const event of events) {\n    const current = next[event.id] ?? ZERO_STATS;\n    next[event.id] = {\n      incoming: current.incoming + (event.kind === \"in\" ? 1 : 0),\n      outgoing: current.outgoing + (event.kind === \"out\" ? 1 : 0),\n      tone: event.tone,\n    };\n  }\n  return next;\n}\n\nfunction arrivalReport(arrivals: readonly string[], placeById: ReadonlyMap<string, GlobeLocation>) {\n  const tally = new Map<string, number>();\n  let top = arrivals[0];\n  for (const id of arrivals) {\n    const count = (tally.get(id) ?? 0) + 1;\n    tally.set(id, count);\n    if (count > (tally.get(top) ?? 0)) top = id;\n  }\n  const count = arrivals.length;\n  const name = placeById.get(top)?.label ?? top;\n  return `${count} ${count === 1 ? \"connection\" : \"connections\"} in the last 10 seconds, most into ${name}`;\n}\n\n/* Frame steps --------------------------------------------------------------------------------------------- */\n\nfunction byTone<T>(make: (tone: GlobeTone) => T): Record<GlobeTone, T> {\n  return {\n    accent: make(\"accent\"),\n    info: make(\"info\"),\n    success: make(\"success\"),\n    warning: make(\"warning\"),\n    destructive: make(\"destructive\"),\n  };\n}\n\n/** Colours for a theme. The hottest shade is the glint in dark themes and the deep shine in light ones. */\nfunction applyInk(run: Runtime, ink: GeoInk) {\n  run.ink = ink;\n  run.inkStale = false;\n  run.hot = ink.hot;\n  run.discFill = rgba(mixRgb(ink.card, ink.foreground, 0.03));\n  run.limb = rgba(ink.border);\n  run.coast = rgba(ink.coast, 0.16);\n  run.base = createDotBatch(8192, [ink.landStrong], { tones: 1, levels: 24 });\n  run.lit = byTone((tone) => createDotBatch(512, [ink.landStrong, toneColor(ink, tone), run.hot], { tones: 24 }));\n  run.trail = byTone((tone) => createDotBatch(1024, [toneColor(ink, tone), run.hot], { tones: 12 }));\n  run.globeDirty = true;\n}\n\nfunction updateView(run: Runtime, motion: GlobeMotion, width: number, height: number) {\n  const radius = Math.min(width, height) * RADIUS_SHARE * motion.zoom;\n  const view = run.view;\n  if (\n    motion.lon === run.lastLon &&\n    motion.lat === run.lastLat &&\n    radius === view.radius &&\n    width === run.width &&\n    height === run.height\n  )\n    return;\n  rotationFromView(motion.lon, motion.lat, view.rotation);\n  view.cx = width / 2;\n  view.cy = height / 2;\n  view.radius = radius;\n  run.width = width;\n  run.height = height;\n  run.lastLon = motion.lon;\n  run.lastLat = motion.lat;\n  run.globeDirty = true;\n}\n\n/** Lattice spacing for a radius, on an 8 % ladder so zooming back and forth reuses cached lattices. */\nfunction latticeSpacing(radius: number, pitch: number) {\n  const exact = spacingForRadius(radius, pitch);\n  const step = Math.log(1.08);\n  return Math.exp(Math.round(Math.log(exact) / step) * step);\n}\n\n/**\n * The land lattice for the current radius. The first one builds at once; later ones (resize, zoom) build after the\n * radius rests for 160 ms, so a pinch never stalls on a rebuild.\n */\nfunction ensureLattice(run: Runtime, pitch: number, rebuilt: () => void) {\n  if (run.view.radius <= 0) return;\n  const spacing = latticeSpacing(run.view.radius, pitch);\n  if (!run.lattice) {\n    run.lattice = sphereLattice({ spacingDeg: spacing, method: \"rows\", landOnly: true });\n    run.latticeSpacing = spacing;\n    return;\n  }\n  if (spacing === run.latticeSpacing || spacing === run.latticePending) return;\n  run.latticePending = spacing;\n  window.clearTimeout(run.latticeTimer);\n  run.latticeTimer = window.setTimeout(() => {\n    run.lattice = sphereLattice({ spacingDeg: spacing, method: \"rows\", landOnly: true });\n    run.latticeSpacing = spacing;\n    run.latticePending = 0;\n    run.globeDirty = true;\n    rebuilt();\n  }, 160);\n}\n\n/** Ages the arcs, fires departures and arrivals, springs the emphasis. Returns whether an emphasis still moves. */\nfunction advanceArcs(\n  run: Runtime,\n  selected: string | null,\n  delta: number,\n  reduced: boolean,\n  arrive: (arc: Arc) => void,\n  depart: (arc: Arc) => void,\n) {\n  let springing = false;\n  let write = 0;\n  for (const arc of run.arcs) {\n    arc.age += delta;\n    if (!arc.departed && arc.age >= 0) {\n      arc.departed = true;\n      arc.still = reduced;\n      depart(arc);\n    }\n    if (arc.departed && !arc.arrived && (arc.still || arc.age >= arc.duration)) {\n      arc.arrived = true;\n      arrive(arc);\n    }\n    const { connection, emphasis } = arc;\n    const target = selected === null || connection.from === selected || connection.to === selected ? 1 : 0.15;\n    if (reduced) {\n      emphasis.position = target;\n      emphasis.velocity = 0;\n    } else if (Math.abs(emphasis.position - target) > 0.001 || Math.abs(emphasis.velocity) > 0.001) {\n      springStep(emphasis, target, delta, 260, 0.8);\n      springing = true;\n    }\n    const end = arc.still ? STILL_SECONDS : arc.duration * 2 + ARC_HOLD;\n    if (arc.age < end) run.arcs[write++] = arc;\n  }\n  run.arcs.length = write;\n\n  let glowWrite = 0;\n  for (const glow of run.glows) {\n    glow.age += delta;\n    if (glow.age < GLOW_SECONDS) run.glows[glowWrite++] = glow;\n  }\n  run.glows.length = glowWrite;\n  return springing;\n}\n\nfunction advanceRipples(run: Runtime, delta: number) {\n  let write = 0;\n  for (const ripple of run.ripples) {\n    ripple.age += delta;\n    if (ripple.age >= RIPPLE_SECONDS) continue;\n    const t = ripple.age / RIPPLE_SECONDS;\n    ripple.radius = RIPPLE_REACH * easeOutCubic(t);\n    ripple.fade = 1 - t;\n    run.ripples[write++] = ripple;\n  }\n  if (write !== run.ripples.length) run.globeDirty = true;\n  run.ripples.length = write;\n}\n\n/* Drawing ------------------------------------------------------------------------------------------------- */\n\n/** The globe: atmosphere, disc, land dots (lit around arrivals), coastline and limb. */\nfunction drawGlobe(surface: CanvasSurface, run: Runtime, ink: GeoInk, coastline: boolean) {\n  const { context, width, height } = surface;\n  const { view, lattice, base, lit } = run;\n  const { cx, cy, radius } = view;\n  context.clearRect(0, 0, width, height);\n  if (radius <= 0) return;\n\n  const atmosphere = context.createRadialGradient(cx, cy, radius * 0.98, cx, cy, radius * 1.1);\n  atmosphere.addColorStop(0, rgba(ink.accent, ink.dark ? 0.16 : 0.1));\n  atmosphere.addColorStop(1, rgba(ink.accent, 0));\n  context.fillStyle = atmosphere;\n  context.beginPath();\n  context.arc(cx, cy, radius * 1.1, 0, TAU);\n  context.fill();\n\n  context.fillStyle = run.discFill;\n  context.beginPath();\n  context.arc(cx, cy, radius, 0, TAU);\n  context.fill();\n\n  if (lattice && base && lit) {\n    const m = view.rotation;\n    const { xyz, jitter } = lattice;\n    const ripples = run.ripples;\n    const rippleCount = ripples.length;\n    for (let i = 0; i < lattice.count; i++) {\n      const x = xyz[i * 3];\n      const y = xyz[i * 3 + 1];\n      const z = xyz[i * 3 + 2];\n      const vz = m[6] * x + m[7] * y + m[8] * z;\n      if (vz < LIMB_CUTOFF) continue;\n      const sx = cx + (m[0] * x + m[1] * y + m[2] * z) * radius;\n      const sy = cy - (m[3] * x + m[4] * y + m[5] * z) * radius;\n      const alpha = 0.22 + 0.78 * Math.pow(vz, 0.6);\n      let glow = 0;\n      let glowTone: GlobeTone = \"accent\";\n      for (let r = 0; r < rippleCount; r++) {\n        const ripple = ripples[r];\n        const v = ripple.vector;\n        const cos = x * v[0] + y * v[1] + z * v[2];\n        if (cos < RIPPLE_COS) continue;\n        const distance = Math.acos(Math.min(1, cos)) * radius;\n        const b = ringFront(distance, ripple.radius, RIPPLE_WIDTH, jitter[i], 5) * ripple.fade;\n        if (b > glow) {\n          glow = b;\n          glowTone = ripple.tone;\n        }\n      }\n      if (glow > 0.03) {\n        lit[glowTone].add(sx, sy, LAND_DOT + glow * 0.5, Math.min(1, glow * 1.15), Math.min(1, alpha + 0.8 * glow));\n      } else {\n        base.add(sx, sy, LAND_DOT, 0, alpha);\n      }\n    }\n    base.flush(context);\n    for (const tone of TONES) lit[tone].flush(context);\n  }\n\n  if (coastline) {\n    context.beginPath();\n    traceGlobeCoastlines(context, view);\n    context.strokeStyle = run.coast;\n    context.lineWidth = 0.75;\n    context.stroke();\n  }\n\n  context.beginPath();\n  context.arc(cx, cy, Math.max(0, radius - 0.5), 0, TAU);\n  context.strokeStyle = run.limb;\n  context.lineWidth = 1;\n  context.stroke();\n}\n\n/** Arcs, packets, arrival glows and sparks, on the canvas that reaches past the stage. */\nfunction drawEffects(surface: CanvasSurface, run: Runtime, delta: number) {\n  const { context, width, height } = surface;\n  const { trail, ink } = run;\n  const drawing = run.arcs.some((arc) => arc.departed) || run.glows.length > 0 || run.sparks.active;\n  if (!drawing || !trail || !ink) {\n    if (run.fxDirty) {\n      context.clearRect(0, 0, width, height);\n      run.fxDirty = false;\n    }\n    return;\n  }\n  run.fxDirty = true;\n  context.clearRect(0, 0, width, height);\n  const { view, point } = run;\n\n  for (const glow of run.glows) {\n    if (!projectGlobeVector(view, glow.vector, point) || point.z < MARKER_HIDE_Z) continue;\n    const fade = 1 - glow.age / GLOW_SECONDS;\n    const color = toneColor(ink, glow.tone);\n    const y = point.y + FX_Y;\n    const halo = context.createRadialGradient(point.x, y, 0, point.x, y, 13);\n    halo.addColorStop(0, rgba(color, 0.42 * fade * fade));\n    halo.addColorStop(1, rgba(color, 0));\n    context.fillStyle = halo;\n    context.fillRect(point.x - 13, y - 13, 26, 26);\n  }\n\n  for (const arc of run.arcs) {\n    if (arc.departed) drawArc(run, arc);\n  }\n  for (const tone of TONES) trail[tone].flush(context);\n\n  run.sparks.step(context, delta);\n}\n\nfunction projectGlobeVector(view: GlobeView, v: Vec3, out: ScreenPoint) {\n  const m = view.rotation;\n  const x = m[0] * v[0] + m[1] * v[1] + m[2] * v[2];\n  const y = m[3] * v[0] + m[4] * v[1] + m[5] * v[2];\n  const z = m[6] * v[0] + m[7] * v[1] + m[8] * v[2];\n  out.x = view.cx + x * view.radius;\n  out.y = view.cy - y * view.radius;\n  out.z = z;\n  return z > 0;\n}\n\n/**\n * One arc: the samples are projected, the hidden ones (behind the globe's disc) break the stroke, and dots sit every\n * 3.5 px of screen length between the erasing tail and the drawing head. The packet rides the head.\n */\nfunction drawArc(run: Runtime, arc: Arc) {\n  const { view, cursor, trail } = run;\n  if (!trail) return;\n  const m = view.rotation;\n  const { cx, cy, radius } = view;\n  const { samples, xs, ys, zs, visible } = arc;\n  const count = xs.length;\n  for (let i = 0; i < count; i++) {\n    const x = samples[i * 3];\n    const y = samples[i * 3 + 1];\n    const z = samples[i * 3 + 2];\n    const vx = m[0] * x + m[1] * y + m[2] * z;\n    const vy = m[3] * x + m[4] * y + m[5] * z;\n    const vz = m[6] * x + m[7] * y + m[8] * z;\n    xs[i] = cx + vx * radius;\n    ys[i] = cy - vy * radius + FX_Y;\n    zs[i] = vz;\n    visible[i] = isOccluded(vx, vy, vz) ? 0 : 1;\n  }\n  const table = buildArcLength(xs, ys, count, arc.table);\n  const length = table.length;\n\n  let head = 1;\n  let tail = 0;\n  if (!arc.still) {\n    head = ARC_EASE(clamp(arc.age / arc.duration, 0, 1));\n    tail = ARC_EASE(clamp((arc.age - arc.duration - ARC_HOLD) / arc.duration, 0, 1));\n  }\n  if (tail >= 1) return;\n\n  cursor.arc = arc;\n  cursor.batch = trail[arc.tone];\n  cursor.segment = 0;\n  cursor.head = head * length;\n  cursor.tail = tail * length;\n  cursor.flying = !arc.still && head < 1;\n  cursor.emphasis = arc.emphasis.position;\n  forEachDot(table, ARC_DOT_SPACING, cursor.tail, cursor.head, run.visitArcDot);\n\n  // the packet: a hot head and eight squares of tail, hidden when another location is selected\n  const packet = clamp((arc.emphasis.position - 0.15) / 0.85, 0, 1);\n  if (!cursor.flying || packet <= 0.02) return;\n  const batch = trail[arc.tone];\n  for (let k = 8; k >= 0; k--) {\n    const s = cursor.head - k * 3;\n    if (s < 0) continue;\n    const segment = segmentAt(table, s);\n    if (!visible[segment] || !visible[Math.min(count - 1, segment + 1)]) continue;\n    pointAtDistance(table, s, run.packet);\n    const depth = zs[segment] < 0 ? 0.55 : 1;\n    if (k === 0) batch.add(run.packet.x, run.packet.y, 2.5, 1, packet * depth);\n    else\n      batch.add(run.packet.x, run.packet.y, k < 3 ? 2 : 1.5, 0.85 - k * 0.08, (0.9 - (k - 1) * 0.1) * packet * depth);\n  }\n}\n\n/** forEachDot visitor for the arc in `cursor`: skips hidden stretches, brightens toward the head. */\nfunction visitArcDot(cursor: DotCursor, x: number, y: number, s: number) {\n  const arc = cursor.arc;\n  const batch = cursor.batch;\n  if (!arc || !batch) return;\n  const { table, visible, zs } = arc;\n  const last = table.count - 1;\n  while (cursor.segment < last - 1 && table.distances[cursor.segment + 1] < s) cursor.segment++;\n  const j = cursor.segment;\n  if (!visible[j] || !visible[Math.min(last, j + 1)]) return;\n  const depth = zs[j] < 0 ? 0.45 : 1;\n  const nearHead = cursor.flying ? smoothstep(cursor.head - 30, cursor.head, s) : 0;\n  const tailFade = cursor.tail > 0 ? smoothstep(cursor.tail, cursor.tail + 14, s) : 1;\n  const alpha = (ARC_ALPHA + 0.4 * nearHead) * cursor.emphasis * depth * tailFade;\n  batch.add(x, y, LAND_DOT, nearHead * 0.55, alpha);\n}\n\n/** Index of the table segment that holds distance `s` (binary search). */\nfunction segmentAt(table: ArcLengthTable, s: number) {\n  let low = 0;\n  let high = Math.max(0, table.count - 2);\n  while (low < high) {\n    const middle = (low + high + 1) >> 1;\n    if (table.distances[middle] <= s) low = middle;\n    else high = middle - 1;\n  }\n  return low;\n}\n\n/** Top-left of the chip: it keeps its side while that side fits, else placeLabels picks a new one. */\nfunction chipBox(run: Runtime, anchor: { x: number; y: number }, others: readonly { x: number; y: number }[]) {\n  const width = run.chipWidth;\n  const height = run.chipHeight;\n  const gap = 12;\n  const boxFor = (side: LabelPlacement[\"side\"]) => ({\n    x: side === \"right\" ? anchor.x + gap : side === \"left\" ? anchor.x - gap - width : anchor.x - width / 2,\n    y: side === \"top\" ? anchor.y - gap - height : side === \"bottom\" ? anchor.y + gap : anchor.y - height / 2,\n  });\n  const fits = (box: { x: number; y: number }) =>\n    box.x >= 0 &&\n    box.y >= 0 &&\n    box.x + width <= run.width &&\n    box.y + height <= run.height &&\n    others.every((p) => p.x <= box.x - 4 || p.x >= box.x + width + 4 || p.y <= box.y - 4 || p.y >= box.y + height + 4);\n  if (run.chipSide) {\n    const box = boxFor(run.chipSide);\n    if (fits(box)) return box;\n  }\n  const anchors: LabelAnchor[] = [\n    { x: anchor.x, y: anchor.y, width, height, priority: 1, gap },\n    ...others.map((p) => ({ x: p.x, y: p.y, width: 0, height: 0, priority: 0 })),\n  ];\n  const [placement] = placeLabels(anchors, run.width, run.height);\n  run.chipSide = placement.visible ? placement.side : \"right\";\n  const box = boxFor(run.chipSide);\n  return {\n    x: clamp(box.x, 0, Math.max(0, run.width - width)),\n    y: clamp(box.y, 0, Math.max(0, run.height - height)),\n  };\n}\n",
      "type": "registry:component",
      "target": "@components/lumesec/geo-globe.tsx"
    }
  ],
  "meta": {
    "tag": "geo-globe",
    "collection": "location",
    "react": "GeoGlobe",
    "kind": "react",
    "data": "input"
  },
  "docs": "Connection globe docs: https://elements.lumesec.ai/components/location/globe",
  "categories": [
    "location",
    "globes"
  ],
  "type": "registry:component"
}