import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from "react";
import {
  Cartesian2,
  Cartesian3,
  BingMapsImageryProvider,
  BingMapsStyle,
  Color,
  Credit,
  Cesium3DTileset,
  Cesium3DTileStyle,
  CesiumTerrainProvider,
  CallbackProperty,
  Cartographic,
  ConstantPositionProperty,
  CustomDataSource,
  DefaultProxy,
  DistanceDisplayCondition,
  EllipsoidTerrainProvider,
  Entity,
  HeightReference,
  HeadingPitchRange,
  HorizontalOrigin,
  ImageryLayer,
  JulianDate,
  LabelGraphics,
  Matrix4,
  Math as CesiumMath,
  PolygonHierarchy,
  PointGraphics,
  Resource,
  sampleTerrainMostDetailed,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  SunLight,
  VerticalOrigin,
  Viewer,
} from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
import sceneFixture from "../../../registry/fixtures/map/map-operational-v0.1.json";
import { spiralSurfaceFrame, type GeodeticRadians } from "./mapSpiralMath.js";
import { mapRuntimeEntityId, type MapRuntimeBinding, type MapRuntimeFact } from "./useMapDataProductRuntime.js";

type Position = [number, number, number?];
const MAX_SPIRAL_SUBSTEPS_PER_FRAME = 300;
const TERRAIN_SAMPLE_TIMEOUT_MS = 12_000;
type PinPresentation = {
  variant: "elevated-spike";
  stemHeightMeters: number;
  headSizePx: number;
  stemWidthPx: number;
  outlineColor: string;
  outlineOpacity: number;
  outlineWidthPx: number;
  labelOffsetX: number;
  labelOffsetY: number;
  pinHideCameraHeightMeters?: number;
  labelHideCameraHeightMeters?: number;
};
type MapStyleProfile = {
  id: string;
  kind: string;
  color?: string;
  opacity?: number;
  size?: number;
  pinPresentation?: PinPresentation;
};
type RuntimeConfig = {
  cesiumVersion: string;
  provider: string;
  ionReady: boolean;
  gatewayReady: boolean;
  osmBuildingsReady: boolean;
  gaussianSplatsReady: boolean;
  gaussianAssetId?: string | null;
  assetEndpointBase: string;
  resourceProxyBase?: string | null;
  gatewayHealthUrl?: string | null;
};

export type MapGatewayHealth = {
  cache?: {
    mode?: string;
    writePolicy?: string;
    entries?: number;
    bytes?: number;
    maxBytes?: number;
    atCapacity?: boolean;
    persistent?: boolean;
  };
  diagnostics?: {
    cacheHits?: number;
    cacheMisses?: number;
    cacheRefreshes?: number;
    upstreamRequests?: number;
    egressRequests?: number;
    upstreamFailures?: number;
    slowUpstreamRequests?: number;
    lastFailure?: string | null;
    lastFailureAt?: string | null;
  };
  ionConfigured?: boolean;
};

type MapProviderState = "loading" | "ready" | "error" | "not-configured";

// Provider loading must be observable independently. In particular, imagery
// is optional for scene construction: a Bing metadata failure must never
// prevent Cesium World Terrain from being requested and rendered.
export type MapProviderStatus = {
  imagery: MapProviderState;
  terrain: MapProviderState;
  buildings: MapProviderState;
  errors: Partial<Record<"imagery" | "terrain" | "buildings", string>>;
};

type IonAssetEndpoint = {
  assetId: string;
  type: "TERRAIN" | "3DTILES" | "IMAGERY";
  url?: string;
  credentialMode?: "gateway";
  externalType?: "BING";
  options?: { url?: string; mapStyle?: string };
  attributions: Array<{ html?: string; collapsible?: boolean }>;
};

export type MapPresentation = {
  imagerySource: "cesium-live";
  imageryVisible: boolean;
  cacheEnabled: boolean;
  cacheNoOverwrite: boolean;
  terrainEnabled: boolean;
  terrainExaggeration: number;
  monochrome: boolean;
  monochromeColor: string;
  imageryGamma: number;
  imageryHue: number;
  imageryAlpha: number;
  globeColor: string;
  backgroundColor: string;
  atmosphereEnabled: boolean;
  atmosphereHue: number;
  atmosphereSaturation: number;
  atmosphereBrightness: number;
  fogEnabled: boolean;
  fogDensity: number;
  sunEnabled: boolean;
  sunHour: number;
  sunIntensity: number;
  shadowsEnabled: boolean;
  buildingsVisible: boolean;
  buildingsColor: string;
  buildingsOpacity: number;
  buildingsDetail: number;
  imageryBrightness: number;
  imageryContrast: number;
  imagerySaturation: number;
  gridVisible: boolean;
  gridLodEnabled: boolean;
  gridHeightMeters: number;
  gridLod1MaxHeightKm: number;
  gridLod1StepKm: number;
  gridLod2MaxHeightKm: number;
  gridLod2StepKm: number;
  gridLod3StepKm: number;
  gridRadiusKm: number;
  gridLineWidth: number;
  gridColor: string;
  gridOpacity: number;
  gridDotsEnabled: boolean;
  gridDotsSize: number;
  gridDotsColor: string;
  gridDotsOpacity: number;
  cacheRefresh: boolean;
};

export type MapCameraView = {
  longitude: number;
  latitude: number;
  height: number;
  heading: number;
  pitch: number;
  roll: number;
};

export type CameraSpiralConfig = {
  heightAboveGroundMeters: number;
  speedMetersPerSecond: number;
  pitchMetersPerTurn: number;
};

export type CameraSpiralState = {
  running: boolean;
  reason?: "stopped" | "mode_disabled" | "renderer_restarted" | "page_hidden" | "render_error" | "spiral_extent_limit" | "spiral_runtime_error" | "terrain_sampling_error";
};

export type CesiumMapRendererHandle = {
  startSpiralAnimation: (config: CameraSpiralConfig) => boolean;
  stopSpiralAnimation: (reason?: CameraSpiralState["reason"]) => void;
  getCameraView: () => MapCameraView | null;
};

type TerrainRouteSample = {
  distanceMeters: number;
  heightMeters: number;
};

type SpiralSession = {
  viewer: Viewer;
  origin: GeodeticRadians;
  initialHeading: number;
  pitch: number;
  roll: number;
  config: CameraSpiralConfig;
  surfaceDistanceMeters: number;
  lastTimestamp: number | null;
  pendingElapsedSeconds: number;
  requestId: number | null;
  previousCameraInputsEnabled: boolean;
  terrainProvider: CesiumTerrainProvider | null;
  terrainSamples: TerrainRouteSample[];
  terrainSamplePending: boolean;
  terrainSampleExhausted: boolean;
  terrainSampleFailures: number;
  terrainRequestGeneration: number;
  terrainRetryAt: number;
  terrainSampleSpacingMeters: number;
};

const toCartesian = ([longitude, latitude, height = 0]: Position) => Cartesian3.fromDegrees(longitude, latitude, height);
const toCartesianArray = (positions: Position[]) => positions.map(toCartesian);
const accent = Color.fromCssColorString("#ff2f92");
const violet = Color.fromCssColorString("#8f72dc");
const clamp = (value: number, minimum: number, maximum: number) => Math.max(minimum, Math.min(maximum, value));
const defaultElevatedPin: PinPresentation = {
  variant: "elevated-spike",
  stemHeightMeters: 120,
  headSizePx: 8,
  stemWidthPx: 2,
  outlineColor: "#0c0d12",
  outlineOpacity: 0.6,
  outlineWidthPx: 1,
  labelOffsetX: 10,
  labelOffsetY: 0,
};

function showBelowCameraHeight(viewer: Viewer, limit?: number) {
  if (!limit) return true;
  return new CallbackProperty(() => Number(viewer.camera.positionCartographic?.height || 0) <= limit, false);
}

function getCameraView(viewer: Viewer): MapCameraView {
  const position = viewer.camera.positionCartographic;
  return {
    longitude: CesiumMath.toDegrees(position.longitude),
    latitude: CesiumMath.toDegrees(position.latitude),
    height: position.height,
    heading: viewer.camera.heading,
    pitch: viewer.camera.pitch,
    roll: viewer.camera.roll,
  };
}

function interpolateTerrainRouteHeight(samples: TerrainRouteSample[], distanceMeters: number) {
  if (samples.length === 0) return null;
  if (distanceMeters === samples[0].distanceMeters) return samples[0].heightMeters;
  for (let index = 1; index < samples.length; index += 1) {
    const upper = samples[index];
    if (distanceMeters > upper.distanceMeters) continue;
    const lower = samples[index - 1];
    const span = upper.distanceMeters - lower.distanceMeters;
    if (span <= 0) return upper.heightMeters;
    const progress = clamp((distanceMeters - lower.distanceMeters) / span, 0, 1);
    return lower.heightMeters + (upper.heightMeters - lower.heightMeters) * progress;
  }
  return null;
}

function addFixtureEntities(viewer: Viewer) {
  const styleProfiles = new Map<string, MapStyleProfile>(
    (sceneFixture.styleProfiles as unknown as MapStyleProfile[]).map((profile) => [profile.id, profile]),
  );
  for (const place of sceneFixture.scene.places) {
    viewer.entities.add({
      id: place.id,
      position: toCartesian(place.position as Position),
      label: {
        text: place.label.text,
        font: "700 28px Arial",
        fillColor: Color.WHITE,
        outlineColor: Color.BLACK.withAlpha(0.8),
        outlineWidth: 4,
        style: 2,
        distanceDisplayCondition: new DistanceDisplayCondition(100_000, 50_000_000),
      },
    });
  }

  for (const route of sceneFixture.scene.routes) {
    viewer.entities.add({
      id: route.id,
      polyline: {
        positions: toCartesianArray(route.coordinates as Position[]),
        width: 4,
        material: accent.withAlpha(0.92),
        clampToGround: true,
      },
    });
  }

  for (const track of sceneFixture.scene.tracks) {
    viewer.entities.add({
      id: track.id,
      polyline: {
        positions: toCartesianArray(track.coordinates as Position[]),
        width: 2,
        material: violet.withAlpha(0.88),
        clampToGround: true,
      },
    });
  }

  for (const zone of sceneFixture.scene.zones) {
    const ring = zone.geometry.type === "Polygon" ? zone.geometry.coordinates[0] : zone.geometry.coordinates[0][0];
    viewer.entities.add({
      id: zone.id,
      polygon: {
        hierarchy: new PolygonHierarchy(toCartesianArray(ring as Position[])),
        material: accent.withAlpha(0.2),
      },
    });
    viewer.entities.add({
      id: `${zone.id}:boundary`,
      polyline: {
        positions: toCartesianArray(ring as Position[]),
        width: 2,
        material: accent.withAlpha(0.78),
        clampToGround: true,
      },
    });
  }

  for (const object of sceneFixture.scene.movingObjects) {
    if (object.trace) {
      viewer.entities.add({
        id: `${object.id}:trace`,
        polyline: {
          positions: toCartesianArray(object.trace as Position[]),
          width: 2,
          material: accent.withAlpha(0.52),
          clampToGround: true,
        },
      });
    }
    const pinStyle = styleProfiles.get(object.pinStyleProfileId);
    const pin = pinStyle?.pinPresentation ?? defaultElevatedPin;
    const pinColor = Color.fromCssColorString(pinStyle?.color || "#ff2f92").withAlpha(pinStyle?.opacity ?? 1);
    const outlineColor = Color.fromCssColorString(pin.outlineColor).withAlpha(pin.outlineOpacity);
    const [longitude, latitude] = object.position as Position;
    const base = Cartesian3.fromDegrees(longitude, latitude, 0);
    const top = Cartesian3.fromDegrees(longitude, latitude, pin.stemHeightMeters);
    viewer.entities.add({
      id: object.id,
      position: top,
      polyline: {
        positions: [base, top],
        width: pin.stemWidthPx,
        material: pinColor,
        show: showBelowCameraHeight(viewer, pin.pinHideCameraHeightMeters),
      },
      point: {
        pixelSize: pin.headSizePx,
        color: pinColor,
        outlineColor,
        outlineWidth: pin.outlineWidthPx,
        show: showBelowCameraHeight(viewer, pin.pinHideCameraHeightMeters),
      },
      label: {
        text: object.label.text,
        font: "700 13px Arial",
        fillColor: Color.WHITE,
        showBackground: true,
        backgroundColor: Color.BLACK.withAlpha(0.72),
        backgroundPadding: new Cartesian2(10, 7),
        pixelOffset: new Cartesian2(pin.labelOffsetX, pin.labelOffsetY),
        horizontalOrigin: HorizontalOrigin.LEFT,
        verticalOrigin: VerticalOrigin.BOTTOM,
        heightReference: HeightReference.NONE,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        show: showBelowCameraHeight(viewer, pin.labelHideCameraHeightMeters),
      },
    });
  }

  for (const station of sceneFixture.scene.stations) {
    viewer.entities.add({
      id: station.id,
      position: toCartesian(station.position as Position),
      point: { pixelSize: station.stationType === "metro" ? 21 : 18, color: violet, outlineColor: Color.WHITE, outlineWidth: 3 },
      label: {
        text: station.label.text,
        font: "700 14px Arial",
        fillColor: Color.WHITE,
        showBackground: true,
        backgroundColor: Color.BLACK.withAlpha(0.72),
        backgroundPadding: new Cartesian2(10, 7),
        pixelOffset: new Cartesian2(0, -33),
      },
    });
  }
}

function runtimeDisplayLabel(fact: MapRuntimeFact) {
  for (const key of ["label", "name", "title", "subject_id"]) {
    const value = fact.attributes[key];
    if (typeof value === "string" && value.trim()) return value.trim();
  }
  return fact.sourceId;
}

function runtimePointColor(fact: MapRuntimeFact) {
  // This is a semantic default for the generic Map entity-stream adapter,
  // not a provider style. A renderer-neutral style profile can refine it
  // later without changing a data product or its L2 workflow.
  return fact.semanticType === "map.moving_object" ? accent : violet;
}

function syncRuntimeDataSources(
  viewer: Viewer,
  dataSources: Map<string, CustomDataSource>,
  bindings: MapRuntimeBinding[],
) {
  const activeBindings = new Map(bindings
    .filter((binding) => binding.slotId === "points")
    .map((binding) => [binding.bindingId, binding]));

  for (const [bindingId, dataSource] of dataSources) {
    if (activeBindings.has(bindingId)) continue;
    viewer.dataSources.remove(dataSource, true);
    dataSources.delete(bindingId);
  }

  for (const binding of activeBindings.values()) {
    let dataSource = dataSources.get(binding.bindingId);
    if (!dataSource) {
      dataSource = new CustomDataSource(`nodedc-map-slot:${binding.bindingId}`);
      viewer.dataSources.add(dataSource);
      dataSources.set(binding.bindingId, dataSource);
    }
    const wanted = new Set<string>();
    for (const fact of binding.facts) {
      if (!fact.geometry) continue;
      const entityId = mapRuntimeEntityId(binding.bindingId, fact);
      wanted.add(entityId);
      const [longitude, latitude] = fact.geometry.coordinates;
      const color = runtimePointColor(fact);
      const label = runtimeDisplayLabel(fact);
      const entity = dataSource.entities.getById(entityId) ?? dataSource.entities.add({ id: entityId });
      entity.name = label;
      entity.position = new ConstantPositionProperty(Cartesian3.fromDegrees(longitude, latitude, 0));
      entity.point = new PointGraphics({
        pixelSize: 10,
        color,
        outlineColor: Color.fromCssColorString("#0c0d12").withAlpha(0.72),
        outlineWidth: 2,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
      });
      entity.label = new LabelGraphics({
        text: label,
        font: "700 13px Arial",
        fillColor: Color.WHITE,
        showBackground: true,
        backgroundColor: Color.BLACK.withAlpha(0.72),
        backgroundPadding: new Cartesian2(10, 7),
        pixelOffset: new Cartesian2(10, 0),
        horizontalOrigin: HorizontalOrigin.LEFT,
        verticalOrigin: VerticalOrigin.BOTTOM,
        heightReference: HeightReference.NONE,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
      });
    }
    for (const entity of [...dataSource.entities.values]) {
      if (typeof entity.id === "string" && !wanted.has(entity.id)) dataSource.entities.remove(entity);
    }
  }
  viewer.scene.requestRender();
}

function rebuildElevatedGrid(viewer: Viewer, dataSource: CustomDataSource, presentation: MapPresentation) {
  const entities = dataSource.entities;
  entities.removeAll();
  if (!presentation.gridVisible) return;

  const cameraHeightKm = Math.max(0, Number(viewer.camera.positionCartographic?.height || 0) / 1000);
  const stepKm = !presentation.gridLodEnabled || cameraHeightKm <= presentation.gridLod1MaxHeightKm
    ? presentation.gridLod1StepKm
    : cameraHeightKm <= presentation.gridLod2MaxHeightKm
      ? presentation.gridLod2StepKm
      : presentation.gridLod3StepKm;
  const safeStepKm = clamp(stepKm, 0.25, 100);
  const safeRadiusKm = clamp(presentation.gridRadiusKm, safeStepKm, 150);
  const stepsPerSide = Math.min(32, Math.max(1, Math.floor(safeRadiusKm / safeStepKm)));
  const center = sceneFixture.viewport.center as Position;
  const latitude = center[1];
  const longitude = center[0];
  const metersPerLatitudeDegree = 110_574;
  const metersPerLongitudeDegree = Math.max(1, 111_320 * Math.cos(CesiumMath.toRadians(latitude)));
  const stepMeters = safeStepKm * 1000;
  const radiusMeters = stepsPerSide * stepMeters;
  const deltaLatitude = stepMeters / metersPerLatitudeDegree;
  const deltaLongitude = stepMeters / metersPerLongitudeDegree;
  const radiusLatitude = radiusMeters / metersPerLatitudeDegree;
  const radiusLongitude = radiusMeters / metersPerLongitudeDegree;
  const lineColor = Color.fromCssColorString(presentation.gridColor).withAlpha(clamp(presentation.gridOpacity / 100, 0, 1));
  const dotColor = Color.fromCssColorString(presentation.gridDotsColor).withAlpha(clamp(presentation.gridDotsOpacity / 100, 0, 1));
  const elevation = Math.max(0, presentation.gridHeightMeters);

  for (let index = -stepsPerSide; index <= stepsPerSide; index += 1) {
    const nextLatitude = latitude + index * deltaLatitude;
    const nextLongitude = longitude + index * deltaLongitude;
    entities.add({
      polyline: {
        positions: [
          Cartesian3.fromDegrees(longitude - radiusLongitude, nextLatitude, elevation),
          Cartesian3.fromDegrees(longitude + radiusLongitude, nextLatitude, elevation),
        ],
        width: clamp(presentation.gridLineWidth, 1, 8),
        material: lineColor,
      },
    });
    entities.add({
      polyline: {
        positions: [
          Cartesian3.fromDegrees(nextLongitude, latitude - radiusLatitude, elevation),
          Cartesian3.fromDegrees(nextLongitude, latitude + radiusLatitude, elevation),
        ],
        width: clamp(presentation.gridLineWidth, 1, 8),
        material: lineColor,
      },
    });
  }

  if (!presentation.gridDotsEnabled) return;
  const dotStride = Math.max(1, Math.ceil((stepsPerSide * 2 + 1) / 25));
  for (let row = -stepsPerSide; row <= stepsPerSide; row += dotStride) {
    for (let column = -stepsPerSide; column <= stepsPerSide; column += dotStride) {
      entities.add({
        position: Cartesian3.fromDegrees(longitude + column * deltaLongitude, latitude + row * deltaLatitude, elevation),
        point: {
          pixelSize: clamp(presentation.gridDotsSize, 2, 28),
          color: dotColor,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
      });
    }
  }
}

function applyPresentation(
  viewer: Viewer,
  imageryLayer: ImageryLayer | null,
  buildings: Cesium3DTileset | null,
  terrain: { world: CesiumTerrainProvider | null; ellipsoid: EllipsoidTerrainProvider },
  presentation: MapPresentation,
) {
  if (imageryLayer) {
    imageryLayer.show = presentation.imageryVisible && !presentation.monochrome;
    imageryLayer.brightness = presentation.imageryBrightness / 100;
    imageryLayer.contrast = presentation.imageryContrast / 100;
    imageryLayer.saturation = presentation.imagerySaturation / 100;
    imageryLayer.gamma = presentation.imageryGamma / 100;
    imageryLayer.hue = CesiumMath.toRadians(presentation.imageryHue);
    imageryLayer.alpha = presentation.imageryAlpha / 100;
  }
  if (buildings) {
    buildings.show = presentation.buildingsVisible;
    buildings.maximumScreenSpaceError = presentation.buildingsDetail;
    buildings.style = new Cesium3DTileStyle({
      color: `color('${presentation.buildingsColor}', ${presentation.buildingsOpacity})`,
    });
  }
  viewer.terrainProvider = presentation.terrainEnabled && terrain.world ? terrain.world : terrain.ellipsoid;
  viewer.scene.globe.show = true;
  viewer.scene.globe.baseColor = Color.fromCssColorString(presentation.monochrome ? presentation.monochromeColor : presentation.globeColor);
  viewer.scene.globe.enableLighting = presentation.sunEnabled;
  (viewer.scene as unknown as { verticalExaggeration?: number }).verticalExaggeration = clamp(presentation.terrainExaggeration, 0.25, 3);
  viewer.scene.backgroundColor = Color.fromCssColorString(presentation.backgroundColor);
  viewer.scene.fog.enabled = presentation.fogEnabled;
  viewer.scene.fog.density = clamp(presentation.fogDensity / 10_000, 0, 0.01);
  const atmosphere = viewer.scene.skyAtmosphere;
  if (atmosphere) {
    atmosphere.show = presentation.atmosphereEnabled;
    atmosphere.hueShift = clamp(presentation.atmosphereHue / 100, -1, 1);
    atmosphere.saturationShift = clamp(presentation.atmosphereSaturation / 100, -1, 1);
    atmosphere.brightnessShift = clamp(presentation.atmosphereBrightness / 100, -1, 1);
  }
  viewer.shadows = presentation.shadowsEnabled;
  const sunDate = JulianDate.toDate(JulianDate.now());
  sunDate.setUTCHours(clamp(Math.round(presentation.sunHour), 0, 24), 0, 0, 0);
  viewer.clock.currentTime = JulianDate.fromDate(sunDate);
  viewer.clock.shouldAnimate = false;
  const sun = new SunLight();
  (sun as unknown as { intensity?: number }).intensity = clamp(presentation.sunIntensity / 100, 0, 2);
  viewer.scene.light = sun;
  viewer.scene.requestRender();
}

export const CesiumMapRenderer = forwardRef<CesiumMapRendererHandle, {
  onSelect?: (entityId: string) => void;
  onGatewayHealth?: (health: MapGatewayHealth | null) => void;
  onProviderStatus?: (status: MapProviderStatus) => void;
  onCameraChange?: (camera: MapCameraView) => void;
  onCacheRefreshConsumed?: () => void;
  onReadyChange?: (ready: boolean) => void;
  onSpiralStateChange?: (state: CameraSpiralState) => void;
  initialCamera?: MapCameraView;
  presentation: MapPresentation;
  runtimeBindings?: MapRuntimeBinding[];
}>(function CesiumMapRenderer({
  onSelect,
  onGatewayHealth,
  onProviderStatus,
  onCameraChange,
  onCacheRefreshConsumed,
  onReadyChange,
  onSpiralStateChange,
  initialCamera,
  presentation,
  runtimeBindings = [],
}, ref) {
  const containerRef = useRef<HTMLDivElement>(null);
  const creditContainerRef = useRef<HTMLDivElement>(null);
  const viewerRef = useRef<Viewer | null>(null);
  const imageryLayerRef = useRef<ImageryLayer | null>(null);
  const buildingsRef = useRef<Cesium3DTileset | null>(null);
  const terrainRef = useRef<{ world: CesiumTerrainProvider | null; ellipsoid: EllipsoidTerrainProvider } | null>(null);
  const rebuildGridRef = useRef<(() => void) | null>(null);
  const runtimeDataSourcesRef = useRef(new Map<string, CustomDataSource>());
  const presentationRef = useRef(presentation);
  const runtimeBindingsRef = useRef(runtimeBindings);
  const onSelectRef = useRef(onSelect);
  const onCameraChangeRef = useRef(onCameraChange);
  const onCacheRefreshConsumedRef = useRef(onCacheRefreshConsumed);
  const onReadyChangeRef = useRef(onReadyChange);
  const onSpiralStateChangeRef = useRef(onSpiralStateChange);
  const spiralSessionRef = useRef<SpiralSession | null>(null);

  useEffect(() => {
    onSelectRef.current = onSelect;
  }, [onSelect]);

  useEffect(() => {
    onCameraChangeRef.current = onCameraChange;
  }, [onCameraChange]);

  useEffect(() => {
    onCacheRefreshConsumedRef.current = onCacheRefreshConsumed;
  }, [onCacheRefreshConsumed]);

  useEffect(() => {
    onReadyChangeRef.current = onReadyChange;
  }, [onReadyChange]);

  useEffect(() => {
    onSpiralStateChangeRef.current = onSpiralStateChange;
  }, [onSpiralStateChange]);

  const stopSpiralAnimation = useCallback((reason: CameraSpiralState["reason"] = "stopped") => {
    const session = spiralSessionRef.current;
    if (!session) return;
    spiralSessionRef.current = null;
    if (session.requestId !== null) window.cancelAnimationFrame(session.requestId);
    if (!session.viewer.isDestroyed()) {
      session.viewer.scene.screenSpaceCameraController.enableInputs = session.previousCameraInputsEnabled;
      session.viewer.scene.requestRender();
      rebuildGridRef.current?.();
      onCameraChangeRef.current?.(getCameraView(session.viewer));
    }
    onSpiralStateChangeRef.current?.({ running: false, reason });
  }, []);

  const startSpiralAnimation = useCallback((input: CameraSpiralConfig) => {
    const viewer = viewerRef.current;
    const position = viewer?.camera.positionCartographic;
    if (!viewer || viewer.isDestroyed() || !position) return false;
    if (![input.heightAboveGroundMeters, input.speedMetersPerSecond, input.pitchMetersPerTurn].every(Number.isFinite)) return false;
    const terrainProvider = presentationRef.current.terrainEnabled ? terrainRef.current?.world ?? null : null;
    if (presentationRef.current.terrainEnabled && !terrainProvider) return false;
    const config: CameraSpiralConfig = {
      heightAboveGroundMeters: clamp(input.heightAboveGroundMeters, 10, 100_000),
      speedMetersPerSecond: clamp(input.speedMetersPerSecond, 1, 5_000),
      pitchMetersPerTurn: clamp(input.pitchMetersPerTurn, 20, 100_000),
    };
    stopSpiralAnimation("renderer_restarted");
    viewer.camera.cancelFlight();
    viewer.camera.lookAtTransform(Matrix4.IDENTITY);
    const controller = viewer.scene.screenSpaceCameraController;
    const session: SpiralSession = {
      viewer,
      origin: { longitude: position.longitude, latitude: position.latitude },
      initialHeading: Number.isFinite(viewer.camera.heading) ? viewer.camera.heading : 0,
      pitch: clamp(Number.isFinite(viewer.camera.pitch) ? viewer.camera.pitch : -Math.PI / 4, -Math.PI / 2 + 0.01, -0.05),
      roll: 0,
      config,
      surfaceDistanceMeters: 0,
      lastTimestamp: null,
      pendingElapsedSeconds: 0,
      requestId: null,
      previousCameraInputsEnabled: controller.enableInputs,
      terrainProvider,
      terrainSamples: [],
      terrainSamplePending: false,
      terrainSampleExhausted: false,
      terrainSampleFailures: 0,
      terrainRequestGeneration: 0,
      terrainRetryAt: 0,
      terrainSampleSpacingMeters: clamp(config.speedMetersPerSecond / 30, 10, 250),
    };
    controller.enableInputs = false;
    spiralSessionRef.current = session;

    const groundHeightAtDistance = (distanceMeters: number) => {
      if (!session.terrainProvider) return 0;
      // Only the most-detailed sampled route is stable enough for AGL.
      // globe.getHeight() follows the currently rendered LOD and can jump as
      // tiles refine, so it must not drive the camera altitude.
      return interpolateTerrainRouteHeight(session.terrainSamples, distanceMeters);
    };

    const applyFrame = (frame: ReturnType<typeof spiralSurfaceFrame>, rawGround: number) => {
      if (spiralSessionRef.current !== session || viewer.isDestroyed()) return;
      const scene = viewer.scene as unknown as {
        verticalExaggeration?: number;
        verticalExaggerationRelativeHeight?: number;
      };
      const terrainActive = Boolean(session.terrainProvider);
      const exaggeration = terrainActive && Number.isFinite(scene.verticalExaggeration) ? Number(scene.verticalExaggeration) : 1;
      const relativeHeight = terrainActive && Number.isFinite(scene.verticalExaggerationRelativeHeight)
        ? Number(scene.verticalExaggerationRelativeHeight)
        : 0;
      const renderedGround = relativeHeight + (rawGround - relativeHeight) * exaggeration;
      viewer.camera.setView({
        destination: Cartesian3.fromRadians(
          frame.longitude,
          frame.latitude,
          renderedGround + session.config.heightAboveGroundMeters,
        ),
        orientation: {
          heading: frame.tangentHeading,
          pitch: session.pitch,
          roll: session.roll,
        },
      });
      viewer.scene.requestRender();
    };

    const requestTerrainSamples = () => {
      if (!session.terrainProvider || session.terrainSamplePending || spiralSessionRef.current !== session) return;
      if (Date.now() < session.terrainRetryAt) return;
      const lastSample = session.terrainSamples.at(-1);
      // Prefetch before the camera reaches the buffer tail. At normal and
      // high speeds this leaves roughly three seconds for Gateway/VPN latency.
      if (lastSample && lastSample.distanceMeters - session.surfaceDistanceMeters > session.terrainSampleSpacingMeters * 90) return;
      const startDistance = lastSample ? lastSample.distanceMeters + session.terrainSampleSpacingMeters : 0;
      const distances: number[] = [];
      const positions: Cartographic[] = [];
      let reachedExtent = false;
      for (let index = 0; index < 120; index += 1) {
        const distanceMeters = startDistance + index * session.terrainSampleSpacingMeters;
        try {
          const frame = spiralSurfaceFrame(
            session.origin,
            session.initialHeading,
            distanceMeters,
            session.config.pitchMetersPerTurn,
          );
          distances.push(distanceMeters);
          positions.push(new Cartographic(frame.longitude, frame.latitude, 0));
        } catch (error) {
          if (error instanceof Error && error.message === "spiral_extent_limit") {
            reachedExtent = true;
            session.terrainSampleExhausted = true;
          } else {
            stopSpiralAnimation("spiral_runtime_error");
          }
          break;
        }
      }
      if (positions.length === 0 || spiralSessionRef.current !== session) {
        if (reachedExtent && spiralSessionRef.current === session) stopSpiralAnimation("spiral_extent_limit");
        return;
      }
      session.terrainSamplePending = true;
      const requestGeneration = ++session.terrainRequestGeneration;
      let timeoutId = 0;
      const timeout = new Promise<never>((_resolve, reject) => {
        timeoutId = window.setTimeout(() => reject(new Error("terrain_sample_timeout")), TERRAIN_SAMPLE_TIMEOUT_MS);
      });
      void Promise.race([
        sampleTerrainMostDetailed(session.terrainProvider, positions),
        timeout,
      ]).then((sampledPositions) => {
        window.clearTimeout(timeoutId);
        if (
          spiralSessionRef.current !== session
          || session.terrainRequestGeneration !== requestGeneration
          || viewer.isDestroyed()
        ) return;
        const nextSamples = sampledPositions.map((sampledPosition, index) => {
          if (!Number.isFinite(sampledPosition.height)) throw new Error("terrain_height_unavailable");
          return {
            distanceMeters: distances[index],
            heightMeters: Number(sampledPosition.height),
          };
        });
        session.terrainSamples = [...session.terrainSamples, ...nextSamples]
          .filter((sample) => sample.distanceMeters >= session.surfaceDistanceMeters - session.terrainSampleSpacingMeters * 2);
        session.terrainSamplePending = false;
        session.terrainSampleFailures = 0;
        session.terrainRetryAt = 0;
        viewer.scene.requestRender();
      }).catch(() => {
        window.clearTimeout(timeoutId);
        if (spiralSessionRef.current !== session || session.terrainRequestGeneration !== requestGeneration) return;
        session.terrainSamplePending = false;
        session.terrainSampleFailures += 1;
        if (session.terrainSampleFailures >= 4) {
          stopSpiralAnimation("terrain_sampling_error");
          return;
        }
        const retryDelay = [500, 1_500, 4_000][session.terrainSampleFailures - 1] ?? 4_000;
        session.terrainRetryAt = Date.now() + retryDelay;
        viewer.scene.requestRender();
      });
    };

    const tick = (timestamp: number) => {
      if (spiralSessionRef.current !== session || viewer.isDestroyed()) return;
      if (document.hidden) {
        session.lastTimestamp = null;
        session.pendingElapsedSeconds = 0;
      } else if (session.lastTimestamp === null) {
        session.lastTimestamp = timestamp;
      } else {
        const elapsedSeconds = Math.max(0, (timestamp - session.lastTimestamp) / 1000);
        session.lastTimestamp = timestamp;
        session.pendingElapsedSeconds += elapsedSeconds;
        try {
          let nextFrame: ReturnType<typeof spiralSurfaceFrame> | null = null;
          let nextGround: number | null = null;
          let substeps = 0;
          while (session.pendingElapsedSeconds > 0.000_001 && substeps < MAX_SPIRAL_SUBSTEPS_PER_FRAME) {
            const stepSeconds = Math.min(session.pendingElapsedSeconds, 1 / 30);
            const candidateDistance = session.surfaceDistanceMeters + session.config.speedMetersPerSecond * stepSeconds;
            const candidateFrame = spiralSurfaceFrame(
              session.origin,
              session.initialHeading,
              candidateDistance,
              session.config.pitchMetersPerTurn,
            );
            const candidateGround = groundHeightAtDistance(candidateDistance);
            if (candidateGround === null) {
              const lastTerrainSample = session.terrainSamples.at(-1);
              if (session.terrainSampleExhausted && (!lastTerrainSample || candidateDistance > lastTerrainSample.distanceMeters)) {
                throw new Error("spiral_extent_limit");
              }
              // Missing terrain is a loading state, never an ellipsoid-height
              // fallback. Pause the route clock until a sampled buffer exists.
              session.pendingElapsedSeconds = 0;
              session.lastTimestamp = timestamp;
              requestTerrainSamples();
              break;
            }
            session.surfaceDistanceMeters = candidateDistance;
            session.pendingElapsedSeconds -= stepSeconds;
            nextFrame = candidateFrame;
            nextGround = candidateGround;
            substeps += 1;
          }
          if (nextFrame && nextGround !== null) applyFrame(nextFrame, nextGround);
          requestTerrainSamples();
        } catch (error) {
          stopSpiralAnimation(error instanceof Error && error.message === "spiral_extent_limit"
            ? "spiral_extent_limit"
            : "spiral_runtime_error");
          return;
        }
      }
      if (spiralSessionRef.current === session) session.requestId = window.requestAnimationFrame(tick);
    };

    try {
      requestTerrainSamples();
      const initialFrame = spiralSurfaceFrame(session.origin, session.initialHeading, 0, session.config.pitchMetersPerTurn);
      const initialGround = groundHeightAtDistance(0);
      if (initialGround !== null) applyFrame(initialFrame, initialGround);
    } catch {
      stopSpiralAnimation("spiral_runtime_error");
      return false;
    }
    session.requestId = window.requestAnimationFrame(tick);
    rebuildGridRef.current?.();
    onSpiralStateChangeRef.current?.({ running: true });
    return true;
  }, [stopSpiralAnimation]);

  useImperativeHandle(ref, () => ({
    startSpiralAnimation,
    stopSpiralAnimation,
    getCameraView: () => {
      const viewer = viewerRef.current;
      return viewer && !viewer.isDestroyed() ? getCameraView(viewer) : null;
    },
  }), [startSpiralAnimation, stopSpiralAnimation]);

  useEffect(() => {
    const stopForPageLeave = () => stopSpiralAnimation("stopped");
    const resetHiddenClock = () => {
      const session = spiralSessionRef.current;
      if (!session || !document.hidden) return;
      session.lastTimestamp = null;
      session.pendingElapsedSeconds = 0;
    };
    window.addEventListener("pagehide", stopForPageLeave);
    document.addEventListener("visibilitychange", resetHiddenClock);
    return () => {
      window.removeEventListener("pagehide", stopForPageLeave);
      document.removeEventListener("visibilitychange", resetHiddenClock);
    };
  }, [stopSpiralAnimation]);

  useEffect(() => {
    presentationRef.current = presentation;
    const activeSpiral = spiralSessionRef.current;
    if (activeSpiral && Boolean(activeSpiral.terrainProvider) !== presentation.terrainEnabled) {
      stopSpiralAnimation("renderer_restarted");
    }
    if (viewerRef.current && terrainRef.current) applyPresentation(viewerRef.current, imageryLayerRef.current, buildingsRef.current, terrainRef.current, presentation);
    rebuildGridRef.current?.();
    const viewer = viewerRef.current;
    const terrain = terrainRef.current;
    onReadyChangeRef.current?.(Boolean(
      viewer
      && !viewer.isDestroyed()
      && terrain
      && (!presentation.terrainEnabled || terrain.world),
    ));
  }, [presentation, stopSpiralAnimation]);

  useEffect(() => {
    runtimeBindingsRef.current = runtimeBindings;
    if (viewerRef.current && !viewerRef.current.isDestroyed()) {
      syncRuntimeDataSources(viewerRef.current, runtimeDataSourcesRef.current, runtimeBindings);
    }
  }, [runtimeBindings]);

  useEffect(() => {
    let viewer: Viewer | undefined;
    let handler: ScreenSpaceEventHandler | undefined;
    let resizeObserver: ResizeObserver | undefined;
    let removeGridCameraListener: (() => void) | undefined;
    let removeRefreshRenderListener: (() => void) | undefined;
    let removeRenderErrorListener: (() => void) | undefined;
    let cancelled = false;

    const start = async () => {
      try {
        const response = await fetch("/api/map/runtime-config");
        const config = response.ok ? await response.json() as RuntimeConfig : null;
        if (config?.gatewayHealthUrl) {
          void fetch(config.gatewayHealthUrl)
            .then((healthResponse) => healthResponse.ok ? healthResponse.json() as Promise<MapGatewayHealth> : null)
            .then((health) => { if (!cancelled) onGatewayHealth?.(health); })
            .catch(() => { if (!cancelled) onGatewayHealth?.(null); });
        }
        if (!containerRef.current || cancelled) return;

        viewer = new Viewer(containerRef.current, {
          animation: false,
          baseLayer: false,
          baseLayerPicker: false,
          fullscreenButton: false,
          geocoder: false,
          homeButton: false,
          infoBox: false,
          navigationHelpButton: false,
          sceneModePicker: false,
          selectionIndicator: false,
          timeline: false,
          requestRenderMode: true,
          maximumRenderTimeChange: Number.POSITIVE_INFINITY,
          // The default Cesium panel hides the useful UI state and displays
          // `[object Object]` for several non-Error render faults. We report a
          // safe diagnostic through the Map panel and attempt one bounded
          // recovery instead of leaving a modal over a stopped renderer.
          showRenderLoopErrors: false,
          // Sandbox-only: Cesium writes credits into a dedicated, visually
          // suppressed container. Runtime attribution metadata is preserved;
          // external and commercial surfaces must provide visible credits.
          creditContainer: creditContainerRef.current ?? undefined,
        });
        const resourceProxy = config?.resourceProxyBase ? new DefaultProxy(config.resourceProxyBase) : undefined;
        const buildResource = (url: string) => {
          // Put cache intent into the upstream URL itself. Cesium providers
          // derive child resources (metadata, imagery tiles, terrain and 3D
          // tiles) from this URL; DefaultProxy then forwards the exact intent
          // to Gateway for every derived request.
          const routedUrl = new URL(url);
          // Provider bytes are cached once by Platform Map Gateway. Version
          // the browser-facing route so an old malformed HTTP response cannot
          // shadow the shared TileCache after a transport fix.
          routedUrl.searchParams.set("nodedc_client_revision", "2");
          if (!presentationRef.current.cacheEnabled) routedUrl.searchParams.set("nodedc_cache_mode", "passthrough");
          if (presentationRef.current.cacheRefresh || !presentationRef.current.cacheNoOverwrite) routedUrl.searchParams.set("nodedc_cache_refresh", "1");
          return new Resource({
            url: routedUrl.toString(),
            proxy: resourceProxy,
          });
        };
        const loadEndpoint = async (assetId: string) => {
          if (!config?.gatewayReady) throw new Error("map_gateway_not_ready");
          const endpointResponse = await fetch(`${config.assetEndpointBase}/${assetId}/endpoint`);
          if (!endpointResponse.ok) throw new Error(`Map Gateway asset ${assetId}: ${endpointResponse.status}`);
          return endpointResponse.json() as Promise<IonAssetEndpoint>;
        };
        const gridDataSource = new CustomDataSource("nodedc-map-grid");
        viewer.dataSources.add(gridDataSource);
        const terrain = { world: null as CesiumTerrainProvider | null, ellipsoid: new EllipsoidTerrainProvider() };
        viewer.terrainProvider = terrain.ellipsoid;
        viewer.scene.globe.depthTestAgainstTerrain = true;
        addFixtureEntities(viewer);
        syncRuntimeDataSources(viewer, runtimeDataSourcesRef.current, runtimeBindingsRef.current);
        viewerRef.current = viewer;
        terrainRef.current = terrain;
        const rebuildGrid = () => rebuildElevatedGrid(viewer!, gridDataSource, presentationRef.current);
        rebuildGridRef.current = rebuildGrid;
        removeGridCameraListener = viewer.camera.moveEnd.addEventListener(() => {
          rebuildGrid();
          onCameraChangeRef.current?.(getCameraView(viewer!));
        });

        const providerStatus: MapProviderStatus = {
          imagery: config?.gatewayReady ? "loading" : "not-configured",
          terrain: config?.gatewayReady ? "loading" : "not-configured",
          buildings: config?.gatewayReady ? "loading" : "not-configured",
          errors: config?.gatewayReady ? {} : {
            imagery: "Platform Map Gateway недоступен",
            terrain: "Platform Map Gateway недоступен",
            buildings: "Platform Map Gateway недоступен",
          },
        };
        const reportProvider = (provider: "imagery" | "terrain" | "buildings", state: MapProviderState, error?: unknown) => {
          providerStatus[provider] = state;
          if (state === "error") {
            providerStatus.errors[provider] = error instanceof Error && error.message ? error.message : "provider_unavailable";
          } else {
            delete providerStatus.errors[provider];
          }
          if (!cancelled) onProviderStatus?.({ ...providerStatus, errors: { ...providerStatus.errors } });
        };
        onProviderStatus?.({ ...providerStatus, errors: { ...providerStatus.errors } });
        let renderRecoveryScheduled = false;
        removeRenderErrorListener = viewer.scene.renderError.addEventListener((_scene, error) => {
          stopSpiralAnimation("render_error");
          const raw = error instanceof Error ? error.message : "cesium_render_error";
          const safe = raw.replace(/[^A-Za-z0-9_.:-]/g, "_").slice(0, 120) || "cesium_render_error";
          reportProvider("imagery", "error", safe);
          reportProvider("terrain", "error", safe);
          reportProvider("buildings", "error", safe);
          if (renderRecoveryScheduled) return;
          renderRecoveryScheduled = true;
          window.setTimeout(() => {
            if (cancelled || !viewer || viewer.isDestroyed()) return;
            // Cesium's default listener stops its render loop after a scene
            // error. One retry handles a transient resource/resize race but
            // remains bounded if the browser or GPU fault is persistent.
            viewer.useDefaultRenderLoop = true;
            viewer.scene.requestRender();
          }, 0);
        });

        if (config?.gatewayReady) {
          // Do not serialize provider startup. A failure in Bing imagery is
          // recoverable and must not stop terrain, buildings, or the scene.
          void loadEndpoint("2").then(async (endpoint) => {
            if (endpoint.externalType !== "BING" || !endpoint.options?.url || endpoint.credentialMode !== "gateway") throw new Error("cesium_live_imagery_endpoint_invalid");
            const imageryProvider = await BingMapsImageryProvider.fromUrl(buildResource(endpoint.options.url), {
              // Cesium requires a key-shaped value to form its Bing URL. This
              // public marker is stripped by Map Gateway before upstream use.
              key: "nodedc-gateway",
              mapStyle: (endpoint.options.mapStyle || "Aerial") as BingMapsStyle,
              tileProtocol: "https",
            });
            if (cancelled || !viewer || viewer.isDestroyed()) return;
            for (const attribution of endpoint.attributions) if (attribution.html) viewer.creditDisplay.addStaticCredit(new Credit(attribution.html, attribution.collapsible));
            imageryLayerRef.current = viewer.imageryLayers.addImageryProvider(imageryProvider);
            applyPresentation(viewer, imageryLayerRef.current, buildingsRef.current, terrain, presentationRef.current);
            reportProvider("imagery", "ready");
          }).catch((error) => reportProvider("imagery", "error", error));
          void loadEndpoint("1").then(async (terrainEndpoint) => {
            if (!terrainEndpoint.url || terrainEndpoint.credentialMode !== "gateway") throw new Error("terrain_endpoint_invalid");
            const terrainResource = buildResource(terrainEndpoint.url);
            const world = await CesiumTerrainProvider.fromUrl(terrainResource, { requestVertexNormals: true, requestWaterMask: true });
            if (cancelled || !viewer || viewer.isDestroyed()) return;
            terrain.world = world;
            for (const attribution of terrainEndpoint.attributions) if (attribution.html) viewer.creditDisplay.addStaticCredit(new Credit(attribution.html, attribution.collapsible));
            applyPresentation(viewer, imageryLayerRef.current, buildingsRef.current, terrain, presentationRef.current);
            onReadyChangeRef.current?.(!presentationRef.current.terrainEnabled || Boolean(terrain.world));
            reportProvider("terrain", "ready");
          }).catch((error) => reportProvider("terrain", "error", error));
          void loadEndpoint("96188").then(async (buildingsEndpoint) => {
            if (!buildingsEndpoint.url || buildingsEndpoint.credentialMode !== "gateway") throw new Error("buildings_endpoint_invalid");
            const buildingsResource = buildResource(buildingsEndpoint.url);
            const buildings = await Cesium3DTileset.fromUrl(buildingsResource);
            if (cancelled || !viewer || viewer.isDestroyed()) return;
            viewer.scene.primitives.add(buildings);
            buildingsRef.current = buildings;
            for (const attribution of buildingsEndpoint.attributions) if (attribution.html) viewer.creditDisplay.addStaticCredit(new Credit(attribution.html, attribution.collapsible));
            applyPresentation(viewer, imageryLayerRef.current, buildings, terrain, presentationRef.current);
            reportProvider("buildings", "ready");
          }).catch((error) => reportProvider("buildings", "error", error));
          if (config.gaussianSplatsReady && config.gaussianAssetId) {
            void loadEndpoint(config.gaussianAssetId).then(async (gaussianEndpoint) => {
              if (!gaussianEndpoint.url || gaussianEndpoint.credentialMode !== "gateway") throw new Error("gaussian_endpoint_invalid");
              const gaussianResource = buildResource(gaussianEndpoint.url);
              const gaussian = await Cesium3DTileset.fromUrl(gaussianResource);
              if (cancelled || !viewer || viewer.isDestroyed()) return;
              viewer.scene.primitives.add(gaussian);
            }).catch(() => undefined);
          }
        }

        applyPresentation(viewer, imageryLayerRef.current, buildingsRef.current, terrain, presentationRef.current);

        if (initialCamera) {
          viewer.camera.setView({
            destination: Cartesian3.fromDegrees(initialCamera.longitude, initialCamera.latitude, initialCamera.height),
            orientation: {
              heading: initialCamera.heading,
              pitch: initialCamera.pitch,
              roll: initialCamera.roll,
            },
          });
        } else {
          const center = toCartesian(sceneFixture.viewport.center as Position);
          viewer.camera.lookAt(center, new HeadingPitchRange(
            CesiumMath.toRadians(sceneFixture.viewport.heading),
            CesiumMath.toRadians(sceneFixture.viewport.pitch),
            sceneFixture.viewport.range,
          ));
          viewer.camera.lookAtTransform(Matrix4.IDENTITY);
        }
        rebuildGrid();
        onCameraChangeRef.current?.(getCameraView(viewer));
        onReadyChangeRef.current?.(!presentationRef.current.terrainEnabled || Boolean(terrain.world));

        if (presentationRef.current.cacheRefresh && onCacheRefreshConsumedRef.current) {
          // All root provider resources for the current view were created with
          // `nodedc_cache_refresh=1`. Reset after the first render so later
          // navigation goes back to the selected steady-state policy.
          removeRefreshRenderListener = viewer.scene.postRender.addEventListener(() => {
            removeRefreshRenderListener?.();
            removeRefreshRenderListener = undefined;
            if (!cancelled) onCacheRefreshConsumedRef.current?.();
          });
          viewer.scene.requestRender();
        }

        handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction((movement: { position: Cartesian2 }) => {
          const picked = viewer?.scene.pick(movement.position);
          const entity = picked?.id instanceof Entity ? picked.id : undefined;
          if (entity?.id) onSelectRef.current?.(entity.id);
        }, ScreenSpaceEventType.LEFT_CLICK);
        resizeObserver = new ResizeObserver(() => {
          if (!viewer || viewer.isDestroyed()) return;
          viewer.resize();
          viewer.scene.requestRender();
        });
        resizeObserver.observe(containerRef.current);
      } catch (error) {
        // Failure before viewer creation is distinct from a provider failure;
        // surface it through the Inspector without exposing any credentials.
        if (!cancelled) onProviderStatus?.({
          imagery: "error",
          terrain: "error",
          buildings: "error",
          errors: {
            imagery: error instanceof Error ? error.message : "map_start_failed",
            terrain: error instanceof Error ? error.message : "map_start_failed",
            buildings: error instanceof Error ? error.message : "map_start_failed",
          },
        });
      }
    };

    void start();
    return () => {
      cancelled = true;
      stopSpiralAnimation("renderer_restarted");
      onReadyChangeRef.current?.(false);
      resizeObserver?.disconnect();
      removeGridCameraListener?.();
      removeRefreshRenderListener?.();
      removeRenderErrorListener?.();
      handler?.destroy();
      if (viewer && !viewer.isDestroyed()) viewer.destroy();
      viewerRef.current = null;
      imageryLayerRef.current = null;
      buildingsRef.current = null;
      terrainRef.current = null;
      rebuildGridRef.current = null;
      runtimeDataSourcesRef.current.clear();
    };
  }, [onGatewayHealth, onProviderStatus, stopSpiralAnimation]);

  return (
    <div className="catalog-cesium-map">
      <div ref={containerRef} className="catalog-cesium-map__canvas" />
      <div ref={creditContainerRef} className="catalog-cesium-map__credits" aria-hidden="true" />
    </div>
  );
});
