{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-geomap-chart",
  "title": "Geomap Chart",
  "description": "A geographic map component for rendering GeoJSON/TopoJSON data with tooltips, zooming (optional zoom controls), full-screen expand, choropleth, and point markers.",
  "dependencies": [
    "react-simple-maps",
    "geojson",
    "class-variance-authority",
    "lucide-react"
  ],
  "devDependencies": [
    "@types/geojson"
  ],
  "registryDependencies": [
    "@lema-ds/skeleton",
    "@lema-ds/tooltip",
    "@lema-ds/button",
    "@lema-ds/dialog",
    "@lema-ds/ui-i18n",
    "@lema-ds/format-utils",
    "@lema-ds/ds-locale-provider",
    "@lema-ds/client-only"
  ],
  "files": [
    {
      "path": "components/ds/ds-geomap-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport type { FeatureCollection } from \"geojson\"\nimport { cva } from \"class-variance-authority\"\nimport { Maximize2, Minimize2, Minus, Plus, RotateCcw } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { ClientOnly } from \"@/lib/client-only\"\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogTitle,\n} from \"@/components/ui/dialog\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport { formatChartValue, type FormatPreset } from \"@/lib/format-utils\"\nimport { UI_I18N, type UILocale } from \"@/lib/ui-i18n\"\nimport { useUILocale } from \"@/components/ui/ds-locale-provider\"\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from \"@/components/ui/tooltip\"\n\n// react-simple-maps is heavy (~30kB) — code-split with React.lazy and render\n// only on the client (ClientOnly + Suspense) to avoid SSR window mismatch.\n// Framework-agnostic: no next/dynamic.\nconst ComposableMap = React.lazy(() =>\n  import(\"react-simple-maps\").then((m) => ({\n    default: m.ComposableMap as unknown as React.ComponentType<\n      React.ComponentProps<typeof m.ComposableMap>\n    >,\n  }))\n) as unknown as typeof import(\"react-simple-maps\").ComposableMap\n\nconst Geographies = React.lazy(() =>\n  import(\"react-simple-maps\").then((m) => ({\n    default: m.Geographies as unknown as React.ComponentType<\n      React.ComponentProps<typeof m.Geographies>\n    >,\n  }))\n) as unknown as typeof import(\"react-simple-maps\").Geographies\n\nconst Geography = React.lazy(() =>\n  import(\"react-simple-maps\").then((m) => ({\n    default: m.Geography as unknown as React.ComponentType<\n      React.ComponentProps<typeof m.Geography>\n    >,\n  }))\n) as unknown as typeof import(\"react-simple-maps\").Geography\n\nconst Marker = React.lazy(() =>\n  import(\"react-simple-maps\").then((m) => ({\n    default: m.Marker as unknown as React.ComponentType<\n      React.ComponentProps<typeof m.Marker>\n    >,\n  }))\n) as unknown as typeof import(\"react-simple-maps\").Marker\n\nconst ZoomableGroup = React.lazy(() =>\n  import(\"react-simple-maps\").then((m) => ({\n    default: m.ZoomableGroup as unknown as React.ComponentType<\n      React.ComponentProps<typeof m.ZoomableGroup>\n    >,\n  }))\n) as unknown as typeof import(\"react-simple-maps\").ZoomableGroup\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type GeoProjection =\n  | \"geoMercator\"\n  | \"geoEqualEarth\"\n  | \"geoNaturalEarth1\"\n  | \"geoAlbersUsa\"\n  | \"geoOrthographic\"\n  | \"geoAzimuthalEqualArea\"\n\n/** Where to render the choropleth color legend */\nexport type LegendPosition =\n  \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\" | \"bottom\"\n\n/** Gradient bar direction in the color legend */\nexport type LegendOrientation = \"horizontal\" | \"vertical\"\n\nexport interface GeoMapFeature {\n  /** Must match the GeoJSON feature's `id` or `properties.id` */\n  id: string | number\n  name?: string\n  value?: number\n  color?: string\n  [key: string]: unknown\n}\n\nexport interface GeoMapMarker {\n  id: string | number\n  coordinates: [number, number]\n  label?: string\n  value?: number\n  color?: string\n  size?: number\n}\n\nexport interface GeoMapChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  /**\n   * GeoJSON FeatureCollection object **or** a URL string.\n   * When a string is passed, react-simple-maps fetches it internally —\n   * ideal for files served from `/public` (e.g. `\"/geojson/world.geojson\"`).\n   */\n  geoData: FeatureCollection | string\n  /**\n   * Which feature property to use as the ID when the GeoJSON features have no\n   * top-level `id` field (e.g. `\"sigla\"` for Brazilian states, `\"ISO_A3\"` for\n   * Natural Earth country files). Takes precedence over `properties.id`.\n   */\n  featureIdProperty?: string\n  /** Values to overlay on features (choropleth / highlight) — matched by id */\n  data?: GeoMapFeature[]\n  /** Point markers to render on top of the map */\n  markers?: GeoMapMarker[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  /**\n   * Chart canvas height — width is always 100%. A number is px; a string is\n   * any CSS length (e.g. `\"calc(100dvh - 3rem)\"`).\n   */\n  height?: number | string\n  /** D3 projection name — defaults to \"geoMercator\" */\n  projection?: GeoProjection\n  projectionConfig?: {\n    scale?: number\n    center?: [number, number]\n    rotate?: [number, number, number]\n  }\n  /** Enable zoom and pan via scroll / drag */\n  enableZoom?: boolean\n  /** Min/max zoom multiplier when zoom is enabled */\n  zoomRange?: [number, number]\n  /**\n   * Show zoom in / zoom out / reset buttons on the right edge of the map.\n   * Implies zoom and pan (drag), so `enableZoom` is not needed. Defaults to\n   * `false`.\n   */\n  showZoomControls?: boolean\n  /**\n   * Show an expand button in the top-right corner that opens the map in a\n   * full-screen dialog (with the same data, legend, tooltip and zoom controls).\n   * The button toggles to \"collapse\" inside the dialog. Defaults to `false`.\n   */\n  expandable?: boolean\n  /** Called when the full-screen dialog opens or closes (`expandable` only) */\n  onExpandedChange?: (expanded: boolean) => void\n  /** Choropleth: interpolate fill between these two colors by value */\n  colorRange?: [string, string]\n  /** Default fill for features with no matching data entry */\n  defaultFill?: string\n  /** Feature IDs to highlight with a distinct stroke */\n  selectedFeatureIds?: (string | number)[]\n  /** Stroke color for selected features */\n  selectedStroke?: string\n  showTooltip?: boolean\n  /**\n   * Show a color scale legend when `colorRange` is set.\n   * Defaults to `true` whenever `colorRange` is provided.\n   */\n  showLegend?: boolean\n  /**\n   * Where to render the legend.\n   * Overlay options (`top-left`, `top-right`, `bottom-left`, `bottom-right`) float\n   * inside the map canvas. `\"bottom\"` renders below the canvas.\n   * Defaults to `\"bottom-right\"`.\n   */\n  legendPosition?: LegendPosition\n  /** Short label displayed above the gradient bar in the legend */\n  legendLabel?: string\n  /** Gradient bar direction in the legend — defaults to `\"horizontal\"` */\n  legendOrientation?: LegendOrientation\n  onFeatureClick?: (\n    feature: GeoMapFeature | null,\n    originalId: string | number\n  ) => void\n  onMarkerClick?: (marker: GeoMapMarker) => void\n  valueFormatter?: (value: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  locale?: UILocale\n  /** Show animated skeleton in place of the map while data loads */\n  loading?: boolean\n}\n\n// ── Skeleton ───────────────────────────────────────────────────────────────\n\ninterface GeoMapChartSkeletonProps {\n  height?: number | string\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  className?: string\n}\n\nfunction GeoMapChartSkeleton({\n  height = 400,\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  className,\n}: GeoMapChartSkeletonProps) {\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"geomap-chart-skeleton\"\n    >\n      {(hasTitle || hasSubtitle) && (\n        <div className=\"flex flex-col gap-1.5 px-1 pb-4\">\n          {hasTitle && (\n            <Skeleton\n              className=\"h-3.5 w-44 rounded-md\"\n              style={{ animationDelay: \"0s\" }}\n            />\n          )}\n          {hasSubtitle && (\n            <Skeleton\n              className=\"mt-0.5 h-2.5 w-28 rounded-md\"\n              style={{ animationDelay: \"0.1s\" }}\n            />\n          )}\n        </div>\n      )}\n\n      <Skeleton\n        className=\"relative w-full overflow-hidden rounded-md\"\n        style={{ height }}\n      >\n        {/* Continent blob overlays */}\n        <svg\n          viewBox={`0 0 800 ${typeof height === \"number\" ? height : 400}`}\n          width=\"100%\"\n          height=\"100%\"\n          className=\"absolute inset-0\"\n          style={{ opacity: 0.25 }}\n        >\n          {/* Europe/Africa blob */}\n          <ellipse\n            cx=\"400\"\n            cy=\"220\"\n            rx=\"80\"\n            ry=\"110\"\n            fill=\"var(--muted-foreground)\"\n          />\n          {/* Americas blob */}\n          <ellipse\n            cx=\"200\"\n            cy=\"240\"\n            rx=\"65\"\n            ry=\"120\"\n            fill=\"var(--muted-foreground)\"\n          />\n          {/* Asia blob */}\n          <ellipse\n            cx=\"560\"\n            cy=\"180\"\n            rx=\"100\"\n            ry=\"80\"\n            fill=\"var(--muted-foreground)\"\n          />\n          {/* Oceania blob */}\n          <ellipse\n            cx=\"620\"\n            cy=\"340\"\n            rx=\"50\"\n            ry=\"35\"\n            fill=\"var(--muted-foreground)\"\n          />\n          {/* North America upper */}\n          <ellipse\n            cx=\"160\"\n            cy=\"140\"\n            rx=\"60\"\n            ry=\"50\"\n            fill=\"var(--muted-foreground)\"\n          />\n        </svg>\n      </Skeleton>\n\n      {hasFooter && (\n        <div className=\"mt-4 flex items-center gap-2 border-t border-border px-1 pt-3\">\n          <Skeleton\n            className=\"h-3.5 w-3.5 shrink-0 rounded-full\"\n            style={{ animationDelay: \"0.7s\" }}\n          />\n          <Skeleton\n            className=\"h-2.5 w-36 rounded-md\"\n            style={{ animationDelay: \"0.8s\" }}\n          />\n          <Skeleton\n            className=\"ml-auto h-2.5 w-20 rounded-md\"\n            style={{ animationDelay: \"0.9s\" }}\n          />\n        </div>\n      )}\n    </div>\n  )\n}\n\n// ── Variants ───────────────────────────────────────────────────────────────\n\nconst chartWrapperVariants = cva(\"flex w-full flex-col\")\n\nconst chartHeaderVariants = cva(\"flex flex-col px-1 pb-4\")\n\nconst chartTitleVariants = cva(\n  \"text-sm leading-tight font-semibold text-foreground\"\n)\n\nconst chartSubtitleVariants = cva(\"mt-0.5 text-xs text-muted-foreground\")\n\nconst chartFooterVariants = cva(\n  \"mt-4 flex items-center gap-2 border-t border-border px-1 pt-3 text-xs text-muted-foreground\"\n)\n\nconst ZOOM_STEP = 1.5\n\n/** Square icon button shared by the zoom controls and the expand action. */\nconst mapControlButtonClass = \"bg-card/90 backdrop-blur-sm\"\n\n// Hover / keyboard-focus look of a feature. Classes (not inline style) so they\n// win over the stroke attributes set for the resting state.\nconst geographyVariants = cva(\n  \"outline-none hover:stroke-primary hover:[stroke-width:1] hover:opacity-85 focus-visible:stroke-primary focus-visible:[stroke-width:1.5]\"\n)\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction resolveFeatureId(\n  properties: Record<string, unknown> | null,\n  id: string | number | undefined,\n  featureIdProperty?: string\n): string | number | null {\n  if (id !== undefined && id !== null) return id as string | number\n  if (featureIdProperty && properties?.[featureIdProperty] !== undefined)\n    return properties[featureIdProperty] as string | number\n  if (properties?.id !== undefined) return properties.id as string | number\n  if (properties?.ID !== undefined) return properties.ID as string | number\n  return null\n}\n\nfunction buildDataMap(\n  data: GeoMapFeature[]\n): Map<string | number, GeoMapFeature> {\n  const map = new Map<string | number, GeoMapFeature>()\n  for (const f of data) map.set(f.id, f)\n  return map\n}\n\nfunction getValueRange(data: GeoMapFeature[]): [number, number] {\n  const values = data.map((d) => d.value ?? 0).filter((v) => isFinite(v))\n  if (!values.length) return [0, 1]\n  return [Math.min(...values), Math.max(...values)]\n}\n\nfunction interpolateColor(color1: string, color2: string, t: number): string {\n  const parse = (hex: string) => {\n    const c = hex.replace(\"#\", \"\")\n    const full =\n      c.length === 3\n        ? c\n            .split(\"\")\n            .map((x) => x + x)\n            .join(\"\")\n        : c\n    return [\n      parseInt(full.slice(0, 2), 16),\n      parseInt(full.slice(2, 4), 16),\n      parseInt(full.slice(4, 6), 16),\n    ]\n  }\n\n  // Fall back gracefully if colors are not hex\n  try {\n    const [r1, g1, b1] = parse(color1)\n    const [r2, g2, b2] = parse(color2)\n    const r = Math.round(r1 + (r2 - r1) * t)\n    const g = Math.round(g1 + (g2 - g1) * t)\n    const b = Math.round(b1 + (b2 - b1) * t)\n    return `rgb(${r},${g},${b})`\n  } catch {\n    return t > 0.5 ? color2 : color1\n  }\n}\n\n// ── Tooltip ────────────────────────────────────────────────────────────────\n\ninterface TooltipState {\n  visible: boolean\n  x: number\n  y: number\n  name: string\n  value?: number\n}\n\nfunction MapTooltip({\n  state,\n  fmt,\n}: {\n  state: TooltipState\n  fmt: (v: number) => string\n}) {\n  if (!state.visible) return null\n  return (\n    <div\n      className=\"pointer-events-none absolute z-10 min-w-24 rounded-lg border border-border bg-card px-3 py-2 shadow-md\"\n      style={{ left: state.x + 12, top: state.y - 12 }}\n    >\n      <p className=\"text-xs font-semibold text-foreground\">{state.name}</p>\n      {state.value !== undefined && (\n        <p className=\"mt-0.5 text-xs text-muted-foreground\">\n          {fmt(state.value)}\n        </p>\n      )}\n    </div>\n  )\n}\n\n// ── ColorLegend ────────────────────────────────────────────────────────────\n\n// Horizontal overlay: anchored to corner, natural size\nconst overlayPositionClasses: Record<\n  Exclude<LegendPosition, \"bottom\">,\n  string\n> = {\n  \"top-left\": \"absolute top-2 left-2\",\n  \"top-right\": \"absolute top-2 right-2\",\n  \"bottom-left\": \"absolute bottom-2 left-2\",\n  \"bottom-right\": \"absolute bottom-2 right-2\",\n}\n\n// Vertical overlay: stretch full height of the canvas (inset-y-2)\nconst overlayPositionClassesVertical: Record<\n  Exclude<LegendPosition, \"bottom\">,\n  string\n> = {\n  \"top-left\": \"absolute inset-y-2 left-2\",\n  \"top-right\": \"absolute inset-y-2 right-2\",\n  \"bottom-left\": \"absolute inset-y-2 left-2\",\n  \"bottom-right\": \"absolute inset-y-2 right-2\",\n}\n\nfunction ColorLegend({\n  colorRange,\n  valueRange: [min, max],\n  fmt,\n  label,\n  position = \"bottom-right\",\n  orientation = \"horizontal\",\n  reserveTopRight = false,\n}: {\n  colorRange: [string, string]\n  valueRange: [number, number]\n  fmt: (v: number) => string\n  label?: string\n  position?: LegendPosition\n  orientation?: LegendOrientation\n  /** Keep the top-right corner free for the expand button */\n  reserveTopRight?: boolean\n}) {\n  const [tooltipOpen, setTooltipOpen] = React.useState(false)\n  const [hoverValue, setHoverValue] = React.useState<number | null>(null)\n  const barRef = React.useRef<HTMLDivElement>(null)\n\n  function handleBarMouseMove(e: React.MouseEvent<HTMLDivElement>) {\n    if (!barRef.current) return\n    const rect = barRef.current.getBoundingClientRect()\n    const t =\n      orientation === \"vertical\"\n        ? Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height))\n        : Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))\n    // vertical: top = max color, bottom = min color → value decreases downward\n    const value =\n      orientation === \"vertical\" ? max - t * (max - min) : min + t * (max - min)\n    setHoverValue(value)\n  }\n\n  const gradientBar = (\n    <TooltipProvider>\n      <Tooltip open={tooltipOpen}>\n        <TooltipTrigger asChild>\n          <div\n            ref={barRef}\n            className={cn(\n              \"cursor-crosshair rounded-sm\",\n              orientation === \"vertical\" ? \"w-3 flex-1\" : \"h-2 w-full\"\n            )}\n            style={{\n              background:\n                orientation === \"vertical\"\n                  ? `linear-gradient(to bottom, ${colorRange[1]}, ${colorRange[0]})`\n                  : `linear-gradient(to right, ${colorRange[0]}, ${colorRange[1]})`,\n            }}\n            onMouseEnter={() => setTooltipOpen(true)}\n            onMouseLeave={() => {\n              setTooltipOpen(false)\n              setHoverValue(null)\n            }}\n            onMouseMove={handleBarMouseMove}\n          />\n        </TooltipTrigger>\n        <TooltipContent side={orientation === \"vertical\" ? \"right\" : \"top\"}>\n          {hoverValue !== null ? fmt(hoverValue) : \"\"}\n        </TooltipContent>\n      </Tooltip>\n    </TooltipProvider>\n  )\n\n  const isOverlay = position !== \"bottom\"\n\n  const card =\n    orientation === \"vertical\" ? (\n      <div\n        className={cn(\n          \"flex flex-col items-center gap-1 rounded-md border border-border bg-card/90 px-2.5 py-2 text-xs shadow-sm backdrop-blur-sm\",\n          isOverlay && \"h-full\"\n        )}\n      >\n        {label && (\n          <p className=\"leading-none font-medium text-foreground\">{label}</p>\n        )}\n        <span className=\"leading-none text-muted-foreground\">{fmt(max)}</span>\n        {gradientBar}\n        <span className=\"leading-none text-muted-foreground\">{fmt(min)}</span>\n      </div>\n    ) : (\n      <div className=\"flex min-w-32 flex-col gap-1.5 rounded-md border border-border bg-card/90 px-3 py-2 text-xs shadow-sm backdrop-blur-sm\">\n        {label && (\n          <p className=\"leading-none font-medium text-foreground\">{label}</p>\n        )}\n        {gradientBar}\n        <div className=\"flex justify-between text-muted-foreground\">\n          <span>{fmt(min)}</span>\n          <span>{fmt(max)}</span>\n        </div>\n      </div>\n    )\n\n  if (position === \"bottom\") {\n    return <div className=\"mt-3\">{card}</div>\n  }\n\n  const shiftForCorner = reserveTopRight && position === \"top-right\"\n  const posClass = shiftForCorner\n    ? orientation === \"vertical\"\n      ? \"absolute top-12 right-2 bottom-2\"\n      : \"absolute top-2 right-12\"\n    : orientation === \"vertical\"\n      ? overlayPositionClassesVertical[position]\n      : overlayPositionClasses[position]\n\n  return <div className={cn(\"z-10\", posClass)}>{card}</div>\n}\n\n// ── GeoMapChart ────────────────────────────────────────────────────────────\n\ninterface GeoMapChartViewProps extends Omit<\n  GeoMapChartProps,\n  \"expandable\" | \"onExpandedChange\"\n> {\n  /** Corner button state — set by the `expandable` wrapper. */\n  expandAction?: { expanded: boolean; onToggle: () => void }\n}\n\nfunction GeoMapChartView({\n  geoData,\n  featureIdProperty,\n  data = [],\n  markers = [],\n  title,\n  subtitle,\n  footer,\n  height = 400,\n  projection = \"geoMercator\",\n  projectionConfig,\n  enableZoom = false,\n  zoomRange = [1, 8],\n  showZoomControls = false,\n  expandAction,\n  colorRange,\n  defaultFill,\n  selectedFeatureIds = [],\n  selectedStroke,\n  showTooltip = true,\n  showLegend,\n  legendPosition = \"bottom-right\",\n  legendOrientation = \"horizontal\",\n  legendLabel,\n  onFeatureClick,\n  onMarkerClick,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  locale: localeProp,\n  loading = false,\n  className,\n  ...props\n}: GeoMapChartViewProps) {\n  const locale = useUILocale(localeProp)\n  const t = UI_I18N[locale]?.geomapChart ?? UI_I18N[\"en-US\"].geomapChart\n\n  // Hooks must be called unconditionally before any early returns\n  const fmt = React.useCallback(\n    (v: number) =>\n      formatChartValue(v, {\n        format,\n        decimals,\n        locale,\n        currency,\n        abbreviate,\n        valueFormatter,\n      }),\n    [valueFormatter, format, decimals, locale, currency, abbreviate]\n  )\n\n  const shouldShowLegend = showLegend !== false && !!colorRange\n\n  const dataMap = React.useMemo(() => buildDataMap(data), [data])\n  const valueRange = React.useMemo(() => getValueRange(data), [data])\n  const selectedSet = React.useMemo(\n    () => new Set(selectedFeatureIds.map(String)),\n    [selectedFeatureIds]\n  )\n\n  const [tooltip, setTooltip] = React.useState<TooltipState>({\n    visible: false,\n    x: 0,\n    y: 0,\n    name: \"\",\n  })\n\n  const containerRef = React.useRef<HTMLDivElement>(null)\n\n  // Controlled zoom: ZoomableGroup only moves programmatically when its\n  // `zoom` / `center` props change, so external buttons need this state.\n  // `center` must start at the projection center, otherwise the group would\n  // recenter the map on [0, 0] when it mounts.\n  const zoomEnabled = enableZoom || showZoomControls\n  const initialCenter: [number, number] = projectionConfig?.center ?? [0, 0]\n  const [initialLon, initialLat] = initialCenter\n  const [minZoom, maxZoom] = zoomRange\n  const framingKey = `${initialLon},${initialLat},${projectionConfig?.scale}`\n  const [viewState, setViewState] = React.useState<{\n    key: string\n    zoom: number\n    center: [number, number]\n  }>({ key: framingKey, zoom: 1, center: initialCenter })\n\n  // A new framing (another projection center / scale) restarts from the\n  // default view — derived here instead of reset in an effect.\n  const view =\n    viewState.key === framingKey\n      ? viewState\n      : { key: framingKey, zoom: 1, center: initialCenter }\n\n  const setView = (next: { zoom: number; center: [number, number] }) =>\n    setViewState({ key: framingKey, ...next })\n  const changeZoom = (factor: number) =>\n    setView({\n      center: view.center,\n      zoom: Math.min(maxZoom, Math.max(minZoom, view.zoom * factor)),\n    })\n  const resetZoom = () => setView({ zoom: 1, center: initialCenter })\n\n  if (loading) {\n    return (\n      <GeoMapChartSkeleton\n        height={height}\n        hasTitle={!!title}\n        hasSubtitle={!!subtitle}\n        hasFooter={!!footer}\n        className={className}\n      />\n    )\n  }\n\n  function getFeatureFill(featureId: string | number | null): string {\n    if (featureId === null) return defaultFill ?? \"var(--muted)\"\n\n    const entry = dataMap.get(featureId) ?? dataMap.get(String(featureId))\n\n    if (entry?.color) return entry.color\n\n    if (colorRange && entry?.value !== undefined) {\n      const [min, max] = valueRange\n      const t = max === min ? 0 : (entry.value - min) / (max - min)\n      return interpolateColor(colorRange[0], colorRange[1], t)\n    }\n\n    return defaultFill ?? \"var(--muted)\"\n  }\n\n  function handleFeatureEnter(\n    e: React.MouseEvent,\n    featureId: string | number | null\n  ) {\n    if (!showTooltip) return\n    const entry =\n      featureId !== null\n        ? (dataMap.get(featureId) ?? dataMap.get(String(featureId)))\n        : undefined\n    const rect = containerRef.current?.getBoundingClientRect()\n    const x = rect ? e.clientX - rect.left : e.clientX\n    const y = rect ? e.clientY - rect.top : e.clientY\n    setTooltip({\n      visible: true,\n      x,\n      y,\n      name: entry?.name ?? String(featureId ?? \"\"),\n      value: entry?.value,\n    })\n  }\n\n  function handleFeatureLeave() {\n    setTooltip((prev) => ({ ...prev, visible: false }))\n  }\n\n  function handleMouseMove(e: React.MouseEvent) {\n    if (!tooltip.visible) return\n    const rect = containerRef.current?.getBoundingClientRect()\n    const x = rect ? e.clientX - rect.left : e.clientX\n    const y = rect ? e.clientY - rect.top : e.clientY\n    setTooltip((prev) => ({ ...prev, x, y }))\n  }\n\n  const mapContent = (\n    <Geographies geography={geoData}>\n      {({ geographies }) =>\n        geographies.map((geo) => {\n          const rawId = resolveFeatureId(\n            geo.properties as Record<string, unknown> | null,\n            geo.id as string | number | undefined,\n            featureIdProperty\n          )\n          const isSelected = rawId !== null && selectedSet.has(String(rawId))\n          const fill = getFeatureFill(rawId)\n\n          return (\n            <Geography\n              key={geo.rsmKey}\n              geography={geo}\n              fill={fill}\n              stroke={\n                isSelected\n                  ? (selectedStroke ?? \"var(--primary)\")\n                  : \"var(--background)\"\n              }\n              strokeWidth={isSelected ? 1.5 : 0.5}\n              // keeps the border width constant while zoomed in\n              vectorEffect={showZoomControls ? \"non-scaling-stroke\" : undefined}\n              // react-simple-maps v5 has no per-state `style`: the resting\n              // look is SVG attributes (above), hover/focus are classes\n              className={cn(\n                geographyVariants(),\n                onFeatureClick ? \"cursor-pointer\" : \"cursor-default\"\n              )}\n              onMouseEnter={(e) => handleFeatureEnter(e, rawId)}\n              onMouseLeave={handleFeatureLeave}\n              onMouseMove={handleMouseMove}\n              onClick={() =>\n                onFeatureClick?.(\n                  rawId !== null\n                    ? (dataMap.get(rawId) ?? dataMap.get(String(rawId)) ?? null)\n                    : null,\n                  rawId ?? \"\"\n                )\n              }\n            />\n          )\n        })\n      }\n    </Geographies>\n  )\n\n  const markerElements = markers.map((m) => (\n    <Marker key={m.id} coordinates={m.coordinates}>\n      <circle\n        r={m.size ?? 5}\n        fill={m.color ?? \"var(--chart-1)\"}\n        stroke=\"var(--background)\"\n        strokeWidth={1}\n        style={{ cursor: onMarkerClick ? \"pointer\" : \"default\" }}\n        onMouseEnter={(e) => {\n          if (!showTooltip) return\n          const rect = containerRef.current?.getBoundingClientRect()\n          const x = rect ? e.clientX - rect.left : e.clientX\n          const y = rect ? e.clientY - rect.top : e.clientY\n          setTooltip({\n            visible: true,\n            x,\n            y,\n            name: m.label ?? String(m.id),\n            value: m.value,\n          })\n        }}\n        onMouseLeave={handleFeatureLeave}\n        onClick={() => onMarkerClick?.(m)}\n      />\n      {m.label && (\n        <text\n          textAnchor=\"middle\"\n          y={-(m.size ?? 5) - 3}\n          style={{\n            fontSize: \"10px\",\n            fill: \"var(--foreground)\",\n            pointerEvents: \"none\",\n          }}\n        >\n          {m.label}\n        </text>\n      )}\n    </Marker>\n  ))\n\n  return (\n    <div\n      ref={containerRef}\n      className={cn(\n        chartWrapperVariants(),\n        \"relative\",\n        !expandAction?.expanded && className\n      )}\n      data-slot=\"geomap-chart\"\n      {...(expandAction?.expanded ? {} : props)}\n    >\n      {(title || subtitle) && (\n        <div className={chartHeaderVariants()} data-slot=\"geomap-chart-header\">\n          {title && <p className={chartTitleVariants()}>{title}</p>}\n          {subtitle && <p className={chartSubtitleVariants()}>{subtitle}</p>}\n        </div>\n      )}\n\n      {/* map canvas + overlay legend */}\n      <div className=\"relative\" data-slot=\"geomap-chart-map\">\n        <div style={{ height }} className=\"w-full overflow-hidden rounded-md\">\n          <ClientOnly fallback={<Skeleton className=\"size-full\" />}>\n            <React.Suspense fallback={<Skeleton className=\"size-full\" />}>\n              <ComposableMap\n                projection={projection}\n                projectionConfig={projectionConfig}\n                style={{ width: \"100%\", height: \"100%\" }}\n              >\n                {zoomEnabled ? (\n                  <ZoomableGroup\n                    zoom={view.zoom}\n                    center={view.center}\n                    minZoom={minZoom}\n                    maxZoom={maxZoom}\n                    onMoveEnd={({ coordinates, zoom }) => {\n                      if (!coordinates || zoom === undefined) return\n                      setView({ zoom, center: coordinates })\n                    }}\n                  >\n                    {mapContent}\n                    {markerElements}\n                  </ZoomableGroup>\n                ) : (\n                  <>\n                    {mapContent}\n                    {markerElements}\n                  </>\n                )}\n              </ComposableMap>\n            </React.Suspense>\n          </ClientOnly>\n        </div>\n\n        {expandAction && (\n          <div className=\"absolute top-2 right-2 z-10\">\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"icon-sm\"\n              className={mapControlButtonClass}\n              aria-label={expandAction.expanded ? t.collapse : t.expand}\n              title={expandAction.expanded ? t.collapse : t.expand}\n              aria-haspopup={expandAction.expanded ? undefined : \"dialog\"}\n              aria-expanded={expandAction.expanded ? undefined : false}\n              onClick={expandAction.onToggle}\n            >\n              {expandAction.expanded ? <Minimize2 /> : <Maximize2 />}\n            </Button>\n          </div>\n        )}\n\n        {showZoomControls && (\n          <div\n            role=\"group\"\n            aria-label={t.zoomControls}\n            className={cn(\n              \"absolute top-1/2 z-10 flex -translate-y-1/2 flex-col gap-1\",\n              // a vertical legend on the right owns that edge — move the buttons across\n              shouldShowLegend &&\n                legendOrientation === \"vertical\" &&\n                legendPosition.endsWith(\"right\")\n                ? \"left-2\"\n                : \"right-2\"\n            )}\n          >\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"icon-sm\"\n              className={mapControlButtonClass}\n              aria-label={t.zoomIn}\n              title={t.zoomIn}\n              disabled={view.zoom >= maxZoom}\n              onClick={() => changeZoom(ZOOM_STEP)}\n            >\n              <Plus />\n            </Button>\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"icon-sm\"\n              className={mapControlButtonClass}\n              aria-label={t.zoomOut}\n              title={t.zoomOut}\n              disabled={view.zoom <= minZoom}\n              onClick={() => changeZoom(1 / ZOOM_STEP)}\n            >\n              <Minus />\n            </Button>\n            <Button\n              type=\"button\"\n              variant=\"outline\"\n              size=\"icon-sm\"\n              className={mapControlButtonClass}\n              aria-label={t.resetZoom}\n              title={t.resetZoom}\n              onClick={resetZoom}\n            >\n              <RotateCcw />\n            </Button>\n          </div>\n        )}\n\n        {shouldShowLegend && legendPosition !== \"bottom\" && (\n          <ColorLegend\n            colorRange={colorRange!}\n            valueRange={valueRange}\n            fmt={fmt}\n            label={legendLabel}\n            position={legendPosition}\n            orientation={legendOrientation}\n            reserveTopRight={!!expandAction}\n          />\n        )}\n      </div>\n\n      {shouldShowLegend && legendPosition === \"bottom\" && (\n        <ColorLegend\n          colorRange={colorRange!}\n          valueRange={valueRange}\n          fmt={fmt}\n          label={legendLabel}\n          position=\"bottom\"\n          orientation={legendOrientation}\n        />\n      )}\n\n      {showTooltip && <MapTooltip state={tooltip} fmt={fmt} />}\n\n      {footer && (\n        <div className={chartFooterVariants()} data-slot=\"geomap-chart-footer\">\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n\nexport function GeoMapChart({\n  expandable = false,\n  onExpandedChange,\n  ...viewProps\n}: GeoMapChartProps) {\n  const [expanded, setExpanded] = React.useState(false)\n  const locale = viewProps.locale ?? \"en-US\"\n  const t = UI_I18N[locale]?.geomapChart ?? UI_I18N[\"en-US\"].geomapChart\n\n  if (!expandable) return <GeoMapChartView {...viewProps} />\n\n  const setOpen = (next: boolean) => {\n    setExpanded(next)\n    onExpandedChange?.(next)\n  }\n\n  return (\n    <>\n      <GeoMapChartView\n        {...viewProps}\n        expandAction={{ expanded: false, onToggle: () => setOpen(true) }}\n      />\n      <Dialog open={expanded} onOpenChange={setOpen}>\n        <DialogContent\n          showCloseButton={false}\n          className=\"top-0 left-0 h-dvh w-screen max-w-none translate-x-0 translate-y-0 gap-0 rounded-none p-4 sm:max-w-none\"\n        >\n          <DialogTitle className=\"sr-only\">\n            {viewProps.title ?? t.expandedTitle}\n          </DialogTitle>\n          <DialogDescription className=\"sr-only\">\n            {viewProps.subtitle ?? t.expandedTitle}\n          </DialogDescription>\n          <GeoMapChartView\n            {...viewProps}\n            title={undefined}\n            subtitle={undefined}\n            footer={undefined}\n            height=\"calc(100dvh - 2rem)\"\n            expandAction={{ expanded: true, onToggle: () => setOpen(false) }}\n          />\n        </DialogContent>\n      </Dialog>\n    </>\n  )\n}\n\n// Client-only wrapper — renders GeoMapChart after hydration (no SSR).\n// Framework-agnostic replacement for next/dynamic with ssr:false.\nexport function DynamicGeoMapChart(props: GeoMapChartProps) {\n  return (\n    <ClientOnly>\n      <GeoMapChart {...props} />\n    </ClientOnly>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
