{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"people-globe","type":"registry:component","title":"People Globe","description":"A dotted globe where people pin themselves, like a friend map: search a city, add a name and photo, and their avatar appears. People in the same city share one pin. Drag to spin, tap a pin to fly to it.","dependencies":["d3-geo","topojson-client","world-atlas"],"devDependencies":["@types/d3-geo","@types/topojson-client"],"files":[{"path":"registry/dot/people-globe.tsx","type":"registry:component","target":"components/dot/people-globe.tsx","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from \"react\";\nimport { geoDistance, geoEquirectangular, geoOrthographic, geoPath } from \"d3-geo\";\nimport { feature } from \"topojson-client\";\nimport land110 from \"world-atlas/land-110m.json\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface GlobePlace {\n  city: string;\n  state?: string;\n  country: string;\n  /** ISO 3166-1 alpha-2, e.g. \"IN\"; used for the flag */\n  countryCode?: string;\n  lat: number;\n  lng: number;\n}\n\nexport interface GlobePerson extends GlobePlace {\n  id?: string;\n  name: string;\n  /** Image URL (or data URL); omitted shows their initials */\n  avatar?: string;\n}\n\nexport interface PeopleGlobeProps {\n  /** People already on the globe */\n  people?: GlobePerson[];\n  /** Called when someone adds themselves; save it to your backend here. Rejecting shows an error. */\n  onAdd?: (person: GlobePerson) => void | Promise<void>;\n  /** Show the \"Add your place\" button */\n  allowAdd?: boolean;\n  /** Keep people added in this browser (localStorage) under this key, e.g. for demos */\n  storageKey?: string;\n  /** Place search for the add form; defaults to the free Open-Meteo geocoder */\n  searchPlaces?: (query: string, signal: AbortSignal) => Promise<GlobePlace[]>;\n  /** Spin slowly when nobody is dragging */\n  autoRotate?: boolean;\n  /** Degrees per second while spinning */\n  rotationSpeed?: number;\n  background?: string;\n  /** Land dots */\n  dotColor?: string;\n  /** Pins, highlights and the add button */\n  accentColor?: string;\n  textColor?: string;\n  /** Text above the people count */\n  title?: string;\n  /** Show the title and people count in the corner */\n  showCount?: boolean;\n  /** Fly to this place, and open this person's card when `id` matches; change it to move again */\n  focus?: { lat: number; lng: number; id?: string } | null;\n  className?: string;\n  style?: CSSProperties;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n// Inter: the site's next/font Inter when it has one (--font-inter), else Inter from Google Fonts\nconst FONT = 'var(--font-inter, \"Inter\"), system-ui, sans-serif';\nconst DOTS = 14000; // points spread evenly over the sphere; the ones on land are drawn\nconst AVATAR_PX = 160; // uploaded photos are cropped and shrunk to this, so they stay small\n\n/** True when the site already ships Inter through next/font, so there's nothing to download */\nconst siteHasInter = () =>\n  [document.documentElement, document.body].some((el) => getComputedStyle(el).getPropertyValue(\"--font-inter\").trim() !== \"\");\n\nfunction loadInter() {\n  const id = \"dot-google-font-inter\";\n  if (document.getElementById(id) || siteHasInter()) return;\n  const link = document.createElement(\"link\");\n  link.id = id;\n  link.rel = \"stylesheet\";\n  link.href = \"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap\";\n  document.head.appendChild(link);\n}\n\nlet landDots: [number, number][] | null = null;\n\n/** Evenly spaced points (a Fibonacci sphere), keeping the ones that fall on land. Land is found by\n * painting the world once onto a small map and reading its pixels, which is much faster than a\n * point-in-polygon test per dot. Computed once per page. */\nfunction getLandDots() {\n  if (landDots) return landDots;\n  const W = 1024;\n  const H = 512;\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = W;\n  canvas.height = H;\n  const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n  if (!ctx) return (landDots = []);\n  // The shapes of every landmass, as TopoJSON (typed loosely so no extra types package is needed)\n  const topo = land110 as unknown as Parameters<typeof feature>[0] & { objects: { land: Parameters<typeof feature>[1] } };\n  const land = feature(topo, topo.objects.land);\n  const projection = geoEquirectangular().scale(W / (2 * Math.PI)).translate([W / 2, H / 2]);\n  ctx.fillStyle = \"#000\";\n  ctx.beginPath();\n  geoPath(projection, ctx)(land);\n  ctx.fill();\n  const pixels = ctx.getImageData(0, 0, W, H).data;\n  const golden = Math.PI * (3 - Math.sqrt(5));\n  const dots: [number, number][] = [];\n  for (let i = 0; i < DOTS; i++) {\n    const y = 1 - (i / (DOTS - 1)) * 2;\n    const lat = (Math.asin(y) * 180) / Math.PI;\n    const lng = ((((i * golden * 180) / Math.PI) % 360) + 360) % 360 - 180;\n    const px = Math.min(W - 1, Math.floor(((lng + 180) / 360) * W));\n    const py = Math.min(H - 1, Math.floor(((90 - lat) / 180) * H));\n    if (pixels[(py * W + px) * 4 + 3] > 128) dots.push([lng, lat]);\n  }\n  return (landDots = dots);\n}\n\nconst flag = (code?: string) =>\n  code && /^[A-Za-z]{2}$/.test(code) ? String.fromCodePoint(...[...code.toUpperCase()].map((c) => 0x1f1a5 + c.charCodeAt(0))) : \"\";\n\nconst initials = (name: string) =>\n  name\n    .trim()\n    .split(/\\s+/)\n    .slice(0, 2)\n    .map((w) => w[0]?.toUpperCase() ?? \"\")\n    .join(\"\") || \"?\";\n\n/** A stable colour per name for initials avatars */\nconst hue = (name: string) => [...name].reduce((h, c) => (h * 31 + c.charCodeAt(0)) % 360, 7);\n\nconst placeLine = (p: GlobePlace) => [p.city, p.state, p.country].filter((part, i, all) => part && all.indexOf(part) === i).join(\", \");\n\nconst personId = (p: GlobePerson) => p.id ?? `${p.name}|${p.lat.toFixed(3)}|${p.lng.toFixed(3)}`;\n\n/** People this close together (about 20 km, i.e. the same city) share one pin; radians on the globe */\nconst SAME_PLACE = 20 / 6371;\n\ninterface PinGroup {\n  key: string;\n  lat: number;\n  lng: number;\n  /** Newest first, so the latest arrival is on top of the stack */\n  people: GlobePerson[];\n}\n\n/** Free, keyless place search (Open-Meteo, built on GeoNames). Its free tier is for\n * non-commercial use; pass your own `searchPlaces` for production. */\nasync function openMeteoSearch(query: string, signal: AbortSignal): Promise<GlobePlace[]> {\n  const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=8&language=en&format=json`;\n  const response = await fetch(url, { signal });\n  if (!response.ok) throw new Error(\"Search failed\");\n  const data = (await response.json()) as {\n    results?: { name: string; admin1?: string; country?: string; country_code?: string; latitude: number; longitude: number }[];\n  };\n  return (data.results ?? []).map((r) => ({\n    city: r.name,\n    state: r.admin1,\n    country: r.country ?? \"\",\n    countryCode: r.country_code,\n    lat: r.latitude,\n    lng: r.longitude,\n  }));\n}\n\n/** Crop to a square and shrink, so the photo is a few KB and safe to store */\nfunction shrinkImage(file: File): Promise<string> {\n  return new Promise((resolve, reject) => {\n    const url = URL.createObjectURL(file);\n    const img = new Image();\n    img.onload = () => {\n      const side = Math.min(img.width, img.height);\n      const canvas = document.createElement(\"canvas\");\n      canvas.width = canvas.height = AVATAR_PX;\n      const ctx = canvas.getContext(\"2d\");\n      if (!ctx) return reject(new Error(\"No canvas\"));\n      ctx.drawImage(img, (img.width - side) / 2, (img.height - side) / 2, side, side, 0, 0, AVATAR_PX, AVATAR_PX);\n      URL.revokeObjectURL(url);\n      resolve(canvas.toDataURL(\"image/jpeg\", 0.85));\n    };\n    img.onerror = () => {\n      URL.revokeObjectURL(url);\n      reject(new Error(\"That file couldn't be read as an image\"));\n    };\n    img.src = url;\n  });\n}\n\nfunction readStored(key?: string): GlobePerson[] {\n  if (!key) return [];\n  try {\n    const parsed = JSON.parse(localStorage.getItem(key) ?? \"[]\");\n    return Array.isArray(parsed) ? parsed.filter((p) => p && typeof p.name === \"string\" && Number.isFinite(p.lat) && Number.isFinite(p.lng)) : [];\n  } catch {\n    return [];\n  }\n}\n\nconst ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);\n\n// ─── Avatar ──────────────────────────────────────────────────────────────────\n\nfunction Avatar({ person, size, ring }: { person: { name: string; avatar?: string }; size: number; ring?: string }) {\n  const h = hue(person.name);\n  return (\n    <span\n      style={{\n        display: \"grid\",\n        placeItems: \"center\",\n        width: size,\n        height: size,\n        borderRadius: \"50%\",\n        overflow: \"hidden\",\n        flexShrink: 0,\n        background: person.avatar ? \"#222\" : `hsl(${h} 45% 42%)`,\n        boxShadow: ring ? `0 0 0 2px ${ring}` : undefined,\n        color: \"#fff\",\n        fontSize: size * 0.38,\n        fontWeight: 600,\n        letterSpacing: \"-0.02em\",\n      }}\n    >\n      {person.avatar ? (\n        // eslint-disable-next-line @next/next/no-img-element -- any image or data URL\n        <img src={person.avatar} alt=\"\" draggable={false} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n      ) : (\n        initials(person.name)\n      )}\n    </span>\n  );\n}\n\n// ─── Component ───────────────────────────────────────────────────────────────\n\n/**\n * An interactive dotted globe where people pin themselves: drag or flick to spin, click an avatar to\n * fly to it, and \"Add your place\" to search a city and add a name and photo. Works with your own\n * data (`people`, `onAdd`) or on its own in the browser (`storageKey`).\n */\nexport function PeopleGlobe({\n  people = [],\n  onAdd,\n  allowAdd = true,\n  storageKey,\n  searchPlaces = openMeteoSearch,\n  autoRotate = true,\n  rotationSpeed = 6,\n  background = \"#000000\",\n  dotColor = \"#FFFFFF\",\n  accentColor = \"#FFFFFF\",\n  textColor = \"#FFFFFF\",\n  title = \"People around the world\",\n  showCount = true,\n  focus = null,\n  className,\n  style,\n}: PeopleGlobeProps) {\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const canvasRef = useRef<HTMLCanvasElement | null>(null);\n  const pinRefs = useRef(new Map<string, HTMLButtonElement>());\n  const [added, setAdded] = useState<GlobePerson[]>([]);\n  const [selected, setSelected] = useState<string | null>(null);\n  const [panel, setPanel] = useState<\"closed\" | \"place\" | \"avatar\">(\"closed\");\n\n  // People added in this browser come back after a reload\n  useEffect(() => {\n    if (!storageKey) return;\n    let cancelled = false;\n    Promise.resolve().then(() => !cancelled && setAdded(readStored(storageKey)));\n    return () => {\n      cancelled = true;\n    };\n  }, [storageKey]);\n\n  const everyone = useMemo(() => {\n    const seen = new Set<string>();\n    return [...people, ...added].filter((p) => {\n      const id = personId(p);\n      if (seen.has(id)) return false;\n      seen.add(id);\n      return true;\n    });\n  }, [people, added]);\n  const countries = new Set(everyone.map((p) => p.countryCode || p.country)).size;\n  // One pin per place: each person joins the first pin within SAME_PLACE of them\n  const groups = useMemo(() => {\n    const list: PinGroup[] = [];\n    for (const person of everyone) {\n      const group = list.find((g) => geoDistance([g.lng, g.lat], [person.lng, person.lat]) < SAME_PLACE);\n      if (group) group.people.unshift(person);\n      else list.push({ key: personId(person), lat: person.lat, lng: person.lng, people: [person] });\n    }\n    return list;\n  }, [everyone]);\n  const chosen = everyone.find((p) => personId(p) === selected) ?? null;\n  const chosenGroup = chosen ? (groups.find((g) => g.people.includes(chosen)) ?? null) : null;\n  const selectedKey = chosenGroup?.key ?? null;\n\n  // Globe state that the animation loop reads and writes, outside React renders\n  const view = useRef({ lambda: -20, phi: -15, vl: 0, vp: 0, dragging: false, lastInteract: 0, touched: false, fly: null as null | { from: [number, number]; to: [number, number]; start: number; ms: number } });\n  const live = useRef({ autoRotate, rotationSpeed, dotColor, groups, selectedKey });\n  useEffect(() => {\n    live.current = { autoRotate, rotationSpeed, dotColor, groups, selectedKey };\n  });\n\n  const flyTo = (lng: number, lat: number) => {\n    const v = view.current;\n    // Take the short way round\n    let target = -lng;\n    while (target - v.lambda > 180) target -= 360;\n    while (target - v.lambda < -180) target += 360;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const to: [number, number] = [target, Math.max(-60, Math.min(60, -lat))];\n    v.vl = v.vp = 0;\n    if (reduce) {\n      v.lambda = to[0];\n      v.phi = to[1];\n      v.fly = null;\n    } else v.fly = { from: [v.lambda, v.phi], to, start: 0, ms: 1100 }; // the loop stamps the start time\n    v.touched = true;\n  };\n\n  useEffect(loadInter, []);\n\n  // Outside focus: open that person's card now, fly there from an effect\n  const focusKey = focus ? `${focus.lat},${focus.lng},${focus.id ?? \"\"}` : \"\";\n  const [lastFocus, setLastFocus] = useState(focusKey);\n  if (focusKey !== lastFocus) {\n    setLastFocus(focusKey);\n    if (focus?.id) setSelected(focus.id);\n  }\n  useEffect(() => {\n    if (focus) flyTo(focus.lng, focus.lat);\n    // eslint-disable-next-line react-hooks/exhaustive-deps -- re-run only when the focus itself changes\n  }, [focusKey]);\n\n  // ─── Drawing loop ──────────────────────────────────────────────────────────\n  useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!root || !canvas || !ctx) return;\n    const dots = getLandDots();\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const v = view.current;\n    let width = 0;\n    let height = 0;\n    let radius = 0;\n    let frame = 0;\n    let last = performance.now();\n    let visible = true;\n\n    const resize = () => {\n      const rect = root.getBoundingClientRect();\n      width = rect.width;\n      height = rect.height;\n      radius = Math.min(width, height) * 0.4;\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      canvas.width = Math.round(width * dpr);\n      canvas.height = Math.round(height * dpr);\n      canvas.style.width = `${width}px`;\n      canvas.style.height = `${height}px`;\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    };\n\n    const tick = (now: number) => {\n      const dt = Math.min(0.05, (now - last) / 1000);\n      last = now;\n      const s = live.current;\n      if (v.touched) {\n        v.touched = false;\n        v.lastInteract = now;\n      }\n\n      if (v.fly) {\n        if (!v.fly.start) v.fly.start = now;\n        const t = Math.min(1, (now - v.fly.start) / v.fly.ms);\n        const k = ease(t);\n        v.lambda = v.fly.from[0] + (v.fly.to[0] - v.fly.from[0]) * k;\n        v.phi = v.fly.from[1] + (v.fly.to[1] - v.fly.from[1]) * k;\n        if (t >= 1) v.fly = null;\n      } else if (!v.dragging) {\n        // Momentum from a flick, then the slow spin resumes after a moment\n        v.lambda += v.vl * dt;\n        v.phi = Math.max(-60, Math.min(60, v.phi + v.vp * dt));\n        const decay = Math.exp(-dt * 3);\n        v.vl *= decay;\n        v.vp *= decay;\n        if (s.autoRotate && !reduce.matches && !s.selectedKey && now - v.lastInteract > 2500) v.lambda += s.rotationSpeed * dt;\n      }\n\n      const cx = width / 2;\n      const cy = height / 2;\n      const projection = geoOrthographic().scale(radius).translate([cx, cy]).rotate([v.lambda, v.phi]).clipAngle(90);\n      const center: [number, number] = [-v.lambda, -v.phi];\n\n      ctx.clearRect(0, 0, width, height);\n      // Sphere: a faint body and rim so the globe reads as round\n      const body = ctx.createRadialGradient(cx - radius * 0.35, cy - radius * 0.4, radius * 0.1, cx, cy, radius);\n      body.addColorStop(0, \"rgba(255,255,255,0.06)\");\n      body.addColorStop(1, \"rgba(255,255,255,0.015)\");\n      ctx.beginPath();\n      ctx.arc(cx, cy, radius, 0, Math.PI * 2);\n      ctx.fillStyle = body;\n      ctx.fill();\n      ctx.strokeStyle = \"rgba(255,255,255,0.08)\";\n      ctx.lineWidth = 1;\n      ctx.stroke();\n\n      // Land dots, fading towards the edge\n      ctx.fillStyle = s.dotColor;\n      const size = Math.max(1, radius / 230);\n      for (const dot of dots) {\n        const d = geoDistance(dot, center);\n        if (d > 1.55) continue;\n        const p = projection(dot);\n        if (!p) continue;\n        ctx.globalAlpha = 0.18 + 0.62 * Math.cos(d);\n        ctx.fillRect(p[0] - size / 2, p[1] - size / 2, size, size);\n      }\n      ctx.globalAlpha = 1;\n\n      // Pins follow the globe; hidden on the far side\n      for (const group of s.groups) {\n        const el = pinRefs.current.get(group.key);\n        if (!el) continue;\n        const point: [number, number] = [group.lng, group.lat];\n        const d = geoDistance(point, center);\n        const p = d < Math.PI / 2 - 0.08 ? projection(point) : null;\n        if (!p) {\n          el.style.visibility = \"hidden\";\n          continue;\n        }\n        const facing = Math.cos(d);\n        const isSelected = group.key === s.selectedKey;\n        el.style.visibility = \"visible\";\n        el.style.opacity = String(Math.min(1, facing * 2.2));\n        el.style.zIndex = String(isSelected ? 2000 : Math.round(facing * 1000));\n        el.style.transform = `translate(${p[0]}px, ${p[1]}px) translate(-50%, -100%) scale(${(0.7 + 0.3 * facing) * (isSelected ? 1.15 : 1)})`;\n      }\n\n      frame = visible ? requestAnimationFrame(tick) : 0;\n    };\n\n    // Drag to spin, with momentum on release\n    let lastX = 0;\n    let lastY = 0;\n    let lastT = 0;\n    const onDown = (e: PointerEvent) => {\n      if ((e.target as HTMLElement).closest(\"button, input, [data-globe-ui]\")) return;\n      v.dragging = true;\n      v.fly = null;\n      v.vl = v.vp = 0;\n      lastX = e.clientX;\n      lastY = e.clientY;\n      lastT = performance.now();\n      root.setPointerCapture(e.pointerId);\n    };\n    const onMove = (e: PointerEvent) => {\n      if (!v.dragging) return;\n      const now = performance.now();\n      const k = 180 / (Math.PI * Math.max(1, radius));\n      const dl = (e.clientX - lastX) * k;\n      const dp = (e.clientY - lastY) * k;\n      v.lambda += dl;\n      v.phi = Math.max(-60, Math.min(60, v.phi - dp));\n      const dt = Math.max(1, now - lastT) / 1000;\n      v.vl = v.vl * 0.6 + (dl / dt) * 0.4;\n      v.vp = v.vp * 0.6 + (-dp / dt) * 0.4;\n      lastX = e.clientX;\n      lastY = e.clientY;\n      lastT = now;\n      v.lastInteract = now;\n    };\n    const onUp = () => {\n      if (!v.dragging) return;\n      v.dragging = false;\n      if (performance.now() - lastT > 80) v.vl = v.vp = 0;\n      v.lastInteract = performance.now();\n    };\n\n    const observer = new ResizeObserver(resize);\n    observer.observe(root);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible && !frame) {\n        last = performance.now();\n        frame = requestAnimationFrame(tick);\n      }\n    });\n    io.observe(root);\n    root.addEventListener(\"pointerdown\", onDown);\n    root.addEventListener(\"pointermove\", onMove);\n    root.addEventListener(\"pointerup\", onUp);\n    root.addEventListener(\"pointercancel\", onUp);\n    resize();\n    frame = requestAnimationFrame(tick);\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n      io.disconnect();\n      root.removeEventListener(\"pointerdown\", onDown);\n      root.removeEventListener(\"pointermove\", onMove);\n      root.removeEventListener(\"pointerup\", onUp);\n      root.removeEventListener(\"pointercancel\", onUp);\n    };\n  }, []);\n\n  const select = (person: GlobePerson) => {\n    setSelected(personId(person));\n    flyTo(person.lng, person.lat);\n  };\n\n  const addPerson = async (person: GlobePerson) => {\n    await onAdd?.(person);\n    setAdded((current) => {\n      const next = [...current.filter((p) => personId(p) !== personId(person)), person];\n      if (storageKey) {\n        try {\n          localStorage.setItem(storageKey, JSON.stringify(next));\n        } catch {\n          // storage full or blocked: it still shows until the page reloads\n        }\n      }\n      return next;\n    });\n    setPanel(\"closed\");\n    setSelected(personId(person));\n    flyTo(person.lng, person.lat);\n  };\n\n  const muted = `color-mix(in srgb, ${textColor} 55%, transparent)`;\n\n  return (\n    <div\n      ref={rootRef}\n      className={className}\n      style={{\n        position: \"relative\",\n        width: \"100%\",\n        height: \"100%\",\n        minHeight: 420,\n        overflow: \"hidden\",\n        background,\n        color: textColor,\n        fontFamily: FONT,\n        touchAction: \"none\",\n        userSelect: \"none\",\n        cursor: \"grab\",\n        ...style,\n      }}\n    >\n      <canvas ref={canvasRef} aria-hidden style={{ position: \"absolute\", inset: 0, display: \"block\" }} />\n\n      {/* Pins */}\n      {/* Own layer (z-index 0), so pins never draw over the cards and forms that follow */}\n      <div role=\"list\" aria-label={`${everyone.length} people on the globe`} style={{ position: \"absolute\", inset: 0, zIndex: 0, pointerEvents: \"none\" }}>\n        {groups.map((group) => {\n          const isSelected = group.key === selectedKey;\n          const lead = group.people[0];\n          const many = group.people.length > 1;\n          return (\n            <button\n              key={group.key}\n              role=\"listitem\"\n              type=\"button\"\n              aria-label={many ? `${group.people.length} people in ${placeLine(lead)}` : `${lead.name}, ${placeLine(lead)}`}\n              ref={(el) => {\n                if (el) pinRefs.current.set(group.key, el);\n                else pinRefs.current.delete(group.key);\n              }}\n              onClick={() => select(isSelected && chosen ? chosen : lead)}\n              className=\"dot-globe-pin\"\n              style={{\n                position: \"absolute\",\n                left: 0,\n                top: 0,\n                visibility: \"hidden\",\n                display: \"flex\",\n                flexDirection: \"column\",\n                alignItems: \"center\",\n                gap: 4,\n                padding: 0,\n                border: 0,\n                background: \"transparent\",\n                color: textColor,\n                font: `500 11px ${FONT}`,\n                cursor: \"pointer\",\n                pointerEvents: \"auto\",\n                transformOrigin: \"50% 100%\",\n                willChange: \"transform, opacity\",\n              }}\n            >\n              <span style={{ position: \"relative\", display: \"flex\" }}>\n                {group.people.slice(0, 3).map((person, i) => (\n                  <span\n                    key={personId(person)}\n                    style={{\n                      marginLeft: i ? -14 : 0,\n                      zIndex: 3 - i,\n                      padding: 2,\n                      borderRadius: \"50%\",\n                      background: isSelected ? accentColor : \"rgba(255,255,255,0.9)\",\n                      boxShadow: \"0 6px 18px rgba(0,0,0,0.45)\",\n                    }}\n                  >\n                    <Avatar person={person} size={30} />\n                  </span>\n                ))}\n                {many && (\n                  <span\n                    style={{\n                      position: \"absolute\",\n                      top: -6,\n                      right: -8,\n                      zIndex: 4,\n                      minWidth: 18,\n                      height: 18,\n                      padding: \"0 5px\",\n                      boxSizing: \"border-box\",\n                      borderRadius: 999,\n                      background: accentColor,\n                      color: \"#000\",\n                      font: `600 10px/18px ${FONT}`,\n                      textAlign: \"center\",\n                    }}\n                  >\n                    {group.people.length}\n                  </span>\n                )}\n              </span>\n              <span\n                className=\"dot-globe-name\"\n                style={{\n                  padding: \"2px 7px\",\n                  borderRadius: 999,\n                  background: \"rgba(0,0,0,0.65)\",\n                  border: \"1px solid rgba(255,255,255,0.12)\",\n                  whiteSpace: \"nowrap\",\n                  opacity: isSelected ? 1 : undefined,\n                }}\n              >\n                {many ? `${lead.city} · ${group.people.length}` : lead.name.split(/\\s+/)[0]}\n              </span>\n            </button>\n          );\n        })}\n      </div>\n      {/* Names show on hover, focus and for the selected pin */}\n      <style>{`.dot-globe-pin .dot-globe-name{opacity:0;transition:opacity .15s}.dot-globe-pin:hover .dot-globe-name,.dot-globe-pin:focus-visible .dot-globe-name{opacity:1}.dot-globe-pin:focus-visible{outline:none}.dot-globe-pin:focus-visible>span:first-child{outline:2px solid ${accentColor};outline-offset:2px}`}</style>\n\n      {/* Count */}\n      {showCount && (\n        <div data-globe-ui style={{ position: \"absolute\", top: 20, left: 20, pointerEvents: \"none\" }}>\n          <div style={{ fontSize: 12, fontWeight: 500, letterSpacing: \"0.08em\", textTransform: \"uppercase\", color: muted }}>{title}</div>\n          <div style={{ marginTop: 6, fontSize: 22, fontWeight: 500, letterSpacing: \"-0.02em\" }}>\n            {everyone.length.toLocaleString()} {everyone.length === 1 ? \"person\" : \"people\"}\n            <span style={{ color: muted }}> · {countries} {countries === 1 ? \"country\" : \"countries\"}</span>\n          </div>\n        </div>\n      )}\n\n      {/* Selected person */}\n      {chosen && chosenGroup && chosenGroup.people.length > 1 && panel === \"closed\" && (\n        <div\n          data-globe-ui\n          role=\"dialog\"\n          aria-label={`${chosenGroup.people.length} people in ${placeLine(chosen)}`}\n          style={{\n            position: \"absolute\",\n            left: 16,\n            right: 16,\n            bottom: allowAdd ? 76 : 16,\n            margin: \"0 auto\",\n            maxWidth: 340,\n            padding: 12,\n            background: \"rgba(12,12,14,0.92)\",\n            border: \"1px solid rgba(255,255,255,0.1)\",\n            backdropFilter: \"blur(12px)\",\n            cursor: \"default\",\n          }}\n        >\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 10, marginBottom: 8 }}>\n            <div style={{ minWidth: 0, flex: 1 }}>\n              <div style={{ fontSize: 15, fontWeight: 600, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>\n                {flag(chosen.countryCode)} {placeLine(chosen)}\n              </div>\n              <div style={{ marginTop: 2, fontSize: 13, color: muted }}>{chosenGroup.people.length} people here</div>\n            </div>\n            <button type=\"button\" aria-label=\"Close\" onClick={() => setSelected(null)} style={iconButton(textColor)}>\n              ×\n            </button>\n          </div>\n          <ul style={{ margin: 0, padding: 0, listStyle: \"none\", maxHeight: 176, overflowY: \"auto\" }}>\n            {chosenGroup.people.map((person) => {\n              const on = personId(person) === selected;\n              return (\n                <li key={personId(person)}>\n                  <button\n                    type=\"button\"\n                    aria-current={on || undefined}\n                    onClick={() => setSelected(personId(person))}\n                    style={{\n                      display: \"flex\",\n                      alignItems: \"center\",\n                      gap: 10,\n                      width: \"100%\",\n                      padding: \"6px 8px\",\n                      border: 0,\n                      background: on ? \"rgba(255,255,255,0.08)\" : \"transparent\",\n                      color: textColor,\n                      font: `500 14px ${FONT}`,\n                      textAlign: \"left\",\n                      cursor: \"pointer\",\n                    }}\n                  >\n                    <Avatar person={person} size={30} />\n                    <span style={{ overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{person.name}</span>\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n        </div>\n      )}\n      {chosen && (!chosenGroup || chosenGroup.people.length === 1) && panel === \"closed\" && (\n        <div\n          data-globe-ui\n          role=\"dialog\"\n          aria-label={chosen.name}\n          style={{\n            position: \"absolute\",\n            left: 16,\n            right: 16,\n            bottom: allowAdd ? 76 : 16,\n            margin: \"0 auto\",\n            maxWidth: 340,\n            display: \"flex\",\n            alignItems: \"center\",\n            gap: 12,\n            padding: 12,\n            background: \"rgba(12,12,14,0.92)\",\n            border: \"1px solid rgba(255,255,255,0.1)\",\n            backdropFilter: \"blur(12px)\",\n            cursor: \"default\",\n          }}\n        >\n          <Avatar person={chosen} size={44} />\n          <div style={{ minWidth: 0, flex: 1 }}>\n            <div style={{ fontSize: 15, fontWeight: 600, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>{chosen.name}</div>\n            <div style={{ marginTop: 2, fontSize: 13, color: muted, overflow: \"hidden\", textOverflow: \"ellipsis\", whiteSpace: \"nowrap\" }}>\n              {flag(chosen.countryCode)} {placeLine(chosen)}\n            </div>\n          </div>\n          <button type=\"button\" aria-label=\"Close\" onClick={() => setSelected(null)} style={iconButton(textColor)}>\n            ×\n          </button>\n        </div>\n      )}\n\n      {/* Add your place */}\n      {allowAdd && panel === \"closed\" && (\n        <button\n          data-globe-ui\n          type=\"button\"\n          onClick={() => setPanel(\"place\")}\n          style={{\n            position: \"absolute\",\n            left: \"50%\",\n            bottom: 20,\n            transform: \"translateX(-50%)\",\n            height: 40,\n            padding: \"0 18px\",\n            border: 0,\n            background: accentColor,\n            color: \"#000\",\n            font: `600 14px ${FONT}`,\n            cursor: \"pointer\",\n            whiteSpace: \"nowrap\",\n          }}\n        >\n          + Add your place\n        </button>\n      )}\n      {allowAdd && panel !== \"closed\" && (\n        <AddPanel\n          step={panel}\n          onStep={setPanel}\n          onCancel={() => setPanel(\"closed\")}\n          onSubmit={addPerson}\n          onPreview={(place) => flyTo(place.lng, place.lat)}\n          searchPlaces={searchPlaces}\n          accentColor={accentColor}\n          textColor={textColor}\n        />\n      )}\n    </div>\n  );\n}\n\nfunction iconButton(color: string): CSSProperties {\n  return {\n    width: 28,\n    height: 28,\n    flexShrink: 0,\n    border: 0,\n    background: \"rgba(255,255,255,0.08)\",\n    color,\n    font: `400 18px/1 ${FONT}`,\n    cursor: \"pointer\",\n  };\n}\n\n// ─── Add flow ────────────────────────────────────────────────────────────────\n\nexport interface AddPlaceFormProps {\n  /** Called with the new person; reject to show an error */\n  onSubmit: (person: GlobePerson) => void | Promise<void>;\n  /** Called when a place is picked, e.g. to fly a globe there */\n  onPreview?: (place: GlobePlace) => void;\n  searchPlaces?: (query: string, signal: AbortSignal) => Promise<GlobePlace[]>;\n  accentColor?: string;\n  textColor?: string;\n  className?: string;\n  style?: CSSProperties;\n}\n\n/**\n * The two-step \"Add your place\" form on its own (name and city, then a photo), to place in a\n * sidebar, modal or page next to a PeopleGlobe. It clears itself after each person is added.\n */\nexport function AddPlaceForm({ onSubmit, onPreview, searchPlaces = openMeteoSearch, accentColor = \"#FFFFFF\", textColor = \"#FFFFFF\", className, style }: AddPlaceFormProps) {\n  const [step, setStep] = useState<\"place\" | \"avatar\">(\"place\");\n  const [round, setRound] = useState(0);\n  return (\n    <AddPanel\n      key={round}\n      inline\n      step={step}\n      onStep={setStep}\n      onSubmit={async (person) => {\n        await onSubmit(person);\n        setStep(\"place\");\n        setRound((r) => r + 1); // fresh, empty form\n      }}\n      onPreview={onPreview ?? (() => {})}\n      searchPlaces={searchPlaces}\n      accentColor={accentColor}\n      textColor={textColor}\n      className={className}\n      style={style}\n    />\n  );\n}\n\nfunction AddPanel({\n  step,\n  onStep,\n  onCancel,\n  onSubmit,\n  onPreview,\n  searchPlaces,\n  accentColor,\n  textColor,\n  inline = false,\n  className,\n  style,\n}: {\n  step: \"place\" | \"avatar\";\n  onStep: (step: \"place\" | \"avatar\") => void;\n  /** Overlay only: the × button */\n  onCancel?: () => void;\n  onSubmit: (person: GlobePerson) => void | Promise<void>;\n  onPreview: (place: GlobePlace) => void;\n  searchPlaces: (query: string, signal: AbortSignal) => Promise<GlobePlace[]>;\n  accentColor: string;\n  textColor: string;\n  /** In the page flow (sidebar) rather than floating over the globe */\n  inline?: boolean;\n  className?: string;\n  style?: CSSProperties;\n}) {\n  const [name, setName] = useState(\"\");\n  const [query, setQuery] = useState(\"\");\n  const [results, setResults] = useState<GlobePlace[]>([]);\n  const [searching, setSearching] = useState(false);\n  const [searchedFor, setSearchedFor] = useState(\"\");\n  const [searchError, setSearchError] = useState(\"\");\n  const [active, setActive] = useState(0);\n  const [place, setPlace] = useState<GlobePlace | null>(null);\n  const [avatar, setAvatar] = useState<string | undefined>();\n  const [busy, setBusy] = useState(false);\n  const [error, setError] = useState(\"\");\n  const fileRef = useRef<HTMLInputElement | null>(null);\n  const muted = `color-mix(in srgb, ${textColor} 55%, transparent)`;\n\n  // Search as they type (debounced; earlier searches are cancelled)\n  useEffect(() => {\n    const q = query.trim();\n    if (place && q === placeLine(place)) return;\n    const controller = new AbortController();\n    const timer = setTimeout(async () => {\n      if (q.length < 2) {\n        setResults([]);\n        setSearching(false);\n        setSearchedFor(q);\n        return;\n      }\n      setSearching(true);\n      setSearchError(\"\");\n      try {\n        const found = await searchPlaces(q, controller.signal);\n        setResults(found);\n        setActive(0);\n        setSearchedFor(q);\n      } catch (err) {\n        if (!controller.signal.aborted) setSearchError(err instanceof Error ? err.message : \"Search failed\");\n      } finally {\n        if (!controller.signal.aborted) setSearching(false);\n      }\n    }, 250);\n    return () => {\n      clearTimeout(timer);\n      controller.abort();\n    };\n  }, [query, place, searchPlaces]);\n\n  const choose = (p: GlobePlace) => {\n    setPlace(p);\n    setQuery(placeLine(p));\n    setResults([]);\n    onPreview(p);\n  };\n\n  const onSearchKey = (e: ReactKeyboardEvent<HTMLInputElement>) => {\n    if (!results.length) return;\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n      e.preventDefault();\n      setActive((i) => (i + (e.key === \"ArrowDown\" ? 1 : results.length - 1)) % results.length);\n    } else if (e.key === \"Enter\") {\n      e.preventDefault();\n      choose(results[active]);\n    }\n  };\n\n  const upload = async (file?: File) => {\n    if (!file) return;\n    setError(\"\");\n    try {\n      setAvatar(await shrinkImage(file));\n    } catch (err) {\n      setError(err instanceof Error ? err.message : \"That image couldn't be used\");\n    }\n  };\n\n  const submit = async () => {\n    if (!place) return;\n    setBusy(true);\n    setError(\"\");\n    try {\n      await onSubmit({ ...place, name: name.trim(), avatar, id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}` });\n    } catch (err) {\n      setError(err instanceof Error ? err.message : \"Couldn't add you just now. Try again.\");\n      setBusy(false);\n    }\n  };\n\n  const field: CSSProperties = {\n    width: \"100%\",\n    height: 40,\n    padding: \"0 12px\",\n    boxSizing: \"border-box\",\n    border: \"1px solid rgba(255,255,255,0.12)\",\n    background: \"rgba(255,255,255,0.04)\",\n    color: textColor,\n    font: `400 14px ${FONT}`,\n    outline: \"none\",\n  };\n  const primary: CSSProperties = {\n    flex: 1,\n    height: 40,\n    border: 0,\n    background: accentColor,\n    color: \"#000\",\n    font: `600 14px ${FONT}`,\n    cursor: \"pointer\",\n  };\n  const secondary: CSSProperties = { ...primary, flex: \"none\", padding: \"0 14px\", background: \"rgba(255,255,255,0.08)\", color: textColor, fontWeight: 500 };\n\n  return (\n    <form\n      data-globe-ui\n      aria-label=\"Add your place\"\n      className={className}\n      onSubmit={(e) => {\n        e.preventDefault();\n        if (step === \"place\" && place && name.trim()) onStep(\"avatar\");\n        else if (step === \"avatar\") void submit();\n      }}\n      style={{\n        ...(inline\n          ? { position: \"relative\", width: \"100%\", boxSizing: \"border-box\" }\n          : { position: \"absolute\", left: 16, right: 16, bottom: 16, margin: \"0 auto\", maxWidth: 360 }),\n        padding: 16,\n        background: \"rgba(12,12,14,0.94)\",\n        border: \"1px solid rgba(255,255,255,0.1)\",\n        backdropFilter: \"blur(14px)\",\n        color: textColor,\n        fontFamily: FONT,\n        cursor: \"default\",\n        userSelect: \"text\",\n        ...style,\n      }}\n    >\n      <div style={{ display: \"flex\", alignItems: \"center\", justifyContent: \"space-between\", marginBottom: 14 }}>\n        <div>\n          <div style={{ fontSize: 15, fontWeight: 600 }}>{step === \"place\" ? \"Add your place\" : \"Add a photo\"}</div>\n          <div style={{ marginTop: 2, fontSize: 12, color: muted }}>Step {step === \"place\" ? 1 : 2} of 2</div>\n        </div>\n        {onCancel && (\n          <button type=\"button\" aria-label=\"Close\" onClick={onCancel} style={iconButton(textColor)}>\n            ×\n          </button>\n        )}\n      </div>\n\n      {step === \"place\" ? (\n        <div style={{ display: \"flex\", flexDirection: \"column\", gap: 10 }}>\n          <input aria-label=\"Your name\" placeholder=\"Your name\" value={name} maxLength={40} onChange={(e) => setName(e.target.value)} style={field} autoFocus={!inline} />\n          <div style={{ position: \"relative\" }}>\n            <input\n              aria-label=\"Your city\"\n              role=\"combobox\"\n              aria-expanded={results.length > 0}\n              aria-controls=\"dot-globe-results\"\n              aria-autocomplete=\"list\"\n              placeholder=\"Search your city\"\n              value={query}\n              onChange={(e) => {\n                setQuery(e.target.value);\n                setPlace(null);\n              }}\n              onKeyDown={onSearchKey}\n              style={field}\n            />\n            {(results.length > 0 || searching || searchError || (query.trim().length >= 2 && !place)) && (\n              <ul\n                id=\"dot-globe-results\"\n                role=\"listbox\"\n                style={{\n                  position: \"absolute\",\n                  left: 0,\n                  right: 0,\n                  ...(inline ? { top: \"calc(100% + 6px)\" } : { bottom: \"calc(100% + 6px)\" }),\n                  margin: 0,\n                  padding: 4,\n                  listStyle: \"none\",\n                  maxHeight: 220,\n                  overflowY: \"auto\",\n                  background: \"#111114\",\n                  border: \"1px solid rgba(255,255,255,0.12)\",\n                  zIndex: 1,\n                }}\n              >\n                {!results.length && !searchError && (\n                  <li style={{ padding: \"8px 10px\", fontSize: 13, color: muted }}>\n                    {searching || searchedFor !== query.trim() ? \"Searching…\" : \"No places found\"}\n                  </li>\n                )}\n                {searchError && <li style={{ padding: \"8px 10px\", fontSize: 13, color: \"#F87171\" }}>{searchError}</li>}\n                {results.map((r, i) => (\n                  <li\n                    key={`${r.lat},${r.lng},${i}`}\n                    role=\"option\"\n                    aria-selected={i === active}\n                    onMouseEnter={() => setActive(i)}\n                    onMouseDown={(e) => {\n                      e.preventDefault();\n                      choose(r);\n                    }}\n                    style={{ display: \"flex\", gap: 8, padding: \"8px 10px\", fontSize: 13, cursor: \"pointer\", background: i === active ? \"rgba(255,255,255,0.08)\" : \"transparent\" }}\n                  >\n                    <span>{flag(r.countryCode) || \"📍\"}</span>\n                    <span style={{ minWidth: 0 }}>\n                      <span style={{ fontWeight: 500 }}>{r.city}</span>\n                      <span style={{ color: muted }}> {[r.state, r.country].filter(Boolean).join(\", \")}</span>\n                    </span>\n                  </li>\n                ))}\n              </ul>\n            )}\n          </div>\n          {place && (\n            <div style={{ fontSize: 12, color: muted }}>\n              {flag(place.countryCode)} {[place.city, place.state, place.country].filter(Boolean).join(\" · \")}\n            </div>\n          )}\n          <div style={{ display: \"flex\", gap: 8, marginTop: 4 }}>\n            <button type=\"submit\" disabled={!place || !name.trim()} style={{ ...primary, opacity: !place || !name.trim() ? 0.4 : 1 }}>\n              Next\n            </button>\n          </div>\n        </div>\n      ) : (\n        <div style={{ display: \"flex\", flexDirection: \"column\", gap: 14 }}>\n          <div style={{ display: \"flex\", alignItems: \"center\", gap: 14 }}>\n            <Avatar person={{ name, avatar }} size={64} ring=\"rgba(255,255,255,0.9)\" />\n            <div style={{ minWidth: 0 }}>\n              <div style={{ fontSize: 15, fontWeight: 600 }}>{name.trim()}</div>\n              <div style={{ marginTop: 2, fontSize: 13, color: muted }}>{place ? `${flag(place.countryCode)} ${placeLine(place)}` : \"\"}</div>\n            </div>\n          </div>\n          <input ref={fileRef} type=\"file\" accept=\"image/*\" hidden onChange={(e) => void upload(e.target.files?.[0])} />\n          <div style={{ display: \"flex\", gap: 8 }}>\n            <button type=\"button\" onClick={() => fileRef.current?.click()} style={{ ...secondary, flex: 1 }}>\n              {avatar ? \"Change photo\" : \"Upload photo\"}\n            </button>\n            {avatar && (\n              <button type=\"button\" onClick={() => setAvatar(undefined)} style={secondary}>\n                Remove\n              </button>\n            )}\n          </div>\n          {error && <div style={{ fontSize: 12, color: \"#F87171\" }}>{error}</div>}\n          <div style={{ display: \"flex\", gap: 8 }}>\n            <button type=\"button\" onClick={() => onStep(\"place\")} style={secondary}>\n              Back\n            </button>\n            <button type=\"submit\" disabled={busy} style={{ ...primary, opacity: busy ? 0.6 : 1 }}>\n              {busy ? \"Pinning…\" : avatar ? \"Pin me\" : \"Pin me with initials\"}\n            </button>\n          </div>\n        </div>\n      )}\n    </form>\n  );\n}\n"}],"docs":"People Globe is ready. Props and a live canvas: https://bydot.co/component/people-globe","meta":{"tier":"free","category":"Interactive","version":"1.0.0"}}