# Game Map

A world map and a HUD minimap that share one set of data, laid out like a maps app: small pins whose labels make room for each other, numbered clusters when zoomed out, a place panel (side panel on wide maps, bottom sheet on phones), filter chips, search, "find me", zoom and a scale bar. Regions can sit under clouds until discovered. Everything is in your game's own units, so markers come straight from game state.

Docs: https://cozy-ui.solo.engineer/docs/components/game-map/

Install: `npx shadcn@latest add @cozy/game-map`

### Usage

```tsx
import { GameMap, MiniMap } from "@/components/ui/game-map"

const world = {
  mapWidth: 1200, mapHeight: 800, background: "/maps/village.png",
  markers: [{ id: "market", x: 746, y: 466, label: "Market", kind: "shop", tracked: true }],
  regions: [{ id: "hill", name: "Temple hill", points: [[880, 0], [1200, 0], [1200, 280]], discovered: false }],
  kinds: { shop: { label: "Shops", icon: <CoinIcon />, color: "#7FC4E0" } },
  player: { x: 520, y: 300, heading: 90 },
}

<MiniMap {...world} onOpen={() => setOpen(true)} />
<GameMap {...world} search height={480} onMarkerSelect={(m) => console.log(m)} />
```

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| mapWidth / mapHeight | `number` | – | Map size in your units. x runs 0..mapWidth to the right, y 0..mapHeight down. |
| background | `ReactNode \| string` | – | An image URL, or an SVG, canvas or tile grid drawn at mapWidth × mapHeight. |
| markers | `MapMarker<T>[]` | – | { id, x, y, label, kind?, icon?, color?, subtitle?, description?, image?, priority?, tracked?, alert?, hidden?, data? }. Higher priority wins label space. Markers inside regions under clouds are hidden. |
| regions | `MapRegion[]` | – | { id, name, points, color?, discovered?, labelAt? }. `discovered: false` covers the region with clouds. |
| paths / player / waypoint / kinds | `MapPath[] / MapPlayer / [x, y] / Record<string, MapKind>` | – | Routes { points, color?, dashed?, width? }, the player { x, y, heading?, icon?, label? }, a waypoint flag, and marker kinds { label, icon?, color? } for the filter chips. |
| GameMap: height | `number \| string` | `460` | Box height; width fills the container. |
| GameMap: view / defaultView / onViewChange | `{ x, y, zoom }` | `player, fill` | Control the centre and zoom. Zoom 1 = one map unit per px. |
| GameMap: minZoom / maxZoom / labelZoom / focusZoom | `number` | `fill / 4 / always / 1.8×fill` | Zoom limits (by default the map just fills the box), when labels appear, and the zoom used when flying to a place. |
| GameMap: selectedId / onMarkerSelect | `string \| null / (marker \| null) => void` | – | The open place. The map moves so it is never under the panel; Escape, the close button, a click on the map or pulling the sheet down closes it. |
| GameMap: renderMarker / renderDetails / markerActions | `fn` | – | Your own pin, place panel body, or buttons in the default panel. |
| GameMap: cluster | `number` | `34` | Pins closer than this many px merge into a numbered bubble; clicking it zooms in. 0 turns it off. |
| GameMap: onWaypointChange | `(point \| null) => void` | – | Right-click or long-press on the map gives you a point to store as `waypoint`. |
| GameMap: scale | `{ perUnit, unit }` | – | Scale bar: one map unit is perUnit of unit, e.g. { perUnit: 0.5, unit: "m" }. |
| GameMap: search / legend / controls / followPlayer | `boolean` | `false / true / true / false` | Place search, filter chips, zoom and find-me buttons, and keeping the player centred. |
| GameMap: hiddenKinds / onHiddenKindsChange | `string[]` | `[]` | Control the legend filter. |
| MiniMap: size / shape | `number / "circle" \| "square"` | `168 / "circle"` | Box size in px and shape. |
| MiniMap: zoom / defaultZoom / onZoomChange | `number` | `1` | Zoom level, with + and − buttons (zoomControls). |
| MiniMap: rotate / compass / showRegion | `boolean` | `false / true / true` | Heading-up map, the north marker, and the name of the region you are in. |
| MiniMap: center / onOpen / children | `[x, y] / () => void / ReactNode` | `player` | Centre (defaults to the player), click to open the full map, and overlays like a clock. |
| regionAt / useRegionChange | `function / hook` | – | The region that contains a point, and a hook that calls you when the player moves into another region (e.g. to show "Entering the Rice paddies"). |

### Example

```tsx
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { GameMap, type MapPlayer, type MapPoint } from "@/components/ui/game-map";
import { VillageMapArt } from "@/docs/art/map";
import { KINDS, MAP_H, MAP_W, MARKERS, PLAYER_ICON, REGIONS, ROUTE } from "./map-data";

export default function GameMapDemo() {
  const [player, setPlayer] = useState<MapPlayer>({ x: 520, y: 300, heading: 120, label: "Mai (you)", icon: PLAYER_ICON });
  const [regions, setRegions] = useState(REGIONS);
  const [waypoint, setWaypoint] = useState<MapPoint | null>(null);
  const hidden = regions.filter((r) => r.discovered === false);

  return (
    <div className="grid w-full gap-3">
      <GameMap
        mapWidth={MAP_W}
        mapHeight={MAP_H}
        background={<VillageMapArt />}
        markers={MARKERS}
        regions={regions}
        paths={ROUTE}
        kinds={KINDS}
        player={player}
        waypoint={waypoint}
        onWaypointChange={(p) => { setWaypoint(p); toast("Waypoint set"); }}
        scale={{ perUnit: 0.5, unit: "m" }}
        search
        markerActions={(m) => (
          <>
            <Button size="sm" variant="reward" onClick={() => { setPlayer((p) => ({ ...p, x: m.x, y: m.y + 20 })); toast.success(`Walking to ${m.label}`); }}>Travel</Button>
            <Button size="sm" variant="outline" onClick={() => { setWaypoint([m.x, m.y]); toast(`Waypoint set: ${m.label}`); }}>Set waypoint</Button>
          </>
        )}
      />
      <div className="flex flex-wrap items-center gap-2">
        <Button
          size="sm"
          variant="secondary"
          disabled={!hidden.length}
          onClick={() => {
            const next = hidden[0];
            setRegions((rs) => rs.map((r) => (r.id === next.id ? { ...r, discovered: true } : r)));
            toast.success(`Discovered ${next.name}`);
          }}
        >
          {hidden.length ? `Explore (${hidden.length} left under clouds)` : "Everything explored"}
        </Button>
        {waypoint && <Button size="sm" variant="outline" onClick={() => setWaypoint(null)}>Clear waypoint</Button>}
        <span className="text-sm text-text-muted">Drag, scroll or pinch. Double-click to zoom in, right-click (or long-press) to drop a waypoint.</span>
      </div>
    </div>
  );
}
```

### Source (components/ui/game-map.tsx)

```tsx
import * as React from "react";
import { cn } from "@/lib/utils";
import { GameIcon } from "./game-core";

/* A world map and a HUD minimap that share one set of data, laid out like a
   modern maps app: small pins with labels that make room for each other,
   clusters when zoomed out, a place panel (side panel on wide screens, bottom
   sheet on phones) that never covers the place you picked, filter chips,
   zoom and "find me" buttons and a scale bar. Everything is in your game's
   own units (x right, y down), so markers come straight from game state.
   Regions can sit under clouds until discovered. Data in, events out. */

export type MapPoint = [x: number, y: number];

export type MapKind = {
  label: string;
  icon?: React.ReactNode;
  /** Any CSS colour for the pin. */
  color?: string;
};

export type MapMarker<T = unknown> = {
  id: string;
  x: number;
  y: number;
  label: string;
  /** Key into `kinds` (filter chips, default icon and colour). */
  kind?: string;
  /** Overrides the kind icon: a React node or an image URL. */
  icon?: React.ReactNode;
  color?: string;
  /** Second line in the place panel, e.g. "Open 5–9 am". */
  subtitle?: React.ReactNode;
  description?: React.ReactNode;
  /** Picture at the top of the place panel: a React node or an image URL. */
  image?: React.ReactNode;
  /** Higher wins when labels compete for space. Default 0. */
  priority?: number;
  /** On the minimap, show an arrow on the edge when it is out of range. */
  tracked?: boolean;
  /** Small dot on the pin, e.g. a quest that is ready. */
  alert?: boolean;
  hidden?: boolean;
  data?: T;
};

export type MapRegion = {
  id: string;
  name: string;
  /** Polygon in map units. */
  points: MapPoint[];
  color?: string;
  /** false covers the region with clouds and hides markers inside it. Default true. */
  discovered?: boolean;
  /** Where to put the name. Default: the centre of the points. */
  labelAt?: MapPoint;
};

export type MapPath = {
  id: string;
  points: MapPoint[];
  color?: string;
  /** Dashed line, e.g. a quest route. Default false. */
  dashed?: boolean;
  /** Stroke width in screen px. Default 4. */
  width?: number;
  label?: string;
};

export type MapPlayer = {
  x: number;
  y: number;
  /** Facing in degrees, 0 = up (north), clockwise. */
  heading?: number;
  label?: string;
  icon?: React.ReactNode;
};

export type MapView = { x: number; y: number; zoom: number };

type MapData<T> = {
  /** Map size in your units (x 0..mapWidth, y 0..mapHeight). */
  mapWidth: number;
  mapHeight: number;
  /** A React node drawn at mapWidth × mapHeight (an SVG, a canvas, tiles) or an image URL. */
  background?: React.ReactNode;
  markers?: MapMarker<T>[];
  regions?: MapRegion[];
  paths?: MapPath[];
  player?: MapPlayer | null;
  /** A flag the player placed; the minimap points to it when it is out of range. */
  waypoint?: MapPoint | null;
  kinds?: Record<string, MapKind>;
};

/** The region that contains a point, if any (last one wins when they overlap). */
export function regionAt(regions: MapRegion[] | undefined, x: number, y: number): MapRegion | undefined {
  let hit: MapRegion | undefined;
  for (const r of regions ?? []) {
    let inside = false;
    const p = r.points;
    for (let i = 0, j = p.length - 1; i < p.length; j = i++) {
      const [xi, yi] = p[i], [xj, yj] = p[j];
      if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
    }
    if (inside) hit = r;
  }
  return hit;
}

/** Calls `onChange` when the point moves into a different region (e.g. to show "Entering the Rice paddies"). */
export function useRegionChange(regions: MapRegion[] | undefined, point: { x: number; y: number } | null | undefined, onChange: (region: MapRegion | undefined) => void) {
  const id = point ? regionAt(regions, point.x, point.y)?.id : undefined;
  const first = React.useRef(true);
  const cb = React.useRef(onChange);
  cb.current = onChange;
  React.useEffect(() => {
    if (first.current) { first.current = false; return; }
    cb.current(id ? regions?.find((r) => r.id === id) : undefined);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);
}

const centroid = (pts: MapPoint[]): MapPoint => {
  const n = pts.length || 1;
  return [pts.reduce((s, p) => s + p[0], 0) / n, pts.reduce((s, p) => s + p[1], 0) / n];
};
const clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));

/* Text width for label layout. Canvas when available, an estimate otherwise. */
let measureCtx: CanvasRenderingContext2D | null | undefined;
function textWidth(text: string, px: number, family: string) {
  if (measureCtx === undefined) measureCtx = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : null;
  if (!measureCtx) return text.length * px * 0.56;
  measureCtx.font = `${px}px ${family}`;
  return measureCtx.measureText(text).width;
}

/* ---------- label and cluster layout ---------- */

const PIN_W = 30, PIN_H = 38, LABEL_PX = 13.5, REGION_PX = 17;

type Box = [x0: number, y0: number, x1: number, y1: number];
const hits = (a: Box, b: Box) => a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1];

type Cluster<T> = { id: string; x: number; y: number; members: MapMarker<T>[] };
type Layout<T> = {
  singles: MapMarker<T>[];
  clusters: Cluster<T>[];
  /** Label side for each shown marker label. */
  labels: Map<string, "right" | "left">;
  regionNames: Set<string>;
};

function useLayout<T>(opts: {
  markers: MapMarker<T>[];
  regions: MapRegion[];
  zoom: number;
  selectedId: string | null;
  cluster: number;
  labelZoom: number;
  family: string;
  enabled: boolean;
}): Layout<T> {
  const { markers, regions, zoom, selectedId, cluster, labelZoom, family, enabled } = opts;
  return React.useMemo(() => {
    const order = markers
      .map((m, i) => ({ m, i }))
      .sort((a, b) => Number(b.m.id === selectedId) - Number(a.m.id === selectedId) || (b.m.priority ?? 0) - (a.m.priority ?? 0)
        || Number(!!b.m.alert || !!b.m.tracked) - Number(!!a.m.alert || !!a.m.tracked) || a.i - b.i)
      .map((o) => o.m);
    const singles: MapMarker<T>[] = [];
    const clusters: Cluster<T>[] = [];
    if (enabled && cluster > 0) {
      const groups: { x: number; y: number; members: MapMarker<T>[] }[] = [];
      for (const m of order) {
        if (m.id === selectedId) { groups.push({ x: m.x, y: m.y, members: [m] }); continue; }
        const g = groups.find((g) => g.members[0].id !== selectedId && Math.hypot((g.x - m.x) * zoom, (g.y - m.y) * zoom) < cluster);
        if (g) g.members.push(m);
        else groups.push({ x: m.x, y: m.y, members: [m] });
      }
      for (const g of groups) {
        if (g.members.length === 1) singles.push(g.members[0]);
        else {
          const x = g.members.reduce((s, m) => s + m.x, 0) / g.members.length, y = g.members.reduce((s, m) => s + m.y, 0) / g.members.length;
          clusters.push({ id: `cluster-${g.members.map((m) => m.id).join("-")}`, x, y, members: g.members });
        }
      }
    } else singles.push(...order);

    const labels = new Map<string, "right" | "left">();
    const regionNames = new Set<string>();
    if (!enabled) return { singles, clusters, labels, regionNames };
    // Everything below is in screen px relative to the map origin.
    const taken: Box[] = [];
    for (const m of singles) taken.push([m.x * zoom - PIN_W / 2, m.y * zoom - PIN_H, m.x * zoom + PIN_W / 2, m.y * zoom]);
    for (const c of clusters) taken.push([c.x * zoom - 22, c.y * zoom - 22, c.x * zoom + 22, c.y * zoom + 22]);
    for (const m of singles) {
      if (m.id !== selectedId && zoom < labelZoom) continue;
      const w = textWidth(m.label, LABEL_PX, family) + 6, h = 20;
      const sx = m.x * zoom, sy = m.y * zoom - PIN_H / 2 - h / 2 - 2;
      const own: Box = [sx - PIN_W / 2, m.y * zoom - PIN_H, sx + PIN_W / 2, m.y * zoom];
      const right: Box = [sx + PIN_W / 2 - 2, sy, sx + PIN_W / 2 - 2 + w, sy + h];
      const left: Box = [sx - PIN_W / 2 + 2 - w, sy, sx - PIN_W / 2 + 2, sy + h];
      const free = (b: Box) => !taken.some((t) => t !== own && hits(b, t) && !(t[0] === own[0] && t[1] === own[1]));
      if (m.id === selectedId || free(right)) { labels.set(m.id, "right"); taken.push(right); }
      else if (free(left)) { labels.set(m.id, "left"); taken.push(left); }
    }
    for (const r of regions) {
      const [x, y] = r.labelAt ?? centroid(r.points);
      const text = r.discovered === false ? "???" : r.name;
      const w = textWidth(text, REGION_PX, family) + 12, h = 26;
      const box: Box = [x * zoom - w / 2, y * zoom - h / 2, x * zoom + w / 2, y * zoom + h / 2];
      if (r.discovered === false || !taken.some((t) => hits(box, t))) { regionNames.add(r.id); taken.push(box); }
    }
    return { singles, clusters, labels, regionNames };
  }, [markers, regions, zoom, selectedId, cluster, labelZoom, family, enabled]);
}

/* ---------- shared drawing layer ---------- */

function PlayerArrow() {
  return (
    <svg viewBox="0 0 32 32" aria-hidden>
      <path d="M16 3 27 27 16 21 5 27Z" fill="var(--cz-reward)" stroke="var(--cz-outline)" strokeWidth="3" strokeLinejoin="round" />
    </svg>
  );
}

function Flag() {
  return (
    <svg viewBox="0 0 32 40" aria-hidden>
      <path d="M8 38V4" stroke="var(--cz-outline)" strokeWidth="3.5" strokeLinecap="round" />
      <path d="M9 5h17l-4 6 4 6H9Z" fill="var(--cz-danger)" stroke="var(--cz-outline)" strokeWidth="3" strokeLinejoin="round" />
    </svg>
  );
}

type LayerProps<T> = MapData<T> & {
  layout: Layout<T>;
  hiddenKinds?: Set<string>;
  selectedId?: string | null;
  interactive: boolean;
  onMarker?: (m: MapMarker<T>) => void;
  onCluster?: (c: Cluster<T>) => void;
  renderMarker?: (m: MapMarker<T>, state: { selected: boolean }) => React.ReactNode;
  lockedName: React.ReactNode;
  fogId: string;
  /** Extra screen-px scale for pins (the minimap draws smaller pins). */
  pinScale?: number;
  /** Counter-rotation for pins and labels when the layer is rotated. */
  counterRotate?: number;
};

function MapLayer<T>({
  mapWidth: width, mapHeight: height, background, regions, paths, player, waypoint, kinds, layout, selectedId, interactive, onMarker, onCluster,
  renderMarker, lockedName, fogId, pinScale = 1, counterRotate = 0,
}: LayerProps<T>) {
  const fogged = (regions ?? []).filter((r) => r.discovered === false);
  const bg = typeof background === "string" ? <img src={background} alt="" draggable={false} /> : background;
  const kindOf = (m: MapMarker<T>) => (m.kind ? kinds?.[m.kind] : undefined);

  return (
    <>
      <div className="cz-map__bg" aria-hidden>{bg}</div>
      <svg className="cz-map__shapes" viewBox={`0 0 ${width} ${height}`} width={width} height={height} aria-hidden>
        <defs>
          <pattern id={fogId} width="120" height="90" patternUnits="userSpaceOnUse">
            <rect width="120" height="90" fill="var(--cz-map-fog)" />
            <g fill="var(--cz-map-cloud)">
              <circle cx="22" cy="30" r="20" /><circle cx="46" cy="22" r="24" /><circle cx="70" cy="34" r="18" />
              <circle cx="90" cy="72" r="16" /><circle cx="110" cy="66" r="20" /><circle cx="2" cy="70" r="14" />
            </g>
          </pattern>
        </defs>
        {(regions ?? []).filter((r) => r.discovered !== false).map((r) => (
          <polygon key={r.id} className="cz-map__region" points={r.points.join(" ")} style={{ "--rc": r.color ?? "var(--cz-primary)" } as React.CSSProperties} />
        ))}
        {(paths ?? []).map((p) => (
          <polyline
            key={p.id}
            className="cz-map__path"
            data-dashed={p.dashed || undefined}
            points={p.points.join(" ")}
            style={{ "--pc": p.color ?? "var(--cz-reward)", "--pw": `${p.width ?? 4}px` } as React.CSSProperties}
          >
            {p.label && <title>{p.label}</title>}
          </polyline>
        ))}
        {fogged.map((r) => <polygon key={r.id} className="cz-map__fog" points={r.points.join(" ")} fill={`url(#${fogId})`} />)}
      </svg>
      {(regions ?? []).filter((r) => layout.regionNames.has(r.id)).map((r) => {
        const [x, y] = r.labelAt ?? centroid(r.points);
        return (
          <span key={r.id} className="cz-map__region-name" data-fog={r.discovered === false || undefined} style={{ left: x, top: y, "--cr": `${counterRotate}deg` } as React.CSSProperties}>
            {r.discovered === false ? lockedName : r.name}
          </span>
        );
      })}
      {layout.clusters.map((c) => {
        const k = c.members[0].kind ? kinds?.[c.members[0].kind!] : undefined;
        const same = c.members.every((m) => m.kind === c.members[0].kind);
        const style = { left: c.x, top: c.y, "--kc": same ? k?.color ?? "var(--cz-primary)" : "var(--cz-surface-top)", "--ps": pinScale, "--cr": `${counterRotate}deg` } as React.CSSProperties;
        const names = c.members.map((m) => m.label).join(", ");
        return interactive ? (
          <button key={c.id} type="button" className="cz-map__cluster" style={style} aria-label={`${c.members.length} places: ${names}. Zoom in`} onClick={() => onCluster?.(c)}>
            {c.members.length}
            {c.members.some((m) => m.alert) && <span className="cz-map__alert" />}
          </button>
        ) : (
          <span key={c.id} className="cz-map__cluster" style={style} aria-hidden>{c.members.length}</span>
        );
      })}
      {layout.singles.map((m) => {
        const kind = kindOf(m);
        const selected = selectedId === m.id;
        const side = layout.labels.get(m.id);
        const style = { left: m.x, top: m.y, "--kc": m.color ?? kind?.color ?? "var(--cz-primary)", "--ps": pinScale, "--cr": `${counterRotate}deg` } as React.CSSProperties;
        const inner = renderMarker ? renderMarker(m, { selected }) : (
          <span className="cz-map__pin"><span className="cz-map__pin-icon"><GameIcon icon={m.icon ?? kind?.icon} alt="" /></span>{m.alert && <span className="cz-map__alert" />}</span>
        );
        const label = interactive ? <span className="cz-map__label" data-side={side ?? "right"} data-hidden={!side || undefined}>{m.label}</span> : null;
        return interactive ? (
          <button
            key={m.id}
            type="button"
            data-marker-id={m.id}
            className="cz-map__marker"
            data-kind={m.kind}
            data-selected={selected || undefined}
            aria-label={`${m.label}${kind ? `, ${kind.label}` : ""}`}
            aria-pressed={selected}
            style={style}
            onClick={() => onMarker?.(m)}
          >
            {inner}{label}
          </button>
        ) : (
          <span key={m.id} className="cz-map__marker" data-kind={m.kind} style={style} aria-hidden>{inner}</span>
        );
      })}
      {waypoint && (
        <span className="cz-map__waypoint" role="img" aria-label="Waypoint" style={{ left: waypoint[0], top: waypoint[1], "--ps": pinScale, "--cr": `${counterRotate}deg` } as React.CSSProperties}><Flag /></span>
      )}
      {player && (
        <span className="cz-map__player" role="img" aria-label={player.label ?? "You"} style={{ left: player.x, top: player.y, "--heading": `${player.heading ?? 0}deg`, "--ps": pinScale } as React.CSSProperties}>
          <span className="cz-map__player-ring" />
          {player.icon ? <span className="cz-map__player-icon"><GameIcon icon={player.icon} alt="" /></span> : <PlayerArrow />}
        </span>
      )}
    </>
  );
}

/** Markers that are not hidden, filtered out, or under clouds. */
function useVisible<T>(markers: MapMarker<T>[] | undefined, regions: MapRegion[] | undefined, hidden?: Set<string>) {
  return React.useMemo(() => {
    const fogged = (regions ?? []).filter((r) => r.discovered === false);
    return (markers ?? []).filter((m) => !m.hidden && !(m.kind && hidden?.has(m.kind)) && !(fogged.length && regionAt(fogged, m.x, m.y)));
  }, [markers, regions, hidden]);
}

function useFontFamily(ref: React.RefObject<HTMLElement | null>) {
  const [family, setFamily] = React.useState("sans-serif");
  React.useEffect(() => {
    if (!ref.current) return;
    setFamily(getComputedStyle(ref.current).fontFamily || "sans-serif");
    document.fonts?.ready.then(() => { measureCtx = undefined; if (ref.current) setFamily(getComputedStyle(ref.current).fontFamily + " "); });
  }, [ref]);
  return family;
}

/* ---------- scale bar ---------- */

function ScaleBar({ zoom, perUnit, unit }: { zoom: number; perUnit: number; unit: string }) {
  // Pick a round distance that draws as 60–120 px.
  const target = 100 / zoom * perUnit;
  const pow = 10 ** Math.floor(Math.log10(target));
  const nice = [1, 2, 5, 10].map((n) => n * pow).reduce((best, n) => (Math.abs(n - target) < Math.abs(best - target) ? n : best), pow);
  const px = (nice / perUnit) * zoom;
  return (
    <div className="cz-map__scale" aria-hidden>
      <span>{nice.toLocaleString("en")} {unit}</span>
      <span className="cz-map__scale-bar" style={{ width: px }} />
    </div>
  );
}

/* ---------- GameMap ---------- */

type GameMapProps<T> = Omit<React.ComponentProps<"div">, "children"> & MapData<T> & {
  /** Height of the map box (any CSS length). Width fills the container. Default 460. */
  height?: number | string;
  /** Controlled view: centre in map units and zoom (1 = one map unit per screen px). */
  view?: MapView;
  defaultView?: Partial<MapView>;
  onViewChange?: (view: MapView) => void;
  /** Smallest zoom. Default: the map just fills the box. */
  minZoom?: number;
  /** Largest zoom. Default 4. */
  maxZoom?: number;
  /** Pin labels show from this zoom up, where there is room. Default: the fill zoom (always). */
  labelZoom?: number;
  /** Zoom used when flying to a place or the player. Default 1.8 × the fill zoom. */
  focusZoom?: number;
  /** Group pins closer than this many screen px into a numbered bubble. 0 turns it off. Default 34. */
  cluster?: number;
  /** Keep the player centred when it moves. Default false. */
  followPlayer?: boolean;
  selectedId?: string | null;
  defaultSelectedId?: string | null;
  onMarkerSelect?: (marker: MapMarker<T> | null) => void;
  /** Replace the pin. */
  renderMarker?: (marker: MapMarker<T>, state: { selected: boolean }) => React.ReactNode;
  /** Replace the body of the place panel. */
  renderDetails?: (marker: MapMarker<T>) => React.ReactNode;
  /** Buttons in the place panel, e.g. "Travel" or "Set waypoint". */
  markerActions?: (marker: MapMarker<T>) => React.ReactNode;
  /** Right-click or long-press on the map sets a waypoint there. */
  onWaypointChange?: (point: MapPoint | null) => void;
  /** Filter chips, one per kind. Default true when kinds are given. */
  legend?: boolean;
  hiddenKinds?: string[];
  defaultHiddenKinds?: string[];
  onHiddenKindsChange?: (kinds: string[]) => void;
  /** Search box for place names (true or a placeholder). */
  search?: boolean | string;
  /** Zoom and "find me" buttons. Default true. */
  controls?: boolean;
  /** "greedy" (default): wheel and one finger move the map. "cooperative": for maps inside a scrolling page,
   *  like embedded web maps: Ctrl/⌘ + wheel zooms and two fingers pan, so the page still scrolls. */
  gestures?: "greedy" | "cooperative";
  /** Scale bar: one map unit is `perUnit` of `unit`, e.g. { perUnit: 0.5, unit: "m" }. */
  scale?: { perUnit: number; unit: string };
  /** Name for regions still under clouds. Default "???". */
  lockedName?: React.ReactNode;
  /** Extra overlay inside the frame. */
  children?: React.ReactNode;
  label?: string;
};

function GameMap<T = unknown>({
  mapWidth, mapHeight, background, markers, regions, paths, player, waypoint, kinds, height = 460, view: viewProp, defaultView, onViewChange, minZoom, maxZoom = 4,
  labelZoom, focusZoom, cluster = 34, followPlayer = false, selectedId: selProp, defaultSelectedId = null, onMarkerSelect, renderMarker, renderDetails,
  markerActions, onWaypointChange, gestures = "greedy", legend, hiddenKinds: hiddenProp, defaultHiddenKinds = [], onHiddenKindsChange, search, controls = true, scale,
  lockedName = "???", children, label = "Map", className, style, ...props
}: GameMapProps<T>) {
  const rootRef = React.useRef<HTMLDivElement>(null);
  const boxRef = React.useRef<HTMLDivElement>(null);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const topRef = React.useRef<HTMLDivElement>(null);
  const [topH, setTopH] = React.useState(0);
  const [box, setBox] = React.useState({ w: 0, h: 0 });
  const [panelSize, setPanelSize] = React.useState({ w: 0, h: 0 });
  const fogId = `cz-fog-${React.useId().replace(/:/g, "")}`;
  const family = useFontFamily(rootRef);

  React.useEffect(() => {
    const el = boxRef.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setBox({ w: el.clientWidth, h: el.clientHeight }));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  React.useEffect(() => {
    const el = topRef.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setTopH(el.offsetHeight));
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const wide = box.w >= 560;
  const fill = box.w && box.h ? Math.max(box.w / mapWidth, box.h / mapHeight) : 1;
  const minZ = minZoom ?? fill;
  const maxZ = Math.max(maxZoom, minZ);
  const lblZ = labelZoom ?? 0;
  const focZ = clamp(focusZoom ?? fill * 1.8, minZ, maxZ);

  // Selection.
  const [selInner, setSelInner] = React.useState<string | null>(defaultSelectedId);
  const selectedId = selProp !== undefined ? selProp : selInner;
  const selected = (markers ?? []).find((m) => m.id === selectedId) ?? null;

  React.useEffect(() => {
    const el = panelRef.current;
    if (!el) { setPanelSize({ w: 0, h: 0 }); return; }
    const ro = new ResizeObserver(() => setPanelSize({ w: el.offsetWidth, h: el.offsetHeight }));
    ro.observe(el);
    return () => ro.disconnect();
  }, [selected?.id, wide]);

  // The part of the box not covered by the panel. Clamping allows the map to slide under the panel.
  // While a place is open the map may slide past its edges by the size of the panel and the buttons,
  // so a pin in a corner can still be brought into the free area.
  const chrome = { l: 12, r: controls ? 64 : 12, t: (topH ? topH + 12 : 0) + 8, b: 12 };
  const padFor = (panel: { w: number; h: number }) => ({
    l: chrome.l + (wide ? panel.w + 12 : 0), r: chrome.r, t: chrome.t, b: chrome.b + (wide ? 0 : panel.h),
  });
  const zeroPad = { l: 0, r: 0, t: 0, b: 0 };
  const pad = selected ? padFor(panelSize) : zeroPad;

  const [inner, setInner] = React.useState<MapView | null>(null);
  const raw: MapView = viewProp ?? inner ?? { x: defaultView?.x ?? player?.x ?? mapWidth / 2, y: defaultView?.y ?? player?.y ?? mapHeight / 2, zoom: defaultView?.zoom ?? fill };
  const clampView = (v: MapView, p = pad): MapView => {
    const z = clamp(v.zoom, minZ, maxZ);
    const axis = (c: number, size: number, a: number, b: number, map: number) => {
      const lo = (size / 2 - a) / z, hi = map - (size / 2 - b) / z;
      return lo > hi ? (lo + hi) / 2 : clamp(c, lo, hi);
    };
    return { x: axis(v.x, box.w, p.l, p.r, mapWidth), y: axis(v.y, box.h, p.t, p.b, mapHeight), zoom: z };
  };
  const view = box.w ? clampView(raw) : raw;
  const viewRef = React.useRef(view);
  viewRef.current = view;
  const setView = (v: MapView, p = pad) => {
    const c = clampView(v, p);
    if (viewProp === undefined) setInner(c);
    onViewChange?.(c);
  };
  const zoomAt = (z: number, px = box.w / 2, py = box.h / 2) => {
    const v = viewRef.current;
    const z2 = clamp(z, minZ, maxZ);
    const wx = v.x + (px - box.w / 2) / v.zoom, wy = v.y + (py - box.h / 2) / v.zoom;
    setView({ x: wx - (px - box.w / 2) / z2, y: wy - (py - box.h / 2) / z2, zoom: z2 });
  };

  // Show a point inside the free area (not under the panel, search bar or buttons), centring it if it is outside.
  const reveal = (x: number, y: number, z = viewRef.current.zoom, p = pad) => {
    const v = viewRef.current;
    const fx0 = p.l + PIN_W, fx1 = box.w - p.r - PIN_W, fy0 = p.t + PIN_H * 1.6, fy1 = box.h - p.b - 8;
    const sx = box.w / 2 + (x - v.x) * z, sy = box.h / 2 + (y - v.y) * z;
    if (sx >= fx0 && sx <= fx1 && sy >= fy0 && sy <= fy1 && z === v.zoom) return;
    const cx = (fx0 + fx1) / 2, cy = (fy0 + fy1) / 2;
    setView({ x: x - (cx - box.w / 2) / z, y: y - (cy - box.h / 2) / z, zoom: z }, p);
  };
  const panelPadFor = () => padFor(wide ? { w: Math.min(340, box.w * 0.45), h: 0 } : { w: 0, h: Math.min(box.h * 0.5, 230) });
  const select = (m: MapMarker<T> | null, opts: { fly?: boolean } = {}) => {
    if (selProp === undefined) setSelInner(m?.id ?? null);
    onMarkerSelect?.(m);
    if (m) reveal(m.x, m.y, opts.fly ? Math.max(viewRef.current.zoom, focZ) : viewRef.current.zoom, panelPadFor());
  };
  // A controlled selection from outside also brings the place into view.
  const lastSel = React.useRef(selectedId);
  React.useEffect(() => {
    if (selProp !== undefined && selProp !== lastSel.current && selected && box.w) reveal(selected.x, selected.y, viewRef.current.zoom, panelPadFor());
    lastSel.current = selectedId;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedId, box.w]);

  React.useEffect(() => {
    if (followPlayer && player && box.w) setView({ ...viewRef.current, x: player.x, y: player.y });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [followPlayer, player?.x, player?.y, box.w]);

  // Wheel zoom (needs a non-passive listener).
  const [moving, setMoving] = React.useState(false);
  const [hint, setHint] = React.useState<string | null>(null);
  const hintTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const showHint = (text: string) => { setHint(text); clearTimeout(hintTimer.current); hintTimer.current = setTimeout(() => setHint(null), 1400); };
  const coop = gestures === "cooperative";
  const coopRef = React.useRef(coop);
  coopRef.current = coop;
  const wheelTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const zoomAtRef = React.useRef(zoomAt);
  zoomAtRef.current = zoomAt;
  const showHintRef = React.useRef(showHint);
  showHintRef.current = showHint;
  React.useEffect(() => {
    const el = boxRef.current;
    if (!el) return;
    const onWheel = (e: WheelEvent) => {
      if (coopRef.current && !e.ctrlKey && !e.metaKey) {
        showHintRef.current(/Mac|iPhone|iPad/.test(navigator.platform) ? "Use ⌘ + scroll to zoom the map" : "Use Ctrl + scroll to zoom the map");
        return;
      }
      e.preventDefault();
      const r = el.getBoundingClientRect();
      setMoving(true);
      clearTimeout(wheelTimer.current);
      wheelTimer.current = setTimeout(() => setMoving(false), 160);
      zoomAtRef.current(viewRef.current.zoom * Math.exp(-e.deltaY * 0.0018), e.clientX - r.left, e.clientY - r.top);
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, []);

  // Drag to pan (with a little glide), two fingers to zoom, double-tap to zoom in, long-press for a waypoint.
  const pointers = React.useRef(new Map<number, { x: number; y: number }>());
  const touches = React.useRef(new Map<number, { x: number; y: number }>());
  const hintArm = React.useRef(false);
  const gesture = React.useRef<{ x: number; y: number; view: MapView; dist?: number; dragged: boolean } | null>(null);
  const samples = React.useRef<{ t: number; x: number; y: number }[]>([]);
  const glide = React.useRef(0);
  const suppressClick = React.useRef(false);
  const lastTap = React.useRef({ t: 0, x: 0, y: 0 });
  const press = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const local = (e: { clientX: number; clientY: number }) => {
    const r = boxRef.current!.getBoundingClientRect();
    return { x: e.clientX - r.left, y: e.clientY - r.top };
  };
  const toMap = (p: { x: number; y: number }): MapPoint => {
    const v = viewRef.current;
    return [v.x + (p.x - box.w / 2) / v.zoom, v.y + (p.y - box.h / 2) / v.zoom];
  };
  const startGesture = () => {
    const pts = [...pointers.current.values()];
    const mid = pts.length > 1 ? { x: (pts[0].x + pts[1].x) / 2, y: (pts[0].y + pts[1].y) / 2 } : pts[0];
    gesture.current = { ...mid, view: viewRef.current, dist: pts.length > 1 ? Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) : undefined, dragged: gesture.current?.dragged ?? false };
  };
  const onPointerDown = (e: React.PointerEvent) => {
    if (e.button !== 0 && e.pointerType === "mouse") return;
    if (coop && e.pointerType === "touch") {
      // Cooperative: one finger scrolls the page; the map starts moving when a second finger lands.
      touches.current.set(e.pointerId, local(e));
      if (touches.current.size < 2) { hintArm.current = true; return; }
      hintArm.current = false;
      cancelAnimationFrame(glide.current);
      pointers.current = new Map(touches.current);
      suppressClick.current = true;
      samples.current = [];
      startGesture();
      return;
    }
    cancelAnimationFrame(glide.current);
    const p = local(e);
    pointers.current.set(e.pointerId, p);
    suppressClick.current = false;
    samples.current = [{ t: performance.now(), ...p }];
    startGesture();
    clearTimeout(press.current);
    if (onWaypointChange && e.pointerType !== "mouse" && pointers.current.size === 1) {
      press.current = setTimeout(() => { if (!gesture.current?.dragged) { onWaypointChange(toMap(p)); suppressClick.current = true; } }, 550);
    }
  };
  const onPointerMove = (e: React.PointerEvent) => {
    if (coop && e.pointerType === "touch") {
      if (touches.current.has(e.pointerId)) touches.current.set(e.pointerId, local(e));
      if (hintArm.current && touches.current.size === 1) {
        const t0 = [...touches.current.values()][0];
        if (t0 && gesture.current === null) { hintArm.current = false; showHint("Use two fingers to move the map"); }
      }
    }
    if (!pointers.current.has(e.pointerId) || !gesture.current) return;
    const p = local(e);
    pointers.current.set(e.pointerId, p);
    const g = gesture.current;
    const pts = [...pointers.current.values()];
    if (pts.length > 1 && g.dist) {
      const d = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
      const mid = { x: (pts[0].x + pts[1].x) / 2, y: (pts[0].y + pts[1].y) / 2 };
      const z2 = clamp(g.view.zoom * (d / g.dist), minZ, maxZ);
      const wx = g.view.x + (g.x - box.w / 2) / g.view.zoom, wy = g.view.y + (g.y - box.h / 2) / g.view.zoom;
      g.dragged = true;
      clearTimeout(press.current);
      setMoving(true);
      setView({ x: wx - (mid.x - box.w / 2) / z2, y: wy - (mid.y - box.h / 2) / z2, zoom: z2 });
      return;
    }
    const dx = pts[0].x - g.x, dy = pts[0].y - g.y;
    if (!g.dragged && Math.hypot(dx, dy) < 6) return;
    if (!g.dragged) { g.dragged = true; clearTimeout(press.current); boxRef.current?.setPointerCapture(e.pointerId); setMoving(true); }
    samples.current = [...samples.current.filter((s) => performance.now() - s.t < 100), { t: performance.now(), ...p }];
    setView({ x: g.view.x - dx / g.view.zoom, y: g.view.y - dy / g.view.zoom, zoom: g.view.zoom });
  };
  const onPointerUp = (e: React.PointerEvent) => {
    if (coop && e.pointerType === "touch") {
      touches.current.delete(e.pointerId);
      if (!pointers.current.has(e.pointerId)) return;
      if (touches.current.size < 2) { pointers.current.clear(); gesture.current = null; setMoving(false); return; }
    }
    clearTimeout(press.current);
    const wasDrag = gesture.current?.dragged;
    pointers.current.delete(e.pointerId);
    if (wasDrag) suppressClick.current = true;
    if (pointers.current.size) { startGesture(); return; }
    gesture.current = null;
    const s = samples.current;
    const reduced = typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
    if (wasDrag && s.length > 1 && !reduced) {
      const a = s[0], b = s[s.length - 1], dt = Math.max(16, b.t - a.t);
      let vx = (b.x - a.x) / dt, vy = (b.y - a.y) / dt, last = performance.now();
      const step = (now: number) => {
        const t = now - last; last = now;
        vx *= Math.pow(0.94, t / 16); vy *= Math.pow(0.94, t / 16);
        if (Math.hypot(vx, vy) < 0.03) { setMoving(false); return; }
        const v = viewRef.current;
        setView({ x: v.x - (vx * t) / v.zoom, y: v.y - (vy * t) / v.zoom, zoom: v.zoom });
        glide.current = requestAnimationFrame(step);
      };
      if (Math.hypot(vx, vy) > 0.25) { glide.current = requestAnimationFrame(step); return; }
    }
    setMoving(false);
    // Double-tap (touch and pen; mouse uses dblclick) zooms in.
    if (!wasDrag && e.pointerType !== "mouse") {
      const p = local(e), now = performance.now();
      if (now - lastTap.current.t < 300 && Math.hypot(p.x - lastTap.current.x, p.y - lastTap.current.y) < 30) { zoomAt(viewRef.current.zoom * 2, p.x, p.y); lastTap.current.t = 0; }
      else lastTap.current = { t: now, ...p };
    }
  };
  React.useEffect(() => () => { cancelAnimationFrame(glide.current); clearTimeout(press.current); clearTimeout(wheelTimer.current); clearTimeout(hintTimer.current); }, []);

  // Filter chips.
  const [hiddenInner, setHiddenInner] = React.useState<string[]>(defaultHiddenKinds);
  const hidden = hiddenProp ?? hiddenInner;
  const hiddenSet = React.useMemo(() => new Set(hidden), [hidden]);
  const toggleKind = (k: string) => {
    const next = hidden.includes(k) ? hidden.filter((x) => x !== k) : [...hidden, k];
    if (hiddenProp === undefined) setHiddenInner(next);
    onHiddenKindsChange?.(next);
    if (selected?.kind === k && !hidden.includes(k)) select(null);
  };
  const kindIds = Object.keys(kinds ?? {});
  const showChips = (legend ?? kindIds.length > 0) && kindIds.length > 0;

  const visible = useVisible(markers, regions, hiddenSet);
  const layout = useLayout({ markers: visible, regions: regions ?? [], zoom: view.zoom, selectedId, cluster, labelZoom: lblZ, family, enabled: true });

  // Search over places that are not under clouds.
  const [query, setQuery] = React.useState("");
  const [active, setActive] = React.useState(0);
  const searchable = useVisible(markers, regions);
  const q = query.trim().toLowerCase();
  const results = q ? searchable.filter((m) => m.label.toLowerCase().includes(q)).slice(0, 6) : [];
  const listId = `${fogId}-results`;
  const pick = (m: MapMarker<T>) => {
    if (m.kind && hiddenSet.has(m.kind)) toggleKind(m.kind);
    select(m, { fly: true });
    setQuery("");
  };

  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.target !== boxRef.current) return;
    const step = 80 / view.zoom;
    const pan: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };
    if (e.key in pan) { e.preventDefault(); setView({ ...view, x: view.x + pan[e.key][0], y: view.y + pan[e.key][1] }); }
    else if (e.key === "+" || e.key === "=") { e.preventDefault(); zoomAt(view.zoom * 1.5); }
    else if (e.key === "-" || e.key === "_") { e.preventDefault(); zoomAt(view.zoom / 1.5); }
    else if (e.key === "0" || e.key === "Home") { e.preventDefault(); findMe(); }
  };
  const findMe = () => (player ? setView({ x: player.x, y: player.y, zoom: Math.max(view.zoom, focZ) }) : setView({ x: mapWidth / 2, y: mapHeight / 2, zoom: fill }));
  const onCluster = (c: Cluster<T>) => {
    const xs = c.members.map((m) => m.x), ys = c.members.map((m) => m.y);
    const spanX = Math.max(...xs) - Math.min(...xs) + 1, spanY = Math.max(...ys) - Math.min(...ys) + 1;
    const z = clamp(Math.min((box.w - pad.l) * 0.5 / spanX, (box.h - pad.b) * 0.5 / spanY, view.zoom * 3), view.zoom * 1.6, maxZ);
    setView({ x: (Math.min(...xs) + Math.max(...xs)) / 2, y: (Math.min(...ys) + Math.max(...ys)) / 2, zoom: z });
  };

  // Sheet drag on phones: pull down to close.
  const sheetDrag = React.useRef<{ y: number; dy: number } | null>(null);
  const [sheetDy, setSheetDy] = React.useState(0);

  const kindOf = (m: MapMarker<T>) => (m.kind ? kinds?.[m.kind] : undefined);
  const where = selected ? regionAt(regions, selected.x, selected.y) : undefined;

  return (
    <div ref={rootRef} data-slot="game-map" className={cn("cz-map", className)} data-layout={wide ? "wide" : "narrow"} style={{ height: typeof height === "number" ? `${height}px` : height, ...style }}
      onKeyDown={(e) => { if (e.key === "Escape" && selected && !e.defaultPrevented) { e.preventDefault(); select(null); boxRef.current?.focus(); } }}
      {...props}>
      <div
        ref={boxRef}
        className="cz-map__viewport"
        role="application"
        aria-roledescription="map"
        aria-label={`${label}. Drag or use arrow keys to move, plus and minus to zoom, 0 to find yourself.`}
        tabIndex={0}
        data-moving={moving || undefined}
        data-gestures={gestures}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
        onDoubleClick={(e) => { if ((e.target as HTMLElement).closest("button")) return; const p = local(e); zoomAt(view.zoom * 2, p.x, p.y); }}
        onContextMenu={onWaypointChange ? (e) => { e.preventDefault(); onWaypointChange(toMap(local(e))); } : undefined}
        onClickCapture={(e) => { if (suppressClick.current) { e.stopPropagation(); e.preventDefault(); suppressClick.current = false; } }}
        onClick={(e) => { if (!(e.target as HTMLElement).closest("button")) select(null); }}
        onKeyDown={onKeyDown}
      >
        <div
          className="cz-map__world"
          style={{ width: mapWidth, height: mapHeight, "--z": view.zoom, transform: `translate(${box.w / 2 - view.x * view.zoom}px, ${box.h / 2 - view.y * view.zoom}px) scale(${view.zoom})` } as React.CSSProperties}
        >
          <MapLayer
            mapWidth={mapWidth} mapHeight={mapHeight} background={background} regions={regions} paths={paths} player={player} waypoint={waypoint} kinds={kinds}
            layout={layout} selectedId={selectedId} interactive onMarker={(m) => select(selectedId === m.id ? null : m)} onCluster={onCluster}
            renderMarker={renderMarker} lockedName={lockedName} fogId={fogId}
          />
        </div>
      </div>

      {(search || showChips) && (
        <div ref={topRef} className="cz-map__top">
          {search ? (
            <div className="cz-map__search">
              <svg viewBox="0 0 24 24" aria-hidden className="cz-map__search-icon"><circle cx="10.5" cy="10.5" r="6.5" fill="none" stroke="currentColor" strokeWidth="2.6" /><path d="m15.5 15.5 5 5" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" /></svg>
              <input
                type="search"
                role="combobox"
                aria-expanded={!!q}
                aria-controls={listId}
                aria-activedescendant={results[active] ? `${listId}-${results[active].id}` : undefined}
                aria-autocomplete="list"
                placeholder={typeof search === "string" ? search : "Search places"}
                aria-label="Search places"
                value={query}
                onChange={(e) => { setQuery(e.target.value); setActive(0); }}
                onKeyDown={(e) => {
                  if (e.key === "ArrowDown") { e.preventDefault(); setActive((a) => Math.min(results.length - 1, a + 1)); }
                  else if (e.key === "ArrowUp") { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
                  else if (e.key === "Enter" && results[active]) { e.preventDefault(); pick(results[active]); }
                  else if (e.key === "Escape" && query) { e.preventDefault(); e.stopPropagation(); setQuery(""); }
                }}
              />
              {query && <button type="button" className="cz-map__search-clear" aria-label="Clear search" onClick={() => setQuery("")}>×</button>}
              {q && (
                <ul id={listId} className="cz-map__results" role="listbox" aria-label="Places">
                  {results.length ? results.map((m, i) => (
                    <li key={m.id} id={`${listId}-${m.id}`} role="option" aria-selected={i === active} data-active={i === active || undefined} onPointerDown={(e) => e.preventDefault()} onClick={() => pick(m)}>
                      <span className="cz-map__results-icon" style={{ "--kc": m.color ?? kindOf(m)?.color ?? "var(--cz-primary)" } as React.CSSProperties}><GameIcon icon={m.icon ?? kindOf(m)?.icon} alt="" /></span>
                      <span className="cz-map__results-text">
                        <span>{m.label}</span>
                        <small>{[kindOf(m)?.label, regionAt(regions, m.x, m.y)?.name].filter(Boolean).join(" · ")}</small>
                      </span>
                    </li>
                  )) : <li className="cz-map__results-empty" role="presentation">No places found</li>}
                </ul>
              )}
            </div>
          ) : null}
          {showChips && (
            <div className="cz-map__chips" role="group" aria-label="Show on map">
              {kindIds.map((k) => (
                <button key={k} type="button" className="cz-map__chip" aria-pressed={!hiddenSet.has(k)} onClick={() => toggleKind(k)} style={{ "--kc": kinds![k].color ?? "var(--cz-primary)" } as React.CSSProperties}>
                  <span className="cz-map__chip-icon"><GameIcon icon={kinds![k].icon} alt="" /></span>
                  {kinds![k].label}
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      {selected && (
        <div
          ref={panelRef}
          className="cz-map__panel"
          role="dialog"
          aria-label={selected.label}
          style={sheetDy ? { translate: `0 ${sheetDy}px`, transition: "none" } : undefined}
        >
          {!wide && (
            <div
              className="cz-map__handle"
              aria-hidden
              onPointerDown={(e) => { sheetDrag.current = { y: e.clientY, dy: 0 }; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); }}
              onPointerMove={(e) => { if (sheetDrag.current) { sheetDrag.current.dy = Math.max(0, e.clientY - sheetDrag.current.y); setSheetDy(sheetDrag.current.dy); } }}
              onPointerUp={() => { const d = sheetDrag.current?.dy ?? 0; sheetDrag.current = null; setSheetDy(0); if (d > 70) select(null); }}
              onPointerCancel={() => { sheetDrag.current = null; setSheetDy(0); }}
            ><span /></div>
          )}
          <button type="button" className="cz-map__panel-close" aria-label="Close" onClick={() => { select(null); boxRef.current?.focus(); }}>×</button>
          {renderDetails ? renderDetails(selected) : (
            <>
              {selected.image != null && (
                <div className="cz-map__panel-image">{typeof selected.image === "string" ? <img src={selected.image} alt="" /> : selected.image}</div>
              )}
              <div className="cz-map__panel-head">
                <span className="cz-map__panel-icon" style={{ "--kc": selected.color ?? kindOf(selected)?.color ?? "var(--cz-primary)" } as React.CSSProperties}>
                  <GameIcon icon={selected.icon ?? kindOf(selected)?.icon} alt="" />
                </span>
                <div className="cz-map__panel-title">
                  <h3>{selected.label}</h3>
                  <small>{[kindOf(selected)?.label, where?.discovered !== false ? where?.name : undefined].filter(Boolean).join(" · ")}</small>
                </div>
              </div>
              {selected.subtitle != null && <div className="cz-map__panel-sub">{selected.subtitle}</div>}
              {markerActions && <div className="cz-map__panel-actions">{markerActions(selected)}</div>}
              {selected.description != null && <div className="cz-map__panel-desc">{selected.description}</div>}
            </>
          )}
        </div>
      )}

      {controls && (
        <div className="cz-map__controls" style={!wide && selected ? { bottom: panelSize.h + 12 } : undefined}>
          <button type="button" className="cz-map__fab" aria-label={player ? "Find me" : "Show the whole map"} onClick={findMe}>
            <svg viewBox="0 0 24 24" aria-hidden><circle cx="12" cy="12" r="6.5" fill="none" stroke="currentColor" strokeWidth="2.4" /><circle cx="12" cy="12" r="2.4" fill="currentColor" /><path d="M12 2v3.5M12 18.5V22M2 12h3.5M18.5 12H22" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" /></svg>
          </button>
          <div className="cz-map__zoom" role="group" aria-label="Zoom">
            <button type="button" aria-label="Zoom in" onClick={() => zoomAt(view.zoom * 1.5)} disabled={view.zoom >= maxZ - 1e-6}>+</button>
            <button type="button" aria-label="Zoom out" onClick={() => zoomAt(view.zoom / 1.5)} disabled={view.zoom <= minZ + 1e-6}>−</button>
          </div>
        </div>
      )}
      {scale && !(selected && !wide) && <div className="cz-map__scale-wrap" style={selected && wide ? { left: panelSize.w + 24 } : undefined}><ScaleBar zoom={view.zoom} perUnit={scale.perUnit} unit={scale.unit} /></div>}
      {hint && <div className="cz-map__hint" role="status">{hint}</div>}
      {children}
    </div>
  );
}

/* ---------- MiniMap ---------- */

type MiniMapProps<T> = Omit<React.ComponentProps<"div">, "children"> & MapData<T> & {
  /** Box size in px. Default 168. */
  size?: number;
  shape?: "circle" | "square";
  /** Screen px per map unit. Default 1. */
  zoom?: number;
  defaultZoom?: number;
  onZoomChange?: (zoom: number) => void;
  /** Default 0.4 and 3. */
  minZoom?: number;
  maxZoom?: number;
  /** Centre. Default: the player. */
  center?: MapPoint;
  /** Turn the map so the player's heading points up. Default false (north up). */
  rotate?: boolean;
  /** North marker on the rim. Default true. */
  compass?: boolean;
  /** Small + and − buttons. Default true. */
  zoomControls?: boolean;
  /** Name of the region under the player. Default true. */
  showRegion?: boolean;
  /** Click or Enter on the map, e.g. open the full GameMap. */
  onOpen?: () => void;
  lockedName?: React.ReactNode;
  /** Overlay, e.g. a clock or the weather. */
  children?: React.ReactNode;
  label?: string;
};

function MiniMap<T = unknown>({
  mapWidth, mapHeight, background, markers, regions, paths, player, waypoint, kinds, size = 168, shape = "circle", zoom: zoomProp, defaultZoom = 1, onZoomChange,
  minZoom = 0.4, maxZoom = 3, center, rotate = false, compass = true, zoomControls = true, showRegion = true, onOpen, lockedName = "???", children,
  label = "Minimap", className, style, ...props
}: MiniMapProps<T>) {
  const [zInner, setZInner] = React.useState(defaultZoom);
  const zoom = clamp(zoomProp ?? zInner, minZoom, maxZoom);
  const setZoom = (z: number) => {
    const c = clamp(z, minZoom, maxZoom);
    if (zoomProp === undefined) setZInner(c);
    onZoomChange?.(c);
  };
  const fogId = `cz-fog-${React.useId().replace(/:/g, "")}`;
  const [cx, cy] = center ?? (player ? [player.x, player.y] : [mapWidth / 2, mapHeight / 2]);
  const turn = rotate ? player?.heading ?? 0 : 0;
  const half = size / 2;
  const region = showRegion ? regionAt(regions, cx, cy) : undefined;
  const visible = useVisible(markers, regions);
  const layout = useLayout({ markers: visible, regions: [], zoom, selectedId: null, cluster: 0, labelZoom: Infinity, family: "", enabled: false });

  const rad = (-turn * Math.PI) / 180;
  const edge = half - 13;
  const targets = [
    ...visible.filter((m) => m.tracked).map((m) => ({ id: m.id, label: m.label, x: m.x, y: m.y, color: m.color ?? (m.kind ? kinds?.[m.kind]?.color : undefined), icon: m.icon ?? (m.kind ? kinds?.[m.kind]?.icon : undefined) })),
    ...(waypoint ? [{ id: "__waypoint", label: "Waypoint", x: waypoint[0], y: waypoint[1], color: "var(--cz-danger)", icon: <Flag /> }] : []),
  ];
  const arrows = targets.flatMap((m) => {
    const dx = (m.x - cx) * zoom, dy = (m.y - cy) * zoom;
    const rx = dx * Math.cos(rad) - dy * Math.sin(rad), ry = dx * Math.sin(rad) + dy * Math.cos(rad);
    const far = shape === "circle" ? Math.hypot(rx, ry) : Math.max(Math.abs(rx), Math.abs(ry));
    if (far <= edge) return [];
    const k = edge / far;
    return [{ ...m, ax: half + rx * k, ay: half + ry * k, angle: (Math.atan2(ry, rx) * 180) / Math.PI + 90 }];
  });
  const where = region ? (region.discovered === false ? "unexplored" : region.name) : "";

  const world = (
    <div
      className="cz-minimap__world"
      style={{ width: mapWidth, height: mapHeight, "--z": zoom, transform: `translate(${half}px, ${half}px) rotate(${-turn}deg) scale(${zoom}) translate(${-cx}px, ${-cy}px)` } as React.CSSProperties}
    >
      <MapLayer
        mapWidth={mapWidth} mapHeight={mapHeight} background={background} regions={regions} paths={paths} player={player} waypoint={waypoint} kinds={kinds}
        layout={layout} interactive={false} lockedName={lockedName} fogId={fogId} pinScale={0.6} counterRotate={turn}
      />
    </div>
  );

  return (
    <div data-slot="minimap" className={cn("cz-minimap", className)} data-shape={shape} style={{ "--mm": `${size}px`, ...style } as React.CSSProperties} {...props}>
      {onOpen ? (
        <button type="button" className="cz-minimap__view" aria-label={`${label}${where ? `, ${where}` : ""}. Open the map`} onClick={onOpen}>{world}</button>
      ) : (
        <div className="cz-minimap__view" role="img" aria-label={`${label}${where ? `, ${where}` : ""}`}>{world}</div>
      )}
      {arrows.map((a) => (
        <span key={a.id} className="cz-minimap__arrow" title={a.label} style={{ left: a.ax, top: a.ay, "--a": `${a.angle}deg`, "--kc": a.color ?? "var(--cz-reward)" } as React.CSSProperties}>
          <span className="cz-minimap__arrow-tip" />
          <span className="cz-minimap__arrow-icon"><GameIcon icon={a.icon} alt="" /></span>
        </span>
      ))}
      {compass && (
        <span className="cz-minimap__north" aria-hidden style={{ "--a": `${-turn}deg` } as React.CSSProperties}><span>N</span></span>
      )}
      {zoomControls && (
        <span className="cz-minimap__zoom">
          <button type="button" aria-label="Zoom in minimap" onClick={() => setZoom(zoom * 1.4)} disabled={zoom >= maxZoom}>+</button>
          <button type="button" aria-label="Zoom out minimap" onClick={() => setZoom(zoom / 1.4)} disabled={zoom <= minZoom}>−</button>
        </span>
      )}
      {region && <span className="cz-minimap__region">{region.discovered === false ? lockedName : region.name}</span>}
      {children}
    </div>
  );
}

export { GameMap, MiniMap };
export type { GameMapProps, MiniMapProps };
```

npm: `import { GameMap, MiniMap } from "@0xtrou/cozy-ui"` (after `npm install @0xtrou/cozy-ui` and `import "@0xtrou/cozy-ui/styles.css"`).
