{
  "version": 3,
  "sources": ["../js/state/caches.js", "../js/util/normalize.js", "../js/map/colors.js", "../js/map/legend.js", "../js/map/zoom.js", "../js/map/viewport.js", "../js/util/topo.js", "../js/data/api-url.js", "../js/data/_populate.js", "../js/data/createMemoizedLoader.js", "../js/data/states.js", "../js/data/msas.js", "../js/data/nonmetros.js", "../js/data/provinces.js", "../js/data/ca_areas.js", "../js/data/world.js", "../js/data/job-families.js", "../js/panel/top-occupations/caches.js", "../js/data/nation.js", "../js/data/geography-reset.js", "../js/data/cache-version.js", "../js/data/counties.js", "../js/data/ca_census_divisions.js", "../js/state/geo_urls.js", "../js/ui/layer-toggle.js", "../js/ui/metric-toggle.js", "../js/ui/info-modal.js", "../js/ui/keyboard.js", "../js/ui/tooltip.js", "../js/map/selection.js", "../js/util/perf.js", "../js/map/layers.js", "../js/map/render.js", "../js/map/post-load.js", "../js/panel/side-panel.js", "../js/panel/sheet-snap.js", "../js/panel/mobile-sheet.js", "../js/treemap/index.js", "../js/treemap/tooltip.js", "../js/panel/top-occupations/national-exposure.js", "../js/panel/top-occupations/color-scales.js", "../js/panel/top-occupations/drilldown.js", "../js/panel/top-occupations/treemap-boot.js", "../js/panel/top-occupations/selection-scope.js", "../js/panel/top-occupations/core.js", "../js/panel/top-occupations/index.js", "../js/panel/top-occupations/mobile.js", "../js/ui/mobile-shell.js", "../js/dom.js", "../js/els.js", "../js/ui/layer-toggle-panel.js", "../js/regionSnapshot.js", "../js/geolocate.js", "../js/us_ai_map.js"],
  "sourcesContent": ["// @ts-check\n\n// Data caches. Populated once per layer by the data/*.js fetchers.\n// Write-once per browser session \u2014 reload to refresh. Intentional: the site is\n// read-only for end users and deploys are infrequent; a TTL adds complexity\n// without benefit. If backend metrics change mid-session the user sees stale\n// data until reload.\n//\n// Convention: each cache is owned by exactly one fetcher in data/*.js, which\n// calls .clear() + .set() in its success path. No module outside data/*.js\n// writes to these caches. We export the Maps directly rather than wrapping\n// them in getter/setter functions \u2014 the write side has a single owner, and\n// the read side is hot (per-feature during render); wrapper functions would\n// add ceremony without safety.\n\nimport { signal } from \"../signal.js\";\n\n// Per-geography metric lookups. Values are whatever the fetchers store (arrays of metric values today).\n// Canadian geographies get their own maps (not merged into the US ones)\n// because the code spaces collide: SGC province 48 = Alberta, FIPS 48 = Texas.\nexport const stateMetricsByCode = new Map();\nexport const msaMetricsByCode = new Map();\nexport const nonmetroMetricsByCode = new Map();\nexport const provinceMetricsByCode = new Map();\nexport const cmaMetricsByCode = new Map();\nexport const caNonmetroMetricsByCode = new Map();\n\nexport const stateTotalsByCode = new Map();\nexport const msaTotalsByCode = new Map();\nexport const nonmetroTotalsByCode = new Map();\nexport const provinceTotalsByCode = new Map();\nexport const cmaTotalsByCode = new Map();\nexport const caNonmetroTotalsByCode = new Map();\n\nexport const stateWagesByCode = new Map();\nexport const msaWagesByCode = new Map();\nexport const nonmetroWagesByCode = new Map();\nexport const provinceWagesByCode = new Map();\nexport const cmaWagesByCode = new Map();\nexport const caNonmetroWagesByCode = new Map();\n\nexport const stateExposureByCode = new Map();\nexport const msaExposureByCode = new Map();\nexport const nonmetroExposureByCode = new Map();\nexport const provinceExposureByCode = new Map();\nexport const cmaExposureByCode = new Map();\nexport const caNonmetroExposureByCode = new Map();\n\n// Nation-wide aggregate. Single-value holders (no per-code Map) because there\n// is exactly one US. Populated once by data/nation.js from the drilldown\n// endpoint and consumed by the side panel when no region is selected.\nexport const nation = {\n  totalWorkforce: /** @type {number | null} */ (null),\n  totalWageBill: /** @type {number | null} */ (null),\n  /** @type {import(\"../types.js\").ExposureStats | null} */\n  exposure: null,\n  // Choropleth metric triple [theoretical, current, calibrated] for the Country\n  // fill layer \u2014 same ordering as the per-region metric arrays (see\n  // data/_populate.js) so getMetricValue + getStatesColorScale color it on the\n  // same scale as US states/provinces.\n  /** @type {[number | null, number | null, number | null] | null} */\n  metrics: null,\n};\n\n// Canada nation-wide aggregate. Parallel holder to `nation` (US) \u2014 kept\n// separate rather than keyed by country so the existing US read path\n// (panel/side-panel.js reads `nation.*` directly) is untouched. Populated once\n// by data/nation.js from /api/map/drilldown?scope=nation&code=ca and consumed\n// by the side panel when the Canada nation view is selected.\nexport const nationCa = {\n  totalWorkforce: /** @type {number | null} */ (null),\n  totalWageBill: /** @type {number | null} */ (null),\n  /** @type {import(\"../types.js\").ExposureStats | null} */\n  exposure: null,\n  /** @type {[number | null, number | null, number | null] | null} */\n  metrics: null,\n};\n\n// Topology / feature indexes.\nexport const msaFeatureByCode = new Map();\nexport const areaOutlineFeatureByKey = new Map();\n\n// Color-scale domain cache, keyed by metric index.\n// stateCombined merges the state+province domains (the \"States\" layer renders\n// both countries on one scale); areaCombined merges all four area kinds.\nexport const metricDomainCache = {\n  state: new Map(),\n  msa: new Map(),\n  nonmetro: new Map(),\n  province: new Map(),\n  cma: new Map(),\n  caNonmetro: new Map(),\n  stateCombined: new Map(),\n  areaCombined: new Map(),\n};\n\n// Per-layer \"loaded\" signals \u2014 renderers subscribe to know when a layer's\n// data is ready to draw. Fetchers flip these to true after populating caches.\n//\n// MSA data is split across two signals because its metrics and its topology\n// load on different paths: `msaMetricsLoaded` flips when /api/map/msas metrics\n// land (always needed \u2014 they color the default area layer's metro fills),\n// while `msaTopologyLoaded` flips only when the us_msas.topojson geometry is\n// pulled (lazy \u2014 used solely by the metros-only fallback layer, which is\n// reachable only when the area-composites layer fails to load).\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const statesLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const msaMetricsLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const msaTopologyLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const provincesLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const caAreasLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const nonmetrosLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const worldLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const countyBordersLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const caCdBordersLoaded = signal(false);\n// Nation-aggregate \"loaded\" signals \u2014 flipped by data/nation.js once a\n// country's drilldown summary (incl. its metric triple) lands. Subscribers\n// repaint the Country fill layer when a nation's aggregate arrives late.\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const nationLoaded = signal(false);\n/** @type {import(\"../signal.js\").Signal<boolean>} */\nexport const nationCaLoaded = signal(false);\n\n// ---------------------------------------------------------------------------\n// Region \"kind-ladder\" \u2014 single touch-point for the 6 region kinds.\n//\n// Five sites used to each branch over {state,msa,nonmetro,province,cma,\n// ca_nonmetro} and read the parallel *ByCode maps inline. Adding a country\n// meant touching all five. These two helpers centralize the kind \u2192 maps\n// lookup so a new region kind is a single edit here.\n// ---------------------------------------------------------------------------\n\n// kind \u2192 { totals, wages, exposure } Map triple. Unknown kinds are absent so\n// getRegionMetrics() returns nulls (callers that previously fell through to the\n// nonmetro maps for an unknown kind must pass kind=\"nonmetro\" explicitly).\nconst REGION_METRIC_MAPS = {\n  state: { totals: stateTotalsByCode, wages: stateWagesByCode, exposure: stateExposureByCode },\n  msa: { totals: msaTotalsByCode, wages: msaWagesByCode, exposure: msaExposureByCode },\n  nonmetro: { totals: nonmetroTotalsByCode, wages: nonmetroWagesByCode, exposure: nonmetroExposureByCode },\n  province: { totals: provinceTotalsByCode, wages: provinceWagesByCode, exposure: provinceExposureByCode },\n  cma: { totals: cmaTotalsByCode, wages: cmaWagesByCode, exposure: cmaExposureByCode },\n  ca_nonmetro: { totals: caNonmetroTotalsByCode, wages: caNonmetroWagesByCode, exposure: caNonmetroExposureByCode },\n};\n\n// kind \u2192 { metrics map, scale key, whether the no-data fallback uses the\n// nonmetro-specific color }. scaleKey selects which color scale the caller's\n// getColorScale() returns; states/provinces share the states scale, metros/CMAs\n// and non-metros/CA-remainders share the single area scale (see map/colors.js).\nconst REGION_ACCENT_SPEC = {\n  state: { metrics: stateMetricsByCode, scaleKey: \"states\", nonmetroNoData: false },\n  msa: { metrics: msaMetricsByCode, scaleKey: \"msas\", nonmetroNoData: false },\n  nonmetro: { metrics: nonmetroMetricsByCode, scaleKey: \"nonmetro\", nonmetroNoData: true },\n  province: { metrics: provinceMetricsByCode, scaleKey: \"states\", nonmetroNoData: false },\n  cma: { metrics: cmaMetricsByCode, scaleKey: \"msas\", nonmetroNoData: false },\n  ca_nonmetro: { metrics: caNonmetroMetricsByCode, scaleKey: \"nonmetro\", nonmetroNoData: true },\n};\n\n/**\n * Look up a region's totals/wages/exposure across the 6 region kinds.\n * Returns the raw cached values (undefined when the code isn't present, exactly\n * as the underlying Map.get) so callers can keep their own `?? null` / `|| null`\n * coalescing. Unknown kind \u2192 all nulls.\n * @param {string} kind\n * @param {string} code\n * @returns {{ totalWorkers: any, wageBill: any, exposureStats: any }}\n */\nexport function getRegionMetrics(kind, code) {\n  const maps = REGION_METRIC_MAPS[kind];\n  if (!maps) {\n    return { totalWorkers: null, wageBill: null, exposureStats: null };\n  }\n  return {\n    totalWorkers: maps.totals.get(code),\n    wageBill: maps.wages.get(code),\n    exposureStats: maps.exposure.get(code),\n  };\n}\n\n/**\n * Resolve a region's choropleth accent color: the metric value run through the\n * kind's color scale, or the no-data fallback when the metric is null. Mirrors\n * the original inline branches \u2014 non-metro kinds fall back to the nonmetro-\n * specific no-data color, everything else to the shared no-data color. Unknown\n * kind \u2192 null (no per-region tint, e.g. the nation selection).\n *\n * `getMetricValue` and `getColorScale` are injected (rather than imported from\n * map/colors.js) to avoid a caches.js \u21C4 colors.js import cycle \u2014 colors.js\n * already imports the metric maps from here.\n * @param {string} kind\n * @param {string} code\n * @param {{\n *   mapColors: { noData: string, noDataNonmetro: string },\n *   getMetricValue: (metrics: any) => (number | null),\n *   getColorScale: (scaleKey: string) => ((value: number) => string),\n * }} deps\n * @returns {string | null}\n */\nexport function getRegionAccentColor(kind, code, { mapColors, getMetricValue, getColorScale }) {\n  const spec = REGION_ACCENT_SPEC[kind];\n  if (!spec) return null;\n  const metricValue = getMetricValue(spec.metrics.get(code));\n  if (metricValue == null) {\n    return spec.nonmetroNoData ? mapColors.noDataNonmetro : mapColors.noData;\n  }\n  return getColorScale(spec.scaleKey)(metricValue);\n}\n", "// @ts-check\n\nimport {\n  LAYER_MODE_AREA,\n  LAYER_MODE_STATE,\n  LAYER_MODE_COUNTRY,\n  METRIC_MODE_AI_ABILITIES,\n  METRIC_MODE_AI_EXPOSURE,\n  METRIC_MODE_CALIBRATED,\n} from \"../config.js\";\n\nexport function normalizeLayerMode(value) {\n  if (value === LAYER_MODE_AREA) return LAYER_MODE_AREA;\n  if (value === LAYER_MODE_COUNTRY) return LAYER_MODE_COUNTRY;\n  return LAYER_MODE_STATE;\n}\n\nexport function normalizeMetricMode(value) {\n  if (value === METRIC_MODE_AI_EXPOSURE) return METRIC_MODE_AI_EXPOSURE;\n  if (value === METRIC_MODE_CALIBRATED) return METRIC_MODE_CALIBRATED;\n  return METRIC_MODE_AI_ABILITIES;\n}\n\nexport function normalizeStateCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(2, \"0\");\n  return raw;\n}\n\nexport function normalizeMsaCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(5, \"0\");\n  return raw;\n}\n\nexport function normalizeAreaCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(7, \"0\");\n  return raw;\n}\n\nexport function normalizeCountyCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(5, \"0\");\n  return raw;\n}\n\nexport function normalizeProvinceCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(2, \"0\");\n  return raw;\n}\n\nexport function normalizeCmaCode(value) {\n  const raw = String(value ?? \"\").trim();\n  if (/^\\d+$/.test(raw)) return raw.padStart(3, \"0\");\n  return raw;\n}\n\nexport function getProvinceCode(feature) {\n  const props = feature && feature.properties ? feature.properties : {};\n  return normalizeProvinceCode(props.province_code || props.PRUID || feature?.id || \"\");\n}\n\nexport function getStateCode(feature) {\n  const props = feature && feature.properties ? feature.properties : {};\n  return normalizeStateCode(props.state_code || props.STATEFP || props.statefp || feature?.id || \"\");\n}\n\nexport function getMsaCode(feature) {\n  const props = feature && feature.properties ? feature.properties : {};\n  return normalizeMsaCode(props.msa_code || props.CBSAFP || props.cbsa || feature?.id || \"\");\n}\n\nexport function getAreaKey(feature) {\n  const props = feature && feature.properties ? feature.properties : {};\n  return String(props.area_key || \"\");\n}\n", "// @ts-check\n\n// Color-scale domain computation + the three per-layer sequential scales.\n// Owns the scales as module-local mutable references because the scales are\n// rebuilt whenever metric domains change; consumers read them via getters so\n// they always see the current instance.\n//\n// Legend *domain* + *gradient* math lives here too (it's pure and depends on\n// the same interpolator + domain cache). Legend DOM rendering is in\n// map/legend.js.\n\nimport { selectedMetric, selectedLayer } from \"../state/store.js\";\nimport {\n  stateMetricsByCode,\n  msaMetricsByCode,\n  nonmetroMetricsByCode,\n  provinceMetricsByCode,\n  cmaMetricsByCode,\n  caNonmetroMetricsByCode,\n  metricDomainCache,\n} from \"../state/caches.js\";\nimport { normalizeLayerMode } from \"../util/normalize.js\";\nimport {\n  METRIC_MODE_AI_ABILITIES,\n  METRIC_MODE_AI_EXPOSURE,\n  METRIC_MODE_CALIBRATED,\n  LAYER_MODE_STATE,\n} from \"../config.js\";\n\nconst d3 = /** @type {any} */ (/** @type {any} */ (window).d3);\n\nexport const MAP_AI_SEQUENTIAL_INTERPOLATOR = d3.interpolateRdYlBu;\n\nlet statesColorScale = /** @type {any} */ (\n  d3.scaleSequential().interpolator(MAP_AI_SEQUENTIAL_INTERPOLATOR).clamp(true).domain([1, 0])\n);\n// Single shared scale for the entire area layer (metros + non-metros). Built\n// from the combined domain so fills agree with the unified legend.\nlet areaColorScale = /** @type {any} */ (\n  d3.scaleSequential().interpolator(MAP_AI_SEQUENTIAL_INTERPOLATOR).domain([1, 0])\n);\n\nexport function getStatesColorScale() {\n  return statesColorScale;\n}\n\nexport function getMsasColorScale() {\n  return areaColorScale;\n}\n\nexport function getNonmetroColorScale() {\n  return areaColorScale;\n}\n\n// Maps a region kind's scale key (see state/caches.js REGION_ACCENT_SPEC) to the\n// live color-scale getter: states/provinces \u2192 states scale; metros/CMAs and\n// non-metros/CA-remainders \u2192 the single shared area scale. Single source of\n// truth shared by side-panel.js and mobile-sheet.js (injected into\n// getRegionAccentColor).\nexport function getColorScaleForKey(scaleKey) {\n  if (scaleKey === \"states\") return getStatesColorScale();\n  if (scaleKey === \"msas\") return getMsasColorScale();\n  return getNonmetroColorScale();\n}\n\nexport function getSelectedMetricIndex() {\n  if (selectedMetric.get() === METRIC_MODE_AI_EXPOSURE) {\n    return 1;\n  }\n  if (selectedMetric.get() === METRIC_MODE_CALIBRATED) {\n    return 2;\n  }\n  return 0;\n}\n\nexport function getMetricValue(metrics) {\n  if (!Array.isArray(metrics)) {\n    return null;\n  }\n  const metricValue = metrics[getSelectedMetricIndex()];\n  return Number.isFinite(metricValue) ? metricValue : null;\n}\n\nfunction getMetricValueByIndex(metrics, metricIndex) {\n  if (!Array.isArray(metrics)) {\n    return null;\n  }\n  const metricValue = metrics[metricIndex];\n  return Number.isFinite(metricValue) ? metricValue : null;\n}\n\nexport function getMetricDomain(dataMap, metricIndex = getSelectedMetricIndex()) {\n  const values = [];\n  for (const metrics of dataMap.values()) {\n    const metricValue = getMetricValueByIndex(metrics, metricIndex);\n    if (metricValue != null) {\n      values.push(metricValue);\n    }\n  }\n  const min = d3.min(values);\n  const max = d3.max(values);\n  return {\n    min: Number.isFinite(min) ? min : null,\n    max: Number.isFinite(max) ? max : null,\n  };\n}\n\nexport function setMetricDomainCacheEntry(cacheKey, dataMap) {\n  const abilityDomain = getMetricDomain(dataMap, 0);\n  const exposureDomain = getMetricDomain(dataMap, 1);\n  const calibratedDomain = getMetricDomain(dataMap, 2);\n  metricDomainCache[cacheKey].set(METRIC_MODE_AI_ABILITIES, abilityDomain);\n  metricDomainCache[cacheKey].set(METRIC_MODE_AI_EXPOSURE, exposureDomain);\n  metricDomainCache[cacheKey].set(METRIC_MODE_CALIBRATED, calibratedDomain);\n}\n\nexport function updateCombinedAreaDomainCache() {\n  // One scale spans every area kind \u2014 US metros/nonmetros and Canadian\n  // CMAs/remainders \u2014 so cross-border color comparisons are meaningful.\n  for (const metricMode of [METRIC_MODE_AI_ABILITIES, METRIC_MODE_AI_EXPOSURE, METRIC_MODE_CALIBRATED]) {\n    const domains = [\"msa\", \"nonmetro\", \"cma\", \"caNonmetro\"].map(\n      (key) => metricDomainCache[key].get(metricMode) || { min: null, max: null },\n    );\n    const mins = domains.map((d) => d.min).filter((value) => value != null);\n    const maxes = domains.map((d) => d.max).filter((value) => value != null);\n    metricDomainCache.areaCombined.set(metricMode, {\n      min: mins.length ? d3.min(mins) : null,\n      max: maxes.length ? d3.max(maxes) : null,\n    });\n  }\n}\n\nexport function updateCombinedStateDomainCache() {\n  // The \"States\" layer shows US states and Canadian provinces together;\n  // merge their domains so both countries share one scale and legend.\n  for (const metricMode of [METRIC_MODE_AI_ABILITIES, METRIC_MODE_AI_EXPOSURE, METRIC_MODE_CALIBRATED]) {\n    const domains = [\"state\", \"province\"].map(\n      (key) => metricDomainCache[key].get(metricMode) || { min: null, max: null },\n    );\n    const mins = domains.map((d) => d.min).filter((value) => value != null);\n    const maxes = domains.map((d) => d.max).filter((value) => value != null);\n    metricDomainCache.stateCombined.set(metricMode, {\n      min: mins.length ? d3.min(mins) : null,\n      max: maxes.length ? d3.max(maxes) : null,\n    });\n  }\n}\n\n/**\n * Build an exposure color scale from a raw values array.\n * Returns a `(value) => color` function that:\n *   - maps finite values through an `[max, min]`-domain sequential scale\n *   - collapses to a constant midpoint color when min === max\n *   - falls back to `fallback` when no finite values are present or the input\n *     value itself is non-finite\n * Used by the top-occupations panel's national + local exposure scales.\n * @param {number[]} values\n * @param {{ fallback: string }} opts\n */\nexport function buildExposureScale(values, { fallback }) {\n  const finite = (Array.isArray(values) ? values : []).filter((value) => Number.isFinite(value));\n  if (!finite.length) return () => fallback;\n  const min = d3.min(finite);\n  const max = d3.max(finite);\n  if (!Number.isFinite(min) || !Number.isFinite(max)) return () => fallback;\n  if (min === max) {\n    const constantColor = MAP_AI_SEQUENTIAL_INTERPOLATOR(0.5);\n    return (value) => (Number.isFinite(value) ? constantColor : fallback);\n  }\n  const scale = d3.scaleSequential()\n    .interpolator(MAP_AI_SEQUENTIAL_INTERPOLATOR)\n    .domain([max, min])\n    .clamp(true);\n  return (value) => (Number.isFinite(value) ? scale(value) : fallback);\n}\n\nexport function buildSequentialScaleFromDomain(domain) {\n  let min = domain && Number.isFinite(domain.min) ? domain.min : null;\n  let max = domain && Number.isFinite(domain.max) ? domain.max : null;\n  if (min == null || max == null) {\n    min = 0;\n    max = 1;\n  }\n  if (min === max) {\n    max = min + 1e-6;\n  }\n\n  return d3\n    .scaleSequential()\n    .interpolator(MAP_AI_SEQUENTIAL_INTERPOLATOR)\n    .domain([max, min]);\n}\n\nexport function rebuildColorScales() {\n  if (stateMetricsByCode.size || provinceMetricsByCode.size) {\n    const combined = metricDomainCache.stateCombined.get(selectedMetric.get());\n    const fallback = metricDomainCache.state.get(selectedMetric.get());\n    statesColorScale = buildSequentialScaleFromDomain(combined || fallback).clamp(true);\n  } else {\n    statesColorScale = d3\n      .scaleSequential()\n      .interpolator(MAP_AI_SEQUENTIAL_INTERPOLATOR)\n      .clamp(true)\n      .domain([1, 0]);\n  }\n\n  if (\n    msaMetricsByCode.size\n    || nonmetroMetricsByCode.size\n    || cmaMetricsByCode.size\n    || caNonmetroMetricsByCode.size\n  ) {\n    areaColorScale = buildSequentialScaleFromDomain(\n      metricDomainCache.areaCombined.get(selectedMetric.get()),\n    );\n  }\n}\n\nexport function getLegendGradient() {\n  const interpolator = MAP_AI_SEQUENTIAL_INTERPOLATOR;\n  const stops = [0, 0.25, 0.5, 0.75, 1].map((stop) => {\n    const t = 1 - stop;\n    return `${interpolator(t)} ${Math.round(stop * 100)}%`;\n  });\n  return `linear-gradient(to right, ${stops.join(\", \")})`;\n}\n", "// @ts-check\n\n// Map gradient legend: DOM creation + update driven by the current color\n// domain/gradient in map/colors.js and the selected metric.\n// Legend nodes are module-local so renderers only see `setup()` + `update()`.\n\nimport { getLegendGradient } from \"./colors.js\";\n\nlet legendWrapEl = /** @type {HTMLElement | null} */ (null);\nlet legendScaleEl = /** @type {HTMLElement | null} */ (null);\nlet legendLowEl = /** @type {HTMLElement | null} */ (null);\nlet legendHighEl = /** @type {HTMLElement | null} */ (null);\n\nexport function updateGradientLegend() {\n  if (!legendWrapEl || !legendScaleEl || !legendLowEl || !legendHighEl) {\n    return;\n  }\n\n  legendScaleEl.style.background = getLegendGradient();\n\n  legendLowEl.textContent = \"AI Safe\";\n  legendHighEl.textContent = \"AI Exposed\";\n}\n\nexport function createGradientLegend(container) {\n  if (!container) {\n    return;\n  }\n  if (legendWrapEl) {\n    // Idempotent: callers may re-invoke after layout changes. Keep the existing\n    // nodes rather than leaking a second legend into the DOM.\n    return;\n  }\n\n  legendWrapEl = document.createElement(\"section\");\n  legendWrapEl.className = \"map-gradient-legend\";\n\n  legendScaleEl = document.createElement(\"div\");\n  legendScaleEl.className = \"map-gradient-legend__scale\";\n\n  const labels = document.createElement(\"div\");\n  labels.className = \"map-gradient-legend__labels\";\n\n  legendLowEl = document.createElement(\"span\");\n  legendLowEl.className = \"map-gradient-legend__label\";\n  legendLowEl.textContent = \"AI Safe\";\n\n  legendHighEl = document.createElement(\"span\");\n  legendHighEl.className = \"map-gradient-legend__label\";\n  legendHighEl.textContent = \"AI Exposed\";\n\n  labels.appendChild(legendLowEl);\n  labels.appendChild(legendHighEl);\n\n  legendWrapEl.appendChild(legendScaleEl);\n  legendWrapEl.appendChild(labels);\n  container.appendChild(legendWrapEl);\n  updateGradientLegend();\n}\n", "// @ts-check\n\n// Zoom controller: owns the d3.zoom behavior, the programmatic-zoom guard,\n// and the fit/focus math. Projection + pathGenerator + svg are injected\n// because they are shared with render and re-built by fitProjection.\n\nimport {\n  INITIAL_US_ZOOM_SCALE,\n  ZOOM_MIN_SCALE,\n  ZOOM_MAX_SCALE,\n  ZOOM_REFERENCE_VIEWPORT_WIDTH,\n} from \"../config.js\";\n\nconst d3 = /** @type {any} */ (/** @type {any} */ (window).d3);\n\n// Width threshold for the phone-initial-zoom boost. Intentionally decoupled\n// from the mobile-UI media query \u2014 that query (~1079px / pointer: coarse)\n// gates layout, but the 1.6\u00D7 zoom multiplier only makes sense on truly\n// narrow viewports where fitExtent leaves too much ocean. Tablets in\n// mobile UI mode don't need it (the country already fits comfortably).\nconst BREAKPOINT_PHONE_MAX_PX = 800;\n// Initial-transform scale boost on phones so the country fills more of the\n// visible area (the projection's fitExtent leaves too much ocean otherwise).\nconst MOBILE_INITIAL_ZOOM_MULTIPLIER = 1.6;\n// Upper bound on per-fit padding so single-feature framing on wide desktop\n// monitors doesn't sit in excessive whitespace.\nconst FIT_PADDING_MAX_PX = 120;\n\n/**\n * @param {{\n *   svg: any,\n *   getProjection: () => any,\n *   getPathGenerator: () => any,\n *   setPathGenerator: (p: any) => void,\n *   applyTransform: (t: any) => void,\n *   onUserInteract: () => void,\n *   ensureSelectionOutlineVisible: () => void,\n *   getViewport: (collapsedOverride?: any) => any,\n *   getProvinceFeatures?: () => any[],\n * }} deps\n */\nexport function createZoomController(deps) {\n  const {\n    svg,\n    getProjection,\n    getPathGenerator,\n    setPathGenerator,\n    applyTransform,\n    onUserInteract,\n    ensureSelectionOutlineVisible,\n    getViewport,\n    getProvinceFeatures,\n  } = deps;\n\n  let zoomBehavior = /** @type {any} */ (null);\n  let isProgrammaticZoom = false;\n\n  // The projection is fitExtent'd to the viewport (see fitProjection), so its\n  // internal scale already adapts to screen width \u2014 k=1 means the world fits\n  // the viewport on any screen size. Multiplying INITIAL_US_ZOOM_SCALE by\n  // referenceWidth/currentWidth would double-apply that adjustment and\n  // overflow the US off-screen on phones (k=16+ on a 390px viewport). For the\n  // initial transform we keep the configured scale as-is.\n  //\n  // For user-zoom min/max we keep the rescale so a user can zoom in deep\n  // enough to see counties on a phone \u2014 the per-feature pixel density target\n  // is screen-relative even though the initial fit is not.\n  function getZoomScaleFactor(collapsedOverride = null) {\n    const vp = getViewport(collapsedOverride);\n    const w = Math.max(1, vp.width);\n    return ZOOM_REFERENCE_VIEWPORT_WIDTH / w;\n  }\n  function effMin(c = null) {\n    // Never clamp the initial transform out of range on small screens.\n    return Math.min(INITIAL_US_ZOOM_SCALE, ZOOM_MIN_SCALE * getZoomScaleFactor(c));\n  }\n  function effMax(c = null) {\n    return ZOOM_MAX_SCALE * getZoomScaleFactor(c);\n  }\n  function effInit() {\n    // On narrow viewports the projection's fitExtent renders the US small\n    // relative to the screen, so the configured k=5 leaves a lot of empty\n    // ocean. Bump the initial scale on phones so the country fills more of\n    // the visible area on first paint.\n    const vp = getViewport();\n    if (vp.width <= BREAKPOINT_PHONE_MAX_PX) return INITIAL_US_ZOOM_SCALE * MOBILE_INITIAL_ZOOM_MULTIPLIER;\n    return INITIAL_US_ZOOM_SCALE;\n  }\n\n  function getInitialUsTransform() {\n    const viewport = getViewport();\n    const initialCenterLonLat = [-98.56, 39.81];\n    const projection = getProjection();\n    const projectedUsCenter = projection(initialCenterLonLat);\n    if (!projectedUsCenter) return d3.zoomIdentity;\n\n    const k = effInit();\n    const tx = viewport.centerX - projectedUsCenter[0] * k;\n    const ty = viewport.centerY - projectedUsCenter[1] * k;\n    return d3.zoomIdentity.translate(tx, ty).scale(k);\n  }\n\n  // Canada-centered nation transform. Unlike getInitialUsTransform (which uses\n  // a hardcoded center + the configured INITIAL_US_ZOOM_SCALE), Canada has no\n  // tuned constant, so we fit the projection to the union of the Canada province\n  // geometries \u2014 the same bounds-fit math focusFeatureInViewport uses for a\n  // single feature, applied to a synthetic FeatureCollection of all provinces.\n  // This frames the whole country in the viewport with consistent padding and\n  // clamps to the shared zoom min/max. Returns null if the province topology\n  // isn't loaded yet (caller must ensureProvincesLoaded first) or the bounds are\n  // degenerate, so the caller can decide how to degrade.\n  function getInitialCanadaTransform() {\n    if (typeof getProvinceFeatures !== \"function\") return null;\n    const features = getProvinceFeatures();\n    if (!Array.isArray(features) || features.length === 0) return null;\n    const collection = { type: \"FeatureCollection\", features };\n    return computeFitZoomTransformForFeature(collection);\n  }\n\n  function setZoomTransform(nextTransform) {\n    if (!zoomBehavior) {\n      applyTransform(nextTransform);\n      return;\n    }\n    isProgrammaticZoom = true;\n    svg.call(zoomBehavior.transform, nextTransform);\n    isProgrammaticZoom = false;\n  }\n\n  // Step factor + duration for the in/out buttons. 1.6x per click roughly\n  // matches one notch of a trackpad pinch and animates fast enough that\n  // repeated clicks queue smoothly without feeling laggy.\n  function zoomBy(factor, duration = 220) {\n    if (!zoomBehavior) return;\n    isProgrammaticZoom = true;\n    svg\n      .interrupt()\n      .transition()\n      .duration(duration)\n      .ease(d3.easeCubicOut)\n      .call(zoomBehavior.scaleBy, factor)\n      .on(\"end\", () => {\n        isProgrammaticZoom = false;\n        ensureSelectionOutlineVisible();\n      })\n      .on(\"interrupt\", () => {\n        isProgrammaticZoom = false;\n        ensureSelectionOutlineVisible();\n      });\n  }\n\n  function setZoomTransformAnimated(nextTransform, duration = 700) {\n    if (!zoomBehavior || !Number.isFinite(duration) || duration <= 0) {\n      setZoomTransform(nextTransform);\n      ensureSelectionOutlineVisible();\n      return;\n    }\n\n    isProgrammaticZoom = true;\n    svg\n      .interrupt()\n      .transition()\n      .duration(duration)\n      .ease(d3.easeCubicOut)\n      .call(zoomBehavior.transform, nextTransform)\n      .on(\"end\", () => {\n        isProgrammaticZoom = false;\n        ensureSelectionOutlineVisible();\n      })\n      .on(\"interrupt\", () => {\n        isProgrammaticZoom = false;\n        ensureSelectionOutlineVisible();\n      });\n  }\n\n  function computeFitZoomTransformForFeature(feature, collapsedOverride = null) {\n    const pathGenerator = getPathGenerator();\n    if (!feature || !pathGenerator) return null;\n\n    const viewport = getViewport(collapsedOverride);\n    // Padding is a fraction of the smaller viewport dimension so framing\n    // stays consistent across breakpoints \u2014 a fixed pixel padding would hit\n    // the availW/H floor on narrow screens (e.g. 75vw expanded panel leaves\n    // a strip too small to absorb large fixed padding on each side).\n    const padding = Math.max(12, Math.min(FIT_PADDING_MAX_PX, Math.min(viewport.width, viewport.height) * 0.25));\n    let bounds;\n    try {\n      bounds = pathGenerator.bounds(feature);\n    } catch (e) {\n      bounds = null;\n    }\n\n    if (!bounds || !Array.isArray(bounds[0]) || !Array.isArray(bounds[1])) return null;\n\n    const [x0, y0] = bounds[0];\n    const [x1, y1] = bounds[1];\n    const bw = Math.max(x1 - x0, 1e-4);\n    const bh = Math.max(y1 - y0, 1e-4);\n    const cx = (x0 + x1) / 2;\n    const cy = (y0 + y1) / 2;\n\n    const availW = Math.max(48, viewport.width - 2 * padding);\n    const availH = Math.max(48, viewport.height - 2 * padding);\n\n    let k = Math.min(availW / bw, availH / bh);\n    if (!Number.isFinite(k) || k <= 0) return null;\n\n    k = Math.max(effMin(collapsedOverride), Math.min(effMax(collapsedOverride), k));\n\n    const tx = viewport.centerX - k * cx;\n    const ty = viewport.centerY - k * cy;\n\n    return d3.zoomIdentity.translate(tx, ty).scale(k);\n  }\n\n  function focusFeatureInViewport(feature, { targetScale = 12, duration = 700, collapsedOverride = null, preferFit = true, keepScale = false } = {}) {\n    if (!feature) return;\n\n    const viewport = getViewport(collapsedOverride);\n\n    if (preferFit && !keepScale) {\n      const fitTransform = computeFitZoomTransformForFeature(feature, collapsedOverride);\n      if (fitTransform) {\n        setZoomTransformAnimated(fitTransform, duration);\n        return;\n      }\n    }\n\n    const pathGenerator = getPathGenerator();\n    const projection = getProjection();\n    let projectedCenter = pathGenerator.centroid(feature);\n    if (!projectedCenter || !Number.isFinite(projectedCenter[0]) || !Number.isFinite(projectedCenter[1])) {\n      const geoCenter = d3.geoCentroid(feature);\n      projectedCenter = projection(geoCenter);\n    }\n\n    if (!projectedCenter || !Number.isFinite(projectedCenter[0]) || !Number.isFinite(projectedCenter[1])) return;\n\n    let scale;\n    if (keepScale) {\n      const current = d3.zoomTransform(svg.node());\n      scale = current && Number.isFinite(current.k) ? current.k : effInit();\n    } else {\n      const factor = getZoomScaleFactor(collapsedOverride);\n      const rescaledTarget = targetScale * factor;\n      scale = Math.max(\n        effMin(collapsedOverride),\n        Math.min(effMax(collapsedOverride), rescaledTarget),\n      );\n    }\n    const tx = viewport.centerX - projectedCenter[0] * scale;\n    const ty = viewport.centerY - projectedCenter[1] * scale;\n    setZoomTransformAnimated(d3.zoomIdentity.translate(tx, ty).scale(scale), duration);\n  }\n\n  function setupZoomBehavior() {\n    if (zoomBehavior) return;\n\n    zoomBehavior = d3\n      .zoom()\n      .scaleExtent([effMin(), effMax()])\n      .on(\"zoom\", (event) => {\n        applyTransform(event.transform);\n        if (!isProgrammaticZoom) {\n          onUserInteract();\n        }\n      });\n\n    svg.call(zoomBehavior);\n    svg.on(\"dblclick.zoom\", null);\n  }\n\n  function fitProjection() {\n    const viewport = getViewport();\n    const projection = getProjection();\n    const fitTarget = { type: \"Sphere\" };\n\n    projection.fitExtent(\n      [\n        [viewport.left, viewport.top],\n        [viewport.right, viewport.bottom],\n      ],\n      fitTarget\n    );\n\n    setPathGenerator(d3.geoPath(projection));\n\n    refreshZoomExtent();\n  }\n\n  // Re-applies scaleExtent against the current viewport. Must be called any\n  // time the viewport changes \u2014 including the panel-toggle path, which\n  // deliberately skips fitProjection to avoid a projection snap. Without\n  // this, d3's wheel-zoom limit and the in-flight clamp during programmatic\n  // transitions stay tied to the previous viewport, producing a visible\n  // \"jump\" at the end of focus animations.\n  function refreshZoomExtent(collapsedOverride = null) {\n    if (!zoomBehavior) return;\n    zoomBehavior.scaleExtent([effMin(collapsedOverride), effMax(collapsedOverride)]);\n  }\n\n  return {\n    getInitialUsTransform,\n    getInitialCanadaTransform,\n    setZoomTransform,\n    setZoomTransformAnimated,\n    focusFeatureInViewport,\n    setupZoomBehavior,\n    fitProjection,\n    refreshZoomExtent,\n    zoomBy,\n  };\n}\n", "// @ts-check\n\n// Usable-map-rectangle math, extracted from the composition root\n// (us_ai_map.js). Given the SVG node and the (optional) desktop side panel,\n// compute the box the projection should fit into, reserving space for the\n// mobile bottom sheet and the desktop panel. Depends only on its two DOM\n// inputs plus the mobile-sheet elements it looks up by id, so it has no\n// closure coupling \u2014 the root keeps a thin `getMapViewport` wrapper over it.\n\n/**\n * @param {{ svgNode: Element, sidePanelEl: HTMLElement | null }} deps\n * @param {boolean | null} [collapsedOverride]\n */\nexport function computeMapViewport({ svgNode, sidePanelEl }, collapsedOverride = null) {\n  const rect = svgNode.getBoundingClientRect();\n  const width = Math.max(1, rect.width);\n  const height = Math.max(1, rect.height);\n\n  const pad = 24;\n  let left = pad;\n  let right = width - pad;\n  const top = pad;\n  let bottom = height - pad;\n\n  // On mobile, the bottom sheet covers part of the map. Reserve the\n  // sheet's actual visible height so feature focus centers in the\n  // visible map area above the sheet, not behind it. For peek (and any\n  // transient/mid-animation state) we use measured handle + peek\n  // heights to stay stable while the sheet slides in; for info/expanded\n  // we use the sheet's full offsetHeight so the bigger box is properly\n  // accounted for. MIN_MAP_HEIGHT clamps the resulting bottom so an\n  // 85vh-expanded sheet can't push bottom past top and feed an inverted\n  // extent into projection.fitExtent.\n  const MIN_MAP_HEIGHT = 80;\n  const sheetEl = document.getElementById(\"map-mobile-preview-card\");\n  if (sheetEl && !sheetEl.hidden && sheetEl.dataset.state !== \"closed\") {\n    const handleH = (document.getElementById(\"map-mobile-sheet-handle\") || {}).offsetHeight || 22;\n    const peekContentEl = sheetEl.querySelector(\".map-mobile-sheet__peek\");\n    const peekContentH = (peekContentEl && peekContentEl.offsetHeight) || 120;\n    const peekHeight = handleH + peekContentH;\n    const sheetState = sheetEl.dataset.state;\n    const reservedSheetHeight =\n      sheetState === \"info\" || sheetState === \"expanded\"\n        ? Math.max(sheetEl.offsetHeight || 0, peekHeight)\n        : peekHeight;\n    bottom = Math.min(bottom, height - reservedSheetHeight - 12);\n  }\n  bottom = Math.max(top + MIN_MAP_HEIGHT, bottom);\n\n  const isCollapsed = collapsedOverride == null\n    ? sidePanelEl && sidePanelEl.classList.contains(\"is-collapsed\")\n    : collapsedOverride;\n\n  if (sidePanelEl && !isCollapsed) {\n    const panelRect = sidePanelEl.getBoundingClientRect();\n    const panelRight = panelRect.right - rect.left;\n    // MIN_MAP_WIDTH clamp guards against the panel covering the full SVG\n    // (mobile sheet at 100vw), where reserving its width would otherwise\n    // push `left` past `right` and feed an inverted box into fitExtent.\n    const MIN_MAP_WIDTH = 80;\n    left = Math.max(left, panelRight + 16);\n    left = Math.min(left, right - MIN_MAP_WIDTH);\n  }\n\n  return {\n    left,\n    right,\n    top,\n    bottom,\n    width: Math.max(1, right - left),\n    height: Math.max(1, bottom - top),\n    centerX: (left + right) / 2,\n    centerY: (top + bottom) / 2,\n  };\n}\n", "// @ts-check\n\n// Depends on window.topojson (loaded via <script defer> in the template).\n// Pure extraction of a feature array from a topojson payload, with a preferred\n// object-name list used to pick the right layer when multiple exist.\n\n/**\n * @param {any} topology\n * @param {string[]} [preferredObjectNames]\n * @returns {any[]}\n */\nexport function getTopoFeatures(topology, preferredObjectNames = []) {\n  const object = getTopoObjectByNames(topology, preferredObjectNames);\n  if (!object) {\n    return [];\n  }\n  // @ts-ignore window.topojson global\n  return topojson.feature(topology, object).features || [];\n}\n\n/**\n * Pick a single topology object by a preferred-name list, falling back to the\n * first object present. Returns null when the topology has no objects.\n * @param {any} topology\n * @param {string[]} [preferredObjectNames]\n * @returns {any}\n */\nexport function getTopoObjectByNames(topology, preferredObjectNames = []) {\n  const objects = topology && topology.objects ? topology.objects : {};\n  const objectNames = Object.keys(objects);\n  const selectedName = preferredObjectNames.find((name) => objects[name]) || objectNames[0];\n  return selectedName ? objects[selectedName] : null;\n}\n\n/**\n * Dissolve every geometry of a topology object into one merged polygon Feature\n * (via topojson.merge) \u2014 used to derive whole-country outlines from the\n * per-state / per-province topologies. Returns null when the object is absent\n * or carries no geometries.\n * @param {any} topology\n * @param {string[]} preferredObjectNames\n * @param {Record<string, any>} [properties]\n * @returns {any}\n */\nexport function mergeTopoToFeature(topology, preferredObjectNames, properties = {}) {\n  const object = getTopoObjectByNames(topology, preferredObjectNames);\n  if (!object || !object.geometries) {\n    return null;\n  }\n  return {\n    type: \"Feature\",\n    properties,\n    // @ts-ignore window.topojson global\n    geometry: topojson.merge(topology, object.geometries),\n  };\n}\n\n/**\n * Boundary mesh of a topology object as one MultiLineString geometry\n * (topojson.mesh, all arcs) \u2014 used to draw interior + exterior state/province\n * edges as a single stroke-only path over the Country fill. Returns null when\n * the object is absent.\n * @param {any} topology\n * @param {string[]} preferredObjectNames\n * @returns {any}\n */\nexport function meshTopoObject(topology, preferredObjectNames) {\n  const object = getTopoObjectByNames(topology, preferredObjectNames);\n  if (!object) {\n    return null;\n  }\n  // @ts-ignore window.topojson global\n  return topojson.mesh(topology, object);\n}\n", "// @ts-check\n\n/**\n * Append the active map-cache version as a query param so browser HTTP caches\n * from before a refresh_map_cache promote are not reused for bulk geography\n * or drilldown JSON.\n *\n * @param {string} baseUrl\n * @param {{ mapCacheVersion?: string } | null | undefined} cfg\n * @returns {string}\n */\nexport function appendMapCacheVersion(baseUrl, cfg) {\n  const version = String((cfg && cfg.mapCacheVersion) || \"\").trim();\n  if (!version) return baseUrl;\n  const sep = baseUrl.includes(\"?\") ? \"&\" : \"?\";\n  return `${baseUrl}${sep}v=${encodeURIComponent(version)}`;\n}\n", "// @ts-check\n\n// Shared per-item population of the geography metric/totals/wages/exposure\n// caches. data/states.js, data/msas.js, and data/nonmetros.js differ only in\n// their target Maps, the payload code field, and the code normalizer \u2014 the\n// derived-choropleth-metric math and the exposure object shape are identical,\n// so they live here in one place.\n\nimport { normalizeFiniteNumber, normalizeNullableFiniteNumber } from \"../util/format.js\";\n\n/**\n * Choropleth metric for the calibrated (Current Capabilities) mode.\n *\n * Prefers the server's calibrated_exposure: the backend computes it over\n * covered workers only (occupations lacking a calibrated score are excluded\n * from numerator AND denominator), so recomputing exposed_workforce_calibrated\n * / totEmp here would re-dilute partially-covered geographies toward zero.\n */\nexport function deriveCalibratedMetric(item, totEmp) {\n  const direct = normalizeFiniteNumber(item.calibrated_exposure);\n  if (Number.isFinite(direct)) {\n    // Pre-calibrated cache payloads defaulted calibrated_exposure to 0.0 without\n    // workforce fields \u2014 treat that as missing data (grey), not a real zero (blue).\n    if (direct === 0 && item.exposed_workforce_calibrated == null) return NaN;\n    return direct;\n  }\n  // Fallback for payload shapes without the direct ratio.\n  const exposedCalibrated = normalizeFiniteNumber(item.exposed_workforce_calibrated);\n  if (Number.isFinite(exposedCalibrated) && Number.isFinite(totEmp) && totEmp > 0) {\n    return exposedCalibrated / totEmp;\n  }\n  return NaN;\n}\n\n/**\n * Clear the four per-geography caches and repopulate them from `items`.\n *\n * @param {any[] | null | undefined} items - the API payload array (states / msas / nonmetros); the `items || []` guard tolerates null/undefined.\n * @param {{\n *   metricsMap: Map<string, [number, number, number]>,\n *   totalsMap: Map<string, number>,\n *   wagesMap: Map<string, number>,\n *   exposureMap: Map<string, any>,\n *   codeField: string,\n *   normalizeCode: (raw: any) => string,\n * }} opts\n */\nexport function populateGeographyCaches(\n  items,\n  { metricsMap, totalsMap, wagesMap, exposureMap, codeField, normalizeCode },\n) {\n  metricsMap.clear();\n  totalsMap.clear();\n  wagesMap.clear();\n  exposureMap.clear();\n  for (const item of items || []) {\n    const code = normalizeCode(item[codeField]);\n    const totEmp = Number(item.tot_emp);\n    if (Number.isFinite(totEmp)) totalsMap.set(code, totEmp);\n    // Derive the choropleth metric from the same exposed-workforce /\n    // total-workforce inputs the side-panel gauge consumes, so the map\n    // color and the gauge percentage share one numerator/denominator.\n    const exposedTheoretical = normalizeFiniteNumber(item.exposed_workforce_theoretical);\n    const exposedCurrent = normalizeFiniteNumber(item.exposed_workforce_current);\n    const exposedCalibrated = normalizeFiniteNumber(item.exposed_workforce_calibrated);\n    const theoretical = Number.isFinite(exposedTheoretical) && Number.isFinite(totEmp) && totEmp > 0\n      ? exposedTheoretical / totEmp\n      : NaN;\n    const current = Number.isFinite(exposedCurrent) && Number.isFinite(totEmp) && totEmp > 0\n      ? exposedCurrent / totEmp\n      : NaN;\n    const calibrated = deriveCalibratedMetric(item, totEmp);\n    metricsMap.set(code, [theoretical, current, calibrated]);\n    const wageBill = Number(item.total_wage_bill);\n    if (Number.isFinite(wageBill)) wagesMap.set(code, wageBill);\n    exposureMap.set(code, {\n      ability: {\n        exposedWageBill: normalizeFiniteNumber(item.exposed_wage_bill_theoretical),\n        exposedWorkforce: normalizeFiniteNumber(item.exposed_workforce_theoretical),\n        wageRatio: normalizeFiniteNumber(item.wage_bill_ratio_theoretical),\n      },\n      penetration: {\n        exposedWageBill: normalizeFiniteNumber(item.exposed_wage_bill_current),\n        exposedWorkforce: normalizeFiniteNumber(item.exposed_workforce_current),\n        wageRatio: normalizeFiniteNumber(item.wage_bill_ratio_current),\n      },\n      // The calibrated fields are NULLABLE on the wire: the server emits null\n      // for a zero-coverage geography (map_payloads.py \"Zero covered workers =>\n      // null calibrated\"). Preserve that null \u2014 the plain normalizer would\n      // coerce it to 0 (Number(null) === 0) and the panel would show fake\n      // \"0 workers / $0\" stats while the map fill correctly greys the region.\n      calibrated: {\n        exposedWageBill: normalizeNullableFiniteNumber(item.exposed_wage_bill_calibrated),\n        exposedWorkforce: normalizeNullableFiniteNumber(item.exposed_workforce_calibrated),\n        wageRatio: normalizeNullableFiniteNumber(item.wage_bill_ratio_calibrated),\n      },\n    });\n  }\n}\n", "// @ts-check\n\n// Shared memoize skeleton for the geography data loaders (states / msas \u00D72 /\n// nonmetros / provinces / ca_areas). Each of those loaders repeated the same\n// four-step pattern:\n//\n//   1. early-return if the completion signal is already set (already loaded),\n//   2. return the in-flight promise if one exists (concurrent-call dedup),\n//   3. else run the loader body, set the signal on success,\n//   4. on error, reset the in-flight promise to null so a later call re-runs\n//      (the reset is what makes a failed load retryable), then rethrow.\n//\n// Pulling it here keeps the per-loader files down to just their unique fetch +\n// cache-population body and their own signal. Semantics are preserved exactly;\n// see tests/unit/createMemoizedLoader.test.mjs.\n//\n// Two cross-cutting decisions shared by the loaders that use this skeleton:\n//\n//   * Null-body guard (`payload?.foo`): a 2xx response with a null/non-object\n//     body is treated as an empty payload \u2014 populateGeographyCaches clears the\n//     caches, the loader still calls signal.set(true), and the map renders\n//     empty rather than throwing on the critical paint path. This is the one\n//     intended behavior change in this refactor: degrading to an empty map\n//     beats crashing boot. A null body is a server-contract violation (not a\n//     transient error), so we deliberately do NOT keep it retryable; if that\n//     ever needs to change, throw explicitly on a null body (e.g.\n//     `if (!payload) throw new Error(...)`) so the catch below resets and a\n//     later call re-runs.\n//\n//   * pendingCfg hand-off: each loader stashes its cfg in a module-level\n//     `pendingCfg` that load() reads synchronously before the first await.\n//     This reproduces the original closure-capture semantics and assumes a\n//     SINGLE active cfg per loader \u2014 the first concurrent caller's cfg wins,\n//     and every call site passes the one module-level cfg, so last-writer-wins\n//     is a no-op. If distinct cfgs per loader ever become a thing (e.g. a\n//     second map instance / re-init with a different config), thread cfg\n//     through as an arg \u2014 `ensureLoaded(cfg)` capturing it locally \u2014 instead.\n\n/**\n * @param {{\n *   signal: import(\"../signal.js\").Signal<boolean>,\n *   load: () => Promise<void>,\n *   onFailure?: (err: unknown) => void,\n * }} opts\n * @returns {() => Promise<void>}\n */\nexport function createMemoizedLoader({ signal, load, onFailure }) {\n  // NOTE: loadingPromise is deliberately NOT cleared on success \u2014 nothing in\n  // the codebase resets a loader signal to false mid-session. If a future\n  // feature does (to force a refetch), it must ALSO expose/perform a reset of\n  // loadingPromise here: with only `signal.set(false)`, the next ensureLoaded()\n  // would return this stale resolved promise, load() would never re-run, and\n  // every layer gated on the signal would stay blank.\n  /** @type {Promise<void> | null} */\n  let loadingPromise = null;\n\n  return function ensureLoaded() {\n    if (signal.get()) return Promise.resolve();\n    if (loadingPromise) return loadingPromise;\n\n    loadingPromise = (async () => {\n      try {\n        await load();\n        signal.set(true);\n      } catch (err) {\n        // Reset so a subsequent call re-runs load() (failed load is retryable).\n        loadingPromise = null;\n        if (onFailure) onFailure(err);\n        throw err;\n      }\n    })();\n\n    return loadingPromise;\n  };\n}\n", "// @ts-check\n\n// Fetches the state metrics payload + state topology, populates the per-state\n// caches in state/caches.js, and flips the `statesLoaded` signal. Render and\n// scale updates are driven by subscribers on `statesLoaded` (see map/post-load.js).\n\nimport { normalizeStateCode } from \"../util/normalize.js\";\nimport { getTopoFeatures, mergeTopoToFeature, meshTopoObject } from \"../util/topo.js\";\nimport {\n  stateMetricsByCode,\n  stateTotalsByCode,\n  stateWagesByCode,\n  stateExposureByCode,\n  statesLoaded,\n} from \"../state/caches.js\";\nimport { fetchJson, fetchJsonWithFallback } from \"./fetch.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\nimport { populateGeographyCaches } from \"./_populate.js\";\nimport { createMemoizedLoader } from \"./createMemoizedLoader.js\";\n\nlet statesFeatures = /** @type {any[]} */ ([]);\n// Whole-US polygon for the Country fill layer, derived by dissolving every\n// state geometry (topojson.merge). Null until the states topology loads.\nlet usCountryFeature = /** @type {any} */ (null);\n// State boundary mesh (interior + exterior), drawn as stroke-only state edges\n// over the US country fill so the single-color country still reads as a states\n// map. Null until the states topology loads.\nlet usStateBorders = /** @type {any} */ (null);\n// Single-cfg hand-off to load(): assumes one active cfg per loader (first\n// concurrent caller wins). Safe under current single-cfg usage; see the\n// pendingCfg note in createMemoizedLoader.js.\nlet pendingCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\n\nexport function getStatesFeatures() {\n  return statesFeatures;\n}\n\nexport function getUsCountryFeature() {\n  return usCountryFeature;\n}\n\nexport function getUsStateBorders() {\n  return usStateBorders;\n}\n\nconst loadStates = createMemoizedLoader({\n  signal: statesLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingCfg);\n    const [statePayload, statesTopology] = await Promise.all([\n      fetchJson(appendMapCacheVersion(cfg.statesApiUrl, cfg)),\n      fetchJsonWithFallback([\n        cfg.statesTopoCdnUrl,\n        cfg.statesTopoUrl,\n        \"/static/geo/us_states.topojson\",\n      ], {\n        asset: \"us_states\",\n        fallbackLogUrl: cfg.assetFallbackLogUrl,\n      }),\n    ]);\n\n    // `statePayload?.states`: a null/empty body yields empty caches and the\n    // map degrades rather than throwing on the critical paint path (intended;\n    // see the null-body-guard note in createMemoizedLoader.js).\n    populateGeographyCaches(statePayload?.states, {\n      metricsMap: stateMetricsByCode,\n      totalsMap: stateTotalsByCode,\n      wagesMap: stateWagesByCode,\n      exposureMap: stateExposureByCode,\n      codeField: \"state_code\",\n      normalizeCode: normalizeStateCode,\n    });\n\n    statesFeatures = getTopoFeatures(statesTopology, [\"states\"]);\n    // Dissolve the states into a single US polygon for the Country layer. The\n    // shipped world topology is land-only (no per-country polygons), so the\n    // country outline is derived here from the same topology the states use.\n    usCountryFeature = mergeTopoToFeature(\n      statesTopology,\n      [\"us_states\", \"states\"],\n      { country: \"us\", name: \"United States\" },\n    );\n    usStateBorders = meshTopoObject(statesTopology, [\"us_states\", \"states\"]);\n  },\n});\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureStatesLoaded({ cfg }) {\n  pendingCfg = cfg;\n  return loadStates();\n}\n", "// @ts-check\n\n// MSA data loaders, split along the two independent paths the MSA data takes:\n//\n//   - `ensureMsaMetricsLoaded` fetches the /api/map/msas metrics and populates\n//     the per-MSA metric caches (state/caches.js). These metrics are always\n//     needed \u2014 they color the metro fills of the default area-composites layer\n//     (getAreaFeatureFill) \u2014 so this loader sits on the critical paint path.\n//\n//   - `ensureMsasTopologyLoaded` fetches the us_msas.topojson geometry and\n//     populates the by-code feature index. The geometry is consumed ONLY by the\n//     metros-only fallback layer, which is reachable only when the\n//     area-composites layer fails to load. It is therefore lazy: pulled on\n//     demand from the fallback path, not on boot.\n//\n// Each loader is independently memoized (with the reset-promise-on-error retry\n// pattern) and flips its own signal \u2014 `msaMetricsLoaded` / `msaTopologyLoaded`\n// respectively. Render/scale/legend side effects are driven by subscribers on\n// those signals (see map/post-load.js).\n\nimport { normalizeMsaCode, getMsaCode } from \"../util/normalize.js\";\nimport { getTopoFeatures } from \"../util/topo.js\";\nimport {\n  msaMetricsByCode,\n  msaTotalsByCode,\n  msaWagesByCode,\n  msaExposureByCode,\n  msaFeatureByCode,\n  msaMetricsLoaded,\n  msaTopologyLoaded,\n} from \"../state/caches.js\";\nimport { fetchJson, fetchJsonWithFallback } from \"./fetch.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\nimport { populateGeographyCaches } from \"./_populate.js\";\nimport { createMemoizedLoader } from \"./createMemoizedLoader.js\";\n\nlet msaFeatures = /** @type {any[]} */ ([]);\nlet pendingMetricsCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\nlet pendingTopologyCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\n\nexport function getMsaFeatures() {\n  return msaFeatures;\n}\n\nconst loadMsaMetrics = createMemoizedLoader({\n  signal: msaMetricsLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingMetricsCfg);\n    const msaPayload = await fetchJson(appendMapCacheVersion(cfg.msasApiUrl, cfg));\n\n    populateGeographyCaches(msaPayload?.msas, {\n      metricsMap: msaMetricsByCode,\n      totalsMap: msaTotalsByCode,\n      wagesMap: msaWagesByCode,\n      exposureMap: msaExposureByCode,\n      codeField: \"msa_code\",\n      normalizeCode: normalizeMsaCode,\n    });\n  },\n});\n\n/**\n * Fetch the MSA metrics and populate the per-MSA metric caches. On the\n * critical paint path \u2014 the default area layer colors its metro fills from\n * these caches.\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureMsaMetricsLoaded({ cfg }) {\n  pendingMetricsCfg = cfg;\n  return loadMsaMetrics();\n}\n\nconst loadMsasTopology = createMemoizedLoader({\n  signal: msaTopologyLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingTopologyCfg);\n    const msaTopology = await fetchJsonWithFallback([\n      cfg.msasTopoUrl,\n      \"/static/geo/us_msas.topojson\",\n    ]);\n\n    msaFeatures = getTopoFeatures(msaTopology, [\"msas\", \"cbsas\", \"metros\"]);\n    msaFeatureByCode.clear();\n    for (const feature of msaFeatures) {\n      const code = getMsaCode(feature);\n      if (code) msaFeatureByCode.set(code, feature);\n    }\n  },\n});\n\n/**\n * Fetch the MSA topology and populate the by-code feature index. Lazy \u2014 only\n * the metros-only fallback layer reads this geometry, and that layer is\n * reachable only when the area-composites layer is unavailable.\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureMsasTopologyLoaded({ cfg }) {\n  pendingTopologyCfg = cfg;\n  return loadMsasTopology();\n}\n", "// @ts-check\n\n// Fetches nonmetro metrics + precomputed area composites, populates nonmetro\n// caches and the area-outline-by-key index, and flips `nonmetrosLoaded`.\n// Falls back to reconstructing area outlines from county topology only when\n// the generated composites file is unavailable.\n\nimport {\n  normalizeMsaCode,\n  normalizeAreaCode,\n  normalizeCountyCode,\n} from \"../util/normalize.js\";\nimport { getTopoFeatures } from \"../util/topo.js\";\nimport {\n  nonmetroMetricsByCode,\n  nonmetroTotalsByCode,\n  nonmetroWagesByCode,\n  nonmetroExposureByCode,\n  areaOutlineFeatureByKey,\n  nonmetrosLoaded,\n} from \"../state/caches.js\";\nimport { fetchJson, fetchJsonWithFallback } from \"./fetch.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\nimport { populateGeographyCaches } from \"./_populate.js\";\nimport { createMemoizedLoader } from \"./createMemoizedLoader.js\";\n\nlet detailAreaFeatures = /** @type {any[]} */ ([]);\nlet pendingCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\n\nfunction formatAreaName(name) {\n  if (!name) return name;\n  return String(name).replace(/\\s*nonmetropolitan area\\s*$/i, \" Non-Metropolitan Area\");\n}\n\nexport function getDetailAreaFeatures() {\n  return detailAreaFeatures;\n}\n\nfunction buildAreaOutlineFeaturesFromCountyTopology(countiesTopology, countyMapPayload) {\n  const result = new Map();\n  const areaByCounty = (countyMapPayload && countyMapPayload.counties) || {};\n  const objects = countiesTopology && countiesTopology.objects ? countiesTopology.objects : {};\n  const countyObjectName = [\"counties\", \"us_counties\", \"nation_counties\"].find((name) => objects[name]) || Object.keys(objects)[0];\n  const countyObject = countyObjectName ? objects[countyObjectName] : null;\n  const countyGeometries = countyObject && Array.isArray(countyObject.geometries) ? countyObject.geometries : [];\n  const geometriesByArea = new Map();\n\n  for (const geometry of countyGeometries) {\n    const props = geometry && geometry.properties ? geometry.properties : {};\n    const countyCode = normalizeCountyCode(props.county_fips || props.GEOID || geometry.id || \"\");\n    const areaInfo = areaByCounty[countyCode];\n    if (!areaInfo) continue;\n\n    const areaType = areaInfo.area_type === \"metro\" ? \"metro\" : \"nonmetro\";\n    const normalizedAreaCode = areaType === \"metro\"\n      ? normalizeMsaCode(areaInfo.area_code)\n      : normalizeAreaCode(areaInfo.area_code);\n    const areaKey = `${areaType}:${normalizedAreaCode}`;\n\n    if (!geometriesByArea.has(areaKey)) {\n      geometriesByArea.set(areaKey, {\n        areaType,\n        areaCode: normalizedAreaCode,\n        areaName: formatAreaName(areaInfo.area_name || areaInfo.name || normalizedAreaCode),\n        geometries: [],\n      });\n    }\n    geometriesByArea.get(areaKey).geometries.push(geometry);\n  }\n\n  for (const [areaKey, entry] of geometriesByArea.entries()) {\n    if (!entry.geometries.length) continue;\n    // @ts-ignore window.topojson global\n    const mergedGeometry = topojson.merge(countiesTopology, entry.geometries);\n    result.set(areaKey, {\n      type: \"Feature\",\n      properties: {\n        area_type: entry.areaType,\n        area_code: entry.areaCode,\n        area_name: entry.areaName,\n        area_key: areaKey,\n      },\n      geometry: mergedGeometry,\n    });\n  }\n\n  return result;\n}\n\nfunction normalizeAreaFeature(feature) {\n  const props = feature.properties || {};\n  const areaType = props.area_type === \"metro\" ? \"metro\" : \"nonmetro\";\n  const normalizedAreaCode = areaType === \"metro\"\n    ? normalizeMsaCode(props.area_code)\n    : normalizeAreaCode(props.area_code);\n  const areaKey = props.area_key || `${areaType}:${normalizedAreaCode}`;\n\n  return {\n    ...feature,\n    properties: {\n      ...props,\n      area_type: areaType,\n      area_code: normalizedAreaCode,\n      area_name: formatAreaName(props.area_name || props.name || normalizedAreaCode),\n      area_key: areaKey,\n    },\n  };\n}\n\nasync function loadCountyOutlineFallback(cfg) {\n  const [countiesTopology, countyMapPayload] = await Promise.all([\n    fetchJsonWithFallback([\n      cfg.countiesTopoCdnUrl,\n      cfg.countiesTopoUrl,\n      \"/static/geo/us_counties.topojson\",\n    ], {\n      asset: \"us_counties\",\n      fallbackLogUrl: cfg.assetFallbackLogUrl,\n    }),\n    fetchJson(appendMapCacheVersion(cfg.nonmetroCountyMapUrl, cfg)),\n  ]);\n\n  return buildAreaOutlineFeaturesFromCountyTopology(countiesTopology, countyMapPayload);\n}\n\nconst loadNonmetros = createMemoizedLoader({\n  signal: nonmetrosLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingCfg);\n    const [nonmetroPayload, areaCompositesTopology] = await Promise.all([\n      fetchJson(appendMapCacheVersion(cfg.nonmetrosApiUrl, cfg)),\n      fetchJsonWithFallback([\n        cfg.areaCompositesTopoUrl,\n        \"/static/geo/us_area_composites.topojson\",\n      ]).catch(() => null),\n    ]);\n\n    populateGeographyCaches(nonmetroPayload?.nonmetros, {\n      metricsMap: nonmetroMetricsByCode,\n      totalsMap: nonmetroTotalsByCode,\n      wagesMap: nonmetroWagesByCode,\n      exposureMap: nonmetroExposureByCode,\n      codeField: \"area_code\",\n      normalizeCode: normalizeAreaCode,\n    });\n\n    const precomputedAreaFeatures = areaCompositesTopology\n      ? getTopoFeatures(areaCompositesTopology, [\"areas\", \"area_composites\"])\n      : [];\n\n    // Scrub only this loader's own entries (\"metro:\"/\"nonmetro:\") from the\n    // SHARED outline index. A blanket .clear() would also wipe the Canadian\n    // \"cma:\"/\"ca_nonmetro:\" entries registered by data/ca_areas.js whenever\n    // a nonmetros retry repopulates. The loaders can overlap, so preserve\n    // entries that this loader does not own. Run the scrub inside each branch,\n    // AFTER that branch's last fallible await \u2014 so a throw in the fallback path\n    // leaves the previous outlines intact instead of a scrubbed-but-empty hole.\n    const scrubOwnedOutlineKeys = () => {\n      for (const key of [...areaOutlineFeatureByKey.keys()]) {\n        if (key.startsWith(\"metro:\") || key.startsWith(\"nonmetro:\")) areaOutlineFeatureByKey.delete(key);\n      }\n    };\n    if (precomputedAreaFeatures.length) {\n      scrubOwnedOutlineKeys();\n      detailAreaFeatures = precomputedAreaFeatures\n        .filter((feature) => feature && feature.geometry)\n        .map(normalizeAreaFeature);\n      for (const feature of detailAreaFeatures) {\n        const areaKey = feature?.properties?.area_key;\n        if (areaKey) areaOutlineFeatureByKey.set(areaKey, feature);\n      }\n    } else {\n      const outlines = await loadCountyOutlineFallback(cfg);\n      scrubOwnedOutlineKeys();\n      for (const [key, feature] of outlines.entries()) {\n        areaOutlineFeatureByKey.set(key, feature);\n      }\n      detailAreaFeatures = [...outlines.values()];\n    }\n  },\n});\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureNonmetrosLoaded({ cfg }) {\n  pendingCfg = cfg;\n  return loadNonmetros();\n}\n", "// @ts-check\n\n// Fetches the Canadian province metrics payload + province topology,\n// populates the per-province caches in state/caches.js, and flips the\n// `provincesLoaded` signal. Mirrors data/states.js \u2014 provinces render in the\n// same \"States\" layer mode as US states but keep separate caches because the\n// SGC and FIPS code spaces collide (48 = Alberta and Texas).\n\nimport { normalizeProvinceCode } from \"../util/normalize.js\";\nimport { getTopoFeatures, mergeTopoToFeature, meshTopoObject } from \"../util/topo.js\";\nimport {\n  provinceMetricsByCode,\n  provinceTotalsByCode,\n  provinceWagesByCode,\n  provinceExposureByCode,\n  provincesLoaded,\n} from \"../state/caches.js\";\nimport { fetchJson, fetchJsonWithFallback } from \"./fetch.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\nimport { populateGeographyCaches } from \"./_populate.js\";\nimport { createMemoizedLoader } from \"./createMemoizedLoader.js\";\n\nlet provinceFeatures = /** @type {any[]} */ ([]);\n// Whole-Canada polygon for the Country fill layer (dissolved provinces). Null\n// until the province topology loads.\nlet caCountryFeature = /** @type {any} */ (null);\n// Province boundary mesh (interior + exterior) drawn as stroke-only edges over\n// the Canada country fill. Null until the province topology loads.\nlet caProvinceBorders = /** @type {any} */ (null);\nlet pendingCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\n\nexport function getProvinceFeatures() {\n  return provinceFeatures;\n}\n\nexport function getCaCountryFeature() {\n  return caCountryFeature;\n}\n\nexport function getCaProvinceBorders() {\n  return caProvinceBorders;\n}\n\nconst loadProvinces = createMemoizedLoader({\n  signal: provincesLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingCfg);\n    const [provincePayload, provincesTopology] = await Promise.all([\n      fetchJson(appendMapCacheVersion(cfg.provincesApiUrl, cfg)),\n      fetchJsonWithFallback([\n        cfg.caProvincesTopoUrl,\n        \"/static/geo/ca_provinces.topojson\",\n      ], {\n        asset: \"ca_provinces\",\n        fallbackLogUrl: cfg.assetFallbackLogUrl,\n      }),\n    ]);\n\n    populateGeographyCaches(provincePayload?.provinces, {\n      metricsMap: provinceMetricsByCode,\n      totalsMap: provinceTotalsByCode,\n      wagesMap: provinceWagesByCode,\n      exposureMap: provinceExposureByCode,\n      codeField: \"province_code\",\n      normalizeCode: normalizeProvinceCode,\n    });\n\n    provinceFeatures = getTopoFeatures(provincesTopology, [\"provinces\"]);\n    caCountryFeature = mergeTopoToFeature(\n      provincesTopology,\n      [\"provinces\"],\n      { country: \"ca\", name: \"Canada\" },\n    );\n    caProvinceBorders = meshTopoObject(provincesTopology, [\"provinces\"]);\n  },\n});\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureProvincesLoaded({ cfg }) {\n  pendingCfg = cfg;\n  return loadProvinces();\n}\n", "// @ts-check\n\n// Fetches Canadian CMA/CA metrics + non-CMA remainder metrics + the\n// precomputed Canadian area composites, populates the cma/caNonmetro caches\n// and the shared area-outline-by-key index, and flips `caAreasLoaded`.\n// Mirrors data/nonmetros.js: the composites file carries one feature per\n// CMA/CA (area_type \"cma\") and one \"rest of province\" feature per province\n// (area_type \"ca_nonmetro\"), all rendered in the same \"Metro. areas\" layer\n// mode as the US composites.\n\nimport { normalizeProvinceCode, normalizeCmaCode } from \"../util/normalize.js\";\nimport { getTopoFeatures } from \"../util/topo.js\";\nimport {\n  cmaMetricsByCode,\n  cmaTotalsByCode,\n  cmaWagesByCode,\n  cmaExposureByCode,\n  caNonmetroMetricsByCode,\n  caNonmetroTotalsByCode,\n  caNonmetroWagesByCode,\n  caNonmetroExposureByCode,\n  areaOutlineFeatureByKey,\n  caAreasLoaded,\n} from \"../state/caches.js\";\nimport { fetchJson, fetchJsonWithFallback } from \"./fetch.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\nimport { populateGeographyCaches } from \"./_populate.js\";\nimport { createMemoizedLoader } from \"./createMemoizedLoader.js\";\n\nlet caAreaFeatures = /** @type {any[]} */ ([]);\n// Single-cfg hand-off to load(): assumes one active cfg per loader (first\n// concurrent caller wins). Safe under current single-cfg usage; see the\n// pendingCfg note in createMemoizedLoader.js.\nlet pendingCfg = /** @type {import(\"../types.js\").Cfg | null} */ (null);\n\nexport function getCaAreaFeatures() {\n  return caAreaFeatures;\n}\n\nfunction normalizeCaAreaFeature(feature) {\n  const props = feature.properties || {};\n  // The build pipeline tags remainders \"ca_rest\"; the app vocabulary is\n  // \"ca_nonmetro\" (matches the API scope). Normalize both spellings.\n  const areaType = props.area_type === \"cma\" ? \"cma\" : \"ca_nonmetro\";\n  const normalizedAreaCode = areaType === \"cma\"\n    ? normalizeCmaCode(props.area_code)\n    : normalizeProvinceCode(props.area_code);\n  const areaKey = `${areaType}:${normalizedAreaCode}`;\n\n  return {\n    ...feature,\n    properties: {\n      ...props,\n      area_type: areaType,\n      area_code: normalizedAreaCode,\n      area_name: props.area_name || props.name || normalizedAreaCode,\n      area_key: areaKey,\n    },\n  };\n}\n\nconst loadCaAreas = createMemoizedLoader({\n  signal: caAreasLoaded,\n  load: async () => {\n    const cfg = /** @type {import(\"../types.js\").Cfg} */ (pendingCfg);\n    const [cmaPayload, caNonmetroPayload, compositesTopology] = await Promise.all([\n      fetchJson(appendMapCacheVersion(cfg.cmasApiUrl, cfg)),\n      fetchJson(appendMapCacheVersion(cfg.caNonmetrosApiUrl, cfg)),\n      fetchJsonWithFallback([\n        cfg.caAreaCompositesTopoUrl,\n        \"/static/geo/ca_area_composites.topojson\",\n      ], {\n        asset: \"ca_area_composites\",\n        fallbackLogUrl: cfg.assetFallbackLogUrl,\n      }),\n    ]);\n\n    // `cmaPayload?.cmas` / `caNonmetroPayload?.ca_nonmetros`: a null/empty body\n    // yields empty caches and the map degrades rather than throwing on the\n    // critical paint path (intended; see createMemoizedLoader.js).\n    populateGeographyCaches(cmaPayload?.cmas, {\n      metricsMap: cmaMetricsByCode,\n      totalsMap: cmaTotalsByCode,\n      wagesMap: cmaWagesByCode,\n      exposureMap: cmaExposureByCode,\n      codeField: \"cma_code\",\n      normalizeCode: normalizeCmaCode,\n    });\n\n    populateGeographyCaches(caNonmetroPayload?.ca_nonmetros, {\n      metricsMap: caNonmetroMetricsByCode,\n      totalsMap: caNonmetroTotalsByCode,\n      wagesMap: caNonmetroWagesByCode,\n      exposureMap: caNonmetroExposureByCode,\n      codeField: \"area_code\",\n      normalizeCode: normalizeProvinceCode,\n    });\n\n    caAreaFeatures = getTopoFeatures(compositesTopology, [\"areas\", \"ca_areas\"])\n      .filter((feature) => feature && feature.geometry)\n      .map(normalizeCaAreaFeature);\n    // Register in the shared outline index \u2014 the \"cma:\"/\"ca_nonmetro:\" key\n    // prefixes can't collide with the US \"metro:\"/\"nonmetro:\" entries.\n    for (const feature of caAreaFeatures) {\n      const areaKey = feature?.properties?.area_key;\n      if (areaKey) areaOutlineFeatureByKey.set(areaKey, feature);\n    }\n  },\n});\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureCaAreasLoaded({ cfg }) {\n  pendingCfg = cfg;\n  return loadCaAreas();\n}\n", "// @ts-check\n\n// Fetches the world topology (with CDN fallbacks) and derives the land feature\n// + country-border mesh. On success flips `worldLoaded`; subscribers on that\n// signal (see map/post-load.js) render the base layer. Failure is silently\n// tolerated \u2014 the map renders without world context rather than blocking.\n\nimport { fetchJsonWithFallback } from \"./fetch.js\";\nimport { worldLoaded } from \"../state/caches.js\";\n\nlet loadingPromise = /** @type {Promise<void> | null} */ (null);\nlet worldLandFeature = /** @type {any} */ (null);\nlet worldCountryBorders = /** @type {any} */ (null);\n\nexport function getWorldLandFeature() {\n  return worldLandFeature;\n}\n\nexport function getWorldCountryBorders() {\n  return worldCountryBorders;\n}\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureWorldLoaded({ cfg }) {\n  if (worldLoaded.get()) return;\n  if (loadingPromise) return loadingPromise;\n\n  loadingPromise = (async () => {\n    const worldTopology = await fetchJsonWithFallback([\n      cfg.worldTopoCdnUrl,\n      cfg.worldTopoUrl,\n      \"/static/geo/world_land_110m.topojson\",\n      \"/static/geo/world_land.topojson\",\n    ], {\n      asset: \"world_land_110m\",\n      fallbackLogUrl: cfg.assetFallbackLogUrl,\n    }).catch(() => null);\n\n    if (worldTopology && worldTopology.objects) {\n      const worldObjects = worldTopology.objects;\n      const landObjectName = [\"land\", \"countries\", \"units\"].find((name) => worldObjects[name]);\n      if (landObjectName) {\n        // @ts-ignore window.topojson global\n        worldLandFeature = topojson.feature(worldTopology, worldObjects[landObjectName]);\n      }\n      if (worldObjects.countries) {\n        // @ts-ignore window.topojson global\n        worldCountryBorders = topojson.mesh(worldTopology, worldObjects.countries, (a, b) => a !== b);\n      }\n    }\n\n    worldLoaded.set(true);\n  })();\n\n  return loadingPromise;\n}\n", "// @ts-check\n\n// Single source of truth for the /api/map/top-job-families fetch.\n//\n// Before this module the same per-region job-families payload was fetched\n// from SIX call sites (desktop refresh + nav, mobile refresh + nav, and the\n// two national-exposure loaders), each keyed by scope:code:metric:limit:view.\n// Toggling the metric, switching view mode, or revisiting a region therefore\n// refetched identical bytes, and a first paint could fetch the nation payload\n// 2-4\u00D7.\n//\n// The key realisation: the server ships BOTH exposure fields (current_exposure\n// and theoretical_exposure) on every family object, and its sort/slice is a\n// pure function of the payload (sort by -workers, -metric_field; slice[:limit]).\n// So ONE canonical limit=500 fetch per (scope, code) can serve every view and\n// both metrics \u2014 the client just re-sorts/re-slices in `sortFamiliesForDisplay`\n// / `topFamilies` with exact server parity. This module owns that one fetch as\n// a module-level singleton with an LRU of recent regions (caches are owned by\n// data/* per state/caches.js doc).\n//\n// TRUNCATION ASSUMPTION: we fetch limit=500 (the server clamp \u2014 see\n// views.py::api_map_top_job_families `min(limit, 500)`). A region with more\n// than 500 job families would be silently truncated to the top 500 by workers.\n// In practice the family taxonomy is far under 500 entries, so limit=500 is\n// effectively \"all families\" and the client slice never under-serves a view.\n\nimport { fetchJson } from \"./fetch.js\";\n\n// Server clamps `limit` to 500 (views.py). Fetching at the clamp gives us the\n// full family set in one request so every view/metric can be served from it.\nconst FAMILY_FETCH_LIMIT = 500;\n\n// LRU bound on distinct regions held in memory. 24 comfortably covers a\n// browsing session (US + a handful of states/metros/nonmetros) without letting\n// the cache grow unbounded across a long exploration.\nconst MAX_CACHED_REGIONS = 24;\n\n// The nation payload is fetched on every first paint and underpins the\n// national-exposure color baseline; pin it so it's never the LRU victim.\nconst PINNED_KEY = \"nation:us\";\n\n/**\n * @typedef {{ promise: Promise<any[]>, settled: any[] | null }} FamiliesEntry\n */\n\n/** @type {Map<string, FamiliesEntry>} */\nconst familiesCache = new Map();\n\nfunction cacheKey(scope, code) {\n  return `${scope}:${code}`;\n}\n\n// Evict oldest non-pinned entries until the cache is within bound. Map\n// iteration order is insertion order, so the first non-pinned key is the LRU\n// victim (loadJobFamilies re-inserts on hit to keep recency accurate).\nfunction evictIfNeeded() {\n  while (familiesCache.size > MAX_CACHED_REGIONS) {\n    let victim = null;\n    for (const key of familiesCache.keys()) {\n      if (key !== PINNED_KEY) {\n        victim = key;\n        break;\n      }\n    }\n    if (victim == null) break; // only the pinned key remains\n    familiesCache.delete(victim);\n  }\n}\n\n/**\n * Load the job-families payload for one region, deduped and cached.\n *\n * On a cache hit the entry is LRU-touched (delete + re-set) and its in-flight\n * or settled promise returned. On a miss the promise is stored BEFORE awaiting\n * (in-flight dedup \u2014 two concurrent callers share one fetch), then the\n * canonical `limit=500` URL is fetched with NO metric param (the server\n * accepts it and ships both metric fields). On rejection the entry is evicted\n * before rethrowing so a retry can re-fetch (treemap retry banners depend on\n * this eviction).\n *\n * @param {{ cfg: import(\"../types.js\").Cfg, scope: string, code: string }} args\n * @returns {Promise<any[]>}\n */\nexport function loadJobFamilies({ cfg, scope, code }) {\n  if (!cfg || !cfg.topOccupationsApiUrl || !scope || !code) {\n    return Promise.resolve([]);\n  }\n  const key = cacheKey(scope, code);\n\n  const existing = familiesCache.get(key);\n  if (existing) {\n    // LRU touch: re-insert at the tail so this region is treated as most-recent.\n    familiesCache.delete(key);\n    familiesCache.set(key, existing);\n    return existing.promise;\n  }\n\n  /** @type {FamiliesEntry} */\n  const entry = { promise: /** @type {any} */ (null), settled: null };\n  entry.promise = (async () => {\n    const params = new URLSearchParams({\n      scope,\n      code,\n      limit: String(FAMILY_FETCH_LIMIT),\n    });\n    const version = String((cfg && cfg.mapCacheVersion) || \"\").trim();\n    if (version) params.set(\"v\", version);\n    try {\n      const payload = await fetchJson(`${cfg.topOccupationsApiUrl}?${params.toString()}`);\n      const families = Array.isArray(payload && payload.job_families) ? payload.job_families : [];\n      entry.settled = families;\n      return families;\n    } catch (error) {\n      // Evict before rethrowing so the failed key isn't pinned as a poisoned\n      // entry \u2014 a subsequent call (retry banner) re-fetches. Identity-guard the\n      // delete (compare-and-delete): if this entry was already LRU-evicted and a\n      // newer loadJobFamilies(key) inserted a fresh in-flight entry, a late\n      // rejection here must not remove that healthy successor.\n      if (familiesCache.get(key) === entry) familiesCache.delete(key);\n      throw error;\n    }\n  })();\n\n  // Store the in-flight promise BEFORE awaiting so a concurrent caller dedupes\n  // onto it (same idiom as the old index.js navFamilies path).\n  familiesCache.set(key, entry);\n  evictIfNeeded();\n  return entry.promise;\n}\n\n/**\n * Synchronous cache peek used by the render path to avoid a loading-text flash\n * on metric/resize refresh: if the region is already settled, return its array;\n * otherwise null (caller falls back to the async load).\n *\n * @param {string} scope\n * @param {string} code\n * @returns {any[] | null}\n */\nexport function peekJobFamilies(scope, code) {\n  const entry = familiesCache.get(cacheKey(scope, code));\n  return entry ? entry.settled : null;\n}\n\n/**\n * Sort a COPY of the families with EXACT server parity: descending workers,\n * then descending metric_field, both stable so ties keep payload order (Python\n * `list.sort` is stable; a null/missing value coerces to 0 exactly like the\n * server's `item.get(field) or 0`).\n *\n * @param {any[]} families\n * @param {string} metricField current_exposure | theoretical_exposure\n * @returns {any[]}\n */\nexport function sortFamiliesForDisplay(families, metricField) {\n  const num = (v) => Number(v) || 0;\n  const arr = [...(families || [])];\n  arr.sort((a, b) => (num(b.workers) - num(a.workers)) || (num(b[metricField]) - num(a[metricField])));\n  return arr;\n}\n\n/**\n * Server-parity sort + slice. `limit` mirrors `families[:limit]` after the\n * sort; the server additionally clamps to 500 but the client view limits\n * (5 / 280) are always under it.\n *\n * @param {any[]} families\n * @param {{ metricField: string, limit: number }} opts\n * @returns {any[]}\n */\nexport function topFamilies(families, { metricField, limit }) {\n  const sorted = sortFamiliesForDisplay(families, metricField);\n  return Number.isFinite(limit) && limit >= 0 ? sorted.slice(0, limit) : sorted;\n}\n\n/**\n * Drop all cached regions. Used by data/cache-version.js when the server-side\n * map cache version changes, and by unit tests to reset module state.\n */\nexport function clearJobFamiliesCache() {\n  familiesCache.clear();\n}\n", "// @ts-check\n\n// Request caches owned by the top-occupations drilldown.\n//\n// The per-region job-families payload is no longer cached here \u2014 that fetch is\n// now a module-level singleton in data/job-families.js (one canonical limit=500\n// fetch per region serves every view + both metrics via a client-side re-sort),\n// so the old `topOccupations` and `navFamilies` maps are gone.\n//\n// `occupationTasks` is an LRU keyed by scope:code:soc_code (capped in\n// index.js / mobile.js on insert). `lastSelectionKey` tracks the most recent\n// selection's scope:code so a change can reset drilldown without re-deriving it.\n\n/** @type {Set<ReturnType<typeof createTopOccupationsCaches>>} */\nconst activeCaches = new Set();\n\nexport function createTopOccupationsCaches() {\n  const caches = {\n    /** @type {Map<string, any[]>} */\n    occupationTasks: new Map(),\n    /** @type {Map<string, Promise<any[]>>} */\n    occupationTasksInflight: new Map(),\n    /** Tracks the scope:code of the most recent selection so a change can\n     *  reset drilldown without re-deriving the key. */\n    lastSelectionKey: \"\",\n  };\n  activeCaches.add(caches);\n  return caches;\n}\n\nexport function clearAllOccupationTasksCaches() {\n  for (const caches of activeCaches) {\n    caches.occupationTasks.clear();\n    caches.occupationTasksInflight.clear();\n  }\n}\n", "// @ts-check\n\n// Fetches the nation-wide drilldown payload once per session and populates\n// the single-value holders in state/caches.js (`nation` for US, `nationCa` for\n// Canada). The backend already aggregates every sub-region into this payload\n// (see management/commands/refresh_map_cache.py::_refresh_nation_payload), so\n// the client just consumes it. Used by the side panel to show country-wide\n// totals when the nation view is selected.\n\nimport { normalizeFiniteNumber, normalizeNullableFiniteNumber } from \"../util/format.js\";\nimport { nation, nationCa, nationLoaded, nationCaLoaded } from \"../state/caches.js\";\nimport { fetchJson } from \"./fetch.js\";\nimport { deriveCalibratedMetric } from \"./_populate.js\";\nimport { appendMapCacheVersion } from \"./api-url.js\";\n\n// Per-country in-flight promise guards. Keyed by country code so a US load and\n// a (future) Canada load don't share/clobber each other's promise.\nconst loadingPromises = /** @type {Record<string, Promise<void> | null>} */ ({});\n\n/**\n * Reset hook for data/geography-reset.js: drop the per-country promise guards\n * so a mid-session cache bust can refetch. A settled promise stays in\n * `loadingPromises` for the whole session (it's only nulled on rejection), so\n * without this, `ensureNationLoaded` would keep returning the stale settled\n * promise even after the holders were nulled.\n */\nexport function resetNationLoaders() {\n  for (const country of Object.keys(loadingPromises)) {\n    loadingPromises[country] = null;\n  }\n}\n\n/**\n * @param {string} country\n * @returns {{ totalWorkforce: number | null, totalWageBill: number | null, exposure: any }}\n */\nfunction holderForCountry(country) {\n  return country === \"ca\" ? nationCa : nation;\n}\n\n/**\n * @param {string} country\n * @returns {import(\"../signal.js\").Signal<boolean>}\n */\nfunction loadedSignalForCountry(country) {\n  return country === \"ca\" ? nationCaLoaded : nationLoaded;\n}\n\n/**\n * Load the nation-wide aggregate for a country into its caches holder.\n * Defaults to the US so existing callers (`ensureNationLoaded({ cfg })`) keep\n * their current behavior byte-for-byte. Idempotent per country: a populated\n * holder short-circuits, and concurrent callers share one in-flight promise.\n *\n * @param {{ cfg: import(\"../types.js\").Cfg, country?: string }} opts\n */\nexport async function ensureNationLoaded({ cfg, country = \"us\" }) {\n  const holder = holderForCountry(country);\n  if (holder.totalWorkforce != null || holder.totalWageBill != null || holder.exposure != null) {\n    return;\n  }\n  if (loadingPromises[country]) return loadingPromises[country];\n\n  loadingPromises[country] = (async () => {\n    try {\n      const params = new URLSearchParams({ scope: \"nation\", code: country });\n      const payload = await fetchJson(\n        appendMapCacheVersion(`${cfg.drilldownApiUrl}?${params.toString()}`, cfg),\n      );\n      const summary = (payload && payload.summary) || {};\n\n      const totalWorkforce = Number(summary.total_workforce);\n      const totalWageBill = Number(summary.total_wage_bill);\n      holder.totalWorkforce = Number.isFinite(totalWorkforce) ? totalWorkforce : null;\n      holder.totalWageBill = Number.isFinite(totalWageBill) ? totalWageBill : null;\n      holder.exposure = {\n        ability: {\n          exposedWageBill: normalizeFiniteNumber(summary.exposed_wage_bill_theoretical),\n          exposedWorkforce: normalizeFiniteNumber(summary.exposed_workforce_theoretical),\n          wageRatio: normalizeFiniteNumber(summary.wage_bill_ratio_theoretical),\n        },\n        penetration: {\n          exposedWageBill: normalizeFiniteNumber(summary.exposed_wage_bill_current),\n          exposedWorkforce: normalizeFiniteNumber(summary.exposed_workforce_current),\n          wageRatio: normalizeFiniteNumber(summary.wage_bill_ratio_current),\n        },\n        // Nullable on the wire: null means zero calibrated coverage (no data),\n        // not zero exposure \u2014 preserve it so the panel renders \"--\" instead of\n        // fake zeros (same contract as data/_populate.js).\n        calibrated: {\n          exposedWageBill: normalizeNullableFiniteNumber(summary.exposed_wage_bill_calibrated),\n          exposedWorkforce: normalizeNullableFiniteNumber(summary.exposed_workforce_calibrated),\n          wageRatio: normalizeNullableFiniteNumber(summary.wage_bill_ratio_calibrated),\n        },\n      };\n      // Country-fill metric triple. The nation summary exposes the workforce\n      // exposure fractions directly (exp_workers / total_workers on the\n      // backend \u2014 see _refresh/map_payloads.py), so theoretical/current are a\n      // direct read in the SAME [theoretical, current, calibrated] order the\n      // region metric arrays use (data/_populate.js) and that\n      // getSelectedMetricIndex maps to. The calibrated slot goes through\n      // deriveCalibratedMetric (shared with the region path) so it inherits the\n      // stale-payload guard: a pre-calibrated cache defaulting calibrated_exposure\n      // to 0 without workforce fields paints grey (no-data), not blue 0.\n      holder.metrics = [\n        normalizeFiniteNumber(summary.theoretical_exposure),\n        normalizeFiniteNumber(summary.current_exposure),\n        deriveCalibratedMetric(summary, totalWorkforce),\n      ];\n      loadedSignalForCountry(country).set(true);\n    } catch (err) {\n      loadingPromises[country] = null;\n      throw err;\n    }\n  })();\n\n  return loadingPromises[country];\n}\n", "// @ts-check\n\n// Reset in-memory geography metric caches and loader memoization so a\n// map-cache promote or a switch to Current Capabilities can refetch bulk\n// JSON that includes calibrated workforce fields.\n\nimport {\n  stateMetricsByCode,\n  msaMetricsByCode,\n  nonmetroMetricsByCode,\n  provinceMetricsByCode,\n  cmaMetricsByCode,\n  caNonmetroMetricsByCode,\n  stateTotalsByCode,\n  msaTotalsByCode,\n  nonmetroTotalsByCode,\n  provinceTotalsByCode,\n  cmaTotalsByCode,\n  caNonmetroTotalsByCode,\n  stateWagesByCode,\n  msaWagesByCode,\n  nonmetroWagesByCode,\n  provinceWagesByCode,\n  cmaWagesByCode,\n  caNonmetroWagesByCode,\n  stateExposureByCode,\n  msaExposureByCode,\n  nonmetroExposureByCode,\n  provinceExposureByCode,\n  cmaExposureByCode,\n  caNonmetroExposureByCode,\n  metricDomainCache,\n  nation,\n  nationCa,\n  statesLoaded,\n  msaMetricsLoaded,\n  provincesLoaded,\n  caAreasLoaded,\n  nonmetrosLoaded,\n  nationLoaded,\n  nationCaLoaded,\n} from \"../state/caches.js\";\nimport { resetNationLoaders } from \"./nation.js\";\n\nfunction clearMetricDomainCache() {\n  metricDomainCache.state.clear();\n  metricDomainCache.msa.clear();\n  metricDomainCache.nonmetro.clear();\n  metricDomainCache.province.clear();\n  metricDomainCache.cma.clear();\n  metricDomainCache.caNonmetro.clear();\n  metricDomainCache.stateCombined.clear();\n  metricDomainCache.areaCombined.clear();\n}\n\n/** Drop every geography metrics map and allow loaders to refetch. */\nexport function resetAllGeographyLoaders() {\n  stateMetricsByCode.clear();\n  msaMetricsByCode.clear();\n  nonmetroMetricsByCode.clear();\n  provinceMetricsByCode.clear();\n  cmaMetricsByCode.clear();\n  caNonmetroMetricsByCode.clear();\n\n  stateTotalsByCode.clear();\n  msaTotalsByCode.clear();\n  nonmetroTotalsByCode.clear();\n  provinceTotalsByCode.clear();\n  cmaTotalsByCode.clear();\n  caNonmetroTotalsByCode.clear();\n\n  stateWagesByCode.clear();\n  msaWagesByCode.clear();\n  nonmetroWagesByCode.clear();\n  provinceWagesByCode.clear();\n  cmaWagesByCode.clear();\n  caNonmetroWagesByCode.clear();\n\n  stateExposureByCode.clear();\n  msaExposureByCode.clear();\n  nonmetroExposureByCode.clear();\n  provinceExposureByCode.clear();\n  cmaExposureByCode.clear();\n  caNonmetroExposureByCode.clear();\n\n  clearMetricDomainCache();\n\n  // Country-layer state (post-dates main's version of this file): both nation\n  // holders carry a choropleth `metrics` triple that paints the Country fill,\n  // and data/nation.js memoizes each country's load behind a `loaded` signal\n  // plus a module-level promise guard. Clear all three, or a mid-session bust\n  // would repaint every layer fresh EXCEPT a stale Country fill (and\n  // ensureNationLoaded would short-circuit instead of refetching).\n  nation.totalWorkforce = null;\n  nation.totalWageBill = null;\n  nation.exposure = null;\n  nation.metrics = null;\n  nationCa.totalWorkforce = null;\n  nationCa.totalWageBill = null;\n  nationCa.exposure = null;\n  nationCa.metrics = null;\n  resetNationLoaders();\n\n  statesLoaded.set(false);\n  msaMetricsLoaded.set(false);\n  provincesLoaded.set(false);\n  caAreasLoaded.set(false);\n  nonmetrosLoaded.set(false);\n  nationLoaded.set(false);\n  nationCaLoaded.set(false);\n}\n", "// @ts-check\n\nimport { clearJobFamiliesCache } from \"./job-families.js\";\nimport { clearAllOccupationTasksCaches } from \"../panel/top-occupations/caches.js\";\nimport { clearExplanationCache } from \"../panel/task-explanation.js\";\nimport { resetAllGeographyLoaders } from \"./geography-reset.js\";\n\nconst STORAGE_KEY = \"us-ai-map:cache-version\";\n\n/** @type {Set<() => void>} */\nconst resetNationalExposureHooks = new Set();\n\n/** @param {() => void} reset */\nexport function registerNationalExposureReset(reset) {\n  resetNationalExposureHooks.add(reset);\n}\n\n/**\n * Drop in-memory drilldown caches when the server-side map cache version\n * changes (after refresh_map_cache). Bulk geography payloads are always\n * refetched on page load; job-family payloads are session-cached and can\n * otherwise retain pre-calibrated rows with calibrated_exposure: 0. Occupation-\n * task payloads are session-cached too and can lack calibrated_beta until refetched.\n *\n * @param {{ mapCacheVersion?: string }} cfg\n */\nexport function bustStaleClientCachesIfNeeded(cfg) {\n  const version = String((cfg && cfg.mapCacheVersion) || \"\").trim();\n  if (!version) return;\n  try {\n    const previous = sessionStorage.getItem(STORAGE_KEY);\n    if (previous && previous !== version) {\n      clearJobFamiliesCache();\n      clearAllOccupationTasksCaches();\n      clearExplanationCache();\n      resetAllGeographyLoaders();\n      for (const resetNationalExposure of resetNationalExposureHooks) {\n        resetNationalExposure();\n      }\n    }\n    sessionStorage.setItem(STORAGE_KEY, version);\n  } catch (_error) {\n    // sessionStorage unavailable (private mode) \u2014 skip busting.\n  }\n}\n", "// @ts-check\n\n// Fetches the US counties topology (with CDN + static fallbacks) and derives\n// the interior-only county-border mesh used to draw faint county outlines\n// inside states/metros/nonmetros. On success flips `countyBordersLoaded`;\n// subscribers on that signal (see map/post-load.js) render the layer.\n//\n// Failure is silently tolerated \u2014 the map renders without county detail\n// rather than blocking. Mirrors the world.js pattern.\n\nimport { fetchJsonWithFallback } from \"./fetch.js\";\nimport { countyBordersLoaded } from \"../state/caches.js\";\n\nlet loadingPromise = /** @type {Promise<void> | null} */ (null);\nlet countyBorders = /** @type {any} */ (null);\n\nexport function getCountyBorders() {\n  return countyBorders;\n}\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureCountyBordersLoaded({ cfg }) {\n  if (countyBordersLoaded.get()) return;\n  if (loadingPromise) return loadingPromise;\n\n  loadingPromise = (async () => {\n    const countiesTopology = await fetchJsonWithFallback([\n      cfg.countiesTopoCdnUrl,\n      cfg.countiesTopoUrl,\n      \"/static/geo/us_counties.topojson\",\n    ], {\n      asset: \"us_counties\",\n      fallbackLogUrl: cfg.assetFallbackLogUrl,\n    }).catch(() => null);\n\n    if (countiesTopology && countiesTopology.objects) {\n      const objects = countiesTopology.objects;\n      const countyObjectName = [\"counties\", \"us_counties\", \"nation_counties\"]\n        .find((name) => objects[name]) || Object.keys(objects)[0];\n      if (countyObjectName) {\n        // Interior-only mesh: arcs shared by two counties draw once, exterior\n        // arcs (state borders / coast) are skipped \u2014 those come from the\n        // states layer and dissolved metro/nonmetro composites respectively.\n        // @ts-ignore window.topojson global\n        countyBorders = topojson.mesh(\n          countiesTopology,\n          objects[countyObjectName],\n          (a, b) => a !== b,\n        );\n      }\n    }\n\n    countyBordersLoaded.set(true);\n  })();\n\n  return loadingPromise;\n}\n", "// @ts-check\n\n// Fetches the Canadian census-divisions topology and derives the\n// interior-only border mesh used to draw faint census-division outlines\n// inside provinces/CMAs \u2014 the Canadian counterpart of data/counties.js.\n// On success flips `caCdBordersLoaded`; subscribers on that signal (see\n// map/post-load.js) render the layer.\n//\n// Failure is silently tolerated \u2014 the map renders without census-division\n// detail rather than blocking. Mirrors the counties.js pattern.\n\nimport { fetchJsonWithFallback } from \"./fetch.js\";\nimport { caCdBordersLoaded } from \"../state/caches.js\";\n\nlet loadingPromise = /** @type {Promise<void> | null} */ (null);\nlet caCdBorders = /** @type {any} */ (null);\n\nexport function getCaCdBorders() {\n  return caCdBorders;\n}\n\n/**\n * @param {{ cfg: import(\"../types.js\").Cfg }} opts\n */\nexport async function ensureCaCdBordersLoaded({ cfg }) {\n  if (caCdBordersLoaded.get()) return;\n  if (loadingPromise) return loadingPromise;\n\n  loadingPromise = (async () => {\n    const topology = await fetchJsonWithFallback([\n      cfg.caCensusDivisionsTopoUrl,\n      \"/static/geo/ca_census_divisions.topojson\",\n    ], {\n      asset: \"ca_census_divisions\",\n      fallbackLogUrl: cfg.assetFallbackLogUrl,\n    }).catch(() => null);\n\n    if (topology && topology.objects) {\n      const objects = topology.objects;\n      const objectName = [\"census_divisions\", \"ca_census_divisions\"]\n        .find((name) => objects[name]) || Object.keys(objects)[0];\n      if (objectName) {\n        // Interior-only mesh: arcs shared by two census divisions draw once,\n        // exterior arcs (province borders / coast) are skipped \u2014 those come\n        // from the provinces layer and the CMA/rest-of-province composites.\n        // @ts-ignore window.topojson global\n        caCdBorders = topojson.mesh(\n          topology,\n          objects[objectName],\n          (a, b) => a !== b,\n        );\n      }\n    }\n\n    caCdBordersLoaded.set(true);\n  })();\n\n  return loadingPromise;\n}\n", "// @ts-check\n\n// URL <-> selection map for deep-linking + history sync (plan unit E).\n//\n// The server (views.api_map_geo_urls / utils.geo_registry.geo_url_map) exposes\n// the full `{ \"scope:code\": \"/us-ai-map/<country>/<region>/[<area>/]\" }` table\n// at `cfg.geoUrlsApiUrl`. We fetch it once at boot and build two views:\n//   forward  (\"scope:code\" -> url_path)  for writing history on selection\n//   reverse  (url_path     -> {kind,code}) for resolving a deep-link / popstate\n//\n// The map is fixed for the life of a deploy (built from static topojson at\n// process start), so a single write-once fetch is correct \u2014 no TTL, mirroring\n// the data/*.js cache convention in state/caches.js.\n//\n// `kind` here is the same vocabulary as currentSelection.kind /\n// render.js commitSelection: state | msa | nonmetro | province | cma |\n// ca_nonmetro, plus the synthetic \"nation\" used for the bare /us-ai-map/ root.\n\n/** Canonical root path for the nation (US) view \u2014 server emits no entity row for it. */\nconst NATION_PATH = \"/us-ai-map/\";\n\n/**\n * Per-country hub paths (server emits no entity row for these either). The bare\n * NATION_PATH and the explicit /us-ai-map/us/ both resolve to the US nation; the\n * /us-ai-map/ca/ hub resolves to the Canada nation view.\n * @type {Record<string, string>}\n */\nconst NATION_HUB_PATHS = {\n  \"/us-ai-map/us/\": \"us\",\n  \"/us-ai-map/ca/\": \"ca\",\n};\n\n/** @type {Map<string, string>} forward: \"kind:code\" -> url_path */\nlet forwardMap = new Map();\n/** @type {Map<string, {kind: string, code: string}>} reverse: normalized path -> {kind,code} */\nlet reverseMap = new Map();\nlet loaded = false;\nlet loadingPromise = /** @type {Promise<void> | null} */ (null);\n\n/**\n * Normalize a pathname for reverse lookup: strip query/hash is the caller's job\n * (we only ever receive location.pathname), but we must reconcile trailing\n * slashes since the server keys are always slash-terminated while history /\n * direct navigation may or may not include one.\n * @param {string} pathname\n * @returns {string}\n */\nfunction normalizePath(pathname) {\n  if (!pathname) return NATION_PATH;\n  let path = pathname;\n  // Collapse the bare \"/us-ai-map\" (no trailing slash) to the canonical root.\n  if (path !== \"/\" && path.endsWith(\"/\")) {\n    return path;\n  }\n  return `${path}/`;\n}\n\n/**\n * Fetch the slug table once and build the forward/reverse indexes. Idempotent:\n * concurrent callers share one in-flight promise; a settled load is a no-op.\n * Failure leaves the maps empty (deep-link/history simply degrade to no-op) and\n * is intentionally swallowed by the caller \u2014 URL sync is non-critical UX.\n * @param {{ geoUrlsApiUrl?: string }} cfg\n * @returns {Promise<void>}\n */\nexport async function ensureGeoUrlsLoaded(cfg) {\n  if (loaded) return;\n  if (loadingPromise) return loadingPromise;\n  const url = cfg && cfg.geoUrlsApiUrl;\n  if (!url) {\n    loaded = true;\n    return;\n  }\n  loadingPromise = (async () => {\n    try {\n      const response = await fetch(url, { headers: { Accept: \"application/json\" } });\n      if (!response.ok) {\n        throw new Error(`geo-urls fetch failed: ${response.status}`);\n      }\n      /** @type {Record<string, string>} */\n      const table = await response.json();\n      const nextForward = new Map();\n      const nextReverse = new Map();\n      for (const [key, path] of Object.entries(table)) {\n        nextForward.set(key, path);\n        // key is \"kind:code\"; split on the FIRST colon only (codes are numeric,\n        // but be defensive in case a future code ever contains one).\n        const sep = key.indexOf(\":\");\n        if (sep === -1) continue;\n        const kind = key.slice(0, sep);\n        const code = key.slice(sep + 1);\n        nextReverse.set(normalizePath(path), { kind, code });\n      }\n      forwardMap = nextForward;\n      reverseMap = nextReverse;\n      loaded = true;\n    } catch (err) {\n      // Leave maps empty; callers treat undefined results as \"no URL sync\".\n      loaded = true;\n      throw err;\n    } finally {\n      loadingPromise = null;\n    }\n  })();\n  return loadingPromise;\n}\n\n/**\n * Forward lookup: the canonical URL for a selection, or undefined if unknown.\n * The nation kind maps to its per-country hub: \"us\" (and any unknown/bare code)\n * \u2192 the bare root /us-ai-map/, \"ca\" \u2192 /us-ai-map/ca/.\n * @param {string} kind\n * @param {string} code\n * @returns {string | undefined}\n */\nexport function urlForKey(kind, code) {\n  if (kind === \"nation\") {\n    if (code === \"ca\") return \"/us-ai-map/ca/\";\n    return NATION_PATH;\n  }\n  return forwardMap.get(`${kind}:${code}`);\n}\n\n/**\n * Reverse lookup: the {kind, code} for a pathname, or undefined if unknown.\n * The bare root and the per-country hubs resolve to the nation selection so a\n * popstate back to \"/us-ai-map/\" (or \"/us-ai-map/us/\" / \"/us-ai-map/ca/\") restores\n * the correct country view rather than the wrong nation default.\n * @param {string} pathname\n * @returns {{kind: string, code: string} | undefined}\n */\nexport function keyForPath(pathname) {\n  const path = normalizePath(pathname);\n  if (path === NATION_PATH) return { kind: \"nation\", code: \"us\" };\n  const hubCode = NATION_HUB_PATHS[path];\n  if (hubCode) return { kind: \"nation\", code: hubCode };\n  return reverseMap.get(path);\n}\n", "// @ts-check\n\nimport { LAYER_MODE_AREA, LAYER_MODE_STATE, LAYER_MODE_COUNTRY, MOBILE_QUERY } from \"../config.js\";\n\n// Country codes for the \"Country\" layer's nation aggregates (consumed by\n// us_ai_map.js's onCountrySelect).\nexport const COUNTRY_US = \"us\";\nexport const COUNTRY_CA = \"ca\";\n\n// Visual value for the \"Country\" granularity. It is a real fill layer mode\n// (LAYER_MODE_COUNTRY): selecting it shows the whole-country choropleth (US +\n// Canada polygons filled by their national aggregate). Its layerValue drives\n// setLayerMode like the Metro/States options. Kept as a distinct export (its\n// value equals LAYER_MODE_COUNTRY) so existing importers stay valid.\nexport const LAYER_VISUAL_COUNTRY = LAYER_MODE_COUNTRY;\n\nexport class LayerToggle {\n  /**\n   * @param {{\n   *   mountEl: HTMLElement | null,\n   *   value?: string,\n   *   onChange?: (visualValue: string) => void,\n   * }} opts\n   */\n  constructor({ mountEl, value = LAYER_MODE_AREA, onChange = () => {} }) {\n    this.mountEl = mountEl;\n    this.value = value === LAYER_MODE_AREA ? LAYER_MODE_AREA : LAYER_MODE_STATE;\n    this.onChange = onChange;\n    this.visualValue = this.value;\n    this.optionByVisualValue = new Map();\n    this.groupName = `map-layer-toggle-${Math.random().toString(36).slice(2, 9)}`;\n    this._mq = typeof window !== \"undefined\" && window.matchMedia\n      ? window.matchMedia(MOBILE_QUERY)\n      : null;\n    this._mqHandler = null;\n  }\n\n  render() {\n    if (!this.mountEl) return;\n\n    const isMobile = this._mq ? this._mq.matches : false;\n    if (isMobile) {\n      this._renderSegmented();\n    } else {\n      this._renderRadios();\n    }\n\n    // Re-render on breakpoint cross so desktop\u21C4mobile resize swaps markup.\n    if (this._mq && !this._mqHandler) {\n      this._mqHandler = () => this.render();\n      this._mq.addEventListener(\"change\", this._mqHandler);\n    }\n\n    this.sync();\n  }\n\n  _options() {\n    return [\n      { visualValue: LAYER_MODE_AREA, layerValue: LAYER_MODE_AREA, label: \"Metro. areas\" },\n      { visualValue: LAYER_MODE_STATE, layerValue: LAYER_MODE_STATE, label: \"States\" },\n      { visualValue: LAYER_VISUAL_COUNTRY, layerValue: LAYER_MODE_COUNTRY, label: \"Country\" },\n    ];\n  }\n\n  _renderRadios() {\n    if (!this.mountEl) return;\n    this.mountEl.innerHTML = \"\";\n    this.optionByVisualValue.clear();\n\n    const panel = document.createElement(\"section\");\n    panel.className = \"map-layer-toggle\";\n    panel.setAttribute(\"role\", \"radiogroup\");\n    panel.setAttribute(\"aria-label\", \"Layers\");\n\n    const title = document.createElement(\"h2\");\n    title.className = \"map-layer-toggle__title\";\n    title.textContent = \"Layers\";\n    panel.appendChild(title);\n\n    const optionsWrap = document.createElement(\"div\");\n    optionsWrap.className = \"map-layer-toggle__options\";\n\n    for (const option of this._options()) {\n      const optionRow = document.createElement(\"div\");\n      optionRow.className = \"map-layer-toggle__option\";\n\n      const input = document.createElement(\"input\");\n      const inputId = `${this.groupName}-${option.visualValue}`;\n      input.type = \"radio\";\n      input.className = \"map-layer-toggle__input\";\n      input.name = this.groupName;\n      input.id = inputId;\n      input.value = option.visualValue;\n      input.setAttribute(\"aria-label\", option.label);\n\n      const label = document.createElement(\"label\");\n      label.className = \"map-layer-toggle__label\";\n      label.setAttribute(\"for\", inputId);\n\n      const marker = document.createElement(\"span\");\n      marker.className = \"map-layer-toggle__marker\";\n      marker.setAttribute(\"aria-hidden\", \"true\");\n\n      const text = document.createElement(\"span\");\n      text.className = \"map-layer-toggle__label-text\";\n      text.textContent = option.label;\n\n      label.appendChild(marker);\n      label.appendChild(text);\n\n      input.addEventListener(\"change\", () => {\n        if (!input.checked) return;\n        this.setVisualValue(option.visualValue, true);\n      });\n\n      optionRow.appendChild(input);\n      optionRow.appendChild(label);\n      optionsWrap.appendChild(optionRow);\n\n      this.optionByVisualValue.set(option.visualValue, { ...option, input, label });\n    }\n\n    panel.appendChild(optionsWrap);\n    this.mountEl.appendChild(panel);\n  }\n\n  _renderSegmented() {\n    if (!this.mountEl) return;\n    this.mountEl.innerHTML = \"\";\n    this.optionByVisualValue.clear();\n\n    const panel = document.createElement(\"section\");\n    panel.className = \"map-layer-toggle\";\n    panel.setAttribute(\"role\", \"radiogroup\");\n    panel.setAttribute(\"aria-label\", \"Layers\");\n\n    const title = document.createElement(\"h2\");\n    title.className = \"map-layer-toggle__title\";\n    title.textContent = \"Layers\";\n    panel.appendChild(title);\n\n    const segmented = document.createElement(\"div\");\n    segmented.className = \"glass-segmented map-layer-toggle__segmented\";\n\n    for (const option of this._options()) {\n      const optionEl = document.createElement(\"label\");\n      optionEl.className = \"glass-segmented__option\";\n\n      const input = document.createElement(\"input\");\n      const inputId = `${this.groupName}-${option.visualValue}`;\n      input.type = \"radio\";\n      input.className = \"map-layer-toggle__input\";\n      input.name = this.groupName;\n      input.id = inputId;\n      input.value = option.visualValue;\n      input.setAttribute(\"aria-label\", option.label);\n\n      const text = document.createElement(\"span\");\n      text.className = \"glass-segmented__option-label\";\n      text.textContent = option.label;\n\n      input.addEventListener(\"change\", () => {\n        if (!input.checked) return;\n        this.setVisualValue(option.visualValue, true);\n      });\n\n      optionEl.appendChild(input);\n      optionEl.appendChild(text);\n      segmented.appendChild(optionEl);\n\n      this.optionByVisualValue.set(option.visualValue, { ...option, input, label: optionEl });\n    }\n\n    panel.appendChild(segmented);\n    this.mountEl.appendChild(panel);\n  }\n\n  /**\n   * External sync for the real fill layer (area/state). Never sets the visual\n   * \"Country\" value \u2014 that is user- or caller-driven via setVisualValue.\n   */\n  setValue(nextValue, notify = false) {\n    const normalized = nextValue === LAYER_MODE_AREA ? LAYER_MODE_AREA : LAYER_MODE_STATE;\n    if (normalized === this.value && normalized === this.visualValue) return;\n    this.value = normalized;\n    this.visualValue = normalized;\n    this.sync();\n    if (notify) this.onChange(normalized);\n  }\n\n  setVisualValue(nextVisualValue, notify = false) {\n    const option = this.optionByVisualValue.get(nextVisualValue);\n    if (!option) return;\n    this.visualValue = nextVisualValue;\n    // Every option now carries a real layerValue (area/state/country), so mirror\n    // it into this.value; the guard tolerates a future value-less option.\n    if (option.layerValue) this.value = option.layerValue;\n    this.sync();\n    if (notify) this.onChange(nextVisualValue);\n  }\n\n  sync() {\n    for (const [visualValue, option] of this.optionByVisualValue.entries()) {\n      const active = visualValue === this.visualValue;\n      option.input.checked = active;\n      option.label.classList.toggle(\"is-active\", active);\n    }\n  }\n}\n", "// @ts-check\n\nimport {\n  METRIC_MODE_AI_ABILITIES,\n  METRIC_MODE_AI_EXPOSURE,\n  METRIC_MODE_CALIBRATED,\n  MOBILE_QUERY,\n} from \"../config.js\";\nimport { normalizeMetricMode } from \"../util/normalize.js\";\n\nexport class MetricToggle {\n  /**\n   * @param {{\n   *   mountEl: HTMLElement,\n   *   value?: string,\n   *   onChange?: (value: string) => void,\n   * }} opts\n   */\n  constructor({ mountEl, value = METRIC_MODE_AI_EXPOSURE, onChange = () => {} }) {\n    this.mountEl = mountEl;\n    this.value = normalizeMetricMode(value);\n    this.onChange = onChange;\n    this.optionByVisualValue = new Map();\n    this.groupName = \"map-metric-toggle\";\n    this._mq = typeof window !== \"undefined\" && window.matchMedia\n      ? window.matchMedia(MOBILE_QUERY)\n      : null;\n    this._mqHandler = null;\n  }\n\n  render() {\n    if (!this.mountEl) return;\n\n    const isMobile = this._mq ? this._mq.matches : false;\n    if (isMobile) {\n      this._renderSegmented();\n    } else {\n      this._renderRadios();\n    }\n\n    if (this._mq && !this._mqHandler) {\n      this._mqHandler = () => this.render();\n      this._mq.addEventListener(\"change\", this._mqHandler);\n    }\n\n    this.sync();\n  }\n\n  _options() {\n    return [\n      // Ordered as a spectrum from observed to hypothetical: what AI is doing\n      // today (Adoption), what it could do today (Current Capabilities), what\n      // it might eventually do (Theoretical). Display order only \u2014 metric\n      // resolution goes through visualValue, never option index.\n      { visualValue: METRIC_MODE_AI_EXPOSURE, label: \"Adoption\" },\n      { visualValue: METRIC_MODE_CALIBRATED, label: \"Current Capabilities\" },\n      { visualValue: METRIC_MODE_AI_ABILITIES, label: \"Theoretical\" },\n    ];\n  }\n\n  _buildHeader(panel) {\n    const header = document.createElement(\"div\");\n    header.className = \"map-layer-toggle__header\";\n\n    const title = document.createElement(\"h2\");\n    title.className = \"map-layer-toggle__title\";\n    title.textContent = \"AI Ability\";\n\n    header.appendChild(title);\n    panel.appendChild(header);\n  }\n\n  _renderRadios() {\n    this.mountEl.innerHTML = \"\";\n    this.optionByVisualValue.clear();\n\n    const panel = document.createElement(\"section\");\n    panel.className = \"map-layer-toggle\";\n    panel.setAttribute(\"role\", \"radiogroup\");\n    panel.setAttribute(\"aria-label\", \"AI Ability\");\n\n    this._buildHeader(panel);\n\n    const optionsWrap = document.createElement(\"div\");\n    optionsWrap.className = \"map-layer-toggle__options\";\n\n    for (const option of this._options()) {\n      const optionRow = document.createElement(\"div\");\n      optionRow.className = \"map-layer-toggle__option\";\n\n      const input = document.createElement(\"input\");\n      const inputId = `${this.groupName}-${option.visualValue}`;\n      input.type = \"radio\";\n      input.className = \"map-layer-toggle__input\";\n      input.name = this.groupName;\n      input.id = inputId;\n      input.value = option.visualValue;\n      input.setAttribute(\"aria-label\", option.label);\n\n      const label = document.createElement(\"label\");\n      label.className = \"map-layer-toggle__label\";\n      label.setAttribute(\"for\", inputId);\n\n      const marker = document.createElement(\"span\");\n      marker.className = \"map-layer-toggle__marker\";\n      marker.setAttribute(\"aria-hidden\", \"true\");\n\n      const text = document.createElement(\"span\");\n      text.className = \"map-layer-toggle__label-text\";\n      text.textContent = option.label;\n\n      label.appendChild(marker);\n      label.appendChild(text);\n\n      input.addEventListener(\"change\", () => {\n        if (!input.checked) return;\n        this.setValue(option.visualValue, true);\n      });\n\n      optionRow.appendChild(input);\n      optionRow.appendChild(label);\n      optionsWrap.appendChild(optionRow);\n\n      this.optionByVisualValue.set(option.visualValue, { ...option, input, label });\n    }\n\n    panel.appendChild(optionsWrap);\n    this.mountEl.appendChild(panel);\n  }\n\n  _renderSegmented() {\n    this.mountEl.innerHTML = \"\";\n    this.optionByVisualValue.clear();\n\n    const panel = document.createElement(\"section\");\n    panel.className = \"map-layer-toggle\";\n    panel.setAttribute(\"role\", \"radiogroup\");\n    panel.setAttribute(\"aria-label\", \"AI Ability\");\n\n    this._buildHeader(panel);\n\n    const segmented = document.createElement(\"div\");\n    segmented.className = \"glass-segmented map-layer-toggle__segmented\";\n\n    for (const option of this._options()) {\n      const optionEl = document.createElement(\"label\");\n      optionEl.className = \"glass-segmented__option\";\n\n      const input = document.createElement(\"input\");\n      const inputId = `${this.groupName}-${option.visualValue}`;\n      input.type = \"radio\";\n      input.className = \"map-layer-toggle__input\";\n      input.name = this.groupName;\n      input.id = inputId;\n      input.value = option.visualValue;\n      input.setAttribute(\"aria-label\", option.label);\n\n      const text = document.createElement(\"span\");\n      text.className = \"glass-segmented__option-label\";\n      text.textContent = option.label;\n\n      input.addEventListener(\"change\", () => {\n        if (!input.checked) return;\n        this.setValue(option.visualValue, true);\n      });\n\n      optionEl.appendChild(input);\n      optionEl.appendChild(text);\n      segmented.appendChild(optionEl);\n\n      this.optionByVisualValue.set(option.visualValue, { ...option, input, label: optionEl });\n    }\n\n    panel.appendChild(segmented);\n    this.mountEl.appendChild(panel);\n  }\n\n  setValue(nextValue, notify = false) {\n    const normalized = normalizeMetricMode(nextValue);\n    if (normalized === this.value) return;\n    this.value = normalized;\n    this.sync();\n    if (notify) this.onChange(normalized);\n  }\n\n  sync() {\n    for (const [visualValue, option] of this.optionByVisualValue.entries()) {\n      const active = visualValue === this.value;\n      option.input.checked = active;\n      option.label.classList.toggle(\"is-active\", active);\n    }\n  }\n}\n", "// @ts-check\n\n/**\n * Factory for the map info modal. Encapsulates open/close + focus restoration + Esc-to-close.\n *\n * @param {{\n *   modalEl: HTMLElement | null,\n *   dialogEl: HTMLElement | null,\n * }} opts\n */\nexport function createInfoModal({ modalEl, dialogEl }) {\n  /** @type {Element | null} */\n  let lastFocused = null;\n  /** @type {HTMLElement | null} */\n  let currentTrigger = null;\n\n  function isOpen() {\n    return Boolean(modalEl && !modalEl.hidden);\n  }\n\n  /** @param {HTMLElement | null} [triggerEl] */\n  function open(triggerEl) {\n    if (!modalEl) return;\n    lastFocused = triggerEl || document.activeElement;\n    currentTrigger = triggerEl || null;\n    if (currentTrigger && currentTrigger.hasAttribute(\"aria-expanded\")) {\n      currentTrigger.setAttribute(\"aria-expanded\", \"true\");\n    }\n    modalEl.hidden = false;\n    window.requestAnimationFrame(() => {\n      if (dialogEl) dialogEl.focus();\n    });\n  }\n\n  function close() {\n    if (!modalEl || modalEl.hidden) return;\n    modalEl.hidden = true;\n    if (currentTrigger && currentTrigger.hasAttribute(\"aria-expanded\")) {\n      currentTrigger.setAttribute(\"aria-expanded\", \"false\");\n    }\n    currentTrigger = null;\n    if (lastFocused && typeof (/** @type {HTMLElement} */ (lastFocused)).focus === \"function\") {\n      /** @type {HTMLElement} */ (lastFocused).focus();\n    }\n    lastFocused = null;\n  }\n\n  /** @param {string} tabId */\n  function activateTab(tabId) {\n    if (!modalEl) return;\n    const tabs = /** @type {NodeListOf<HTMLElement>} */ (modalEl.querySelectorAll(\"[data-info-tab]\"));\n    const panels = /** @type {NodeListOf<HTMLElement>} */ (modalEl.querySelectorAll(\"[data-info-panel]\"));\n    tabs.forEach((tab) => {\n      const selected = tab.dataset.infoTab === tabId;\n      tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n      tab.setAttribute(\"tabindex\", selected ? \"0\" : \"-1\");\n    });\n    panels.forEach((panel) => {\n      panel.hidden = panel.dataset.infoPanel !== tabId;\n    });\n  }\n\n  function setup() {\n    if (!modalEl) return;\n\n    modalEl.addEventListener(\"click\", (event) => {\n      const target = /** @type {Element | null} */ (event.target);\n      if (!target) return;\n      if (target.closest(\"[data-close-map-info-modal]\")) {\n        close();\n        return;\n      }\n      const tabBtn = /** @type {HTMLElement | null} */ (target.closest(\"[data-info-tab]\"));\n      if (tabBtn && tabBtn.dataset.infoTab) {\n        activateTab(tabBtn.dataset.infoTab);\n        tabBtn.focus();\n      }\n    });\n\n    modalEl.addEventListener(\"keydown\", (event) => {\n      const target = /** @type {HTMLElement | null} */ (event.target);\n      if (!target || !target.dataset || !target.dataset.infoTab) return;\n      if (event.key !== \"ArrowLeft\" && event.key !== \"ArrowRight\" && event.key !== \"Home\" && event.key !== \"End\") return;\n      const tabs = /** @type {HTMLElement[]} */ (Array.from(modalEl.querySelectorAll(\"[data-info-tab]\")));\n      const idx = tabs.indexOf(target);\n      if (idx === -1) return;\n      event.preventDefault();\n      let nextIdx = idx;\n      if (event.key === \"ArrowLeft\") nextIdx = (idx - 1 + tabs.length) % tabs.length;\n      else if (event.key === \"ArrowRight\") nextIdx = (idx + 1) % tabs.length;\n      else if (event.key === \"Home\") nextIdx = 0;\n      else if (event.key === \"End\") nextIdx = tabs.length - 1;\n      const nextTab = tabs[nextIdx];\n      if (nextTab && nextTab.dataset.infoTab) {\n        activateTab(nextTab.dataset.infoTab);\n        nextTab.focus();\n      }\n    });\n\n    // Escape-to-close is no longer wired here: a single arbitrated document\n    // Escape handler (ui/keyboard.js, installed at app boot) calls close() via\n    // the exposed isOpen()/close() pair so one keypress can't cascade across\n    // overlays. The modal-local keydown above (Arrow/Home/End tab nav) stays.\n  }\n\n  return { open, close, setup, isOpen };\n}\n", "// @ts-check\n\n// Centralized, arbitrated document-level Escape handler.\n//\n// Before PR-9b each overlay (info modal, treemap nav popovers, mobile sheet)\n// and the map itself registered its OWN `document` keydown/Escape listener.\n// With no shared priority, a single Escape press could cascade across several\n// of them (e.g. close a popover AND reset the map zoom) because each listener\n// fired independently. This installs ONE listener that dispatches Escape to\n// the innermost open overlay only, in a fixed priority order, and stops there.\n//\n// Priority (innermost overlay first); the first matching handler runs and we\n// return \u2014 Escape never double-acts:\n//   1. info modal open            \u2192 close it\n//   2. treemap nav popovers open  \u2192 close them\n//   3. mobile sheet showing       \u2192 hide it\n//   4. otherwise                  \u2192 reset map selection to the nation view\n//                                   (country-aware: US \u2192 /us-ai-map/, Canada \u2192\n//                                   /us-ai-map/ca/; see resetMapToNation)\n//\n// Each overlay exposes a predicate + action; the actual close/hide behavior\n// still lives in the owning module (this only centralizes the dispatch).\n\n/**\n * @typedef {{\n *   infoModal: { isOpen: () => boolean, close: () => void },\n *   treemapNav: { hasOpenPopovers: () => boolean, closePopovers: () => void },\n *   mobileSheet: { isShowing: () => boolean, hideForEscape: () => void },\n *   resetMapToNation: () => void,\n * }} EscapeArbiterDeps\n */\n\n/**\n * Returns true when `target` is (or sits inside) a text-entry field, in which\n * case the map-reset default must defer to the field. Mirrors the guard the\n * old us_ai_map.js Escape listener used. Overlay layers ignore this guard (a\n * modal/popover/sheet should still close on Escape even with a field focused),\n * matching the previous per-overlay listeners which never inspected the target.\n *\n * @param {EventTarget | null} target\n * @returns {boolean}\n */\nfunction isTextEntryTarget(target) {\n  const el = /** @type {Element | null} */ (target);\n  return Boolean(\n    el && typeof el.closest === \"function\" &&\n    el.closest(\"input, textarea, [contenteditable='true']\"),\n  );\n}\n\n/**\n * Pure Escape dispatch over the injected deps. Runs at most one action \u2014 the\n * innermost open overlay, else the map default \u2014 and returns which layer\n * handled it, or null if nothing did (the only no-op case is the map default\n * being suppressed because focus is in a text field).\n *\n * Kept DOM-free (the focus check is delegated via the `target` arg) so it is\n * unit-testable with mocked predicates/actions. installEscapeArbiter wires the\n * real KeyboardEvent into it.\n *\n * @param {EscapeArbiterDeps} deps\n * @param {EventTarget | null} [target] focused element when the key was pressed\n * @returns {\"modal\" | \"popover\" | \"sheet\" | \"map\" | null}\n */\nexport function handleEscape(deps, target = null) {\n  const { infoModal, treemapNav, mobileSheet, resetMapToNation } = deps;\n\n  if (infoModal.isOpen()) {\n    infoModal.close();\n    return \"modal\";\n  }\n  if (treemapNav.hasOpenPopovers()) {\n    treemapNav.closePopovers();\n    return \"popover\";\n  }\n  if (mobileSheet.isShowing()) {\n    mobileSheet.hideForEscape();\n    return \"sheet\";\n  }\n  // Default (map reset) only \u2014 preserve the old us_ai_map.js guard so an\n  // Escape inside a text field doesn't blow away the map view.\n  if (isTextEntryTarget(target)) return null;\n  // Single country-aware action (replaces the former clearMapSelection() +\n  // resetZoom() pair): resetMapToNation owns BOTH the selection reset and the\n  // recenter, so the recenter can't clobber the Canada-fit transform when the\n  // current selection is Canadian (plan unit E FIX \u2460).\n  resetMapToNation();\n  return \"map\";\n}\n\n/**\n * Install the single arbitrated Escape listener on `document`. The app boot\n * wires this exactly once where the old us_ai_map.js Escape listener lived.\n * Returns a teardown that removes the listener.\n *\n * The keydown target is injected purely for testability: production passes\n * nothing, so it defaults to the real global `document` and the boot call is\n * unchanged. A DOM-stub may be supplied via `{ doc }` to drive the listener\n * without jsdom.\n *\n * @param {EscapeArbiterDeps} deps\n * @param {{ doc?: { addEventListener: Function, removeEventListener: Function } }} [options]\n * @returns {() => void}\n */\nexport function installEscapeArbiter(\n  deps,\n  { doc = (typeof document !== \"undefined\" ? document : undefined) } = {},\n) {\n  if (!doc) {\n    throw new Error(\"installEscapeArbiter: no document available to bind to\");\n  }\n  /** @param {KeyboardEvent} event */\n  const onKeyDown = (event) => {\n    if (event.key !== \"Escape\") return;\n    const handled = handleEscape(deps, event.target);\n    if (handled) event.stopPropagation();\n  };\n\n  doc.addEventListener(\"keydown\", onKeyDown);\n  return function teardown() {\n    doc.removeEventListener(\"keydown\", onKeyDown);\n  };\n}\n", "// @ts-check\n\nimport { formatWorkers, formatWage, getTotalWorkers } from \"../util/format.js\";\n\nconst HOVER_CARD_OFFSET_PX = 18;\n\nfunction hoverCardTransform(event) {\n  return `translate3d(${event.clientX + HOVER_CARD_OFFSET_PX}px, ${event.clientY + HOVER_CARD_OFFSET_PX}px, 0)`;\n}\n\n/**\n * Factory for the map hover card (\"tooltip\"). Shows region name + workers + wage bill.\n *\n * @param {{\n *   hoverCardEl: HTMLElement | null,\n *   hoverTitleEl: HTMLElement | null,\n *   hoverWorkersEl: HTMLElement | null,\n *   hoverWageEl: HTMLElement | null,\n *   tooltipEl?: HTMLElement | null,\n * }} opts\n */\nexport function createHoverTooltip({ hoverCardEl, hoverTitleEl, hoverWorkersEl, hoverWageEl, tooltipEl = null }) {\n  /**\n   * @param {MouseEvent} event\n   * @param {string} title\n   * @param {unknown} totalWorkers\n   * @param {unknown} wageBill\n   */\n  function show(event, title, totalWorkers, wageBill) {\n    if (!hoverCardEl || !hoverTitleEl || !hoverWorkersEl || !hoverWageEl) return;\n    if (tooltipEl) tooltipEl.style.opacity = \"0\";\n    hoverTitleEl.textContent = title;\n    hoverWorkersEl.textContent = formatWorkers(getTotalWorkers(totalWorkers));\n    hoverWageEl.textContent = formatWage(wageBill);\n    hoverCardEl.classList.remove(\"hidden\");\n    hoverCardEl.style.opacity = \"1\";\n    hoverCardEl.style.transform = hoverCardTransform(event);\n  }\n\n  /**\n   * @param {MouseEvent} event\n   */\n  function position(event) {\n    if (!hoverCardEl) return;\n    hoverCardEl.style.transform = hoverCardTransform(event);\n  }\n\n  function hide() {\n    if (hoverCardEl) {\n      hoverCardEl.classList.add(\"hidden\");\n      hoverCardEl.style.opacity = \"0\";\n    }\n    if (tooltipEl) tooltipEl.style.opacity = \"0\";\n  }\n\n  return { show, hide, position };\n}\n", "// @ts-check\n\n// Selection controller: owns the SVG selection-outline rendering and the\n// \"focus the selected feature in the viewport\" orchestration (which needs\n// to uncollapse the side panel first if it's collapsed). Panel DOM updates\n// driven by a selection live in panel/side-panel.js (future); this module\n// only touches the outline layer + coordinates with the zoom controller.\n\nimport { selectedOutline } from \"../state/store.js\";\n\n/**\n * @param {{\n *   selectionOutlineLayer: any,\n *   getPathGenerator: () => any,\n *   focusFeatureInViewport: (feature: any, opts?: any) => void,\n *   getSidePanelEl: () => HTMLElement | null,\n *   setPanelCollapsed: (collapsed: boolean) => void,\n *   handleLayoutChange: (reason: string) => void,\n *   schedulePanelLayoutRecompute: (reason: string, onDone?: (() => void) | null) => void,\n * }} deps\n */\nexport function createSelectionController(deps) {\n  const {\n    selectionOutlineLayer,\n    getPathGenerator,\n    focusFeatureInViewport,\n    getSidePanelEl,\n    setPanelCollapsed,\n    schedulePanelLayoutRecompute,\n  } = deps;\n\n  function renderSelectionOutline() {\n    const pathGenerator = getPathGenerator();\n    const { feature, key } = selectedOutline.get();\n    const outlineData = feature ? [{ key: key || \"selection\", feature }] : [];\n\n    selectionOutlineLayer\n      .selectAll(\"path\")\n      .data(outlineData, (entry) => entry.key)\n      .join(\"path\")\n      .attr(\"class\", \"map-selection-outline\")\n      .attr(\"d\", (entry) => pathGenerator(entry.feature));\n  }\n\n  function updateSelectionOutline(feature, outlineKey) {\n    selectedOutline.set({ feature: feature || null, key: outlineKey || null });\n    renderSelectionOutline();\n  }\n\n  function ensureSelectionOutlineVisible() {\n    renderSelectionOutline();\n    selectionOutlineLayer.raise();\n  }\n\n  function focusSelectionFeature(feature, { targetScale = 12, duration = 700 } = {}) {\n    if (!feature) return;\n\n    const runFocus = () => {\n      // Desktop selection: zoom/fit to the feature (default keepScale=false).\n      // The mobile recenter-without-zoom path lives in render.js, which calls\n      // focusFeatureInViewport directly with keepScale:true rather than\n      // routing through this controller.\n      focusFeatureInViewport(feature, {\n        targetScale,\n        duration,\n        collapsedOverride: false,\n      });\n      ensureSelectionOutlineVisible();\n    };\n\n    const sidePanelEl = getSidePanelEl();\n    const isCollapsed = sidePanelEl ? sidePanelEl.classList.contains(\"is-collapsed\") : false;\n    if (isCollapsed) {\n      setPanelCollapsed(false);\n      schedulePanelLayoutRecompute(\"panel-toggle\", runFocus);\n      return;\n    }\n\n    runFocus();\n  }\n\n  return {\n    updateSelectionOutline,\n    ensureSelectionOutlineVisible,\n    focusSelectionFeature,\n  };\n}\n", "// @ts-check\n\nlet measureSeq = 0;\n\nfunction canMeasure() {\n  return (\n    typeof performance !== \"undefined\"\n    && typeof performance.mark === \"function\"\n    && typeof performance.measure === \"function\"\n  );\n}\n\nexport function mark(name) {\n  if (!canMeasure()) return;\n  try {\n    performance.mark(name);\n  } catch (_error) {\n    // Performance marks are diagnostic only.\n  }\n}\n\nexport function measureSync(name, fn) {\n  if (!canMeasure()) return fn();\n  const seq = measureSeq += 1;\n  const start = `${name}:start:${seq}`;\n  const end = `${name}:end:${seq}`;\n  try {\n    performance.mark(start);\n    return fn();\n  } finally {\n    try {\n      performance.mark(end);\n      performance.measure(name, start, end);\n      performance.clearMarks(start);\n      performance.clearMarks(end);\n    } catch (_error) {\n      // Performance measurements must never affect map behavior.\n    }\n  }\n}\n\nexport async function measureAsync(name, fn) {\n  if (!canMeasure()) return fn();\n  const seq = measureSeq += 1;\n  const start = `${name}:start:${seq}`;\n  const end = `${name}:end:${seq}`;\n  try {\n    performance.mark(start);\n    return await fn();\n  } finally {\n    try {\n      performance.mark(end);\n      performance.measure(name, start, end);\n      performance.clearMarks(start);\n      performance.clearMarks(end);\n    } catch (_error) {\n      // Performance measurements must never affect map behavior.\n    }\n  }\n}\n\nexport function afterInputPaint(fn) {\n  if (typeof requestAnimationFrame === \"function\") {\n    requestAnimationFrame(() => {\n      if (typeof setTimeout === \"function\") {\n        setTimeout(fn, 0);\n      } else {\n        fn();\n      }\n    });\n    return;\n  }\n  if (typeof setTimeout === \"function\") {\n    setTimeout(fn, 0);\n    return;\n  }\n  fn();\n}\n", "// @ts-check\n\n// Layer/metric mode controller: owns the transitions between state-vs-area\n// visibility and the metric-switch orchestration. `resolveVisibleLayers` is\n// a pure derivation on `selectedLayer` + the loaded flags and is exported\n// standalone so render code can query it without instantiating the\n// controller.\n\nimport { selectedLayer, selectedMetric } from \"../state/store.js\";\nimport { statesLoaded, msaTopologyLoaded, nonmetrosLoaded, caAreasLoaded, provincesLoaded, countyBordersLoaded, caCdBordersLoaded } from \"../state/caches.js\";\nimport { normalizeLayerMode, normalizeMetricMode } from \"../util/normalize.js\";\nimport { LAYER_MODE_STATE, LAYER_MODE_COUNTRY } from \"../config.js\";\nimport { measureAsync } from \"../util/perf.js\";\n\nexport function resolveVisibleLayers(mode) {\n  const normalizedMode = normalizeLayerMode(mode);\n  const inCountryMode = normalizedMode === LAYER_MODE_COUNTRY;\n  const showStateLayer = normalizedMode === LAYER_MODE_STATE;\n  // Country layer draws two dissolved polygons (US + Canada), derived from the\n  // states + provinces topologies (the shipped world asset is land-only), so it\n  // gates on both topologies being loaded.\n  const showCountryLayer = inCountryMode && statesLoaded.get() && provincesLoaded.get();\n  // In country mode every per-region layer (states/areas/borders) is OFF \u2014 the\n  // area-family flags use `!showStateLayer`, which is true in country mode, so\n  // they need an explicit `!inCountryMode` guard. The state-family flags derive\n  // from showStateLayer (false in country mode) and are already off.\n  const showAreaCompositeLayer = !showStateLayer && !inCountryMode && nonmetrosLoaded.get();\n  const showMsaFallbackLayer = !showStateLayer && !inCountryMode && !showAreaCompositeLayer && msaTopologyLoaded.get();\n  const showStateAreaBorders = showStateLayer && nonmetrosLoaded.get();\n  // Canadian layers ride along with their US counterparts: provinces show in\n  // state mode, CMA/rest-of-province composites show in area mode.\n  const showProvincesLayer = showStateLayer && provincesLoaded.get();\n  const showCaAreasLayer = !showStateLayer && !inCountryMode && caAreasLoaded.get();\n  // County outlines render inside both states and metros \u2014 visible whenever\n  // any US data layer is on screen and the counties mesh has loaded.\n  const showCountyBorders = countyBordersLoaded.get()\n    && (showStateLayer || showAreaCompositeLayer || showMsaFallbackLayer);\n  // Canadian census-division outlines: same both-modes contract as the US\n  // county mesh (provinces ride with states, CA composites with areas).\n  const showCaCdBorders = caCdBordersLoaded.get()\n    && (showStateLayer || showAreaCompositeLayer || showMsaFallbackLayer);\n\n  return {\n    showStateLayer,\n    showCountryLayer,\n    showAreaCompositeLayer,\n    showMsaFallbackLayer,\n    showProvincesLayer,\n    showCaAreasLayer,\n    showStateAreaBorders,\n    showCountyBorders,\n    showCaCdBorders,\n    needsStateData: showStateLayer,\n    needsAreaData: !showStateLayer && !inCountryMode,\n    // Country mode needs the states + provinces topologies (for the polygons)\n    // and both nation aggregates (for the fills).\n    needsCountryData: inCountryMode,\n  };\n}\n\n/**\n * @param {{\n *   statesLayer: any,\n *   msasLayer: any,\n *   nonmetrosLayer: any,\n *   provincesLayer: any,\n *   caAreasLayer: any,\n *   countryLayer: any,\n *   countyBordersLayer: any,\n *   caCdBordersLayer: any,\n *   metroNonmetroBordersLayer: any,\n *   ensureStatesLoaded: () => Promise<any>,\n *   ensureMsaMetricsLoaded: () => Promise<any>,\n *   ensureMsasTopologyLoaded: () => Promise<any>,\n *   ensureNonmetrosLoaded: () => Promise<any>,\n *   ensureProvincesLoaded: () => Promise<any>,\n *   ensureCaAreasLoaded: () => Promise<any>,\n *   ensureCountryDataLoaded: () => Promise<any>,\n *   renderCountry: () => void,\n *   refreshLegend: () => void,\n *   refreshSelectionPanel: () => void,\n *   ensureSelectionOutlineVisible: () => void,\n * }} deps\n */\nexport function createLayersController(deps) {\n  const {\n    statesLayer,\n    msasLayer,\n    nonmetrosLayer,\n    provincesLayer,\n    caAreasLayer,\n    countryLayer,\n    countyBordersLayer,\n    caCdBordersLayer,\n    metroNonmetroBordersLayer,\n    ensureStatesLoaded,\n    ensureMsaMetricsLoaded,\n    ensureMsasTopologyLoaded,\n    ensureNonmetrosLoaded,\n    ensureProvincesLoaded,\n    ensureCaAreasLoaded,\n    ensureCountryDataLoaded,\n    renderCountry,\n    refreshLegend,\n    refreshSelectionPanel,\n    ensureSelectionOutlineVisible,\n  } = deps;\n\n  // Two-tier fade. Default is fast for incidental toggles; mode-change paths\n  // (state\u2194area) opt into the slower duration to mask the heavier repaint.\n  const LAYER_FADE_DURATION_MS = 160;\n  const LAYER_FADE_MODE_CHANGE_MS = 380;\n\n  function fadeLayer(layer, visible, { interactive = false, slow = false } = {}) {\n    const duration = slow ? LAYER_FADE_MODE_CHANGE_MS : LAYER_FADE_DURATION_MS;\n    const transition = layer.interrupt().transition().duration(duration).style(\"opacity\", visible ? 1 : 0);\n    if (interactive) {\n      transition.style(\"pointer-events\", visible ? \"auto\" : \"none\");\n    }\n  }\n\n  async function applyLayerVisibility() {\n    const visibility = resolveVisibleLayers(selectedLayer.get());\n    if (visibility.needsCountryData) {\n      // Country layer needs the states + provinces topologies (its two polygons\n      // are dissolved from them) plus both nation aggregates (their fills). A\n      // Canadian failure must not take down the US polygon, so its rejections\n      // are swallowed. renderCountry paints whichever polygons are available.\n      await ensureStatesLoaded();\n      await ensureProvincesLoaded().catch((err) => {\n        console.warn(\"Unable to load Canadian province data; country layer will render without Canada.\", err);\n      });\n      await ensureCountryDataLoaded().catch((err) => {\n        console.warn(\"Unable to load one or more nation aggregates; country fills may be incomplete.\", err);\n      });\n      renderCountry();\n    }\n    if (visibility.needsStateData) {\n      // US states and Canadian provinces are the two halves of state mode.\n      // Start both together so a state-mode reveal doesn't show the US first\n      // and fade Canada in later. Province failures remain non-fatal.\n      await Promise.all([\n        ensureStatesLoaded(),\n        ensureProvincesLoaded().catch((err) => {\n          console.warn(\"Unable to load Canadian province data; map will render without it.\", err);\n        }),\n      ]);\n    }\n    if (visibility.needsAreaData) {\n      // US metro metrics, US area composites, and Canadian area composites are\n      // the visible default map. Load all three together so first reveal can\n      // show US + Canada in one pass. Canadian failures remain non-fatal.\n      const caAreasReady = ensureCaAreasLoaded().catch((err) => {\n        console.warn(\"Unable to load Canadian area data; map will render without it.\", err);\n      });\n      const msaMetricsReady = ensureMsaMetricsLoaded().catch((err) => {\n        console.warn(\"Unable to load MSA metrics; metros will render without fills.\", err);\n      });\n      const nonmetrosReady = (async () => {\n        try {\n          await ensureNonmetrosLoaded();\n        } catch (nonmetroError) {\n          // Composite layer unavailable \u2014 pull the MSA topology so the\n          // metros-only fallback can render. Its failure is logged but still\n          // swallowed: the recomputed visibility below must proceed and simply\n          // shows no area layer (boot failures land the overlay).\n          await ensureMsasTopologyLoaded().catch((topoError) => {\n            console.warn(\"MSA fallback topology also failed to load.\", topoError);\n          });\n          console.warn(\"Area composites unavailable; attempting MSA fallback layer.\", nonmetroError);\n        }\n      })();\n      await msaMetricsReady;\n      await nonmetrosReady;\n      await caAreasReady;\n    }\n\n    const resolvedVisibility = resolveVisibleLayers(selectedLayer.get());\n\n    fadeLayer(statesLayer, resolvedVisibility.showStateLayer, { interactive: true, slow: true });\n    fadeLayer(countryLayer, resolvedVisibility.showCountryLayer, { interactive: true, slow: true });\n    fadeLayer(msasLayer, resolvedVisibility.showMsaFallbackLayer, { interactive: true, slow: true });\n    fadeLayer(nonmetrosLayer, resolvedVisibility.showAreaCompositeLayer, { interactive: true, slow: true });\n    fadeLayer(provincesLayer, resolvedVisibility.showProvincesLayer, { interactive: true, slow: true });\n    fadeLayer(caAreasLayer, resolvedVisibility.showCaAreasLayer, { interactive: true, slow: true });\n    fadeLayer(countyBordersLayer, resolvedVisibility.showCountyBorders, { slow: true });\n    fadeLayer(caCdBordersLayer, resolvedVisibility.showCaCdBorders, { slow: true });\n    fadeLayer(metroNonmetroBordersLayer, resolvedVisibility.showStateAreaBorders, { slow: true });\n\n    refreshLegend();\n    refreshSelectionPanel();\n    // Raise the selection outline now, then again after the fade settles \u2014\n    // otherwise the outgoing layer can repaint on top of it as the\n    // transition completes. Do not collapse into a single call.\n    ensureSelectionOutlineVisible();\n    window.setTimeout(ensureSelectionOutlineVisible, LAYER_FADE_MODE_CHANGE_MS + 20);\n  }\n\n  async function setLayerMode(nextLayerMode) {\n    await measureAsync(\"map:layer-mode\", async () => {\n      selectedLayer.set(normalizeLayerMode(nextLayerMode));\n      await applyLayerVisibility();\n    });\n  }\n\n  function setMetricMode(nextMetricMode) {\n    // selectedMetric subscribers (wired in entry) own the cache-clear,\n    // scale rebuild, fill refresh, legend, and panel refresh chain.\n    selectedMetric.set(normalizeMetricMode(nextMetricMode));\n  }\n\n  return {\n    applyLayerVisibility,\n    setLayerMode,\n    setMetricMode,\n  };\n}\n", "// @ts-check\n\n// Map render controller: owns the d3 join + event-handler wiring for every\n// SVG feature layer (world, states, msas, nonmetros, metro/nonmetro borders).\n// Handlers delegate to injected tooltip/selection helpers so the render module\n// only concerns itself with SVG operations and not panel/tooltip DOM.\n//\n// All mutable closure state (pathGenerator, feature arrays) is pulled through\n// lazy getters so a single render-controller instance stays valid across\n// projection rebuilds and data re-fetches without re-instantiation.\n//\n// No teardown: controllers here are single-instance for the app lifetime, and\n// d3's `.on()` binds overwrite (rather than accumulate) on re-render. If a\n// future module adds handlers outside the d3 join (global listeners, timers)\n// it must add its own teardown \u2014 see treemap/nav.js for the pattern.\n\nimport {\n  getStateCode,\n  getMsaCode,\n  getProvinceCode,\n  getAreaKey,\n  normalizeMsaCode,\n  normalizeAreaCode,\n  normalizeCmaCode,\n  normalizeProvinceCode,\n} from \"../util/normalize.js\";\nimport { currentSelection, selectedMetric } from \"../state/store.js\";\nimport {\n  getRegionMetrics,\n  msaFeatureByCode,\n  areaOutlineFeatureByKey,\n  nation,\n  nationCa,\n} from \"../state/caches.js\";\nimport { hoverCapableMQ } from \"../util/media-queries.js\";\nimport { urlForKey } from \"../state/geo_urls.js\";\nimport { afterInputPaint, measureSync } from \"../util/perf.js\";\n\n/**\n * @param {{\n *   statesLayer: any,\n *   msasLayer: any,\n *   nonmetrosLayer: any,\n *   worldLayer: any,\n *   countryLayer: any,\n *   countyBordersLayer: any,\n *   metroNonmetroBordersLayer: any,\n *   selectionOutlineLayer: any,\n *   getPathGenerator: () => any,\n *   getStatesFeatures: () => any[],\n *   getMsaFeatures: () => any[],\n *   getDetailAreaFeatures: () => any[],\n *   getUsCountryFeature: () => any,\n *   getCaCountryFeature: () => any,\n *   getUsStateBorders: () => any,\n *   getCaProvinceBorders: () => any,\n *   getWorldLandFeature: () => any,\n *   getWorldCountryBorders: () => any,\n *   getCountyBorders: () => any,\n *   getStateFeatureFill: (feature: any) => string,\n *   getMsaFeatureFill: (feature: any) => string,\n *   getAreaFeatureFill: (feature: any) => string,\n *   getCountryFeatureFill: (feature: any) => string,\n *   onCountrySelect: (country: string, feature: any) => void,\n *   setHoveredFeatureElement: (el: any) => void,\n *   clearHoverHighlight: () => void,\n *   showTooltip: (event: any, name: string, totalWorkers: any, wageBill: any) => void,\n *   positionTooltip: (event: any) => void,\n *   hideTooltip: () => void,\n *   updateSelection: (type: string, name: string, totalWorkers: any, wageBill: any, exposureStats: any) => void,\n *   updateSelectionOutline: (feature: any, outlineKey: string) => void,\n *   focusSelectionFeature: (feature: any, opts?: any) => void,\n *   focusFeatureInViewport?: (feature: any, opts?: any) => void,\n *   ensureSelectionOutlineVisible: () => void,\n *   getFeatureName: (feature: any, fallbackPrefix: string) => string,\n *   isMobileLayout?: () => boolean,\n *   showMobilePreview?: (meta: { name: string, type: string, totalWorkers: any, wageBill: any, exposureStats?: any }) => void,\n * }} deps\n */\nexport function createRenderController(deps) {\n  const {\n    statesLayer,\n    msasLayer,\n    nonmetrosLayer,\n    provincesLayer,\n    caAreasLayer,\n    worldLayer,\n    countryLayer,\n    countyBordersLayer,\n    caCdBordersLayer,\n    metroNonmetroBordersLayer,\n    selectionOutlineLayer,\n    getPathGenerator,\n    getStatesFeatures,\n    getMsaFeatures,\n    getDetailAreaFeatures,\n    getProvinceFeatures,\n    getCaAreaFeatures,\n    getUsCountryFeature,\n    getCaCountryFeature,\n    getUsStateBorders,\n    getCaProvinceBorders,\n    getWorldLandFeature,\n    getWorldCountryBorders,\n    getCountyBorders,\n    getCaCdBorders,\n    getStateFeatureFill,\n    getMsaFeatureFill,\n    getAreaFeatureFill,\n    getProvinceFeatureFill,\n    getCaAreaFeatureFill,\n    getCountryFeatureFill,\n    onCountrySelect,\n    setHoveredFeatureElement,\n    clearHoverHighlight,\n    showTooltip,\n    positionTooltip,\n    hideTooltip,\n    updateSelection,\n    updateSelectionOutline,\n    focusSelectionFeature,\n    focusFeatureInViewport = null,\n    ensureSelectionOutlineVisible,\n    getFeatureName,\n    isMobileLayout = () => false,\n    showMobilePreview = null,\n  } = deps;\n\n  // History/URL sync loop guard (plan unit E). When a selection originates from\n  // a deep-link boot or a popstate event we must NOT push a new history entry\n  // for it. The bootstrap + popstate handler set this true around the\n  // history-driven selectByKindCode call, and commitSelection skips its\n  // history.replaceState while it's set. Toggled only through setApplyingHistory.\n  let applyingHistory = false;\n  function setApplyingHistory(value) {\n    applyingHistory = !!value;\n  }\n  // Read-only view of the history-suppression flag so callers outside this\n  // controller (the bootstrap geo-urls re-sync, plan unit E FIX \u2461) can avoid\n  // writing the address bar while a deep-link / popstate restore is mid-flight.\n  function isApplyingHistory() {\n    return applyingHistory;\n  }\n  let selectionCommitSeq = 0;\n\n  // Single source of truth for the address-bar sync (plan unit E): reflect the\n  // CURRENT selection in the URL via replaceState so it is shareable/bookmarkable\n  // and the URL always matches the selected geography \u2014 entity OR nation. Used\n  // by both commitSelection (entity select) and the nation-reset path\n  // (clearMapSelection), so deselecting via background-click / Escape / zoom-reset\n  // rewinds the slug to the nation root instead of leaving a stale region path.\n  // replaceState (not pushState) keeps the deep-link's initial entry as the\n  // single history slot for the map page. Skipped when applyingHistory is set\n  // (the selection was itself driven by a deep-link boot or popstate, so the\n  // browser is already at the right URL). urlForKey returns undefined before the\n  // geo-urls table loads or for an entity absent from it; fall back to the\n  // nation root so we never write a bogus URL.\n  function syncSelectionUrl(kind, code) {\n    if (applyingHistory) return;\n    try {\n      window.history.replaceState({ kind, code }, \"\", urlForKey(kind, code) || \"/us-ai-map/\");\n    } catch (_err) {\n      // history may be unavailable (sandboxed iframe); URL sync is best-effort.\n    }\n  }\n\n  // On mobile, tap selects a region but instead of opening the full-screen\n  // overlay we show a docked preview card (mirrors the desktop hover-card).\n  // The user explicitly opens the overlay via the preview's \"View details\"\n  // button. Selection state and outline are still committed so the overlay\n  // can render straight from current state when invoked.\n  function commitSelection({ kind, code, label, name, snap, feature, outlineKey }) {\n    return measureSync(\"map:selection:commit\", () => {\n      const commitSeq = selectionCommitSeq += 1;\n      const shouldSyncUrl = !applyingHistory;\n      currentSelection.set({ kind, code, label, name });\n      updateSelectionOutline(feature, outlineKey);\n\n      afterInputPaint(() => {\n        if (commitSeq !== selectionCommitSeq) return;\n        if (shouldSyncUrl) syncSelectionUrl(kind, code);\n        updateSelection(label, name, snap.totalWorkers ?? null, snap.wageBill ?? null, snap.exposureStats ?? null);\n        if (isMobileLayout() && showMobilePreview) {\n          showMobilePreview({ name, type: label, totalWorkers: snap.totalWorkers, wageBill: snap.wageBill, exposureStats: snap.exposureStats });\n          // Center the map on the tapped region without uncollapsing the side\n          // panel (which on mobile would open the full-screen overlay).\n          if (focusFeatureInViewport) {\n            focusFeatureInViewport(feature, { duration: 700, collapsedOverride: true, keepScale: true });\n          }\n          ensureSelectionOutlineVisible();\n        } else {\n          focusSelectionFeature(feature, { targetScale: 12, duration: 700 });\n        }\n      });\n    });\n  }\n\n  // All callers pass an explicit known kind (the nonmetro / ca_nonmetro cases\n  // are passed by name), so delegating to getRegionMetrics \u2014 which returns\n  // nulls for an unknown kind rather than the old else\u2192nonmetro fallback \u2014 is\n  // behavior-equivalent here.\n  function getFeatureSnapshot(kind, code) {\n    return getRegionMetrics(kind, code);\n  }\n\n  // Area layers carry their display name on the feature's `area_name` property\n  // (mirrors the click path's `areaInfo.area_name`); states/provinces use\n  // getFeatureName. Used by resolveKindCode for deep-link / popstate restores.\n  function areaName(feature, fallback) {\n    return (feature && feature.properties && feature.properties.area_name) || fallback;\n  }\n\n  // Resolve the canonical feature + label + outlineKey for a (kind, code) pair,\n  // for the deep-link / popstate restore path. Returns null when the code can't\n  // be resolved to a feature in the current render set.\n  function resolveKindCode(kind, code, fallbackFeature) {\n    if (kind === \"state\") {\n      const feature = getStatesFeatures().find((f) => getStateCode(f) === code) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"State\", outlineKey: `state:${code}`, feature, name: getFeatureName(feature, \"State\") };\n    }\n    if (kind === \"province\") {\n      const feature = getProvinceFeatures().find((f) => getProvinceCode(f) === code) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"Province/Territory\", outlineKey: `province:${code}`, feature, name: getFeatureName(feature, \"Province\") };\n    }\n    if (kind === \"msa\") {\n      const outlineKey = `metro:${code}`;\n      const feature = msaFeatureByCode.get(code) || areaOutlineFeatureByKey.get(outlineKey) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"Metropolitan Area\", outlineKey, feature, name: areaName(feature, \"Metropolitan Area\") };\n    }\n    if (kind === \"nonmetro\") {\n      const outlineKey = `nonmetro:${code}`;\n      const feature = areaOutlineFeatureByKey.get(outlineKey) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"Non-Metropolitan Area\", outlineKey, feature, name: areaName(feature, \"Non-Metropolitan Area\") };\n    }\n    if (kind === \"cma\") {\n      const outlineKey = `cma:${code}`;\n      const feature = areaOutlineFeatureByKey.get(outlineKey) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"Metropolitan Area (CMA/CA)\", outlineKey, feature, name: areaName(feature, \"Metropolitan Area (CMA/CA)\") };\n    }\n    if (kind === \"ca_nonmetro\") {\n      const outlineKey = `ca_nonmetro:${code}`;\n      const feature = areaOutlineFeatureByKey.get(outlineKey) || fallbackFeature;\n      if (!feature) return null;\n      return { label: \"Non-Metropolitan Area\", outlineKey, feature, name: areaName(feature, \"Non-Metropolitan Area\") };\n    }\n    return null;\n  }\n\n  // Selection helper shared by clicks (fallback layer), deep-link boot, and\n  // popstate. Resolves (kind, code) -> feature/label/outlineKey and routes\n  // through commitSelection (the single chokepoint that updates state, panel,\n  // outline, focus/zoom, and \u2014 unless applyingHistory \u2014 the URL). `fromHistory`\n  // is set by deep-link/popstate so the history write is skipped. Returns true\n  // if committed, false if (kind, code) couldn't be resolved (caller falls back\n  // to the nation default).\n  function selectByKindCode(kind, code, { name = undefined, fallbackFeature = undefined, fromHistory = false } = {}) {\n    const resolved = resolveKindCode(kind, code, fallbackFeature);\n    if (!resolved) return false;\n    const prevApplyingHistory = applyingHistory;\n    if (fromHistory) applyingHistory = true;\n    try {\n      commitSelection({\n        kind,\n        code,\n        label: resolved.label,\n        name: name ?? resolved.name,\n        snap: getFeatureSnapshot(kind, code),\n        feature: resolved.feature,\n        outlineKey: resolved.outlineKey,\n      });\n    } finally {\n      applyingHistory = prevApplyingHistory;\n    }\n    return true;\n  }\n\n  // --------------------------------------------------------------------------\n  // Layer-join factories. Five fill layers share two structural shapes; the\n  // per-kind nuances (code accessor, kind, label, css class, scope, outline-key\n  // prefix, no-data fill semantics) are passed in as params so nothing is\n  // flattened away. The bordered/mesh renders (world, county/CD meshes,\n  // metro-nonmetro borders) are intentionally NOT routed through these \u2014 they\n  // have no hover/click/tooltip join and stay as standalone functions.\n  // --------------------------------------------------------------------------\n\n  /**\n   * Shape A \u2014 a single code-keyed choropleth layer (states, MSAs, provinces).\n   * Each feature maps 1:1 to a known region kind; the code accessor yields the\n   * lookup key for both the snapshot and the selection outline.\n   * @param {{\n   *   layer: any,\n   *   kind: string,\n   *   label: string,\n   *   featureClass: string,\n   *   scope: string,\n   *   namePrefix: string,\n   *   getFeatures: () => any[],\n   *   getCode: (feature: any) => string,\n   *   getFill: (feature: any) => string,\n   * }} cfg\n   */\n  function renderSimpleFeatureLayer(cfg) {\n    const { layer, kind, label, featureClass, scope, namePrefix, getFeatures, getCode, getFill } = cfg;\n    layer\n      .selectAll(\"path\")\n      .data(getFeatures(), (feature) => getCode(feature))\n      .join(\"path\")\n      .attr(\"class\", featureClass)\n      .attr(\"data-scope\", scope)\n      .attr(\"data-code\", (feature) => getCode(feature))\n      .attr(\"fill\", getFill)\n      .attr(\"d\", getPathGenerator())\n      .on(\"mouseenter\", function (event, feature) {\n        if (!hoverCapableMQ?.matches) return;\n        const snap = getFeatureSnapshot(kind, getCode(feature));\n        setHoveredFeatureElement(this);\n        showTooltip(event, `${getFeatureName(feature, namePrefix)}`, snap.totalWorkers, snap.wageBill);\n      })\n      .on(\"mousemove\", (event) => positionTooltip(event))\n      .on(\"mouseleave\", () => {\n        clearHoverHighlight();\n        hideTooltip();\n      })\n      .on(\"click\", function (event, feature) {\n        if (event?.defaultPrevented) return;\n        event.stopPropagation();\n        const code = getCode(feature);\n        commitSelection({\n          kind, code, label,\n          name: getFeatureName(feature, namePrefix),\n          snap: getFeatureSnapshot(kind, code),\n          feature, outlineKey: `${kind}:${code}`,\n        });\n      });\n  }\n\n  function worldDatumToPath(feature) {\n    const pathGenerator = getPathGenerator();\n    if (!feature) {\n      return null;\n    }\n    if (feature.type === \"Sphere\") {\n      return pathGenerator({ type: \"Sphere\" });\n    }\n    if (feature.feature) {\n      return pathGenerator(feature.feature);\n    }\n    return pathGenerator({\n      type: \"Feature\",\n      geometry: feature.geometry,\n    });\n  }\n\n  function updateFeaturePaths() {\n    const pathGenerator = getPathGenerator();\n    worldLayer.selectAll(\"path\").attr(\"d\", worldDatumToPath);\n    statesLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    msasLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    nonmetrosLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    provincesLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    caAreasLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    countryLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    countyBordersLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    caCdBordersLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    metroNonmetroBordersLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n    selectionOutlineLayer.selectAll(\"path\").attr(\"d\", pathGenerator);\n  }\n\n  function renderWorld() {\n    const worldFeatures = [\n      {\n        key: \"sphere\",\n        type: \"Sphere\",\n      },\n    ];\n\n    const worldLandFeature = getWorldLandFeature();\n    if (worldLandFeature) {\n      worldFeatures.push({\n        key: \"land\",\n        type: \"Feature\",\n        feature: worldLandFeature,\n      });\n    }\n\n    const worldCountryBorders = getWorldCountryBorders();\n    if (worldCountryBorders) {\n      worldFeatures.push({\n        key: \"country-borders\",\n        type: \"Feature\",\n        geometry: worldCountryBorders,\n      });\n    }\n\n    worldLayer\n      .selectAll(\"path\")\n      .data(worldFeatures, (feature) => feature.key)\n      .join(\"path\")\n      .attr(\"class\", (feature) => `map-world map-world-${feature.key}`)\n      .attr(\"d\", worldDatumToPath);\n  }\n\n  /**\n   * Shape B \u2014 a composite \"area\" layer (US metro/nonmetro, CA cma/ca_nonmetro).\n   * One geometry feature per area_key; the concrete region kind is resolved at\n   * interaction time from `feature.properties.area_type`. Both hover and click\n   * early-return when `properties` is missing (hover also clears the tooltip).\n   *\n   * Per-kind nuances captured via params (NOT flattened):\n   *  - resolveSubKind(areaInfo): { kind, code, label, outlineKey } \u2014 owns the\n   *    area_type discriminator, the per-subtype code normalization, the human\n   *    label, and the outline-key prefix (US uses \"metro:\"/\"nonmetro:\", which\n   *    are NOT the same as the region kind \"msa\"; CA uses \"cma:\"/\"ca_nonmetro:\").\n   *  - resolveOutlineFeature({ kind, code, outlineKey, feature }): the canonical\n   *    outline geometry. US metros prefer msaFeatureByCode; everything else uses\n   *    areaOutlineFeatureByKey; all fall back to the hovered feature.\n   * @param {{\n   *   layer: any,\n   *   featureClass: string,\n   *   scope: string,\n   *   getFeatures: () => any[],\n   *   getFill: (feature: any) => string,\n   *   resolveSubKind: (areaInfo: any) => { kind: string, code: string, label: string, outlineKey: string },\n   *   resolveOutlineFeature: (ctx: { kind: string, code: string, outlineKey: string, feature: any }) => any,\n   * }} cfg\n   */\n  function renderCompositeAreaLayer(cfg) {\n    const { layer, featureClass, scope, getFeatures, getFill, resolveSubKind, resolveOutlineFeature } = cfg;\n    layer\n      .selectAll(\"path\")\n      .data(getFeatures(), (feature) => getAreaKey(feature))\n      .join(\"path\")\n      .attr(\"class\", featureClass)\n      // Static scope: this layer renders both metro + nonmetro composites and the\n      // click handler resolves kind from area_type, so the scope is the umbrella\n      // (\"area\"/\"ca_area\"). Note: data-code here is the composite area_key (not a\n      // scope-padded code).\n      .attr(\"data-scope\", scope)\n      .attr(\"data-code\", (feature) => getAreaKey(feature))\n      .attr(\"fill\", getFill)\n      .attr(\"d\", getPathGenerator())\n      .on(\"mouseenter\", function (event, feature) {\n        if (!hoverCapableMQ?.matches) return;\n        const areaInfo = feature && feature.properties ? feature.properties : null;\n        if (!areaInfo) {\n          hideTooltip();\n          return;\n        }\n        const { kind, code } = resolveSubKind(areaInfo);\n        const snap = getFeatureSnapshot(kind, code);\n        setHoveredFeatureElement(this);\n        showTooltip(event, areaInfo.area_name, snap.totalWorkers, snap.wageBill);\n      })\n      .on(\"mousemove\", (event) => positionTooltip(event))\n      .on(\"mouseleave\", () => {\n        clearHoverHighlight();\n        hideTooltip();\n      })\n      .on(\"click\", function (event, feature) {\n        if (event?.defaultPrevented) return;\n        event.stopPropagation();\n        const areaInfo = feature && feature.properties ? feature.properties : null;\n        if (!areaInfo) {\n          return;\n        }\n        const { kind, code, label, outlineKey } = resolveSubKind(areaInfo);\n        commitSelection({\n          kind, code, label,\n          name: areaInfo.area_name,\n          snap: getFeatureSnapshot(kind, code),\n          feature: resolveOutlineFeature({ kind, code, outlineKey, feature }),\n          outlineKey,\n        });\n      });\n  }\n\n  // The two whole-country polygons (US, Canada) for the Country fill layer.\n  // Absent features (topology not yet loaded) are skipped so the layer renders\n  // whichever countries are available.\n  function getCountryFeatures() {\n    const features = [];\n    const usFeature = getUsCountryFeature();\n    if (usFeature) features.push(usFeature);\n    const caFeature = getCaCountryFeature();\n    if (caFeature) features.push(caFeature);\n    return features;\n  }\n\n  function countryCode(feature) {\n    return feature && feature.properties ? feature.properties.country : \"\";\n  }\n\n  // State/province boundary meshes (one MultiLineString per country) drawn as\n  // stroke-only edges over the country fill, so a single-color country still\n  // reads as a familiar states map. Whichever meshes are loaded are rendered.\n  function getCountryEdgeGeometries() {\n    const edges = [];\n    const usEdges = getUsStateBorders();\n    if (usEdges) edges.push(usEdges);\n    const caEdges = getCaProvinceBorders();\n    if (caEdges) edges.push(caEdges);\n    return edges;\n  }\n\n  // Bespoke join (not renderSimpleFeatureLayer): the country features are\n  // property-keyed (\"us\"/\"ca\"), select the NATION scope rather than a region\n  // kind, and read their hover totals from the nation aggregate holders instead\n  // of getRegionMetrics. Click delegates to onCountrySelect (nation selection).\n  // A second, class-scoped join lays the state/province edge meshes ON TOP of\n  // the fills (later in the DOM) as non-interactive strokes \u2014 clicks fall\n  // through to the fill polygon below.\n  function renderCountry() {\n    countryLayer\n      .selectAll(\"path.map-feature-country\")\n      .data(getCountryFeatures(), (feature) => countryCode(feature))\n      .join(\"path\")\n      .attr(\"class\", \"map-feature map-feature-country\")\n      .attr(\"data-scope\", \"nation\")\n      .attr(\"data-code\", (feature) => countryCode(feature))\n      .attr(\"fill\", getCountryFeatureFill)\n      .attr(\"d\", getPathGenerator())\n      .on(\"mouseenter\", function (event, feature) {\n        if (!hoverCapableMQ?.matches) return;\n        const holder = countryCode(feature) === \"ca\" ? nationCa : nation;\n        setHoveredFeatureElement(this);\n        showTooltip(\n          event,\n          (feature.properties && feature.properties.name) || \"\",\n          holder.totalWorkforce,\n          holder.totalWageBill,\n        );\n      })\n      .on(\"mousemove\", (event) => positionTooltip(event))\n      .on(\"mouseleave\", () => {\n        clearHoverHighlight();\n        hideTooltip();\n      })\n      .on(\"click\", function (event, feature) {\n        if (event?.defaultPrevented) return;\n        event.stopPropagation();\n        onCountrySelect(countryCode(feature), feature);\n      });\n\n    countryLayer\n      .selectAll(\"path.map-feature-country-edge\")\n      .data(getCountryEdgeGeometries())\n      .join(\"path\")\n      .attr(\"class\", \"map-feature-country-edge\")\n      .attr(\"aria-hidden\", \"true\")\n      .attr(\"d\", getPathGenerator());\n  }\n\n  function renderStates() {\n    renderSimpleFeatureLayer({\n      layer: statesLayer,\n      kind: \"state\",\n      label: \"State\",\n      featureClass: \"map-feature map-feature-state\",\n      scope: \"state\",\n      namePrefix: \"State\",\n      getFeatures: getStatesFeatures,\n      getCode: getStateCode,\n      getFill: getStateFeatureFill,\n    });\n  }\n\n  function renderMsas() {\n    renderSimpleFeatureLayer({\n      layer: msasLayer,\n      kind: \"msa\",\n      label: \"MSA\",\n      featureClass: \"map-feature map-feature-msa\",\n      scope: \"msa\",\n      namePrefix: \"MSA\",\n      getFeatures: getMsaFeatures,\n      getCode: getMsaCode,\n      getFill: getMsaFeatureFill,\n    });\n  }\n\n  function renderProvinces() {\n    renderSimpleFeatureLayer({\n      layer: provincesLayer,\n      kind: \"province\",\n      label: \"Province/Territory\",\n      featureClass: \"map-feature map-feature-province\",\n      scope: \"province\",\n      namePrefix: \"Province\",\n      getFeatures: getProvinceFeatures,\n      getCode: getProvinceCode,\n      getFill: getProvinceFeatureFill,\n    });\n  }\n\n  function renderNonmetros() {\n    return measureSync(\"map:render:nonmetros\", () => {\n      renderCompositeAreaLayer({\n        layer: nonmetrosLayer,\n        featureClass: \"map-feature map-feature-nonmetro\",\n        scope: \"area\",\n        getFeatures: getDetailAreaFeatures,\n        getFill: getAreaFeatureFill,\n        resolveSubKind(areaInfo) {\n          const isMetro = areaInfo.area_type === \"metro\";\n          const code = isMetro ? normalizeMsaCode(areaInfo.area_code) : normalizeAreaCode(areaInfo.area_code);\n          // outlineKey prefix is \"metro\"/\"nonmetro\" (the area_type), distinct from\n          // the region kind \"msa\"/\"nonmetro\" used for the metric snapshot.\n          return {\n            kind: isMetro ? \"msa\" : \"nonmetro\",\n            code,\n            label: isMetro ? \"Metropolitan Area\" : \"Non-Metropolitan Area\",\n            outlineKey: `${isMetro ? \"metro\" : \"nonmetro\"}:${code}`,\n          };\n        },\n        resolveOutlineFeature({ kind, code, outlineKey, feature }) {\n          // US metros prefer the canonical MSA geometry; nonmetros use the\n          // composite outline index. Both fall back to the hovered feature.\n          return kind === \"msa\"\n            ? (msaFeatureByCode.get(code) || areaOutlineFeatureByKey.get(outlineKey) || feature)\n            : (areaOutlineFeatureByKey.get(outlineKey) || feature);\n        },\n      });\n    });\n  }\n\n  function renderCaAreas() {\n    renderCompositeAreaLayer({\n      layer: caAreasLayer,\n      featureClass: \"map-feature map-feature-nonmetro map-feature-ca-area\",\n      scope: \"ca_area\",\n      getFeatures: getCaAreaFeatures,\n      getFill: getCaAreaFeatureFill,\n      resolveSubKind(areaInfo) {\n        const isCma = areaInfo.area_type === \"cma\";\n        // CA nonmetro codes are province-padded (not area-padded like the US).\n        const code = isCma ? normalizeCmaCode(areaInfo.area_code) : normalizeProvinceCode(areaInfo.area_code);\n        const kind = isCma ? \"cma\" : \"ca_nonmetro\";\n        return {\n          kind,\n          code,\n          label: isCma ? \"Metropolitan Area (CMA/CA)\" : \"Non-Metropolitan Area\",\n          // CA outline-key prefix matches the region kind exactly (\"cma\"/\"ca_nonmetro\").\n          outlineKey: `${kind}:${code}`,\n        };\n      },\n      // CA uses the composite outline index for BOTH subtypes (no msaFeatureByCode\n      // counterpart), falling back to the hovered feature.\n      resolveOutlineFeature({ outlineKey, feature }) {\n        return areaOutlineFeatureByKey.get(outlineKey) || feature;\n      },\n    });\n  }\n\n  function renderMetroNonmetroBorders() {\n    return measureSync(\"map:render:metro-borders\", () => {\n      metroNonmetroBordersLayer\n        .selectAll(\"path\")\n        .data(getDetailAreaFeatures(), (feature) => getAreaKey(feature))\n        .join(\"path\")\n        .attr(\"class\", \"map-metro-nonmetro-border\")\n        .attr(\"fill\", \"none\")\n        .attr(\"d\", getPathGenerator());\n\n      // Keep boundaries above fill layers (same visual logic as Metro. areas)\n      // while leaving selection outline as the top-most overlay.\n      metroNonmetroBordersLayer.raise();\n      ensureSelectionOutlineVisible();\n    });\n  }\n\n  // Single d3-merged mesh path for all interior county borders. Driven by the\n  // counties topology fetched lazily in data/counties.js; arcs are\n  // interior-only (a !== b) so this draws county lines inside states/metros\n  // without re-doubling state borders or coastlines.\n  function renderCountyBorders() {\n    const mesh = getCountyBorders();\n    const data = mesh ? [mesh] : [];\n    countyBordersLayer\n      .selectAll(\"path\")\n      .data(data)\n      .join(\"path\")\n      .attr(\"class\", \"map-county-borders\")\n      .attr(\"fill\", \"none\")\n      .attr(\"d\", getPathGenerator());\n    ensureSelectionOutlineVisible();\n  }\n\n  // Canadian census-division mesh \u2014 the counterpart of renderCountyBorders.\n  // Same single interior-only path, same .map-county-borders styling, so the\n  // two countries' lower-level detail reads identically.\n  function renderCaCdBorders() {\n    const mesh = getCaCdBorders();\n    const data = mesh ? [mesh] : [];\n    caCdBordersLayer\n      .selectAll(\"path\")\n      .data(data)\n      .join(\"path\")\n      .attr(\"class\", \"map-county-borders\")\n      .attr(\"fill\", \"none\")\n      .attr(\"d\", getPathGenerator());\n    ensureSelectionOutlineVisible();\n  }\n\n  // Re-apply fills on existing paths without rebinding events \u2014 used for\n  // metric switches and CSS-driven palette refreshes.\n  function refreshFills() {\n    if (getStatesFeatures().length) {\n      statesLayer.selectAll(\"path\").attr(\"fill\", getStateFeatureFill);\n    }\n    if (getMsaFeatures().length) {\n      msasLayer.selectAll(\"path\").attr(\"fill\", getMsaFeatureFill);\n    }\n    if (getDetailAreaFeatures().length) {\n      nonmetrosLayer.selectAll(\"path\").attr(\"fill\", getAreaFeatureFill);\n    }\n    if (getProvinceFeatures().length) {\n      provincesLayer.selectAll(\"path\").attr(\"fill\", getProvinceFeatureFill);\n    }\n    if (getCaAreaFeatures().length) {\n      caAreasLayer.selectAll(\"path\").attr(\"fill\", getCaAreaFeatureFill);\n    }\n    if (getUsCountryFeature() || getCaCountryFeature()) {\n      countryLayer.selectAll(\"path.map-feature-country\").attr(\"fill\", getCountryFeatureFill);\n    }\n  }\n\n  // Caller invokes once after wiring sibling subscribers in the right order\n  // (rebuildColorScales must fire first so refreshFills sees fresh scales).\n  function subscribeToMetricChanges() {\n    return selectedMetric.subscribe(refreshFills);\n  }\n\n  return {\n    renderWorld,\n    renderStates,\n    renderProvinces,\n    renderMsas,\n    renderNonmetros,\n    renderCaAreas,\n    renderCountry,\n    renderMetroNonmetroBorders,\n    renderCountyBorders,\n    renderCaCdBorders,\n    updateFeaturePaths,\n    refreshFills,\n    subscribeToMetricChanges,\n    // Selection by (kind, code) for deep-link boot + popstate; setApplyingHistory\n    // lets those paths suppress the history write while restoring (plan unit E).\n    selectByKindCode,\n    setApplyingHistory,\n    isApplyingHistory,\n    // Address-bar sync for the nation-reset path (clearMapSelection) so a\n    // deselect rewinds the slug to the nation root, matching commitSelection.\n    syncSelectionUrl,\n  };\n}\n", "// @ts-check\n\n// Post-load orchestration: subscribes to the per-layer `*Loaded` signals and\n// runs the rendering chain (domain cache \u2192 color scales \u2192 render \u2192 legend)\n// once each cache is populated. Data fetchers in data/*.js own the cache\n// writes and flip the signal; this module owns the side-effect chain that\n// follows.\n//\n// Callers wire this once during boot, before any `ensure*Loaded` call. The\n// signals are write-once-per-session, so each subscriber fires exactly once.\n// Order within a single signal's notify is registration order \u2014 keep all\n// related side effects in one subscriber rather than splitting across\n// multiple subscribers on the same signal.\n//\n// Invariant: each signal flip performs exactly ONE domain-cache update and\n// ONE rebuildColorScales() before its renders, so cross-country re-renders\n// (US\u2194Canada sharing one scale) never double-recompute scales.\n\nimport {\n  statesLoaded,\n  msaMetricsLoaded,\n  msaTopologyLoaded,\n  provincesLoaded,\n  caAreasLoaded,\n  nonmetrosLoaded,\n  worldLoaded,\n  countyBordersLoaded,\n  caCdBordersLoaded,\n  nationLoaded,\n  nationCaLoaded,\n  stateMetricsByCode,\n  msaMetricsByCode,\n  nonmetroMetricsByCode,\n  provinceMetricsByCode,\n  cmaMetricsByCode,\n  caNonmetroMetricsByCode,\n} from \"../state/caches.js\";\nimport {\n  setMetricDomainCacheEntry,\n  updateCombinedAreaDomainCache,\n  updateCombinedStateDomainCache,\n  rebuildColorScales,\n} from \"./colors.js\";\nimport { updateGradientLegend } from \"./legend.js\";\n\n/**\n * @param {{\n *   renderWorld: () => void,\n *   renderStates: () => void,\n *   renderProvinces: () => void,\n *   renderMsas: () => void,\n *   renderNonmetros: () => void,\n *   renderCaAreas: () => void,\n *   renderCountry: () => void,\n *   renderMetroNonmetroBorders: () => void,\n *   renderCountyBorders: () => void,\n *   renderCaCdBorders: () => void,\n *   updateFeaturePaths: () => void,\n *   applyLayerVisibility: () => Promise<void> | void,\n * }} deps\n */\nexport function setupPostLoadHandlers(deps) {\n  const {\n    renderWorld,\n    renderStates,\n    renderProvinces,\n    renderMsas,\n    renderNonmetros,\n    renderCaAreas,\n    renderCountry,\n    renderMetroNonmetroBorders,\n    renderCountyBorders,\n    renderCaCdBorders,\n    updateFeaturePaths,\n    applyLayerVisibility,\n  } = deps;\n\n  worldLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderWorld();\n    updateFeaturePaths();\n  });\n\n  statesLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    setMetricDomainCacheEntry(\"state\", stateMetricsByCode);\n    updateCombinedStateDomainCache();\n    rebuildColorScales();\n    // Keep camera/projection stable after first paint to avoid startup jump.\n    // States/world load in the background and should not rebase map geometry.\n    renderStates();\n    // Provinces may have painted on a Canada-only domain before the states\n    // payload landed; re-render so both countries share the merged scale.\n    if (provincesLoaded.get()) renderProvinces();\n    // The US country polygon is derived from the states topology \u2014 (re)build it\n    // now that it's available (no-op paint while not in country mode).\n    renderCountry();\n    updateFeaturePaths();\n    updateGradientLegend();\n  });\n\n  provincesLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    setMetricDomainCacheEntry(\"province\", provinceMetricsByCode);\n    updateCombinedStateDomainCache();\n    rebuildColorScales();\n    renderProvinces();\n    // US states may have rendered with a US-only domain before the province\n    // payload landed; re-render so both countries share the merged scale.\n    // Guard on statesLoaded so a provinces-first arrival doesn't paint states\n    // from an empty cache.\n    if (statesLoaded.get()) renderStates();\n    // Canada country polygon is derived from the provinces topology \u2014 build it.\n    renderCountry();\n    updateGradientLegend();\n  });\n\n  msaMetricsLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    setMetricDomainCacheEntry(\"msa\", msaMetricsByCode);\n    updateCombinedAreaDomainCache();\n    rebuildColorScales();\n    // Grey-metros race (prod incident 2026-06-11): the visible default layer\n    // is `area_composites` (388 metros + 134 nonmetros), rendered by\n    // renderNonmetros() on the `nonmetrosLoaded` signal. That render paints\n    // metro fills from msaMetricsByCode (getAreaFeatureFill). Since msa metrics\n    // and nonmetros now fetch in parallel (#174), nonmetros can resolve first\n    // and trigger the initial render while msaMetricsByCode is still empty \u2014\n    // every metro then paints no-data grey and nothing repaints it. When MSA\n    // metrics land AFTER nonmetros already rendered, re-render the visible area\n    // layer (and its borders) so those 388 metros pick up their real fills.\n    // Guard on nonmetrosLoaded so we only re-render once the layer actually\n    // exists; if msa metrics resolve first, the later nonmetros subscriber does\n    // the single, correct initial render and this branch is skipped.\n    if (nonmetrosLoaded.get()) {\n      renderNonmetros();\n      renderMetroNonmetroBorders();\n    }\n    // Canadian areas share the combined area scale \u2014 repaint them on the\n    // merged domain if they already rendered.\n    if (caAreasLoaded.get()) renderCaAreas();\n    updateGradientLegend();\n  });\n\n  // MSA topology is lazy \u2014 fetched only when the area-composites layer fails\n  // and the metros-only fallback layer must render. renderMsas reads\n  // getPathGenerator() at call time, so this late render (after the projection\n  // has already refit during boot) draws the paths against the current\n  // projection without needing a refit here.\n  msaTopologyLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderMsas();\n  });\n\n  nonmetrosLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    setMetricDomainCacheEntry(\"nonmetro\", nonmetroMetricsByCode);\n    updateCombinedAreaDomainCache();\n    rebuildColorScales();\n    renderNonmetros();\n    renderMetroNonmetroBorders();\n    // Canadian areas share the combined area scale \u2014 repaint them on the\n    // merged domain if they already rendered.\n    if (caAreasLoaded.get()) renderCaAreas();\n    updateGradientLegend();\n  });\n\n  caAreasLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    setMetricDomainCacheEntry(\"cma\", cmaMetricsByCode);\n    setMetricDomainCacheEntry(\"caNonmetro\", caNonmetroMetricsByCode);\n    updateCombinedAreaDomainCache();\n    rebuildColorScales();\n    renderCaAreas();\n    // The US area layers may have painted with a US-only domain before the\n    // Canadian payloads landed; re-render them on the merged scale. Guard on\n    // each US signal so a Canada-first arrival doesn't render from empty\n    // caches (the later US subscribers do the single, correct initial render).\n    if (nonmetrosLoaded.get()) {\n      renderNonmetros();\n      renderMetroNonmetroBorders();\n    }\n    if (msaTopologyLoaded.get()) renderMsas();\n    updateGradientLegend();\n    // A late Canada arrival can still happen after a retry or an on-demand\n    // mode change, so re-apply visibility to fade the layer in for the active\n    // mode.\n    if (applyLayerVisibility) applyLayerVisibility();\n  });\n\n  // County mesh is independent of metric data \u2014 render and re-apply layer\n  // visibility (so the layer fades in for the active mode) as soon as it's\n  // available. The fetch may resolve before or after the data layers; both\n  // orderings are fine because resolveVisibleLayers reads countyBordersLoaded\n  // each time applyLayerVisibility runs.\n  countyBordersLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderCountyBorders();\n    if (applyLayerVisibility) applyLayerVisibility();\n  });\n\n  // Same contract for the Canadian census-division mesh.\n  caCdBordersLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderCaCdBorders();\n    if (applyLayerVisibility) applyLayerVisibility();\n  });\n\n  // Nation aggregates back the Country fill layer's colors (not its geometry).\n  // They can land after the country polygons already painted grey (e.g. the US\n  // aggregate loads for the side panel on boot; Canada loads lazily), so repaint\n  // the country layer when either arrives. renderCountry is a no-op paint while\n  // the layer is hidden (not in country mode).\n  nationLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderCountry();\n  });\n  nationCaLoaded.subscribe((loaded) => {\n    if (!loaded) return;\n    renderCountry();\n  });\n}\n", "// @ts-check\n\n// Side-panel controller: owns collapse state, toggle positioning, layout\n// reflow, the selection summary cards (totals, gauges, exposed metrics),\n// and the \"refresh whole panel from current selection\" pathway.\n// Treemap/top-industries rendering is delegated to panel/top-occupations.js.\n\nimport { METRIC_MODE_AI_EXPOSURE, METRIC_MODE_CALIBRATED, PRESERVE_VIEW_ON_LAYOUT_CHANGE } from \"../config.js\";\nimport { selectedMetric, currentSelection } from \"../state/store.js\";\nimport {\n  getRegionMetrics,\n  getRegionAccentColor,\n  nation,\n  nationCa,\n} from \"../state/caches.js\";\nimport { getColorScaleForKey, getMetricValue } from \"../map/colors.js\";\n\n// The 6 per-region selection kinds (everything except \"nation\"), used to gate\n// refreshSelectionPanel's region path.\nconst REGION_KINDS = new Set([\"state\", \"msa\", \"nonmetro\", \"province\", \"cma\", \"ca_nonmetro\"]);\nimport {\n  formatRoundedCount,\n  formatRoundedWage,\n  formatGaugePercentage,\n  getTotalWorkers,\n  calculateExposureRatio,\n  normalizeNullableFiniteNumber,\n  clamp01,\n} from \"../util/format.js\";\n\n/**\n * @typedef {{\n *   sidePanelEl: HTMLElement | null,\n *   sidePanelToggleEl: HTMLElement | null,\n *   rootEl: HTMLElement | null,\n *   svgNode: SVGSVGElement | HTMLElement,\n *   selectedTypeEl: HTMLElement | null,\n *   selectedNameEl: HTMLElement | null,\n *   selectedTotalWorkforceEl: HTMLElement | null,\n *   selectedTotalWageBillEl: HTMLElement | null,\n *   selectedExposedWageBillEl: HTMLElement | null,\n *   selectedExposedWorkforceEl: HTMLElement | null,\n *   selectedWorkforceGaugeValueEl: HTMLElement | null,\n *   selectedWorkforceGaugeProgressEl: any,\n *   selectedWageBillGaugeValueEl: HTMLElement | null,\n *   selectedWageBillGaugeProgressEl: any,\n * }} SidePanelEls\n *\n * @typedef {{\n *   getMapColors: () => { noData: string, noDataNonmetro: string, worldLand: string, worldOcean: string },\n *   getCurrentTransform: () => any,\n *   getProjection: () => any,\n *   getMapViewport: (collapsedOverride?: any) => any,\n *   fitProjection: () => void,\n *   refreshZoomExtent: (collapsedOverride?: any) => void,\n *   updateFeaturePaths: () => void,\n *   ensureSelectionOutlineVisible: () => void,\n *   setZoomTransform: (transform: any) => void,\n *   setZoomTransformAnimated: (transform: any, duration?: number) => void,\n *   getInitialUsTransform: () => any,\n *   userHasInteractedWithZoom: () => boolean,\n * }} SidePanelMapOps\n *\n * @param {{\n *   els: SidePanelEls,\n *   mapOps: SidePanelMapOps,\n *   refreshTopOccupationsPanel: () => any,\n * }} deps\n */\nexport function createSidePanelController(deps) {\n  const { els, mapOps, refreshTopOccupationsPanel } = deps;\n  const {\n    sidePanelEl,\n    sidePanelToggleEl,\n    rootEl,\n    svgNode,\n    selectedTypeEl,\n    selectedNameEl,\n    selectedTotalWorkforceEl,\n    selectedTotalWageBillEl,\n    selectedExposedWageBillEl,\n    selectedExposedWorkforceEl,\n    selectedWorkforceGaugeValueEl,\n    selectedWorkforceGaugeProgressEl,\n    selectedWageBillGaugeValueEl,\n    selectedWageBillGaugeProgressEl,\n  } = els;\n  const {\n    getMapColors,\n    getCurrentTransform,\n    getProjection,\n    getMapViewport,\n    fitProjection,\n    refreshZoomExtent,\n    updateFeaturePaths,\n    ensureSelectionOutlineVisible,\n    setZoomTransform,\n    setZoomTransformAnimated,\n    getInitialUsTransform,\n    userHasInteractedWithZoom,\n  } = mapOps;\n\n  function updateCircularGauge(progressEl, valueEl, ratio) {\n    if (!progressEl || !valueEl) return;\n    const gaugeEl = valueEl.closest(\".map-exposure-gauge\");\n    const radius = Number(progressEl.getAttribute(\"r\")) || 46;\n    const circumference = 2 * Math.PI * radius;\n    progressEl.setAttribute(\"fill\", \"none\");\n    if (!Number.isFinite(ratio)) {\n      progressEl.style.strokeDasharray = `${circumference}`;\n      progressEl.style.strokeDashoffset = `${circumference}`;\n      valueEl.textContent = \"--\";\n      if (gaugeEl) gaugeEl.classList.add(\"is-empty\");\n      return;\n    }\n    const clampedRatio = clamp01(ratio);\n    progressEl.style.strokeDasharray = `${circumference}`;\n    progressEl.style.strokeDashoffset = `${circumference * (1 - clampedRatio)}`;\n    valueEl.textContent = formatGaugePercentage(clampedRatio);\n    if (gaugeEl) gaugeEl.classList.remove(\"is-empty\");\n  }\n\n  function setGaugeAccentColor(progressEl, color) {\n    if (!progressEl) return;\n    progressEl.setAttribute(\"fill\", \"none\");\n    if (color) {\n      // Map fill colors can be extremely dark; keep the ring legible.\n      if (typeof window !== \"undefined\" && window.d3) {\n        const lab = window.d3.lab(color);\n        if (Number.isFinite(lab.l) && lab.l < 42) {\n          progressEl.style.stroke = window.d3.lab(42, lab.a, lab.b).formatHex();\n          return;\n        }\n      }\n      progressEl.style.stroke = color;\n      return;\n    }\n    progressEl.style.removeProperty(\"stroke\");\n  }\n\n  function getSelectionAccentColor(selection = currentSelection.get()) {\n    if (!selection) return null;\n    // Nation (and any non-region kind) has no per-region color in the\n    // choropleth; getRegionAccentColor returns null for it, falling through to\n    // the default CSS stroke so gauges aren't tinted misleadingly.\n    return getRegionAccentColor(selection.kind, selection.code, {\n      mapColors: getMapColors(),\n      getMetricValue,\n      getColorScale: getColorScaleForKey,\n    });\n  }\n\n  function resolveExposureMetrics(exposureStats) {\n    if (!exposureStats) return { exposedWageBill: null, exposedWorkforce: null };\n    const metric = selectedMetric.get();\n    const modeKey = metric === METRIC_MODE_AI_EXPOSURE\n      ? \"penetration\"\n      : metric === METRIC_MODE_CALIBRATED\n        ? \"calibrated\"\n        : \"ability\";\n    const entry = exposureStats[modeKey] || {};\n    // Null-preserving: a null calibrated entry means zero coverage (no data),\n    // and Number(null) === 0 would fake \"0 workers / $0\" \u2014 keep null so\n    // formatRoundedCount/-Wage render \"--\" and the gauges show no ratio.\n    return {\n      exposedWageBill: normalizeNullableFiniteNumber(entry.exposedWageBill),\n      exposedWorkforce: normalizeNullableFiniteNumber(entry.exposedWorkforce),\n    };\n  }\n\n  function clearSelectionDisplay(name = \"Select a region\") {\n    if (selectedNameEl) selectedNameEl.textContent = name;\n    if (selectedTypeEl) {\n      selectedTypeEl.textContent = \"\";\n      selectedTypeEl.classList.add(\"hidden\");\n    }\n  }\n\n  function updateSelection(type, name, totalWorkers = null, wageBill = null, exposureStats = null) {\n    if (selectedTypeEl) {\n      selectedTypeEl.textContent = type;\n      selectedTypeEl.classList.remove(\"hidden\");\n    }\n    if (selectedNameEl) selectedNameEl.textContent = name;\n\n    const exposure = resolveExposureMetrics(exposureStats);\n    const normalizedTotalWorkers = getTotalWorkers(totalWorkers);\n    const workforceRatio = calculateExposureRatio(exposure.exposedWorkforce, normalizedTotalWorkers);\n    const wageBillRatio = calculateExposureRatio(exposure.exposedWageBill, wageBill);\n    const selectionAccentColor = getSelectionAccentColor();\n\n    if (selectedTotalWorkforceEl) selectedTotalWorkforceEl.textContent = formatRoundedCount(normalizedTotalWorkers);\n    if (selectedTotalWageBillEl) selectedTotalWageBillEl.textContent = formatRoundedWage(wageBill);\n    if (selectedExposedWageBillEl) selectedExposedWageBillEl.textContent = formatRoundedWage(exposure.exposedWageBill);\n    if (selectedExposedWorkforceEl) selectedExposedWorkforceEl.textContent = formatRoundedCount(exposure.exposedWorkforce);\n\n    updateCircularGauge(selectedWorkforceGaugeProgressEl, selectedWorkforceGaugeValueEl, workforceRatio);\n    updateCircularGauge(selectedWageBillGaugeProgressEl, selectedWageBillGaugeValueEl, wageBillRatio);\n    setGaugeAccentColor(selectedWorkforceGaugeProgressEl, selectionAccentColor);\n    setGaugeAccentColor(selectedWageBillGaugeProgressEl, selectionAccentColor);\n    // Metric-switch path also lands here via refreshSelectionPanel; the\n    // top-occupations cache key includes the metric so the fetch is deduped,\n    // and resetTopOccupationsTaskState only fires when the selection-key\n    // (scope:code) changes, so drilldown state survives metric switches.\n    refreshTopOccupationsPanel();\n  }\n\n  function refreshSelectionPanel() {\n    const selection = currentSelection.get();\n    if (!selection) return;\n    if (selection.kind === \"nation\") {\n      // US reads `nation`; Canada reads the parallel `nationCa` holder. Keyed on\n      // selection.code so the US path (code \"us\") is unchanged.\n      const holder = selection.code === \"ca\" ? nationCa : nation;\n      updateSelection(\n        selection.label,\n        selection.name,\n        holder.totalWorkforce,\n        holder.totalWageBill,\n        holder.exposure,\n      );\n      return;\n    }\n    // The 6 region kinds (state/msa/nonmetro/province/cma/ca_nonmetro) all read\n    // their parallel caches through getRegionMetrics. Preserve the original\n    // `|| null` coalescing on each value, and the original's silent no-op for an\n    // unrecognized kind (it fell through without calling updateSelection).\n    if (!REGION_KINDS.has(selection.kind)) return;\n    const metrics = getRegionMetrics(selection.kind, selection.code);\n    updateSelection(\n      selection.label,\n      selection.name,\n      metrics.totalWorkers || null,\n      metrics.wageBill || null,\n      metrics.exposureStats || null,\n    );\n  }\n\n  function updateTogglePosition(collapsed = sidePanelEl && sidePanelEl.classList.contains(\"is-collapsed\")) {\n    if (!sidePanelToggleEl) return;\n    const containerRect = rootEl ? rootEl.getBoundingClientRect() : svgNode.getBoundingClientRect();\n    let left = 16;\n    let top = 16;\n    if (sidePanelEl && !collapsed) {\n      const panelRect = sidePanelEl.getBoundingClientRect();\n      left = panelRect.right - containerRect.left + 8;\n      top = panelRect.top - containerRect.top + 12;\n    }\n    left = Math.max(8, Math.min(left, Math.max(8, containerRect.width - 48)));\n    top = Math.max(8, Math.min(top, Math.max(8, containerRect.height - 48)));\n    sidePanelToggleEl.style.left = `${left}px`;\n    sidePanelToggleEl.style.top = `${top}px`;\n  }\n\n  function setPanelCollapsed(collapsed) {\n    if (!sidePanelEl || !sidePanelToggleEl) return;\n    sidePanelEl.classList.toggle(\"is-collapsed\", collapsed);\n    if (collapsed) sidePanelToggleEl.classList.remove(\"hidden\");\n    else sidePanelToggleEl.classList.add(\"hidden\");\n    sidePanelEl.setAttribute(\"aria-expanded\", String(!collapsed));\n    sidePanelToggleEl.setAttribute(\"aria-expanded\", String(!collapsed));\n    sidePanelToggleEl.setAttribute(\"aria-label\", collapsed ? \"Open side panel\" : \"Close side panel\");\n    if (collapsed) sidePanelEl.classList.remove(\"is-expanded\");\n    updateTogglePosition(collapsed);\n  }\n\n  function captureViewportGeoCenter() {\n    const viewport = getMapViewport();\n    const mapCoordinates = getCurrentTransform().invert([viewport.centerX, viewport.centerY]);\n    const geo = getProjection().invert(mapCoordinates);\n    if (!geo || !Number.isFinite(geo[0]) || !Number.isFinite(geo[1])) return null;\n    return geo;\n  }\n\n  function handleLayoutChange(reason = \"resize\") {\n    const isPanelToggle = reason === \"panel-toggle\";\n\n    // Panel toggle: pan-only, animated. We deliberately skip fitProjection +\n    // updateFeaturePaths here \u2014 refitting would instantly rescale every\n    // feature path and that visible \"snap\" is what made follow-up focus\n    // animations appear to start from somewhere other than the user's\n    // current view. By keeping the projection fixed and animating just the\n    // zoom transform, the panel settle \u2192 map re-center transition stays\n    // smooth, and if a focus animation follows it interrupts this pan\n    // before the first tick renders.\n    if (isPanelToggle) {\n      // Viewport width changed (panel took/freed space). Re-apply the d3\n      // scaleExtent so wheel-zoom limits and in-flight transition clamps\n      // track the new viewport. We deliberately don't call fitProjection\n      // here (see comment below).\n      if (refreshZoomExtent) refreshZoomExtent();\n      const geoCenterBeforeResize = captureViewportGeoCenter();\n      const currentScale = getCurrentTransform().k;\n      if (geoCenterBeforeResize) {\n        const viewport = getMapViewport();\n        const projectedCenter = getProjection()(geoCenterBeforeResize);\n        if (projectedCenter) {\n          const tx = viewport.centerX - projectedCenter[0] * currentScale;\n          const ty = viewport.centerY - projectedCenter[1] * currentScale;\n          setZoomTransformAnimated(\n            window.d3.zoomIdentity.translate(tx, ty).scale(currentScale),\n            320,\n          );\n        }\n      }\n      updateTogglePosition();\n      return;\n    }\n\n    const shouldPreserveView = PRESERVE_VIEW_ON_LAYOUT_CHANGE && userHasInteractedWithZoom();\n    const geoCenterBeforeResize = shouldPreserveView ? captureViewportGeoCenter() : null;\n    const currentTransform = getCurrentTransform();\n    const currentScale = currentTransform.k;\n\n    fitProjection();\n    updateFeaturePaths();\n    ensureSelectionOutlineVisible();\n\n    if (shouldPreserveView && geoCenterBeforeResize) {\n      const viewport = getMapViewport();\n      const projectedCenter = getProjection()(geoCenterBeforeResize);\n      if (projectedCenter) {\n        const tx = viewport.centerX - projectedCenter[0] * currentScale;\n        const ty = viewport.centerY - projectedCenter[1] * currentScale;\n        setZoomTransform(window.d3.zoomIdentity.translate(tx, ty).scale(currentScale));\n        return;\n      }\n    }\n\n    setZoomTransform(getInitialUsTransform());\n  }\n\n  // Defers the expensive map recompute until the panel's CSS transition\n  // settles, so we recompute once against the final panel rect instead of\n  // jumping during the animation. The fallback timeout covers cases where\n  // transitionend never fires (reduced-motion, interrupted transition, etc.).\n  let pendingRecompute = null;\n  const PANEL_TRANSITION_FALLBACK_MS = 220;\n\n  function schedulePanelLayoutRecompute(reason = \"panel-toggle\", onDone = null) {\n    if (!sidePanelEl) {\n      handleLayoutChange(reason);\n      if (onDone) onDone();\n      return;\n    }\n\n    if (pendingRecompute) {\n      sidePanelEl.removeEventListener(\"transitionend\", pendingRecompute.onTransitionEnd);\n      clearTimeout(pendingRecompute.fallbackTimer);\n      pendingRecompute = null;\n    }\n\n    const fire = () => {\n      if (!pendingRecompute) return;\n      sidePanelEl.removeEventListener(\"transitionend\", pendingRecompute.onTransitionEnd);\n      clearTimeout(pendingRecompute.fallbackTimer);\n      const done = pendingRecompute.onDone;\n      pendingRecompute = null;\n      handleLayoutChange(reason);\n      if (done) done();\n    };\n\n    const onTransitionEnd = (event) => {\n      if (event.target !== sidePanelEl) return;\n      if (event.propertyName !== \"transform\" && event.propertyName !== \"width\") return;\n      fire();\n    };\n\n    pendingRecompute = {\n      onTransitionEnd,\n      fallbackTimer: setTimeout(fire, PANEL_TRANSITION_FALLBACK_MS),\n      onDone,\n    };\n    sidePanelEl.addEventListener(\"transitionend\", onTransitionEnd);\n  }\n\n  return {\n    setPanelCollapsed,\n    updateTogglePosition,\n    handleLayoutChange,\n    schedulePanelLayoutRecompute,\n    refreshSelectionPanel,\n    updateSelection,\n    clearSelectionDisplay,\n  };\n}\n", "// @ts-check\n\n// Pure snap math for the mobile bottom sheet, extracted from mobile-sheet.js\n// so it can be unit-tested without a DOM (see tests/unit/sheet-snap.test.mjs,\n// which loads it via the importBrowserModule helper). Nothing in here touches\n// `window`/`document`.\n//\n// The model mirrors iOS gesture conventions:\n//   * velocityFromSamples \u2014 a *recent* release velocity, like\n//     UIPanGestureRecognizer.velocity(in:), so a finger held still before\n//     lifting reports ~0 (no fling) rather than a stale flick reading.\n//   * projectFlingDistance \u2014 Apple's \"Designing Fluid Interfaces\"\n//     (WWDC 2018) projection, used to estimate where an inertial fling\n//     would settle, then snap to the nearest detent from there.\n\n// UIScrollView.DecelerationRate.normal. The projection's only tuning knob.\nexport const DECELERATION_RATE = 0.998;\n\n// Window (ms) over which release velocity is measured. ~100ms tracks the\n// last few frames of motion regardless of display refresh rate.\nexport const VELOCITY_WINDOW_MS = 100;\n\n// A short but deliberate drag (px) that commits one detent step even with\n// no fling velocity behind it.\nexport const COMMIT_PX = 40;\n\n/**\n * Release velocity (px/ms, positive = downward) measured over the trailing\n * `windowMs` of pointer samples. Returns 0 when there is no recent motion\n * \u2014 i.e. the finger was held still before lifting, so there is no fling.\n *\n * @param {Array<{ t: number, y: number }>} samples chronological pointer samples\n * @param {number} releaseTime timestamp of the pointer-up\n * @param {number} [windowMs]\n * @returns {number}\n */\nexport function velocityFromSamples(samples, releaseTime, windowMs = VELOCITY_WINDOW_MS) {\n  if (!samples || samples.length < 2) return 0;\n  const last = samples[samples.length - 1];\n  // Held still before release \u2192 no fling.\n  if (releaseTime - last.t > windowMs) return 0;\n  const cutoff = releaseTime - windowMs;\n  // Walk back to the oldest sample still inside the window.\n  let i = samples.length - 1;\n  while (i > 0 && samples[i - 1].t >= cutoff) i--;\n  const first = samples[i];\n  const dt = last.t - first.t;\n  if (dt > 0) return (last.y - first.y) / dt;\n  // Only one sample landed inside the window \u2014 a quick flick that emitted few\n  // pointermove events, or coincident timestamps. Fall back to the last two\n  // raw samples so a genuine fast flick isn't mis-read as zero velocity. (The\n  // held-still guard above already returned 0 for a finger that paused.)\n  const prev = samples[samples.length - 2];\n  const dtRaw = last.t - prev.t;\n  return dtRaw > 0 ? (last.y - prev.y) / dtRaw : 0;\n}\n\n/**\n * Distance (px, signed in the velocity's direction) a fling would coast\n * before stopping. Apple's WWDC 2018 projection: their formula takes\n * points/second and divides by 1000, which is identical to taking px/ms\n * directly, so `project = velocity * rate / (1 - rate)`.\n *\n * @param {number} velocity px/ms (positive = downward)\n * @param {number} [decelerationRate]\n * @returns {number}\n */\nexport function projectFlingDistance(velocity, decelerationRate = DECELERATION_RATE) {\n  return velocity * (decelerationRate / (1 - decelerationRate));\n}\n\n/**\n * Decide which detent the sheet settles on when a drag ends.\n *\n * A quick flick projects forward along its velocity and snaps to the\n * nearest detent from the projected point \u2014 so a fling collapses or\n * dismisses without dragging the whole way. A slow but deliberate drag has\n * ~no projection, so it would snap back to where it started; the small-drag\n * bias rescues that case by advancing exactly one step in the drag\n * direction once travel passes `COMMIT_PX`.\n *\n * @param {{\n *   currentHeight: number,\n *   startHeight: number,\n *   velocity: number,\n *   detents: { peek: number, expanded: number },\n *   decelerationRate?: number,\n *   commitPx?: number,\n * }} args\n * @returns {\"closed\" | \"peek\" | \"expanded\"}\n */\nexport function decideSheetTarget({\n  currentHeight,\n  startHeight,\n  velocity,\n  detents,\n  decelerationRate = DECELERATION_RATE,\n  commitPx = COMMIT_PX,\n}) {\n  // Detents ascending by height so adjacent indices are adjacent states.\n  const ladder = [\n    { state: \"closed\", h: 0 },\n    { state: \"peek\", h: detents.peek },\n    { state: \"expanded\", h: detents.expanded },\n  ];\n  const nearestIdx = (h) => {\n    let bi = 0;\n    let bd = Math.abs(h - ladder[0].h);\n    for (let i = 1; i < ladder.length; i++) {\n      const d = Math.abs(h - ladder[i].h);\n      if (d < bd) {\n        bd = d;\n        bi = i;\n      }\n    }\n    return bi;\n  };\n\n  const projectedHeight = currentHeight - projectFlingDistance(velocity, decelerationRate);\n  let targetIdx = nearestIdx(projectedHeight);\n\n  const startIdx = nearestIdx(startHeight);\n  if (targetIdx === startIdx) {\n    const downTravel = startHeight - currentHeight; // + = dragged down\n    if (downTravel > commitPx) targetIdx = Math.max(0, startIdx - 1);\n    else if (downTravel < -commitPx) targetIdx = Math.min(ladder.length - 1, startIdx + 1);\n  }\n  return /** @type {\"closed\" | \"peek\" | \"expanded\"} */ (ladder[targetIdx].state);\n}\n", "// @ts-check\n\n// Mobile info sheet: Find My-style draggable bottom sheet. Two snap\n// points (peek, expanded) plus a closed off-screen state. Peek shows\n// the summary plus the two stat rows; expanded hosts the inline-details\n// mount. Drag down past peek dismisses; the caller wires re-show on\n// dismissal so the US-wide preview keeps the sheet visible.\n\nimport { METRIC_MODE_AI_EXPOSURE, METRIC_MODE_CALIBRATED } from \"../config.js\";\nimport { selectedMetric, currentSelection } from \"../state/store.js\";\nimport { getRegionAccentColor } from \"../state/caches.js\";\nimport { getColorScaleForKey, getMetricValue } from \"../map/colors.js\";\nimport {\n  formatRoundedCount,\n  formatRoundedWage,\n  formatPenetrationPercentRounded,\n  getTotalWorkers,\n  calculateExposureRatio,\n  normalizeNullableFiniteNumber,\n} from \"../util/format.js\";\nimport { decideSheetTarget, velocityFromSamples } from \"./sheet-snap.js\";\nimport { measureSync } from \"../util/perf.js\";\n\n/**\n * @param {{\n *   getMapColors: () => { noData: string, noDataNonmetro: string, worldLand: string, worldOcean: string },\n *   bodyDrag?: boolean,\n *   eventLogUrl?: string | null,\n * }} deps\n */\nexport function createMobileSheet(deps) {\n  const { getMapColors, bodyDrag = false, eventLogUrl = null } = deps;\n\n  // When the user prefers reduced motion, drop the inertial fling projection\n  // on release (snap by position only) so the sheet doesn't fling or spring;\n  // a CSS transition-duration cut (us_ai_map.css) handles the slide itself.\n  const reduceMotionMQL =\n    typeof window !== \"undefined\" && window.matchMedia\n      ? window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n      : null;\n\n  const cardEl = document.getElementById(\"map-mobile-preview-card\");\n  const titleEl = document.getElementById(\"map-mobile-preview-title\");\n  const typeEl = document.getElementById(\"map-mobile-preview-type\");\n  const workersEl = document.getElementById(\"map-mobile-preview-workers\");\n  const wageEl = document.getElementById(\"map-mobile-preview-wage\");\n  const handleEl = document.getElementById(\"map-mobile-sheet-handle\");\n  const peekEl = cardEl ? cardEl.querySelector(\".map-mobile-sheet__peek\") : null;\n  const expandedEl = cardEl ? cardEl.querySelector(\".map-mobile-sheet__expanded\") : null;\n\n  // Tracks the in-flight transitionend listener attached by hide() so\n  // show() / a follow-up hide() can detach it and avoid stale callbacks\n  // setting cardEl.hidden=true mid-reveal of a new region preview.\n  let pendingHideOnEnd = null;\n  function clearPendingHide() {\n    if (pendingHideOnEnd && cardEl) {\n      cardEl.removeEventListener(\"transitionend\", pendingHideOnEnd);\n    }\n    pendingHideOnEnd = null;\n  }\n\n  function setSheetTranslate(px) {\n    if (!cardEl) return;\n    cardEl.style.setProperty(\"--sheet-translate-y\", `${px}px`);\n  }\n\n  function getSheetHeight() {\n    return cardEl ? cardEl.offsetHeight : 0;\n  }\n\n  function snapForState(state) {\n    // Sheet auto-sizes to each visible state's content via CSS max-height\n    // rules on the expanded section, so peek/expanded both rest at\n    // translateY(0) \u2014 the box itself shrinks/grows. Only the closed\n    // state needs a translate to push the card off-screen.\n    if (state === \"expanded\" || state === \"peek\") return 0;\n    const h = getSheetHeight();\n    const bottomInset = parseFloat(getComputedStyle(cardEl).bottom) || 0;\n    return h + bottomInset + 8;\n  }\n\n  function setState(state) {\n    if (!cardEl) return;\n    cardEl.dataset.state = state;\n    cardEl.setAttribute(\"aria-hidden\", state === \"closed\" ? \"true\" : \"false\");\n    if (handleEl) handleEl.setAttribute(\"aria-expanded\", state === \"expanded\" ? \"true\" : \"false\");\n    if (expandedEl) expandedEl.setAttribute(\"aria-hidden\", state === \"expanded\" ? \"false\" : \"true\");\n    setSheetTranslate(snapForState(state));\n  }\n\n  let lastMeta = null;\n\n  function resolveExposure(exposureStats) {\n    if (!exposureStats) return { exposedWorkforce: null, exposedWageBill: null };\n    const metric = selectedMetric.get();\n    const modeKey = metric === METRIC_MODE_AI_EXPOSURE\n      ? \"penetration\"\n      : metric === METRIC_MODE_CALIBRATED\n        ? \"calibrated\"\n        : \"ability\";\n    const entry = exposureStats[modeKey] || {};\n    // Null-preserving: a null calibrated entry means zero coverage (no data),\n    // and Number(null) === 0 would fake \"0 workers / $0\" \u2014 keep null so the\n    // formatters render \"--\".\n    return {\n      exposedWorkforce: normalizeNullableFiniteNumber(entry.exposedWorkforce),\n      exposedWageBill: normalizeNullableFiniteNumber(entry.exposedWageBill),\n    };\n  }\n\n  function getMobileAccentColor() {\n    const selection = currentSelection.get();\n    if (!selection) return null;\n    // Non-region kinds (e.g. nation) resolve to null \u2014 no peek accent tint.\n    return getRegionAccentColor(selection.kind, selection.code, {\n      mapColors: getMapColors(),\n      getMetricValue,\n      getColorScale: getColorScaleForKey,\n    });\n  }\n\n  // Builds the peek-style \"12K / 50K (24%)\" markup so peek dd elements\n  // share the same visual treatment as the peek stat: smaller percentage\n  // suffix in parentheses, set in the __peek-stat-pct span.\n  function renderStatWithPercent(el, countsText, ratio) {\n    if (!el) return;\n    el.innerHTML = \"\";\n    const countsEl = document.createElement(\"span\");\n    countsEl.className = \"map-mobile-sheet__peek-stat-counts\";\n    countsEl.textContent = countsText;\n    const pctEl = document.createElement(\"span\");\n    pctEl.className = \"map-mobile-sheet__peek-stat-pct\";\n    pctEl.textContent = `(${formatPenetrationPercentRounded(ratio)})`;\n    el.append(countsEl, document.createTextNode(\" \"), pctEl);\n  }\n\n  function renderMeta(meta) {\n    if (!meta) return;\n    const total = getTotalWorkers(Number(meta.totalWorkers));\n    const wage = Number.isFinite(Number(meta.wageBill)) ? Number(meta.wageBill) : null;\n    const { exposedWorkforce, exposedWageBill } = resolveExposure(meta.exposureStats);\n    const workforceRatio = calculateExposureRatio(exposedWorkforce, total);\n    const wageRatio = calculateExposureRatio(exposedWageBill, wage);\n    if (titleEl) titleEl.textContent = meta.name || \"Region\";\n    if (typeEl) {\n      typeEl.textContent = meta.type || \"\";\n      typeEl.style.display = meta.type ? \"\" : \"none\";\n    }\n    renderStatWithPercent(\n      workersEl,\n      `${formatRoundedCount(exposedWorkforce)} / ${formatRoundedCount(total)}`,\n      workforceRatio,\n    );\n    renderStatWithPercent(\n      wageEl,\n      `${formatRoundedWage(exposedWageBill)} / ${formatRoundedWage(wage)}`,\n      wageRatio,\n    );\n    const accent = getMobileAccentColor();\n    if (cardEl) {\n      if (accent) {\n        cardEl.style.setProperty(\"--mobile-peek-accent\", accent);\n      } else {\n        cardEl.style.removeProperty(\"--mobile-peek-accent\");\n      }\n    }\n  }\n\n  function show({ name, type, totalWorkers, wageBill, exposureStats }) {\n    if (!cardEl) return;\n    lastMeta = { name, type, totalWorkers, wageBill, exposureStats };\n    renderMeta(lastMeta);\n\n    // Always cancel any in-flight close listener first; otherwise its\n    // callback can fire mid-reveal and hide the freshly-shown sheet.\n    clearPendingHide();\n    // A drag-dismiss in flight may have left an inline maxHeight pin at\n    // the user's released height \u2014 clear it so the sheet re-opens at\n    // its full per-state CSS size, not stuck at the dragged-tiny value.\n    cardEl.style.maxHeight = \"\";\n    const wasClosed = cardEl.hidden || cardEl.dataset.state === \"closed\";\n    cardEl.hidden = false;\n    if (wasClosed) {\n      // Set state + aria synchronously to \"peek\" so consumers (e.g.\n      // getViewport's peek-height reservation in us_ai_map.js) see the\n      // final visible state right away. Without this, the transient\n      // \"closed\" state during the slide-in window would skip the\n      // bottom-sheet inset and center the tapped feature behind the\n      // about-to-appear sheet.\n      setState(\"peek\");\n      // Override setState's translate(0) with the off-screen position\n      // before paint so the CSS transition still animates the slide-in\n      // from off-screen \u2192 peek when we reset the translate two RAFs later.\n      setSheetTranslate(snapForState(\"closed\"));\n      requestAnimationFrame(() => {\n        requestAnimationFrame(() => setSheetTranslate(0));\n      });\n    } else {\n      // Already visible from a prior region \u2014 preserve whichever detent\n      // the user had open (peek/expanded) so switching regions only\n      // swaps the content, not the layout. setState re-applies size/aria\n      // so per-state CSS rules pick up the new content's natural height.\n      setState(cardEl.dataset.state || \"peek\");\n    }\n  }\n\n  function hide() {\n    if (!cardEl) return;\n    const wasOpen = !cardEl.hidden && cardEl.dataset.state !== \"closed\";\n    // Drop any prior pending hide listener so the new transition owns the\n    // hidden=true side-effect rather than races with a stale callback.\n    clearPendingHide();\n    setState(\"closed\");\n    if (wasOpen) {\n      const onEnd = (ev) => {\n        if (ev.propertyName !== \"transform\") return;\n        cardEl.removeEventListener(\"transitionend\", onEnd);\n        if (pendingHideOnEnd === onEnd) pendingHideOnEnd = null;\n        if (cardEl.dataset.state === \"closed\") {\n          cardEl.hidden = true;\n          // Reset any inline maxHeight pin left over from a drag-dismiss\n          // so the next show() starts from clean per-state sizing.\n          cardEl.style.maxHeight = \"\";\n        }\n      };\n      pendingHideOnEnd = onEnd;\n      cardEl.addEventListener(\"transitionend\", onEnd);\n    } else {\n      cardEl.hidden = true;\n      cardEl.style.maxHeight = \"\";\n    }\n  }\n\n  function isShowing() {\n    return !!cardEl && !cardEl.hidden && cardEl.dataset.state !== \"closed\";\n  }\n\n  // Escape dismiss, called by the arbitrated document Escape handler\n  // (ui/keyboard.js). Logs the \"escape\" sheet-transition telemetry (matching\n  // the prior inline document listener) and then hides. The arbiter owns the\n  // \"defer to an open modal\" precedence now, so unlike the old listener this\n  // does no modal check of its own \u2014 it only runs once the arbiter has decided\n  // the sheet is the innermost open overlay.\n  function hideForEscape() {\n    if (!isShowing()) return;\n    reportSheetEvent(\"escape\", (cardEl && cardEl.dataset.state) || \"peek\", \"closed\");\n    hide();\n  }\n\n  // ----- Drag handling (iOS-style) -----\n  // While dragging, the sheet's bottom stays anchored at the bottom inset\n  // and its max-height tracks the pointer 1:1 \u2014 top edge follows the\n  // finger. On release the detent is chosen by sheet-snap.js: project the\n  // release point forward along the fling velocity, then snap to the\n  // nearest detent (peek/expanded/closed).\n  let dragStartY = 0;\n  let dragStartHeight = 0;\n  let dragCurrentHeight = 0;\n  let dragDetents = null;\n  let pendingMaxHeight = null;\n  let maxHeightRaf = 0;\n  // Recent {t, y} pointer samples; release velocity is measured over the\n  // trailing window of these (see velocityFromSamples) so a held-still\n  // finger reports no fling.\n  let dragSamples = [];\n  let dragging = false;\n  // True once the pointer has moved enough to count as a drag (vs. a tap).\n  // Used by the peek/handle click handlers to ignore the synthetic click\n  // browsers emit after a short pointerdown\u2192pointerup with no real travel.\n  let dragMoved = false;\n  // Which surface started the active drag, for telemetry (\"header\" = handle\n  // or peek; \"body\" = scroll-coupled drag off the expanded treemap).\n  let lastGestureOrigin = \"header\";\n  // Scroll-coupled body drag (flag-gated): when the expanded treemap is at\n  // the top and the user pulls down on the body we take the gesture over and\n  // drag the whole sheet; otherwise the body scrolls natively.\n  let pendingBodyDrag = false;\n  let bodyStartY = 0;\n\n  function writeMaxHeight(px) {\n    if (!cardEl) return;\n    cardEl.style.maxHeight = `${px}px`;\n  }\n\n  function scheduleMaxHeight(px) {\n    pendingMaxHeight = px;\n    if (typeof requestAnimationFrame !== \"function\") {\n      const next = pendingMaxHeight;\n      pendingMaxHeight = null;\n      if (next != null) writeMaxHeight(next);\n      return;\n    }\n    if (maxHeightRaf) return;\n    maxHeightRaf = requestAnimationFrame(() => {\n      maxHeightRaf = 0;\n      const next = pendingMaxHeight;\n      pendingMaxHeight = null;\n      if (next != null) writeMaxHeight(next);\n    });\n  }\n\n  function flushMaxHeight() {\n    if (maxHeightRaf && typeof cancelAnimationFrame === \"function\") {\n      cancelAnimationFrame(maxHeightRaf);\n    }\n    maxHeightRaf = 0;\n    const next = pendingMaxHeight;\n    pendingMaxHeight = null;\n    if (next != null) writeMaxHeight(next);\n  }\n\n  function clearMaxHeightSchedule() {\n    if (maxHeightRaf && typeof cancelAnimationFrame === \"function\") {\n      cancelAnimationFrame(maxHeightRaf);\n    }\n    maxHeightRaf = 0;\n    pendingMaxHeight = null;\n  }\n\n  // Fire-and-forget sheet interaction telemetry, modeled on data/fetch.js's\n  // reportFallback: sendBeacon with a keepalive-fetch fallback. Lets us\n  // confirm in the wild that the sheet is actually being dismissed/collapsed\n  // and via which surface (the \"hard to close\" complaint this work targets).\n  function reportSheetEvent(method, fromState, toState) {\n    if (!eventLogUrl) return;\n    const payload = JSON.stringify({\n      event: \"map_sheet_transition\",\n      method,\n      fromState,\n      toState,\n      bodyDrag,\n    });\n    try {\n      if (navigator.sendBeacon) {\n        const blob = new Blob([payload], { type: \"application/json\" });\n        if (navigator.sendBeacon(eventLogUrl, blob)) return;\n      }\n    } catch (_e) {\n      // fall through to fetch keepalive\n    }\n    fetch(eventLogUrl, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: payload,\n      keepalive: true,\n    }).catch(() => {});\n  }\n\n  function getMaxSheetHeight() {\n    // Mirror the CSS max-height: 85dvh cap. Prefer visualViewport.height so\n    // the cap tracks the *visible* area as the iOS Safari URL bar / keyboard\n    // show and hide \u2014 window.innerHeight lags or over-reports in those cases,\n    // which would desync the drag clamp and detent math from what's on screen.\n    const vh = (window.visualViewport && window.visualViewport.height) || window.innerHeight;\n    return Math.max(0, vh * 0.85);\n  }\n\n  function getDetentHeights() {\n    // Measure each section's currently rendered height. data-dragging is\n    // true here so all sections are revealed via CSS \u2014 their offsetHeight\n    // reflects their natural content size.\n    const handleH = handleEl ? handleEl.offsetHeight : 22;\n    const peekH = peekEl ? peekEl.offsetHeight : 0;\n    const expandedH = expandedEl ? expandedEl.offsetHeight : 0;\n    const max = getMaxSheetHeight();\n    return {\n      peek: handleH + peekH,\n      expanded: Math.min(max, handleH + peekH + expandedH),\n    };\n  }\n\n  // Shared \"start a committed drag\" used by the handle/peek handlers and by\n  // the scroll-coupled body-drag takeover. `clientY` seeds dragStartY so the\n  // 1:1 max-height tracking is continuous from wherever the gesture began.\n  function beginDrag({ clientY, timeStamp, pointerId, captureEl, origin }) {\n    if (!cardEl) return;\n    lastGestureOrigin = origin || \"header\";\n    // Pin the sheet to its current rendered height before flipping\n    // data-dragging on (which removes per-state max-height caps and would\n    // otherwise let the sheet jump to its full content height).\n    const startH = cardEl.offsetHeight;\n    writeMaxHeight(startH);\n    dragStartHeight = startH;\n    dragCurrentHeight = startH;\n    dragging = true;\n    dragMoved = false;\n    dragStartY = clientY;\n    dragSamples = [{ t: timeStamp || performance.now(), y: clientY }];\n    cardEl.dataset.dragging = \"true\";\n    dragDetents = getDetentHeights();\n    // Capture on the listener element (handle/peek/expanded), not e.target:\n    // e.target can be a nested child (e.g. the grabber <span> or a treemap\n    // tile) that may not support pointer capture, which would drop move/up\n    // events once the pointer leaves it and leave `dragging` stuck true.\n    try { captureEl && captureEl.setPointerCapture && captureEl.setPointerCapture(pointerId); } catch (_) { /* noop */ }\n  }\n\n  function onPointerDown(e) {\n    return measureSync(\"map:mobile-sheet:pointer\", () => {\n      if (!cardEl) return;\n      if (e.button !== undefined && e.button !== 0) return;\n      beginDrag({\n        clientY: e.clientY,\n        timeStamp: e.timeStamp,\n        pointerId: e.pointerId,\n        captureEl: e.currentTarget,\n        origin: \"header\",\n      });\n    });\n  }\n\n  function onPointerMove(e) {\n    return measureSync(\"map:mobile-sheet:pointer\", () => {\n      if (!dragging) return;\n      const dy = e.clientY - dragStartY;\n      if (Math.abs(dy) > 4) dragMoved = true;\n      // Drag up (dy < 0) \u2192 grow sheet. Drag down (dy > 0) \u2192 shrink.\n      const next = Math.max(0, Math.min(getMaxSheetHeight(), dragStartHeight - dy));\n      dragCurrentHeight = next;\n      scheduleMaxHeight(next);\n      dragSamples.push({ t: e.timeStamp || performance.now(), y: e.clientY });\n      // Cap the buffer; only the last ~100ms is read at release, and even a\n      // 120Hz display produces ~12 samples in that window.\n      if (dragSamples.length > 16) dragSamples.shift();\n      e.preventDefault();\n    });\n  }\n\n  function onPointerUp(e) {\n    return measureSync(\"map:mobile-sheet:pointer\", () => {\n      if (!dragging) return;\n      dragging = false;\n      // Pure taps (no movement past the dead-zone) shouldn't run snap logic\n      // \u2014 let the synthetic click event reach the peek/handle click handler\n      // so a tap cycles through states (peek \u2194 expanded).\n      if (!dragMoved) {\n        clearMaxHeightSchedule();\n        delete cardEl.dataset.dragging;\n        cardEl.style.maxHeight = \"\";\n        dragDetents = null;\n        return;\n      }\n      const fromState = cardEl.dataset.state || \"peek\";\n      const currentH = dragCurrentHeight || parseFloat(cardEl.style.maxHeight) || cardEl.offsetHeight;\n      const detents = dragDetents || getDetentHeights();\n      const releaseT = (e && e.timeStamp) || performance.now();\n      // Reduced-motion users get no inertial fling \u2014 snap by position only.\n      const velocity = (reduceMotionMQL && reduceMotionMQL.matches)\n        ? 0\n        : velocityFromSamples(dragSamples, releaseT);\n      const target = decideSheetTarget({\n        currentHeight: currentH,\n        startHeight: dragStartHeight,\n        velocity,\n        detents,\n      });\n\n      if (target !== fromState) reportSheetEvent(lastGestureOrigin, fromState, target);\n      delete cardEl.dataset.dragging;\n      dragDetents = null;\n      if (target === \"closed\") {\n        // Drag-to-bottom dismisses the sheet outright. KEEP the inline\n        // maxHeight pin at the user's dragged value so the close animation\n        // slides the sheet off-screen *from where they let go*. Clearing\n        // the pin here would trigger a CSS max-height transition back up\n        // toward 85vh (the default), making the sheet visibly grow before\n        // it slides \u2014 that's the \"reopen then close\" glitch we hit before.\n        // The pin is cleared by hide()'s transitionend cleanup once the\n        // sheet is fully off-screen and `hidden=true`.\n        flushMaxHeight();\n        hide();\n      } else {\n        // Hand sizing back to per-state CSS rules for the visible detents.\n        clearMaxHeightSchedule();\n        cardEl.style.maxHeight = \"\";\n        setState(target);\n      }\n    });\n  }\n\n  function cycleStateForward() {\n    const s = cardEl.dataset.state;\n    if (s === \"peek\") setState(\"expanded\");\n    else setState(\"peek\");\n  }\n\n  // ----- Scroll-coupled body drag (flag-gated) -----\n  // Lets a downward pull on the expanded treemap drag the whole sheet \u2014 but\n  // only when the content is scrolled to the top, so normal content scrolling\n  // is untouched. This is the iOS/vaul pattern and targets the actual \"hard to\n  // close\" complaint (the handle alone is a small target).\n  const BODY_DRAG_TAKEOVER_PX = 6;\n\n  function onBodyPointerDown(e) {\n    if (!cardEl || dragging) return;\n    if (e.button !== undefined && e.button !== 0) return;\n    // Only the expanded state scrolls; in peek the body isn't the scroller.\n    if (cardEl.dataset.state !== \"expanded\") return;\n    pendingBodyDrag = true;\n    bodyStartY = e.clientY;\n  }\n\n  function onBodyPointerMove(e) {\n    return measureSync(\"map:mobile-sheet:pointer\", () => {\n      if (dragging) {\n        // Already took over \u2014 drive the shared drag logic.\n        onPointerMove(e);\n        return;\n      }\n      if (!pendingBodyDrag) return;\n      const dy = e.clientY - bodyStartY;\n      // Take over only at the top of the scroll AND on a clear downward pull;\n      // otherwise leave the gesture to native scrolling.\n      if (expandedEl.scrollTop <= 0 && dy > BODY_DRAG_TAKEOVER_PX) {\n        pendingBodyDrag = false;\n        beginDrag({\n          clientY: bodyStartY,\n          timeStamp: e.timeStamp,\n          pointerId: e.pointerId,\n          captureEl: expandedEl,\n          origin: \"body\",\n        });\n        onPointerMove(e);\n      }\n    });\n  }\n\n  function onBodyPointerUp(e) {\n    return measureSync(\"map:mobile-sheet:pointer\", () => {\n      pendingBodyDrag = false;\n      if (dragging) onPointerUp(e);\n    });\n  }\n\n  if (bodyDrag && expandedEl) {\n    expandedEl.addEventListener(\"pointerdown\", onBodyPointerDown);\n    // Non-passive so preventDefault in onPointerMove can run; the real\n    // scroll/drag arbitration is done by scrollTop + the data-dragging\n    // touch-action:none rule rather than by cancelling here.\n    expandedEl.addEventListener(\"pointermove\", onBodyPointerMove, { passive: false });\n    expandedEl.addEventListener(\"pointerup\", onBodyPointerUp);\n    expandedEl.addEventListener(\"pointercancel\", onBodyPointerUp);\n  }\n\n  if (handleEl) {\n    handleEl.addEventListener(\"pointerdown\", onPointerDown);\n    handleEl.addEventListener(\"pointermove\", onPointerMove);\n    handleEl.addEventListener(\"pointerup\", onPointerUp);\n    handleEl.addEventListener(\"pointercancel\", onPointerUp);\n    // Tap the handle to toggle between peek (collapsed pill with both\n    // stat rows) and expanded (treemap detail). Suppressed if the user\n    // actually dragged the handle (dragMoved).\n    handleEl.addEventListener(\"click\", (e) => {\n      if (dragMoved) return;\n      e.preventDefault();\n      cycleStateForward();\n    });\n  }\n\n  if (peekEl) {\n    peekEl.addEventListener(\"pointerdown\", onPointerDown);\n    peekEl.addEventListener(\"pointermove\", onPointerMove);\n    peekEl.addEventListener(\"pointerup\", onPointerUp);\n    peekEl.addEventListener(\"pointercancel\", onPointerUp);\n    // Tapping anywhere on the peek body cycles forward \u2014 same as the\n    // handle. Suppressed if the user actually dragged (dragMoved).\n    peekEl.addEventListener(\"click\", (e) => {\n      if (dragMoved) return;\n      e.preventDefault();\n      cycleStateForward();\n    });\n  }\n\n  // Keyboard/switch users have no drag affordance; Escape mirrors the\n  // drag-down dismiss so the sheet is operable without a pointer. The Escape\n  // keypress is now dispatched by the arbitrated document handler\n  // (ui/keyboard.js) into hideForEscape() \u2014 see that method above \u2014 so the\n  // sheet no longer registers its own document-level Escape listener and a\n  // single keypress can't dismiss both the sheet and an open modal.\n\n  // Recompute layout when the visible viewport changes (iOS Safari URL bar /\n  // keyboard show/hide). Re-applying the current state refreshes the\n  // closed-state translate and lets per-state CSS re-measure against the new\n  // height. Skipped mid-drag (the pointer owns sizing) and rAF-throttled.\n  if (cardEl && window.visualViewport) {\n    let vvRaf = 0;\n    window.visualViewport.addEventListener(\"resize\", () => {\n      if (vvRaf) return;\n      vvRaf = requestAnimationFrame(() => {\n        vvRaf = 0;\n        if (dragging || !isShowing()) return;\n        setState(cardEl.dataset.state || \"peek\");\n      });\n    });\n  }\n\n  function refresh() {\n    if (!isShowing() || !lastMeta) return;\n    renderMeta(lastMeta);\n  }\n\n  return { show, hide, hideForEscape, isShowing, refresh };\n}\n", "// @ts-check\n\n// Lazy gate for the treemap subtree. Industry + occupation renderers load\n// together; the task view is a separate dynamic import so a task-module\n// failure cannot block the industry/job treemaps.\n\nimport { TASK_PAGE_UI_VERSION, TREEMAP_UI_VERSION } from \"../tasks/constants.js\";\n\nlet cached = /** @type {null | {\n  createExposureTreemap: Function,\n  createOccupationsTreemap: Function,\n  createTreemapNav: Function,\n}} */ (null);\n/** @type {number | null} */\nlet cachedTreemapVersion = null;\n/** @type {null | { createTaskTreemap: Function, uiVersion: number }} */\nlet taskCached = null;\nlet inflight = /** @type {null | Promise<any>} */ (null);\nlet taskInflight = /** @type {null | Promise<any>} */ (null);\nlet errorBannerTarget = /** @type {HTMLElement | null} */ (null);\nlet errorBannerOnRetry = /** @type {null | (() => any)} */ (null);\n\nexport function clearTreemapModuleCache() {\n  cached = null;\n  cachedTreemapVersion = null;\n  inflight = null;\n}\n\nexport async function loadTreemap() {\n  if (cached && cachedTreemapVersion === TREEMAP_UI_VERSION) return cached;\n  if (cached && cachedTreemapVersion !== TREEMAP_UI_VERSION) {\n    clearTreemapModuleCache();\n  }\n\n  if (inflight) return inflight;\n\n  inflight = (async () => {\n    const [exposureMod, occupationsMod, navMod] = await Promise.all([\n      import(\"./exposure.js\"),\n      import(\"./occupations.js\"),\n      import(\"./nav.js\"),\n    ]);\n    const mods = {\n      createExposureTreemap: exposureMod.createExposureTreemap,\n      createOccupationsTreemap: occupationsMod.createOccupationsTreemap,\n      createTreemapNav: navMod.createTreemapNav,\n    };\n    cached = mods;\n    cachedTreemapVersion = TREEMAP_UI_VERSION;\n    return mods;\n  })();\n\n  try {\n    return await inflight;\n  } catch (err) {\n    console.error(\"[treemap] chunk load failed\", err);\n    clearTreemapModuleCache();\n    showLoadError();\n    return null;\n  } finally {\n    inflight = null;\n  }\n}\n\nexport function clearTaskViewModuleCache() {\n  taskCached = null;\n  taskInflight = null;\n}\n\nexport async function loadTaskView() {\n  if (taskCached && taskCached.uiVersion === TASK_PAGE_UI_VERSION) {\n    return taskCached;\n  }\n  if (taskCached && taskCached.uiVersion !== TASK_PAGE_UI_VERSION) {\n    clearTaskViewModuleCache();\n  }\n\n  if (taskInflight) return taskInflight;\n\n  taskInflight = (async () => {\n    const taskMod = await import(\"./task.js\");\n    const mods = {\n      createTaskTreemap: taskMod.createTaskTreemap,\n      uiVersion: TASK_PAGE_UI_VERSION,\n    };\n    taskCached = mods;\n    return mods;\n  })();\n\n  try {\n    return await taskInflight;\n  } catch (err) {\n    console.error(\"[task-view] chunk load failed\", err);\n    clearTaskViewModuleCache();\n    return null;\n  } finally {\n    taskInflight = null;\n  }\n}\n\n/**\n * Registers the host element + the retry callback for the lazy-load error\n * banner. `onRetry` is invoked after a successful retry so the caller can\n * re-run whatever render path was interrupted. Without it the banner would\n * stay on screen after retry succeeds, because the caller that originally\n * awaited loadTreemap() has already returned.\n *\n * @param {{ target: HTMLElement | null, onRetry?: () => any }} opts\n */\nexport function setTreemapErrorBanner({ target, onRetry = null }) {\n  errorBannerTarget = target;\n  errorBannerOnRetry = onRetry;\n}\n\nfunction clearErrorBanner() {\n  if (errorBannerTarget) errorBannerTarget.innerHTML = \"\";\n}\n\nfunction showLoadError() {\n  const host = errorBannerTarget;\n  if (!host) return;\n  host.innerHTML = \"\";\n  const banner = document.createElement(\"div\");\n  banner.className = \"map-treemap-load-error\";\n  banner.setAttribute(\"role\", \"alert\");\n  const msg = document.createElement(\"p\");\n  msg.textContent = \"Unable to load treemap module. Check your network and try again.\";\n  const btn = document.createElement(\"button\");\n  btn.type = \"button\";\n  btn.className = \"map-treemap-load-error__retry\";\n  btn.textContent = \"Retry\";\n  btn.addEventListener(\"click\", async () => {\n    btn.disabled = true;\n    const mods = await loadTreemap();\n    if (mods) {\n      clearErrorBanner();\n      if (errorBannerOnRetry) {\n        try { await errorBannerOnRetry(); } catch (e) { console.error(\"[treemap] retry callback failed\", e); }\n      }\n    } else {\n      btn.disabled = false;\n    }\n  });\n  banner.appendChild(msg);\n  banner.appendChild(btn);\n  host.appendChild(banner);\n  host.hidden = false;\n}\n", "// @ts-check\n\n// Treemap hover tooltip: pure DOM controller keyed off a single tooltip\n// element. Shared by task/exposure/occupations treemap renderers.\n\n/**\n * @param {{ tooltipEl: HTMLElement | null }} deps\n */\nexport function createTreemapTooltip({ tooltipEl }) {\n  function hide() {\n    if (!tooltipEl) return;\n    tooltipEl.classList.add(\"map-treemap-tooltip--hidden\");\n    tooltipEl.setAttribute(\"aria-hidden\", \"true\");\n    tooltipEl.replaceChildren();\n  }\n\n  function position(clientX, clientY) {\n    if (!tooltipEl || tooltipEl.classList.contains(\"map-treemap-tooltip--hidden\")) {\n      return;\n    }\n    const pad = 10;\n    const offset = 14;\n    const tw = tooltipEl.offsetWidth;\n    const th = tooltipEl.offsetHeight;\n    let x = clientX + offset;\n    let y = clientY + offset;\n    if (x + tw > window.innerWidth - pad) x = clientX - tw - offset;\n    if (y + th > window.innerHeight - pad) y = clientY - th - offset;\n    x = Math.max(pad, Math.min(x, Math.max(pad, window.innerWidth - tw - pad)));\n    y = Math.max(pad, Math.min(y, Math.max(pad, window.innerHeight - th - pad)));\n    tooltipEl.style.left = `${x}px`;\n    tooltipEl.style.top = `${y}px`;\n  }\n\n  function show(event, lineStrings) {\n    if (!tooltipEl || !Array.isArray(lineStrings)) return;\n    const lines = lineStrings.map((s) => String(s || \"\").trim()).filter(Boolean);\n    if (!lines.length) {\n      hide();\n      return;\n    }\n    tooltipEl.replaceChildren();\n    const titleNode = document.createElement(\"div\");\n    titleNode.className = \"map-treemap-tooltip__title\";\n    titleNode.textContent = lines[0];\n    tooltipEl.appendChild(titleNode);\n    for (let i = 1; i < lines.length; i++) {\n      const row = document.createElement(\"div\");\n      row.className = \"map-treemap-tooltip__row\";\n      row.textContent = lines[i];\n      tooltipEl.appendChild(row);\n    }\n    tooltipEl.classList.remove(\"map-treemap-tooltip--hidden\");\n    tooltipEl.setAttribute(\"aria-hidden\", \"false\");\n    window.requestAnimationFrame(() => {\n      position(event.clientX, event.clientY);\n    });\n  }\n\n  return { show, hide, position };\n}\n", "// @ts-check\n\n// National job-families baseline lookup. Loaded once per session (or after\n// the 30s failure cooldown elapses \u2014 see C3 in the post-refactor plan), and\n// used by color-scales.js to build a stable national fill scale so industry\n// colors are comparable across geographies.\n//\n// Failure policy: on fetch error, record the timestamp and no-op subsequent\n// calls until NATIONAL_RETRY_COOLDOWN_MS has elapsed. Callers degrade to the\n// local (per-geography) scale via color-scales.getLocalExposureColorScale.\n\nimport { loadJobFamilies } from \"../../data/job-families.js\";\nimport {\n  getExposureValue,\n  getJobFamilyLookupKey,\n} from \"../../treemap/shared.js\";\n\nconst NATIONAL_RETRY_COOLDOWN_MS = 30_000;\n\n/**\n * @param {{ cfg: import(\"../../types.js\").Cfg }} opts\n */\nexport function createNationalExposureLoader({ cfg }) {\n  /** @type {Map<string, any>} */\n  const byLabel = new Map();\n  /** @type {Promise<void> | null} */\n  let loadPromise = null;\n  let lastFailureAt = 0;\n\n  async function ensureLoaded() {\n    if (!cfg.topOccupationsApiUrl || byLabel.size > 0) return;\n    if (loadPromise) {\n      await loadPromise;\n      return;\n    }\n    if (Date.now() - lastFailureAt < NATIONAL_RETRY_COOLDOWN_MS) return;\n    loadPromise = (async () => {\n      try {\n        // The nation payload is the shared singleton's pinned entry; fetching\n        // it here dedupes with the panel/nav loaders so a first paint pulls it\n        // exactly once instead of 2-4\u00D7. No metric param: both exposure fields\n        // ship on every family and getValue picks the active one.\n        const families = await loadJobFamilies({ cfg, scope: \"nation\", code: \"us\" });\n        for (const family of families) {\n          const labelKey = getJobFamilyLookupKey(family);\n          if (labelKey) byLabel.set(labelKey, family);\n        }\n      } catch (error) {\n        lastFailureAt = Date.now();\n        console.warn(\"Unable to load national industry exposure lookup.\", error);\n      }\n    })();\n    try {\n      await loadPromise;\n    } finally {\n      loadPromise = null;\n    }\n  }\n\n  function getValue(item) {\n    if (!item) return null;\n    const key = getJobFamilyLookupKey(item);\n    if (key && byLabel.has(key)) return getExposureValue(byLabel.get(key));\n    return getExposureValue(item);\n  }\n\n  function hasData() {\n    return byLabel.size > 0;\n  }\n\n  function values() {\n    return [...byLabel.values()];\n  }\n\n  function reset() {\n    byLabel.clear();\n    loadPromise = null;\n    lastFailureAt = 0;\n  }\n\n  return { ensureLoaded, getValue, hasData, values, reset };\n}\n", "// @ts-check\n\n// Exposure color scales for the industries treemap.\n// - National scale: uses national baseline so tile colors are comparable\n//   across geographies.\n// - Local scale: per-payload fallback when the national lookup is empty\n//   (first-call pre-load or post-cooldown failure).\n// - Occupation scale: a fixed 0..1 interpolation used by the occupations/\n//   tasks treemap for per-occupation exposure.\n//\n// All three bind late to `mapColors` via a getter so they pick up theme\n// changes without rebuilding. Scale construction is delegated to\n// `buildExposureScale` in map/colors.js.\n\nimport { MAP_AI_SEQUENTIAL_INTERPOLATOR, buildExposureScale } from \"../../map/colors.js\";\nimport { getExposureValue } from \"../../treemap/shared.js\";\nimport { clamp01 } from \"../../util/format.js\";\n\n/**\n * @param {{\n *   nationalExposure: ReturnType<typeof import(\"./national-exposure.js\").createNationalExposureLoader>,\n *   getMapColors: () => { noData: string },\n * }} deps\n */\nexport function createExposureColorScales({ nationalExposure, getMapColors }) {\n  function buildNationalExposureFillScale() {\n    if (!nationalExposure.hasData()) return null;\n    const values = nationalExposure.values().map((family) => getExposureValue(family));\n    if (!values.some((value) => Number.isFinite(value))) return null;\n    const scale = buildExposureScale(values, { fallback: getMapColors().noData });\n    return (item) => scale(nationalExposure.getValue(item));\n  }\n\n  function getLocalExposureColorScale(items) {\n    const values = (Array.isArray(items) ? items : []).map((item) => getExposureValue(item));\n    const scale = buildExposureScale(values, { fallback: getMapColors().noData });\n    return (item) => scale(getExposureValue(item));\n  }\n\n  function getOccupationExposureColor(value) {\n    if (!Number.isFinite(value)) return getMapColors().noData;\n    const clamped = clamp01(/** @type {number} */ (value));\n    return MAP_AI_SEQUENTIAL_INTERPOLATOR(1 - clamped);\n  }\n\n  return {\n    buildNationalExposureFillScale,\n    getLocalExposureColorScale,\n    getOccupationExposureColor,\n  };\n}\n", "// @ts-check\n\n// Drilldown state machine for the top-occupations panel. Tracks:\n// - Which view level the panel is showing: \"families\" \u2192 \"occupations\" \u2192 \"tasks\".\n// - Which occupation is selected (when in the tasks view).\n// - Per-level request serials used to discard stale responses after a rapid\n//   re-selection (user clicks two industries in quick succession).\n//\n// State is intentionally encapsulated \u2014 all reads/writes go through the\n// returned methods so the orchestrator can't accidentally desync mode from\n// selected-occupation.\n\n/**\n * @typedef {\"families\" | \"occupations\" | \"tasks\"} DrilldownMode\n */\n\nexport function createDrilldownState() {\n  /** @type {DrilldownMode} */\n  let mode = \"families\";\n  /** @type {string | null} */\n  let selectedOccupationKey = null;\n  /** @type {any} */\n  let selectedOccupationData = null;\n  let topSerial = 0;\n  let taskSerial = 0;\n\n  return {\n    getMode: () => mode,\n    /** @param {DrilldownMode} next */\n    setMode: (next) => { mode = next; },\n    getSelectedOccupationKey: () => selectedOccupationKey,\n    getSelectedOccupationData: () => selectedOccupationData,\n    /** @param {any} data @param {string | null} key */\n    setSelectedOccupation: (data, key) => {\n      selectedOccupationData = data;\n      selectedOccupationKey = key;\n    },\n    clearSelectedOccupation: () => {\n      selectedOccupationData = null;\n      selectedOccupationKey = null;\n    },\n    /** Resets to the initial families view. Does not clear fetch caches. */\n    resetToFamilies: () => {\n      mode = \"families\";\n      selectedOccupationData = null;\n      selectedOccupationKey = null;\n    },\n    nextTopSerial: () => ++topSerial,\n    /** @param {number} serial */\n    isCurrentTopSerial: (serial) => serial === topSerial,\n    nextTaskSerial: () => ++taskSerial,\n    /** @param {number} serial */\n    isCurrentTaskSerial: (serial) => serial === taskSerial,\n  };\n}\n", "// @ts-check\n\n// Lazy boot for the four treemap-side controllers (exposure, task, occupations,\n// nav). The treemap/* modules weigh ~1.6k lines and are only needed after the\n// user clicks into a geography, so they are code-split via a dynamic import in\n// treemap/index.js and instantiated once on first use here.\n//\n// All per-controller deps (els, click handlers, section-title setters, etc.)\n// flow in via the `deps` bag so this module owns only the \"boot once, return\n// the cached controllers\" concern.\n\nimport { loadTreemap, loadTaskView } from \"../../treemap/index.js\";\nimport { TASK_PAGE_UI_VERSION } from \"../../tasks/constants.js\";\n\n/**\n * @param {{\n *   cfg: import(\"../../types.js\").Cfg,\n *   els: {\n *     topOccupationsTreemapEl: HTMLElement | null,\n *     topOccupationsTasksEl: HTMLElement | null,\n *     topOccupationsStatusEl: HTMLElement | null,\n *     topOccupationsDetailEl: HTMLElement | null,\n *     topOccupationsDetailMetaEl: HTMLElement | null,\n *   },\n *   treemapNavEls: {\n *     rootEl: HTMLElement | null,\n *     regionLabelEl: HTMLElement | null,\n *     industryBtnEl: HTMLElement | null,\n *     industryLabelEl: HTMLElement | null,\n *     jobsBtnEl: HTMLElement | null,\n *     jobsLabelEl: HTMLElement | null,\n *     industryPopoverEl: HTMLElement | null,\n *     industrySearchEl: HTMLInputElement | null,\n *     industryClearEl: HTMLElement | null,\n *     industryListEl: HTMLElement | null,\n *     jobsPopoverEl: HTMLElement | null,\n *     jobsSearchEl: HTMLInputElement | null,\n *     jobsClearEl: HTMLElement | null,\n *     jobsListEl: HTMLElement | null,\n *     jobsChevronEl: HTMLElement | null,\n *     jobsClearJobEl: HTMLElement | null,\n *     industryChevronEl: HTMLElement | null,\n *     industryClearIndustryEl: HTMLElement | null,\n *   },\n *   tooltip: { hide: () => void },\n *   drilldown: ReturnType<typeof import(\"./drilldown.js\").createDrilldownState>,\n *   getOccupationExposureColor: (value: number) => string,\n *   getNationalExposureValue: (item: any) => number | null,\n *   getSelectionPayload: () => { scope: string, code: string } | null,\n *   loadJobFamilies: () => Promise<any[]>,\n *   updateBackToTop5Visibility: () => void,\n *   syncNavChrome: () => void,\n *   setViewMode: (mode: string, opts?: any) => void,\n *   refreshTopOccupationsPanel: () => void,\n *   refreshTaskTreemapPanel: () => void,\n *   resetTopOccupationsTaskState: () => void,\n *   handleBackToTop5: () => void,\n *   onOccupationClick: (item: any) => void,\n *   onOccupationIntent?: (item: any) => void,\n * }} deps\n */\nexport function createTreemapBoot(deps) {\n  const {\n    cfg,\n    els,\n    treemapNavEls,\n    tooltip,\n    drilldown,\n    getOccupationExposureColor,\n    getNationalExposureValue,\n    getSelectionPayload,\n    loadJobFamilies,\n    updateBackToTop5Visibility,\n    syncNavChrome,\n    setViewMode,\n    refreshTopOccupationsPanel,\n    refreshTaskTreemapPanel,\n    resetTopOccupationsTaskState,\n    handleBackToTop5,\n    onOccupationClick,\n    onOccupationIntent = null,\n    // Overview table-view (desktop): treemap vs table mode + a callback that\n    // mounts the Plot/Table toggle into a freshly-rendered pills row.\n    getOverviewViewMode = () => \"treemap\",\n    mountOverviewToggle = () => {},\n  } = deps;\n\n  /** @type {any} */\n  let exposureCtrl = null;\n  /** @type {any} */\n  let taskCtrl = null;\n  /** @type {number | null} */\n  let taskCtrlUiVersion = null;\n  /** @type {any} */\n  let occupationsCtrl = null;\n  /** @type {any} */\n  let navCtrl = null;\n  // Teardown returned by navCtrl.setup(); retained so a future re-instantiation\n  // can detach nav's global listeners (pointerdown/keydown/resize). Unused on\n  // the happy path \u2014 nav is booted once for the app lifetime.\n  /** @type {(() => void) | null} */\n  let navTeardown = null;\n\n  async function ensureReady() {\n    const mods = await loadTreemap();\n    if (!mods) return null;\n\n    if (!exposureCtrl) {\n      exposureCtrl = mods.createExposureTreemap({\n        treemapEl: els.topOccupationsTreemapEl,\n        statusEl: els.topOccupationsStatusEl,\n        tooltip,\n        getOccupationExposureColor,\n        getViewMode: getOverviewViewMode,\n      });\n    }\n\n    if (!occupationsCtrl) {\n      occupationsCtrl = mods.createOccupationsTreemap({\n        treemapEl: els.topOccupationsTreemapEl,\n        statusEl: els.topOccupationsStatusEl,\n        detailEl: els.topOccupationsDetailEl,\n        detailMetaEl: els.topOccupationsDetailMetaEl,\n        exposureTreemap: exposureCtrl,\n        updateBackToTop5Visibility,\n        syncNavChrome,\n        getNationalExposureValue,\n        onOccupationClick,\n        onOccupationIntent,\n        getSelectedTreemapOccupationKey: () => drilldown.getSelectedOccupationKey(),\n        mountOverviewToggle,\n      });\n    }\n\n    if (!navCtrl) {\n      navCtrl = mods.createTreemapNav({\n        treemapNavEls,\n        getSelectionPayload,\n        loadJobFamilies,\n        getDetailMode: () => drilldown.getMode(),\n        setDetailMode: (m) => drilldown.setMode(m),\n        setSelectedOccupation: (data, key) => drilldown.setSelectedOccupation(data, key),\n        getSelectedOccupationData: () => drilldown.getSelectedOccupationData(),\n        updateBackToTop5Visibility,\n        hideTreemapTooltip: () => tooltip.hide(),\n        setViewMode,\n        refreshTopOccupationsPanel,\n        refreshTaskTreemapPanel,\n        renderOccupations: (occs, family) => {\n          if (occupationsCtrl) occupationsCtrl.render(occs, family);\n        },\n        resetTopOccupationsTaskState,\n        handleBackToTop5,\n      });\n      navTeardown = navCtrl.setup();\n    }\n\n    return mods;\n  }\n\n  // Task view is a separate dynamic import (treemap/index.js \u2192 task.js) so a\n  // broken task module cannot block industry/occupation treemaps. Version-bump\n  // TASK_PAGE_UI_VERSION to force controller recreation after deploy.\n  async function ensureTaskReady() {\n    const treemapMods = await ensureReady();\n    if (!treemapMods) return null;\n\n    if (taskCtrl && taskCtrlUiVersion !== TASK_PAGE_UI_VERSION) {\n      if (taskCtrl.destroyView) taskCtrl.destroyView();\n      taskCtrl = null;\n      taskCtrlUiVersion = null;\n    }\n\n    if (taskCtrl) return taskCtrl;\n\n    const taskMods = await loadTaskView();\n    if (!taskMods) return null;\n\n    taskCtrl = taskMods.createTaskTreemap({\n      cfg,\n      treemapEl: els.topOccupationsTreemapEl,\n      tasksEl: els.topOccupationsTasksEl,\n      statusEl: els.topOccupationsStatusEl,\n      detailEl: els.topOccupationsDetailEl,\n      detailMetaEl: els.topOccupationsDetailMetaEl,\n      tooltip,\n      getOccupationExposureColor,\n      updateBackToTop5Visibility,\n      syncNavChrome,\n    });\n    taskCtrlUiVersion = TASK_PAGE_UI_VERSION;\n    return taskCtrl;\n  }\n\n  // Detach nav's global listeners and drop the cached controller so a\n  // subsequent ensureReady() re-boots it cleanly. Currently unused \u2014 exposed so\n  // future re-instantiation/cleanup paths have a single entry point.\n  function teardownNav() {\n    if (navTeardown) navTeardown();\n    navTeardown = null;\n    navCtrl = null;\n  }\n\n  return {\n    ensureReady,\n    ensureTaskReady,\n    getExposureCtrl: () => exposureCtrl,\n    getTaskCtrl: () => taskCtrl,\n    getOccupationsCtrl: () => occupationsCtrl,\n    getNavCtrl: () => navCtrl,\n    teardownNav,\n  };\n}\n", "// @ts-check\n\n// Single source of truth for the set of map selections that have a drilldown\n// (industries/occupations/tasks) panel, and the {scope, code} payload the\n// drilldown/top-job-families APIs expect.\n//\n// Both the desktop controller (index.js) and the mobile controller (mobile.js)\n// build this payload; keeping the scope list in one place is what prevents the\n// two from drifting (a missing Canada scope on the mobile copy was exactly that\n// bug). The scope strings double as the backend drilldown scope (see\n// us_ai_map/views.py `_SCOPE_PAD_WIDTH`) and must stay in sync with the\n// `FeatureSelection[\"kind\"]` union in ../../state/store.js.\n\n/** @type {ReadonlySet<string>} */\nexport const DRILLDOWN_SCOPES = new Set([\n  \"state\",\n  \"msa\",\n  \"nonmetro\",\n  \"province\",\n  \"cma\",\n  \"ca_nonmetro\",\n  \"nation\",\n]);\n\n/**\n * Pure: map a feature selection to the API payload, or null when the selection\n * is absent/incomplete or its kind has no drilldown scope.\n *\n * @param {import(\"../../state/store.js\").FeatureSelection | null | undefined} selection\n * @returns {{ scope: string, code: string } | null}\n */\nexport function selectionToPayload(selection) {\n  if (!selection || !selection.kind || !selection.code) return null;\n  if (!DRILLDOWN_SCOPES.has(selection.kind)) return null;\n  return { scope: selection.kind, code: String(selection.code) };\n}\n", "// @ts-check\n\n// Shared core for the top-occupations drilldown panel. Both the desktop\n// orchestrator (index.js) and the mobile orchestrator (mobile.js) were ~85%\n// duplicated: the same fetch-tasks \u2192 serial-guard \u2192 LRU-evict \u2192 render task\n// pipeline, the same clear/cancel-paint helpers, the same overview render\n// pipeline (with policy-specific limits/wording/meta), and the same\n// refresh entry points. This module owns that shared logic; the two thin\n// controllers supply only POLICY (limit per view, wording, error-banner\n// registration, view-mode pinning) and keep their genuinely platform-specific\n// chrome (desktop's view-mode transitions / back-to-top-5 / overview toggle;\n// mobile's isMobileLayout gate / expanded-pin).\n//\n// F-12 (request cancellation): each new task fetch aborts the previously\n// in-flight one via an AbortController keyed to the request serial, and threads\n// the signal through fetchOccupationTasks \u2192 fetchJson(url, { signal }). This is\n// a network-savings OPTIMIZATION layered on top of \u2014 not a replacement for \u2014\n// the existing serial staleness guard (drilldown.nextTaskSerial /\n// isCurrentTaskSerial), which remains the correctness mechanism that discards\n// stale responses (a superseded fetch that already resolved, or one whose\n// AbortController the runtime ignored).\n\nimport { fetchJson as defaultFetchJson } from \"../../data/fetch.js\";\nimport { appendMapCacheVersion } from \"../../data/api-url.js\";\nimport { loadJobFamilies, peekJobFamilies, topFamilies } from \"../../data/job-families.js\";\nimport { formatWorkers, formatPenetrationPercentRounded } from \"../../util/format.js\";\nimport {\n  getEmploymentValue,\n  getOccupationKey,\n  getTopOccupationsMetricField,\n  occupationTasksCacheKey,\n  tasksSatisfyCurrentMetric,\n} from \"../../treemap/shared.js\";\nimport { selectedMetric } from \"../../state/store.js\";\n\n// LRU bound on the per-(scope,code,soc) occupation-tasks cache. Held until a\n// new task set is fetched; not cleared on selection change (revisiting a region\n// re-uses warm task results). 40 covers a deep drilldown session. Shared by\n// both controllers \u2014 mobile mirrored this constant before the extraction.\nexport const OCCUPATION_TASKS_MAX_CACHED = 40;\n\n/**\n * @typedef {{\n *   topOccupationsDetailEl: HTMLElement | null,\n *   topOccupationsDetailMetaEl: HTMLElement | null,\n *   topOccupationsStatusEl: HTMLElement | null,\n *   topOccupationsTreemapEl: HTMLElement | null,\n * }} CoreEls\n */\n\n/**\n * @param {{\n *   cfg: import(\"../../types.js\").Cfg,\n *   els: CoreEls,\n *   caches: ReturnType<typeof import(\"./caches.js\").createTopOccupationsCaches>,\n *   drilldown: ReturnType<typeof import(\"./drilldown.js\").createDrilldownState>,\n *   nationalExposure: ReturnType<typeof import(\"./national-exposure.js\").createNationalExposureLoader>,\n *   scales: ReturnType<typeof import(\"./color-scales.js\").createExposureColorScales>,\n *   treemapBoot: ReturnType<typeof import(\"./treemap-boot.js\").createTreemapBoot>,\n *   tooltip: { hide: () => void },\n *\n *   getSelectionPayload: (selection?: any) => { scope: string, code: string } | null,\n *   getSelectionKey: (selection?: any) => string,\n *   getCurrentSelection: () => any,\n *   // Reads the shared selectedTreemapFamilyData signal. Threaded via deps\n *   // (rather than imported here) so a test can drive the occupations-level\n *   // branch without standing up the real signal module.\n *   getSelectedTreemapFamilyData: () => any,\n *\n *   // \u2500\u2500 policy \u2500\u2500\n *   // Number of industry tiles to show at the (families) entry level for the\n *   // CURRENT view. Desktop varies it by view-mode (5 compact / 280 expanded);\n *   // mobile always returns 5.\n *   getOverviewLimit: () => number,\n *   // Status text shown beneath the overview treemap. Desktop returns a\n *   // view-mode-dependent \"Click\u2026\" string; mobile returns the \"Tap\u2026\" string.\n *   getOverviewStatusText: () => string,\n *   // Per-tile compact-label policy. Desktop: only force in 5-tile compact;\n *   // mobile: always force (small screens).\n *   forceCompactTileLabels: (displayItems: any[]) => boolean,\n *   // Render (or hide) the industry-overview meta pills row for the current\n *   // overview. Desktop mounts the Plot/Table toggle into the returned row;\n *   // mobile hides the meta entirely.\n *   renderOverviewMeta: (displayItems: any[], formatters: { formatWorkers: Function, formatPenetrationPercentRounded: Function }) => void,\n *   // Hook fired before the TASK view paints. Desktop detaches the shared\n *   // overview toggle so it can't flash as a stray node; mobile no-ops.\n *   beforeTaskRender: () => void,\n *   // Reset drilldown + detail chrome to the families level. Desktop also\n *   // detaches the overview toggle.\n *   resetTaskState: () => void,\n *   // Sync the breadcrumb/nav chrome to the current drilldown state.\n *   syncNavChrome: () => void,\n *   // Sync any view-mode chrome (desktop: back-to-top-5 + expand button\n *   // visibility); mobile: no-op.\n *   updateOverviewChrome: () => void,\n *   // Commit an industry click \u2192 occupations level (+ desktop view-mode flip).\n *   selectIndustry: (item: any) => void,\n *   // Clear the panel to its empty state. Desktop honors keepSelectionDisplay;\n *   // mobile ignores it.\n *   clearTopOccupationsPanel: (message?: string, opts?: { keepSelectionDisplay?: boolean }) => void,\n *   // Gate for refreshTopOccupationsPanel. Desktop: always true; mobile:\n *   // isMobileLayout() (the desktop side-panel orchestrator owns wide\n *   // viewports).\n *   shouldRefresh: () => boolean,\n *   // Fired at the top of a refresh, after the shouldRefresh gate. Mobile pins\n *   // the shared view-mode signal to \"expanded\"; desktop no-ops.\n *   beforeRefresh: () => void,\n *   // The empty-state message for the \"no families available\" / unavailable\n *   // cases passed to clearTopOccupationsPanel from refresh.\n *   unavailableMessage: string,\n *\n *   // Injection seam for tests; defaults to the real network fetchJson.\n *   fetchJson?: (url: string, init?: { signal?: AbortSignal }) => Promise<any>,\n * }} deps\n */\nexport function createTopOccupationsCore(deps) {\n  const {\n    cfg,\n    els,\n    caches,\n    drilldown,\n    nationalExposure,\n    scales,\n    treemapBoot,\n    getSelectionPayload,\n    getSelectionKey,\n    getCurrentSelection,\n    getOverviewLimit,\n    getOverviewStatusText,\n    forceCompactTileLabels,\n    renderOverviewMeta,\n    beforeTaskRender,\n    resetTaskState,\n    syncNavChrome,\n    updateOverviewChrome,\n    selectIndustry,\n    clearTopOccupationsPanel,\n    shouldRefresh,\n    beforeRefresh,\n    unavailableMessage,\n    fetchJson = defaultFetchJson,\n  } = deps;\n\n  const {\n    topOccupationsDetailEl,\n    topOccupationsDetailMetaEl,\n    topOccupationsStatusEl,\n    topOccupationsTreemapEl,\n  } = els;\n\n  // \u2500\u2500 F-12: in-flight task-fetch cancellation \u2500\u2500\n  // One controller is \"current\" at a time; a new refreshTaskTreemapPanel aborts\n  // the previous before issuing its own. Keyed by serial purely for clarity /\n  // so a late abort() of a superseded controller is provably the right one.\n  /** @type {{ serial: number, controller: AbortController } | null} */\n  let inFlightTaskFetch = null;\n\n  function abortInFlightTaskFetch() {\n    if (inFlightTaskFetch) {\n      inFlightTaskFetch.controller.abort();\n      inFlightTaskFetch = null;\n    }\n  }\n\n  function cancelPendingTreemapPaints() {\n    const exposureCtrl = treemapBoot.getExposureCtrl();\n    const taskCtrl = treemapBoot.getTaskCtrl();\n    if (exposureCtrl && exposureCtrl.cancelPendingPaint) exposureCtrl.cancelPendingPaint();\n    if (taskCtrl && taskCtrl.cancelPendingPaint) taskCtrl.cancelPendingPaint();\n  }\n\n  /**\n   * @param {{ scope: string, code: string }} selectionPayload\n   * @param {any} occupation\n   * @param {AbortSignal=} signal\n   */\n  async function fetchOccupationTasks(selectionPayload, occupation, signal) {\n    if (!cfg.occupationTasksApiUrl || !selectionPayload || !occupation) return null;\n    const params = new URLSearchParams({\n      scope: selectionPayload.scope,\n      code: selectionPayload.code,\n      soc_code: getOccupationKey(occupation),\n    });\n    return fetchJson(\n      appendMapCacheVersion(`${cfg.occupationTasksApiUrl}?${params.toString()}`, cfg),\n      { signal },\n    );\n  }\n\n  async function refreshTaskTreemapPanel(selection) {\n    const sel = selection === undefined ? getCurrentSelection() : selection;\n    const selectionPayload = getSelectionPayload(sel);\n    const occupationData = drilldown.getSelectedOccupationData();\n    if (!selectionPayload || !occupationData) {\n      resetTaskState();\n      return;\n    }\n\n    // Policy hook: desktop detaches the shared overview toggle before the task\n    // meta paints so a racing re-render can't leave it as a stray node.\n    beforeTaskRender();\n\n    // ensureTaskReady() lazily code-splits + creates the task controller (it\n    // calls ensureReady() internally), so the task view JS only loads on the\n    // first drilldown. getTaskCtrl() alone would be null before that.\n    const taskCtrl = await treemapBoot.ensureTaskReady();\n    if (!taskCtrl) return;\n\n    const cacheKey = occupationTasksCacheKey(\n      selectionPayload.scope,\n      selectionPayload.code,\n      getOccupationKey(occupationData),\n    );\n    if (caches.occupationTasks.has(cacheKey)) {\n      // LRU touch: re-insert at the tail so this entry survives eviction.\n      const cached = caches.occupationTasks.get(cacheKey);\n      if (tasksSatisfyCurrentMetric(cached, selectedMetric.get())) {\n        caches.occupationTasks.delete(cacheKey);\n        caches.occupationTasks.set(cacheKey, cached);\n        taskCtrl.render(cached, occupationData);\n        return;\n      }\n      caches.occupationTasks.delete(cacheKey);\n    }\n\n    if (topOccupationsStatusEl) {\n      topOccupationsStatusEl.hidden = false;\n      topOccupationsStatusEl.textContent = \"Loading tasks...\";\n    }\n    // Always invalidate any in-flight rAF paint from a prior render so it\n    // can't stomp the visible state. Only blank the container if it's\n    // currently empty \u2014 keeping a rendered treemap on screen during a\n    // refetch avoids a flash to blank.\n    cancelPendingTreemapPaints();\n    if (topOccupationsTreemapEl && !topOccupationsTreemapEl.firstChild) {\n      topOccupationsTreemapEl.hidden = true;\n      topOccupationsTreemapEl.innerHTML = \"\";\n    }\n\n    const requestSerial = drilldown.nextTaskSerial();\n    // F-12: abort the previous in-flight task fetch before starting this one.\n    // The serial staleness guard below still handles the case where the prior\n    // fetch already resolved (or the runtime ignored the abort).\n    abortInFlightTaskFetch();\n    const controller = new AbortController();\n    inFlightTaskFetch = { serial: requestSerial, controller };\n    try {\n      const payload = await fetchOccupationTasks(selectionPayload, occupationData, controller.signal);\n      if (!drilldown.isCurrentTaskSerial(requestSerial)) return;\n      const tasks = Array.isArray(payload && payload.tasks) ? payload.tasks : [];\n      caches.occupationTasks.set(cacheKey, tasks);\n      // Evict oldest while over the LRU bound (insertion-order iteration).\n      while (caches.occupationTasks.size > OCCUPATION_TASKS_MAX_CACHED) {\n        const oldest = caches.occupationTasks.keys().next().value;\n        if (oldest === undefined) break;\n        caches.occupationTasks.delete(oldest);\n      }\n      taskCtrl.render(tasks, occupationData);\n    } catch (error) {\n      if (!drilldown.isCurrentTaskSerial(requestSerial)) return;\n      if (topOccupationsStatusEl) {\n        topOccupationsStatusEl.hidden = false;\n        topOccupationsStatusEl.textContent = \"Unable to load tasks.\";\n      }\n      if (topOccupationsTreemapEl) {\n        topOccupationsTreemapEl.hidden = true;\n        topOccupationsTreemapEl.innerHTML = \"\";\n      }\n      cancelPendingTreemapPaints();\n      console.error(\"Unable to load tasks.\", error);\n    } finally {\n      // Clear only if THIS request is still the tracked one \u2014 a superseding\n      // refresh that started after us owns inFlightTaskFetch now, and we must\n      // not stomp its controller (which would leak it / break the next abort).\n      if (inFlightTaskFetch && inFlightTaskFetch.serial === requestSerial) {\n        inFlightTaskFetch = null;\n      }\n    }\n  }\n\n  async function renderTopOccupationsPanel(occupations, selection) {\n    if (!topOccupationsTreemapEl || !topOccupationsStatusEl) return;\n    const sel = selection === undefined ? getCurrentSelection() : selection;\n\n    const mods = await treemapBoot.ensureReady();\n    const exposureCtrl = treemapBoot.getExposureCtrl();\n    const occupationsCtrl = treemapBoot.getOccupationsCtrl();\n    if (!mods || !exposureCtrl || !occupationsCtrl) return;\n\n    const selectionKey = getSelectionKey(sel);\n    if (selectionKey !== caches.lastSelectionKey) {\n      caches.lastSelectionKey = selectionKey;\n      resetTaskState();\n    }\n\n    if (drilldown.getMode() === \"tasks\" && drilldown.getSelectedOccupationData()) {\n      refreshTaskTreemapPanel(sel);\n      return;\n    }\n\n    const treemapFamilyData = deps.getSelectedTreemapFamilyData();\n    if (drilldown.getMode() === \"occupations\" && treemapFamilyData) {\n      occupationsCtrl.render(treemapFamilyData.occupations || [], treemapFamilyData);\n      return;\n    }\n\n    const items = Array.isArray(occupations) ? occupations : [];\n    const selectionLabel = sel && sel.name ? sel.name : \"Selected geography\";\n    // Server-parity sort (\u2212workers, \u2212metric_field) + slice for the active view.\n    // One limit=500 payload feeds both metrics and both view modes from here.\n    const displayItems = topFamilies(items, {\n      metricField: getTopOccupationsMetricField(),\n      limit: getOverviewLimit(),\n    });\n    const nationalIndustryFill = scales.buildNationalExposureFillScale();\n    const industryFillAccessor = nationalIndustryFill || scales.getLocalExposureColorScale(displayItems);\n\n    // Policy: desktop renders the industry-overview pills (+ mounts the\n    // Plot/Table toggle) in the expanded view and hides them in compact;\n    // mobile always hides the meta.\n    renderOverviewMeta(displayItems, { formatWorkers, formatPenetrationPercentRounded });\n    updateOverviewChrome();\n\n    if (!displayItems.length) {\n      topOccupationsStatusEl.hidden = false;\n      topOccupationsStatusEl.textContent = \"No industry data available for this geography.\";\n      topOccupationsTreemapEl.hidden = true;\n      topOccupationsTreemapEl.innerHTML = \"\";\n      cancelPendingTreemapPaints();\n      syncNavChrome();\n      return;\n    }\n\n    exposureCtrl.render(displayItems, {\n      emptyMessage: \"No industry data available for this geography.\",\n      statusText: getOverviewStatusText(),\n      ariaLabel: `${selectionLabel} top industries by employment`,\n      titleAccessor: (item) => item.label || item.job_family || \"Industry\",\n      valueAccessor: (item) => getEmploymentValue(item),\n      subtitleAccessor: (item) => `${formatWorkers(getEmploymentValue(item))} workers`,\n      fillAccessor: (item) => industryFillAccessor(item),\n      emphasisAccessor: (item) => `${formatPenetrationPercentRounded(nationalExposure.getValue(item))} AI Exposure`,\n      // Table column uses the same national exposure the tile emphasis shows.\n      exposureAccessor: (item) => nationalExposure.getValue(item),\n      forceCompactTileLabels: forceCompactTileLabels(displayItems),\n      onClick: (item) => selectIndustry(item),\n    });\n    syncNavChrome();\n  }\n\n  async function refreshTopOccupationsPanel() {\n    if (!shouldRefresh()) return;\n    if (!topOccupationsTreemapEl || !topOccupationsStatusEl) return;\n    if (!cfg.topOccupationsApiUrl) {\n      clearTopOccupationsPanel(unavailableMessage, { keepSelectionDisplay: true });\n      return;\n    }\n\n    // Policy: mobile pins the shared view-mode signal to \"expanded\" before the\n    // first refresh; desktop no-ops.\n    beforeRefresh();\n\n    const selectionPayload = getSelectionPayload();\n    if (!selectionPayload) {\n      clearTopOccupationsPanel();\n      return;\n    }\n\n    // Sync cache-hit path: if the region's families are already settled in the\n    // shared singleton AND the national baseline is present, render straight\n    // from them \u2014 no loading-text flash on a metric toggle / view-mode change /\n    // resize refresh, and zero refetch. Gating on hasData() preserves the old\n    // ordering guarantee: if the nation fetch failed, fall through to the async\n    // path so ensureLoaded() re-arms its 30s-cooldown retry (the singleton\n    // dedupes the family fetch, so this costs no extra request) and colors\n    // recover the national scale instead of pinning the local fallback.\n    const peeked = peekJobFamilies(selectionPayload.scope, selectionPayload.code);\n    if (peeked && nationalExposure.hasData()) {\n      // Bump the top serial so any in-flight async refresh can't repaint this\n      // panel with a stale region's families under the current selection label.\n      drilldown.nextTopSerial();\n      renderTopOccupationsPanel(peeked, getCurrentSelection());\n      return;\n    }\n\n    topOccupationsStatusEl.hidden = false;\n    topOccupationsStatusEl.textContent = \"Loading industries...\";\n    // Always invalidate any in-flight rAF paint from a prior render. Keep an\n    // already-rendered treemap on screen during a re-fetch to avoid a flash.\n    cancelPendingTreemapPaints();\n    if (!topOccupationsTreemapEl.firstChild) {\n      topOccupationsTreemapEl.hidden = true;\n      topOccupationsTreemapEl.innerHTML = \"\";\n    }\n\n    const requestSerial = drilldown.nextTopSerial();\n\n    try {\n      // nationalExposure baseline + the region's families load concurrently;\n      // loadJobFamilies dedupes in-flight requests for the same region, so a\n      // rapid resize / metric toggle never fires a second fetch.\n      const [, items] = await Promise.all([\n        nationalExposure.ensureLoaded(),\n        loadJobFamilies({ cfg, scope: selectionPayload.scope, code: selectionPayload.code }),\n      ]);\n      if (!drilldown.isCurrentTopSerial(requestSerial)) return;\n      renderTopOccupationsPanel(items, getCurrentSelection());\n    } catch (error) {\n      if (!drilldown.isCurrentTopSerial(requestSerial)) return;\n      clearTopOccupationsPanel(\"Unable to load industry drilldown.\", { keepSelectionDisplay: true });\n      console.error(\"Unable to load industry drilldown.\", error);\n    }\n  }\n\n  return {\n    OCCUPATION_TASKS_MAX_CACHED,\n    cancelPendingTreemapPaints,\n    fetchOccupationTasks,\n    refreshTaskTreemapPanel,\n    renderTopOccupationsPanel,\n    refreshTopOccupationsPanel,\n  };\n}\n", "// @ts-check\n\n// Top-occupations orchestrator. Thin coordinator over five sub-modules:\n// - caches.js           \u2192 request-result caches\n// - drilldown.js        \u2192 families/occupations/tasks state machine\n// - national-exposure.js \u2192 baseline fetch + lookup (used for color scaling)\n// - color-scales.js     \u2192 industry + occupation color functions\n// - treemap-boot.js     \u2192 lazy-loads the heavy treemap renderers + nav\n//\n// Responsibilities kept here:\n// - View-mode transitions (compact \u2194 expanded) with their layout side effects\n// - The render pipeline entry points (refresh*, render*) called from outside\n// - Panel-close + back-button handlers\n// - The orchestration glue that wires sub-modules to each other\n\nimport {\n  selectedOutline,\n  topOccupationsViewMode,\n  selectedTreemapFamilyData,\n  currentSelection,\n} from \"../../state/store.js\";\nimport { loadJobFamilies } from \"../../data/job-families.js\";\nimport { registerNationalExposureReset } from \"../../data/cache-version.js\";\nimport { setTreemapErrorBanner } from \"../../treemap/index.js\";\nimport {\n  getEmploymentValue,\n  getOccupationKey,\n  getTopOccupationsExposureLabel,\n} from \"../../treemap/shared.js\";\nimport { createTreemapTooltip } from \"../../treemap/tooltip.js\";\nimport { renderIndustryOverviewMeta } from \"../../ui/detail-meta-pills.js\";\n\nimport { createTopOccupationsCaches } from \"./caches.js\";\nimport { createNationalExposureLoader } from \"./national-exposure.js\";\nimport { createExposureColorScales } from \"./color-scales.js\";\nimport { createDrilldownState } from \"./drilldown.js\";\nimport { createTreemapBoot } from \"./treemap-boot.js\";\nimport { selectionToPayload } from \"./selection-scope.js\";\nimport { createTopOccupationsCore } from \"./core.js\";\n\nconst TOP_OCCUPATIONS_COMPACT_LIMIT = 5;\nconst TOP_OCCUPATIONS_EXPANDED_LIMIT = 280;\n\n/**\n * @typedef {{\n *   sidePanelEl: HTMLElement | null,\n *   topOccupationsDetailEl: HTMLElement | null,\n *   topOccupationsDetailMetaEl: HTMLElement | null,\n *   topOccupationsStatusEl: HTMLElement | null,\n *   topOccupationsTreemapEl: HTMLElement | null,\n *   treemapTooltipEl: HTMLElement | null,\n *   panelBackTop5El: HTMLElement | null,\n *   panelExpandEl: HTMLElement | null,\n * }} TopOccupationsEls\n *\n * @typedef {{\n *   rootEl: HTMLElement | null,\n *   regionLabelEl: HTMLElement | null,\n *   industryBtnEl: HTMLElement | null,\n *   industryLabelEl: HTMLElement | null,\n *   jobsBtnEl: HTMLElement | null,\n *   jobsLabelEl: HTMLElement | null,\n *   industryPopoverEl: HTMLElement | null,\n *   industrySearchEl: HTMLInputElement | null,\n *   industryClearEl: HTMLElement | null,\n *   industryListEl: HTMLElement | null,\n *   jobsPopoverEl: HTMLElement | null,\n *   jobsSearchEl: HTMLInputElement | null,\n *   jobsClearEl: HTMLElement | null,\n *   jobsListEl: HTMLElement | null,\n *   jobsChevronEl: HTMLElement | null,\n *   jobsClearJobEl: HTMLElement | null,\n *   industryChevronEl: HTMLElement | null,\n *   industryClearIndustryEl: HTMLElement | null,\n * }} TreemapNavEls\n *\n * @param {{\n *   cfg: import(\"../../types.js\").Cfg,\n *   els: TopOccupationsEls,\n *   treemapNavEls: TreemapNavEls,\n *   mapOps: { getMapColors: () => any, getCurrentTransform: () => any },\n *   panelOps: {\n *     setPanelCollapsed: (collapsed: boolean) => void,\n *     handleLayoutChange: (reason?: string) => void,\n *     schedulePanelLayoutRecompute: (reason: string, onDone?: (() => void) | null) => void,\n *     clearSelectionDisplay: (name?: string) => void,\n *   },\n *   selectionOps: {\n *     focusFeatureInViewport: (feature: any, opts?: any) => void,\n *     ensureSelectionOutlineVisible: () => void,\n *   },\n * }} deps\n */\n/**\n * Treemap / Table view toggle for the industry + occupation overview levels\n * (desktop). Treemap is the default. Reuses the task-toggle styling.\n *\n * @param {{ getMode: () => \"treemap\" | \"table\", onChange: (mode: \"treemap\" | \"table\") => void }} opts\n */\nfunction createOverviewViewToggle({ getMode, onChange }) {\n  const root = document.createElement(\"div\");\n  root.className = \"map-task-view-toggle map-overview-view-toggle\";\n  root.setAttribute(\"role\", \"group\");\n  root.setAttribute(\"aria-label\", \"Overview visualization mode\");\n\n  const treemapBtn = document.createElement(\"button\");\n  treemapBtn.type = \"button\";\n  treemapBtn.className = \"map-task-view-toggle__btn is-active\";\n  treemapBtn.textContent = \"Plot\";\n  treemapBtn.setAttribute(\"aria-pressed\", \"true\");\n\n  const tableBtn = document.createElement(\"button\");\n  tableBtn.type = \"button\";\n  tableBtn.className = \"map-task-view-toggle__btn\";\n  tableBtn.textContent = \"Table\";\n  tableBtn.setAttribute(\"aria-pressed\", \"false\");\n\n  function sync() {\n    const isTable = getMode() === \"table\";\n    tableBtn.classList.toggle(\"is-active\", isTable);\n    treemapBtn.classList.toggle(\"is-active\", !isTable);\n    tableBtn.setAttribute(\"aria-pressed\", isTable ? \"true\" : \"false\");\n    treemapBtn.setAttribute(\"aria-pressed\", !isTable ? \"true\" : \"false\");\n  }\n\n  treemapBtn.addEventListener(\"click\", () => { onChange(\"treemap\"); sync(); });\n  tableBtn.addEventListener(\"click\", () => { onChange(\"table\"); sync(); });\n\n  root.append(treemapBtn, tableBtn);\n\n  // The toggle is a single shared node moved between overview-level pills rows.\n  // It owns its own (idempotent) mount/detach so the lifecycle isn't smeared\n  // across callers: mount() into the current pills row (guarded against a\n  // redundant re-append, like TaskPage's mountViewToggle), detach() when the\n  // overview level is left (task view / panel reset) so no stray node lingers.\n  /** @param {HTMLElement | null | undefined} container */\n  function mount(container) {\n    if (container && root.parentElement !== container) container.appendChild(root);\n  }\n  function detach() {\n    root.remove();\n  }\n\n  return { el: root, sync, mount, detach };\n}\n\nexport function createTopOccupationsController(deps) {\n  const { cfg, els, treemapNavEls, mapOps, panelOps, selectionOps } = deps;\n  const {\n    sidePanelEl,\n    topOccupationsDetailEl, topOccupationsDetailMetaEl,\n    topOccupationsStatusEl, topOccupationsTreemapEl, treemapTooltipEl,\n    panelBackTop5El, panelExpandEl,\n  } = els;\n  const { getMapColors, getCurrentTransform } = mapOps;\n  const {\n    setPanelCollapsed,\n    schedulePanelLayoutRecompute,\n    clearSelectionDisplay,\n  } = panelOps;\n  const { focusFeatureInViewport, ensureSelectionOutlineVisible } = selectionOps;\n\n  const tooltip = createTreemapTooltip({ tooltipEl: treemapTooltipEl });\n\n  // Overview view mode (treemap default | table) for the industry + occupation\n  // levels. The toggle element is threaded into the meta-pills row via\n  // treemap-boot; flipping it re-renders the current overview from cache.\n  let overviewViewMode = /** @type {\"treemap\" | \"table\"} */ (\"treemap\");\n  const overviewToggle = createOverviewViewToggle({\n    getMode: () => overviewViewMode,\n    onChange: (mode) => {\n      overviewViewMode = mode;\n      refreshTopOccupationsPanel();\n    },\n  });\n\n  setTreemapErrorBanner({\n    target: topOccupationsTreemapEl,\n    onRetry: () => refreshTopOccupationsPanel(),\n  });\n\n  const caches = createTopOccupationsCaches();\n  const nationalExposure = createNationalExposureLoader({ cfg });\n  registerNationalExposureReset(() => nationalExposure.reset());\n  const scales = createExposureColorScales({ nationalExposure, getMapColors });\n  const drilldown = createDrilldownState();\n\n  // ---- selection helpers ----\n\n  function getTopOccupationsSelectionPayload(selection = currentSelection.get()) {\n    return selectionToPayload(selection);\n  }\n\n  function getTopOccupationsSelectionKey(selection = currentSelection.get()) {\n    const payload = getTopOccupationsSelectionPayload(selection);\n    if (!payload) return \"\";\n    return `${payload.scope}:${payload.code}`;\n  }\n\n  // ---- chrome setters ----\n\n  function updateBackToTop5Visibility() {\n    if (!panelBackTop5El) return;\n    panelBackTop5El.classList.toggle(\"hidden\", topOccupationsViewMode.get() !== \"expanded\");\n  }\n\n  function updateExpandButtonVisibility() {\n    if (!panelExpandEl) return;\n    panelExpandEl.classList.toggle(\"hidden\", topOccupationsViewMode.get() === \"expanded\");\n  }\n\n  function resetTopOccupationsTaskState() {\n    drilldown.resetToFamilies();\n    selectedTreemapFamilyData.set(null);\n    if (topOccupationsDetailEl) topOccupationsDetailEl.hidden = true;\n    if (topOccupationsDetailMetaEl) topOccupationsDetailMetaEl.textContent = \"\";\n    // The overview toggle is a single shared node threaded into the meta-pills\n    // row only at overview levels. Detach it from any stale host so it can never\n    // be left orphaned/visible during a transition (no-op if already detached).\n    overviewToggle.detach();\n  }\n\n  function syncNavChrome() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    if (navCtrl) navCtrl.syncChrome();\n  }\n\n  // Bridges for the arbitrated document Escape handler (ui/keyboard.js). The\n  // nav controller is lazily booted, so getNavCtrl() may be null before the\n  // user opens the treemap \u2014 in which case there can be no open popover (false)\n  // and closing is a no-op. Mirrors syncNavChrome's null-guard.\n  function hasOpenTreemapPopovers() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    return Boolean(navCtrl && navCtrl.hasOpenPopovers());\n  }\n  function closeTreemapPopovers() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    if (navCtrl) navCtrl.closePopovers();\n  }\n\n  function selectIndustryAndRenderOccupations(item) {\n    if (!item) return;\n    selectedTreemapFamilyData.set({ ...item });\n    drilldown.setMode(\"occupations\");\n    if (topOccupationsViewMode.get() === \"expanded\") {\n      refreshTopOccupationsPanel();\n    }\n  }\n\n  // ---- view-mode transition ----\n\n  // Pending fade-out timer + paint-watch rAF, tracked at factory scope so a\n  // rapid second call (Expand \u2192 Compact within FADE_OUT_MS) can cancel the\n  // earlier transition before it re-applies the stale mode.\n  let pendingViewModeTimerId = null;\n  let pendingViewModeRafId = null;\n  let pendingTransitioningEl = null;\n\n  function setTopOccupationsViewMode(nextMode, { rerender = true, suppressLayout = false } = {}) {\n    const normalizedMode = nextMode === \"expanded\" ? \"expanded\" : \"compact\";\n    const changed = topOccupationsViewMode.get() !== normalizedMode;\n    const contentEl = sidePanelEl ? sidePanelEl.querySelector(\".map-side-panel-content\") : null;\n\n    if (pendingViewModeTimerId !== null) {\n      window.clearTimeout(pendingViewModeTimerId);\n      pendingViewModeTimerId = null;\n    }\n    if (pendingViewModeRafId !== null) {\n      window.cancelAnimationFrame(pendingViewModeRafId);\n      pendingViewModeRafId = null;\n    }\n    if (pendingTransitioningEl) {\n      pendingTransitioningEl.classList.remove(\"is-mode-transitioning\");\n      pendingTransitioningEl = null;\n    }\n\n    const applyMode = () => {\n      topOccupationsViewMode.set(normalizedMode);\n\n      if (sidePanelEl) sidePanelEl.classList.toggle(\"is-expanded\", normalizedMode === \"expanded\");\n      updateBackToTop5Visibility();\n      updateExpandButtonVisibility();\n      if (topOccupationsTreemapEl) {\n        topOccupationsTreemapEl.classList.toggle(\"is-expanded\", normalizedMode === \"expanded\");\n      }\n\n      if (normalizedMode === \"expanded\" && sidePanelEl && sidePanelEl.classList.contains(\"is-collapsed\")) {\n        setPanelCollapsed(false);\n      }\n\n      if (normalizedMode === \"compact\") resetTopOccupationsTaskState();\n\n      if (changed && !suppressLayout) {\n        schedulePanelLayoutRecompute(\"panel-toggle\", () => {\n          const outlineFeature = selectedOutline.get().feature;\n          if (!outlineFeature) return;\n          const currentTransform = getCurrentTransform();\n          const k = currentTransform && Number.isFinite(currentTransform.k) ? currentTransform.k : 12;\n          if (normalizedMode === \"expanded\") {\n            focusFeatureInViewport(outlineFeature, {\n              targetScale: k,\n              duration: 500,\n              collapsedOverride: false,\n              preferFit: true,\n            });\n          } else {\n            focusFeatureInViewport(outlineFeature, {\n              duration: 500,\n              collapsedOverride: false,\n              preferFit: true,\n            });\n          }\n          ensureSelectionOutlineVisible();\n        });\n      }\n\n      if (rerender) refreshTopOccupationsPanel();\n    };\n\n    if (changed && contentEl && !suppressLayout) {\n      contentEl.classList.add(\"is-mode-transitioning\");\n      pendingTransitioningEl = contentEl;\n      const FADE_OUT_MS = 160;\n      const MAX_WAIT_MS = 600;\n      pendingViewModeTimerId = window.setTimeout(() => {\n        pendingViewModeTimerId = null;\n        const oldTreemapChild = topOccupationsTreemapEl\n          ? topOccupationsTreemapEl.firstElementChild\n          : null;\n        applyMode();\n        const start = performance.now();\n        const tick = () => {\n          const newChild = topOccupationsTreemapEl\n            ? topOccupationsTreemapEl.firstElementChild\n            : null;\n          const treemapReady = !!newChild && newChild !== oldTreemapChild;\n          const timedOut = performance.now() - start > MAX_WAIT_MS;\n          if (treemapReady || timedOut) {\n            pendingViewModeRafId = window.requestAnimationFrame(() => {\n              pendingViewModeRafId = null;\n              contentEl.classList.remove(\"is-mode-transitioning\");\n              if (pendingTransitioningEl === contentEl) pendingTransitioningEl = null;\n            });\n          } else {\n            pendingViewModeRafId = window.requestAnimationFrame(tick);\n          }\n        };\n        pendingViewModeRafId = window.requestAnimationFrame(tick);\n      }, FADE_OUT_MS);\n    } else {\n      applyMode();\n    }\n  }\n\n  // ---- nav families fetcher (used by treemap-boot's nav controller) ----\n\n  // The nav popovers need the full family set for the current region; the\n  // shared singleton in data/job-families.js owns the (deduped, cached) fetch,\n  // so this is just an ensureLoaded() + loadJobFamilies() pair. No metric in\n  // the key: one limit=500 payload serves every metric/view.\n  async function loadTreemapNavJobFamilies() {\n    const payload = getTopOccupationsSelectionPayload();\n    if (!payload || !cfg.topOccupationsApiUrl) return [];\n    await nationalExposure.ensureLoaded();\n    return loadJobFamilies({ cfg, scope: payload.scope, code: payload.code });\n  }\n\n  // ---- treemap-boot: lazy controllers ----\n\n  const treemapBoot = createTreemapBoot({\n    cfg,\n    els: {\n      topOccupationsTreemapEl,\n      topOccupationsStatusEl,\n      topOccupationsDetailEl,\n      topOccupationsDetailMetaEl,\n    },\n    treemapNavEls,\n    tooltip,\n    drilldown,\n    getOccupationExposureColor: (value) => scales.getOccupationExposureColor(value),\n    getNationalExposureValue: (item) => nationalExposure.getValue(item),\n    getSelectionPayload: () => getTopOccupationsSelectionPayload(),\n    loadJobFamilies: loadTreemapNavJobFamilies,\n    updateBackToTop5Visibility,\n    syncNavChrome,\n    setViewMode: setTopOccupationsViewMode,\n    refreshTopOccupationsPanel: () => refreshTopOccupationsPanel(),\n    refreshTaskTreemapPanel: () => refreshTaskTreemapPanel(currentSelection.get()),\n    resetTopOccupationsTaskState,\n    handleBackToTop5: () => handleBackToTop5(),\n    onOccupationClick: (item) => {\n      drilldown.setSelectedOccupation({ ...item }, getOccupationKey(item));\n      drilldown.setMode(\"tasks\");\n      refreshTaskTreemapPanel(currentSelection.get());\n    },\n    // Compact (top-5 glance) is always the treemap; the table is offered only in\n    // the expanded-industry and occupation views (where the meta pills + toggle\n    // render). This keeps a stale \"table\" choice from rendering in the small\n    // compact host after a back-to-top-5.\n    getOverviewViewMode: () => (\n      topOccupationsViewMode.get() === \"compact\" ? \"treemap\" : overviewViewMode\n    ),\n    mountOverviewToggle: (pillsEl) => overviewToggle.mount(pillsEl),\n  });\n\n  // ---- render paths (shared core + desktop policy) ----\n\n  // Desktop policy: clear to the empty state. Honors keepSelectionDisplay and\n  // owns the desktop-only \"Select a region\" selection-display reset.\n  function clearTopOccupationsPanel(\n    message = \"Select a geography to view the top industries by employment.\",\n    { keepSelectionDisplay = false } = {},\n  ) {\n    resetTopOccupationsTaskState();\n    tooltip.hide();\n    if (!keepSelectionDisplay) clearSelectionDisplay(\"Select a region\");\n    if (topOccupationsStatusEl) {\n      topOccupationsStatusEl.hidden = false;\n      topOccupationsStatusEl.textContent = message;\n    }\n    if (topOccupationsTreemapEl) {\n      topOccupationsTreemapEl.hidden = true;\n      topOccupationsTreemapEl.innerHTML = \"\";\n    }\n    // Invalidate any stale rAF\u00B2 paint scheduled by a prior render so it\n    // can't unhide+redraw over this cleared state.\n    core.cancelPendingTreemapPaints();\n    syncNavChrome();\n  }\n\n  // Desktop policy: industry-overview pills + Plot/Table toggle in the expanded\n  // view; hidden in compact (mirrors the original render-path branch exactly).\n  function renderOverviewMeta(displayItems, { formatWorkers, formatPenetrationPercentRounded }) {\n    const isExpandedView = topOccupationsViewMode.get() === \"expanded\";\n    if (isExpandedView && displayItems.length) {\n      if (topOccupationsDetailEl) topOccupationsDetailEl.hidden = false;\n      // Industry-level summary pills (workers / industry count / weighted-avg\n      // exposure). renderIndustryOverviewMeta computes the weighted average and\n      // worker totals internally from displayItems, and returns the pills row so\n      // the Plot/Table toggle can mount itself into it.\n      const pillsEl = renderIndustryOverviewMeta(topOccupationsDetailMetaEl, displayItems, {\n        getEmploymentValue,\n        getExposureValue: (item) => nationalExposure.getValue(item),\n        formatWorkers,\n        formatPenetrationPercentRounded,\n        getExposureLabel: getTopOccupationsExposureLabel,\n      });\n      overviewToggle.mount(pillsEl);\n    } else {\n      if (topOccupationsDetailEl) topOccupationsDetailEl.hidden = true;\n      if (topOccupationsDetailMetaEl) topOccupationsDetailMetaEl.textContent = \"\";\n    }\n  }\n\n  const core = createTopOccupationsCore({\n    cfg,\n    els: {\n      topOccupationsDetailEl,\n      topOccupationsDetailMetaEl,\n      topOccupationsStatusEl,\n      topOccupationsTreemapEl,\n    },\n    caches,\n    drilldown,\n    nationalExposure,\n    scales,\n    treemapBoot,\n    tooltip,\n    getSelectionPayload: (selection) => getTopOccupationsSelectionPayload(selection),\n    getSelectionKey: (selection) => getTopOccupationsSelectionKey(selection),\n    getCurrentSelection: () => currentSelection.get(),\n    getSelectedTreemapFamilyData: () => selectedTreemapFamilyData.get(),\n    // Limit varies by view mode: 5 compact / 280 expanded.\n    getOverviewLimit: () =>\n      topOccupationsViewMode.get() === \"expanded\"\n        ? TOP_OCCUPATIONS_EXPANDED_LIMIT\n        : TOP_OCCUPATIONS_COMPACT_LIMIT,\n    getOverviewStatusText: () =>\n      topOccupationsViewMode.get() === \"expanded\"\n        ? \"Click an industry to see occupations.\"\n        : \"Click a tile to expand and view occupations.\",\n    forceCompactTileLabels: (displayItems) =>\n      topOccupationsViewMode.get() === \"compact\" && displayItems.length <= 5,\n    renderOverviewMeta,\n    // Task view renders its own meta (no overview toggle). Detach the shared\n    // overview toggle before the task meta paints so a racing re-render can't\n    // leave it as a stray node that flashes on the way back to the overview.\n    beforeTaskRender: () => overviewToggle.detach(),\n    resetTaskState: resetTopOccupationsTaskState,\n    syncNavChrome,\n    updateOverviewChrome: () => {\n      updateBackToTop5Visibility();\n      updateExpandButtonVisibility();\n    },\n    selectIndustry: (item) => {\n      if (topOccupationsViewMode.get() === \"compact\") {\n        selectIndustryAndRenderOccupations(item);\n        setTopOccupationsViewMode(\"expanded\");\n        return;\n      }\n      selectIndustryAndRenderOccupations(item);\n    },\n    clearTopOccupationsPanel,\n    // Desktop always refreshes (no mobile-layout gate).\n    shouldRefresh: () => true,\n    // Desktop has no view-mode pin step before refresh.\n    beforeRefresh: () => {},\n    unavailableMessage: \"Top industries are unavailable.\",\n  });\n\n  function refreshTaskTreemapPanel(selection = currentSelection.get()) {\n    return core.refreshTaskTreemapPanel(selection);\n  }\n  function refreshTopOccupationsPanel() {\n    return core.refreshTopOccupationsPanel();\n  }\n\n  // ---- user-facing handlers ----\n\n  function handleBackToTop5() {\n    resetTopOccupationsTaskState();\n    setTopOccupationsViewMode(\"compact\");\n  }\n\n  function onPanelClose() {\n    tooltip.hide();\n    resetTopOccupationsTaskState();\n    setTopOccupationsViewMode(\"compact\", { rerender: false, suppressLayout: true });\n    setPanelCollapsed(true);\n    schedulePanelLayoutRecompute(\"panel-toggle\", () => {\n      const outlineFeature = selectedOutline.get().feature;\n      if (!outlineFeature) return;\n      const currentTransform = getCurrentTransform();\n      focusFeatureInViewport(outlineFeature, {\n        targetScale: currentTransform && Number.isFinite(currentTransform.k) ? currentTransform.k : 12,\n        duration: 700,\n        collapsedOverride: true,\n      });\n      ensureSelectionOutlineVisible();\n    });\n  }\n\n  function hideTreemapTooltip() {\n    tooltip.hide();\n  }\n\n  return {\n    refreshTopOccupationsPanel,\n    setTopOccupationsViewMode,\n    clearTopOccupationsPanel,\n    resetTopOccupationsTaskState,\n    handleBackToTop5,\n    onPanelClose,\n    hideTreemapTooltip,\n    syncNavChrome,\n    hasOpenTreemapPopovers,\n    closeTreemapPopovers,\n  };\n}\n", "// @ts-check\n\n// Mobile top-occupations orchestrator. Sibling of `index.js` (the desktop\n// orchestrator) that owns its own DOM hosts inside the mobile sheet's\n// expanded detent. Reuses every shared factory (caches, drilldown,\n// nationalExposure, color scales, treemapBoot, tooltip) plus all of the\n// `treemap/*` renderers \u2014 only the chrome and the orchestration policy are\n// mobile-specific.\n//\n// Mobile-specific UX rules (per product decision):\n// - Top-5 cap on the industries level only. Once the user drills into an\n//   industry, all of its occupations are shown; once they drill into an\n//   occupation, all of its tasks are shown. The cap exists at the entry\n//   level because users land there often and need a fast scan; deeper\n//   levels are intentional drilldowns where exhaustiveness matters more.\n// - The breadcrumb's industry/jobs popovers ARE the escape hatch for\n//   industries outside the top-5 \u2014 they search across the full set.\n// - Renders gated by `isMobileLayout()` so the desktop side-panel\n//   orchestrator owns refresh on wider viewports.\n//\n// One unavoidable side-effect: `treemap/nav.js` and the renderer modules\n// read the global `topOccupationsViewMode` signal directly. To make their\n// drilldown branches take the right path on mobile, this orchestrator\n// pins the signal to \"expanded\" before its first refresh. That means\n// crossing back to a desktop viewport leaves the desktop panel in\n// expanded mode \u2014 the user can revert via desktop's back-to-top-5\n// button. Acceptable trade-off versus refactoring the shared modules.\n\nimport {\n  topOccupationsViewMode,\n  selectedTreemapFamilyData,\n  currentSelection,\n} from \"../../state/store.js\";\nimport { loadJobFamilies } from \"../../data/job-families.js\";\nimport { registerNationalExposureReset } from \"../../data/cache-version.js\";\nimport { getOccupationKey } from \"../../treemap/shared.js\";\nimport { createTreemapTooltip } from \"../../treemap/tooltip.js\";\n\nimport { createTopOccupationsCaches } from \"./caches.js\";\nimport { createNationalExposureLoader } from \"./national-exposure.js\";\nimport { createExposureColorScales } from \"./color-scales.js\";\nimport { createDrilldownState } from \"./drilldown.js\";\nimport { createTreemapBoot } from \"./treemap-boot.js\";\nimport { selectionToPayload } from \"./selection-scope.js\";\nimport { createTopOccupationsCore } from \"./core.js\";\n\nconst MOBILE_TOP_LIMIT = 5;\n\n/**\n * @typedef {{\n *   topOccupationsDetailEl: HTMLElement | null,\n *   topOccupationsDetailMetaEl: HTMLElement | null,\n *   topOccupationsStatusEl: HTMLElement | null,\n *   topOccupationsTreemapEl: HTMLElement | null,\n *   treemapTooltipEl: HTMLElement | null,\n *   cardEl: HTMLElement | null,\n * }} MobileTopOccupationsEls\n *\n * @typedef {{\n *   rootEl: HTMLElement | null,\n *   regionLabelEl: HTMLElement | null,\n *   industryBtnEl: HTMLElement | null,\n *   industryLabelEl: HTMLElement | null,\n *   jobsBtnEl: HTMLElement | null,\n *   jobsLabelEl: HTMLElement | null,\n *   industryPopoverEl: HTMLElement | null,\n *   industrySearchEl: HTMLInputElement | null,\n *   industryClearEl: HTMLElement | null,\n *   industryListEl: HTMLElement | null,\n *   jobsPopoverEl: HTMLElement | null,\n *   jobsSearchEl: HTMLInputElement | null,\n *   jobsClearEl: HTMLElement | null,\n *   jobsListEl: HTMLElement | null,\n *   jobsChevronEl: HTMLElement | null,\n *   jobsClearJobEl: HTMLElement | null,\n *   industryChevronEl: HTMLElement | null,\n *   industryClearIndustryEl: HTMLElement | null,\n * }} TreemapNavEls\n *\n * @param {{\n *   cfg: import(\"../../types.js\").Cfg,\n *   els: MobileTopOccupationsEls,\n *   treemapNavEls: TreemapNavEls,\n *   mapOps: { getMapColors: () => any },\n *   isMobileLayout: () => boolean,\n * }} deps\n */\nexport function createMobileTopOccupationsController(deps) {\n  const { cfg, els, treemapNavEls, mapOps, isMobileLayout } = deps;\n  const {\n    topOccupationsDetailEl,\n    topOccupationsDetailMetaEl,\n    topOccupationsStatusEl,\n    topOccupationsTreemapEl,\n    treemapTooltipEl,\n  } = els;\n  const { getMapColors } = mapOps;\n\n  const tooltip = createTreemapTooltip({ tooltipEl: treemapTooltipEl });\n  // Note: we deliberately do NOT call setTreemapErrorBanner here. The\n  // banner registration is a singleton \u2014 the desktop controller already\n  // registered it, and overwriting from here would route chunk-load\n  // errors into the (hidden) mobile container on desktop viewports. On\n  // mobile, a chunk-load error means our await loadTreemap() in\n  // treemap-boot returns null and the render quietly no-ops; that's an\n  // acceptable trade-off for a rare network failure.\n\n  const caches = createTopOccupationsCaches();\n  const nationalExposure = createNationalExposureLoader({ cfg });\n  registerNationalExposureReset(() => nationalExposure.reset());\n  const scales = createExposureColorScales({ nationalExposure, getMapColors });\n  const drilldown = createDrilldownState();\n\n  let viewModePinned = false;\n  function pinViewModeExpanded() {\n    if (viewModePinned) return;\n    // See module header for why this is necessary. Pinning is one-way:\n    // we never reset to compact from here, since desktop owns its own\n    // view-mode UI and this signal is shared.\n    if (topOccupationsViewMode.get() !== \"expanded\") {\n      topOccupationsViewMode.set(\"expanded\");\n    }\n    viewModePinned = true;\n  }\n\n  function getSelectionPayload(selection = currentSelection.get()) {\n    return selectionToPayload(selection);\n  }\n\n  function getSelectionKey(selection = currentSelection.get()) {\n    const payload = getSelectionPayload(selection);\n    if (!payload) return \"\";\n    return `${payload.scope}:${payload.code}`;\n  }\n\n  function resetTaskState() {\n    drilldown.resetToFamilies();\n    selectedTreemapFamilyData.set(null);\n    if (topOccupationsDetailEl) topOccupationsDetailEl.hidden = true;\n    if (topOccupationsDetailMetaEl) topOccupationsDetailMetaEl.textContent = \"\";\n  }\n\n  function syncNavChrome() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    if (navCtrl) navCtrl.syncChrome();\n  }\n\n  // Bridges for the arbitrated document Escape handler (ui/keyboard.js); see\n  // the desktop controller (index.js) for the rationale. Null-guarded because\n  // the nav controller is lazily booted.\n  function hasOpenTreemapPopovers() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    return Boolean(navCtrl && navCtrl.hasOpenPopovers());\n  }\n  function closeTreemapPopovers() {\n    const navCtrl = treemapBoot.getNavCtrl();\n    if (navCtrl) navCtrl.closePopovers();\n  }\n\n  function selectIndustryAndRenderOccupations(item) {\n    if (!item) return;\n    selectedTreemapFamilyData.set({ ...item });\n    drilldown.setMode(\"occupations\");\n    refreshTopOccupationsPanel();\n  }\n\n  // Mobile has no view modes \u2014 but treemap-boot expects this in its deps\n  // bag and `treemap/nav.js` invokes it from the popover-driven\n  // selectIndustry / selectJob branches with an early-return: those\n  // callers expect setViewMode to internally trigger the render (desktop's\n  // setTopOccupationsViewMode does, since the call sets `rerender: true`).\n  // If we no-op here, popover selection sets drilldown state but never\n  // repaints \u2014 that's the \"job selection no longer shows tasks\" bug.\n  // Always refresh so the render happens regardless of which branch in\n  // nav.js called us.\n  function setViewMode() {\n    pinViewModeExpanded();\n    refreshTopOccupationsPanel();\n  }\n\n  // The popover lists must show the FULL set so users can search past the\n  // top-5 cap. The shared singleton's limit=500 payload IS the full set, so\n  // this is just an ensureLoaded() + loadJobFamilies() pair \u2014 deduped/cached\n  // across desktop, mobile, and the nav popovers.\n  async function loadNavJobFamilies() {\n    const payload = getSelectionPayload();\n    if (!payload || !cfg.topOccupationsApiUrl) return [];\n    await nationalExposure.ensureLoaded();\n    return loadJobFamilies({ cfg, scope: payload.scope, code: payload.code });\n  }\n\n  const treemapBoot = createTreemapBoot({\n    cfg,\n    els: {\n      topOccupationsTreemapEl,\n      topOccupationsStatusEl,\n      topOccupationsDetailEl,\n      topOccupationsDetailMetaEl,\n    },\n    treemapNavEls,\n    tooltip,\n    drilldown,\n    getOccupationExposureColor: (value) => scales.getOccupationExposureColor(value),\n    getNationalExposureValue: (item) => nationalExposure.getValue(item),\n    getSelectionPayload: () => getSelectionPayload(),\n    loadJobFamilies: loadNavJobFamilies,\n    // Mobile has no back-to-top-5 button \u2014 the inline breadcrumb \u00D7 clears\n    // already cover the escape path. Provide a no-op so treemap-boot's\n    // wiring stays intact.\n    updateBackToTop5Visibility: () => {},\n    syncNavChrome,\n    setViewMode,\n    refreshTopOccupationsPanel: () => refreshTopOccupationsPanel(),\n    refreshTaskTreemapPanel: () => refreshTaskTreemapPanel(currentSelection.get()),\n    resetTopOccupationsTaskState: resetTaskState,\n    handleBackToTop5: () => {\n      // From a popover-driven clearSelectedIndustry the desktop would call\n      // back-to-top-5; on mobile we just reset and re-render the families.\n      resetTaskState();\n      refreshTopOccupationsPanel();\n    },\n    onOccupationClick: (item) => {\n      drilldown.setSelectedOccupation({ ...item }, getOccupationKey(item));\n      drilldown.setMode(\"tasks\");\n      refreshTaskTreemapPanel(currentSelection.get());\n    },\n  });\n\n  // Mobile policy: clear to the empty state. No selection-display reset and no\n  // keepSelectionDisplay distinction (the desktop side-panel owns that chrome).\n  function clearTopOccupationsPanel(message = \"Select a geography to view its top industries.\") {\n    resetTaskState();\n    tooltip.hide();\n    if (topOccupationsStatusEl) {\n      topOccupationsStatusEl.hidden = false;\n      topOccupationsStatusEl.textContent = message;\n    }\n    if (topOccupationsTreemapEl) {\n      topOccupationsTreemapEl.hidden = true;\n      topOccupationsTreemapEl.innerHTML = \"\";\n    }\n    core.cancelPendingTreemapPaints();\n    syncNavChrome();\n  }\n\n  const core = createTopOccupationsCore({\n    cfg,\n    els: {\n      topOccupationsDetailEl,\n      topOccupationsDetailMetaEl,\n      topOccupationsStatusEl,\n      topOccupationsTreemapEl,\n    },\n    caches,\n    drilldown,\n    nationalExposure,\n    scales,\n    treemapBoot,\n    tooltip,\n    getSelectionPayload: (selection) => getSelectionPayload(selection),\n    getSelectionKey: (selection) => getSelectionKey(selection),\n    getCurrentSelection: () => currentSelection.get(),\n    getSelectedTreemapFamilyData: () => selectedTreemapFamilyData.get(),\n    // Mobile caps the industries entry level at 5; drilldowns render in full\n    // (handled by the occupations-mode branch in core, which renders the chosen\n    // industry's full occupation list).\n    getOverviewLimit: () => MOBILE_TOP_LIMIT,\n    getOverviewStatusText: () => \"Tap a tile to see all of its occupations.\",\n    // Tile labels matter on small screens \u2014 always force the compact label\n    // layout that puts the key meta first regardless of tile size.\n    forceCompactTileLabels: () => true,\n    // Mobile renders no overview meta pills (no Plot/Table toggle): hide both.\n    renderOverviewMeta: () => {\n      if (topOccupationsDetailEl) topOccupationsDetailEl.hidden = true;\n      if (topOccupationsDetailMetaEl) topOccupationsDetailMetaEl.textContent = \"\";\n    },\n    // Mobile has no overview toggle to detach before the task view paints.\n    beforeTaskRender: () => {},\n    resetTaskState,\n    syncNavChrome,\n    // Mobile has no view-mode chrome (no back-to-top-5 / expand buttons).\n    updateOverviewChrome: () => {},\n    selectIndustry: (item) => selectIndustryAndRenderOccupations(item),\n    clearTopOccupationsPanel,\n    // Renders gated by isMobileLayout() so the desktop side-panel orchestrator\n    // owns refresh on wider viewports.\n    shouldRefresh: () => isMobileLayout(),\n    // Pin the shared view-mode signal to \"expanded\" before the first refresh\n    // (see module header for why this is necessary).\n    beforeRefresh: () => pinViewModeExpanded(),\n    unavailableMessage: \"Top industries are unavailable.\",\n  });\n\n  function refreshTaskTreemapPanel(selection = currentSelection.get()) {\n    return core.refreshTaskTreemapPanel(selection);\n  }\n  function refreshTopOccupationsPanel() {\n    return core.refreshTopOccupationsPanel();\n  }\n\n  function hideTreemapTooltip() {\n    tooltip.hide();\n  }\n\n  return {\n    refreshTopOccupationsPanel,\n    clearTopOccupationsPanel,\n    resetTopOccupationsTaskState: resetTaskState,\n    hideTreemapTooltip,\n    syncNavChrome,\n    hasOpenTreemapPopovers,\n    closeTreemapPopovers,\n  };\n}\n", "// @ts-check\n\n// Mobile shell: hamburger dropdown menu, full-screen settings overlay\n// (with focus trap), layer-toggle relocation between its desktop slot and\n// the settings overlay, plus the document-level Escape handler that closes\n// the menu/overlay before init()'s Escape handler clears map state.\n\nimport { MOBILE_QUERY } from \"../config.js\";\n\n/**\n * @param {{\n *   sidePanelEl: HTMLElement | null,\n *   mobileSheet: { show: any, hide: any, isShowing: () => boolean, refresh: any },\n *   resetMapToNation: () => void,\n *   showUsMobilePreview: () => void,\n *   restoreMobileSheetPreview: () => void,\n *   isMobileLayout: () => boolean,\n *   openMapInfoModal: (triggerEl: any) => void,\n * }} deps\n */\nexport function setupMobileShell(deps) {\n  const {\n    sidePanelEl,\n    mobileSheet,\n    resetMapToNation,\n    showUsMobilePreview,\n    restoreMobileSheetPreview,\n    isMobileLayout,\n    openMapInfoModal,\n  } = deps;\n\n  const menuToggleEl = document.getElementById(\"map-mobile-menu-toggle\");\n  const menuEl = document.getElementById(\"map-mobile-menu\");\n  const settingsFabEl = document.getElementById(\"map-mobile-settings-fab\");\n  const infoFabEl = document.getElementById(\"map-mobile-info-fab\");\n  const settingsOverlayEl = document.getElementById(\"map-settings-overlay\");\n  const settingsOverlayCloseEl = document.getElementById(\"map-settings-overlay-close\");\n  const settingsSlotEl = document.querySelector(\"[data-mobile-settings-slot]\");\n  const resetBtnEl = document.getElementById(\"map-mobile-reset\");\n  const layerToggleEl = document.getElementById(\"map-layer-toggle\");\n\n  if (!menuToggleEl || !menuEl || !settingsOverlayEl) return;\n\n  let layerToggleDesktopParent = layerToggleEl ? layerToggleEl.parentElement : null;\n  let layerToggleDesktopNext = layerToggleEl ? layerToggleEl.nextSibling : null;\n\n  const mq = window.matchMedia(MOBILE_QUERY);\n\n  function applyLayoutForMode() {\n    const mobile = mq.matches;\n    if (mobile) {\n      if (layerToggleEl && settingsSlotEl && layerToggleEl.parentElement !== settingsSlotEl) {\n        layerToggleDesktopParent = layerToggleEl.parentElement;\n        layerToggleDesktopNext = layerToggleEl.nextSibling;\n        settingsSlotEl.appendChild(layerToggleEl);\n        layerToggleEl.classList.remove(\"map-ui-hidden\");\n      }\n      // Crossing back into the mobile breakpoint after the desktop branch\n      // hid the sheet \u2014 re-show whichever region the user currently has\n      // selected (or the US default when none/nation), so a state/MSA\n      // selection from before the resize isn't replaced by US totals.\n      if (!mobileSheet.isShowing()) {\n        if (typeof restoreMobileSheetPreview === \"function\") {\n          restoreMobileSheetPreview();\n        } else if (typeof showUsMobilePreview === \"function\") {\n          showUsMobilePreview();\n        }\n      }\n    } else {\n      closeMenu();\n      closeSettingsOverlay();\n      // Avoid a stale preview persisting after rotation/resize back to desktop.\n      mobileSheet.hide();\n      if (layerToggleEl && layerToggleDesktopParent && layerToggleEl.parentElement !== layerToggleDesktopParent) {\n        // Reference node may have been removed/re-rendered while we were\n        // in mobile mode \u2014 fall back to appendChild rather than throw.\n        if (layerToggleDesktopNext && layerToggleDesktopNext.parentNode === layerToggleDesktopParent) {\n          layerToggleDesktopParent.insertBefore(layerToggleEl, layerToggleDesktopNext);\n        } else {\n          layerToggleDesktopParent.appendChild(layerToggleEl);\n        }\n      }\n    }\n  }\n\n  // ----- Hamburger dropdown menu -----\n  // `inert` is toggled alongside aria-hidden so closed-menu items are\n  // removed from the tab order \u2014 without forcing display:none, which\n  // would cancel the slide-in animation. As a belt-and-braces fallback\n  // for the rare browser that doesn't support `inert`, also toggle\n  // tabindex on each focusable child.\n  const menuFocusables = menuEl.querySelectorAll(\"a, button, [tabindex]\");\n  function setMenuTabbable(tabbable) {\n    menuFocusables.forEach((el) => {\n      if (tabbable) el.removeAttribute(\"tabindex\");\n      else el.setAttribute(\"tabindex\", \"-1\");\n    });\n  }\n  setMenuTabbable(false);\n\n  function openMenu() {\n    menuEl.setAttribute(\"data-open\", \"true\");\n    menuEl.setAttribute(\"aria-hidden\", \"false\");\n    menuEl.removeAttribute(\"inert\");\n    setMenuTabbable(true);\n    menuToggleEl.setAttribute(\"aria-expanded\", \"true\");\n    menuToggleEl.setAttribute(\"aria-label\", \"Close menu\");\n  }\n  function closeMenu() {\n    menuEl.removeAttribute(\"data-open\");\n    menuEl.setAttribute(\"aria-hidden\", \"true\");\n    menuEl.setAttribute(\"inert\", \"\");\n    setMenuTabbable(false);\n    menuToggleEl.setAttribute(\"aria-expanded\", \"false\");\n    menuToggleEl.setAttribute(\"aria-label\", \"Open menu\");\n  }\n  function isMenuOpen() {\n    return menuEl.getAttribute(\"data-open\") === \"true\";\n  }\n\n  menuToggleEl.addEventListener(\"click\", (e) => {\n    e.stopPropagation();\n    if (isMenuOpen()) closeMenu();\n    else openMenu();\n  });\n\n  // Click outside the menu (and not on the toggle) closes it.\n  document.addEventListener(\"click\", (e) => {\n    if (!isMenuOpen()) return;\n    const target = /** @type {Node} */ (e.target);\n    if (menuEl.contains(target) || menuToggleEl.contains(target)) return;\n    closeMenu();\n  });\n\n  // ----- Settings overlay -----\n  // Focus trap: aria-modal=true requires Tab to cycle inside the dialog and\n  // focus to return to the triggering element on close. We don't apply\n  // `inert` to the rest of the page because the overlay covers the screen\n  // and the existing key handlers already block out-of-overlay interaction.\n  /** @type {Element | null} */\n  let settingsOverlayLastFocused = null;\n\n  function getSettingsFocusables() {\n    return /** @type {HTMLElement[]} */ (Array.from(\n      settingsOverlayEl.querySelectorAll(\n        'a[href], button:not([disabled]), input:not([disabled]):not([type=\"hidden\"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex=\"-1\"])'\n      )\n    )).filter((el) => el.offsetParent !== null || el === document.activeElement);\n  }\n\n  function trapSettingsTab(event) {\n    if (event.key !== \"Tab\" || settingsOverlayEl.getAttribute(\"data-open\") !== \"true\") return;\n    const focusables = getSettingsFocusables();\n    if (focusables.length === 0) {\n      event.preventDefault();\n      if (settingsOverlayCloseEl) settingsOverlayCloseEl.focus();\n      return;\n    }\n    const first = focusables[0];\n    const last = focusables[focusables.length - 1];\n    const active = document.activeElement;\n    if (event.shiftKey && (active === first || !settingsOverlayEl.contains(active))) {\n      event.preventDefault();\n      last.focus();\n    } else if (!event.shiftKey && active === last) {\n      event.preventDefault();\n      first.focus();\n    }\n  }\n\n  function openSettingsOverlay() {\n    settingsOverlayLastFocused = document.activeElement;\n    settingsOverlayEl.setAttribute(\"data-open\", \"true\");\n    settingsOverlayEl.setAttribute(\"aria-hidden\", \"false\");\n    if (settingsFabEl) settingsFabEl.setAttribute(\"aria-expanded\", \"true\");\n    document.body.classList.add(\"map-overlay-open\");\n    document.addEventListener(\"keydown\", trapSettingsTab, true);\n    const focusTarget = settingsOverlayCloseEl;\n    if (focusTarget) focusTarget.focus({ preventScroll: true });\n  }\n\n  function closeSettingsOverlay() {\n    settingsOverlayEl.removeAttribute(\"data-open\");\n    settingsOverlayEl.setAttribute(\"aria-hidden\", \"true\");\n    if (settingsFabEl) settingsFabEl.setAttribute(\"aria-expanded\", \"false\");\n    const sidePanelOpen = sidePanelEl && !sidePanelEl.classList.contains(\"is-collapsed\");\n    if (!sidePanelOpen) document.body.classList.remove(\"map-overlay-open\");\n    document.removeEventListener(\"keydown\", trapSettingsTab, true);\n    if (settingsOverlayLastFocused && typeof (/** @type {HTMLElement} */ (settingsOverlayLastFocused)).focus === \"function\") {\n      /** @type {HTMLElement} */ (settingsOverlayLastFocused).focus();\n    }\n    settingsOverlayLastFocused = null;\n  }\n\n  // ----- Menu items -----\n  if (settingsFabEl) {\n    settingsFabEl.addEventListener(\"click\", () => {\n      closeMenu();\n      if (settingsOverlayEl.getAttribute(\"data-open\") === \"true\") closeSettingsOverlay();\n      else openSettingsOverlay();\n    });\n  }\n  if (settingsOverlayCloseEl) {\n    settingsOverlayCloseEl.addEventListener(\"click\", closeSettingsOverlay);\n  }\n  if (infoFabEl) {\n    infoFabEl.addEventListener(\"click\", () => {\n      closeMenu();\n      openMapInfoModal(infoFabEl);\n    });\n  }\n  if (resetBtnEl) {\n    resetBtnEl.addEventListener(\"click\", () => {\n      // Country-aware deselect (plan unit E FIX \u2460): resetMapToNation owns the\n      // selection reset AND the recenter, so on mobile a Canadian selection\n      // rewinds to the Canada nation view (/us-ai-map/ca/ + Canada-fit) instead\n      // of the old unconditional US clear + US recenter.\n      closeMenu();\n      resetMapToNation();\n    });\n  }\n  // Home link closes the menu before navigating away (purely cosmetic).\n  const backLinkEl = document.getElementById(\"map-mobile-back\");\n  if (backLinkEl) backLinkEl.addEventListener(\"click\", () => closeMenu());\n\n  // Capture phase + stopImmediatePropagation: a second document-level\n  // Escape handler in init() clears selection + resets zoom. Without\n  // stopping propagation here, dismissing the menu/overlay would also\n  // wipe map state \u2014 confusing for users.\n  document.addEventListener(\"keydown\", (event) => {\n    if (event.key !== \"Escape\") return;\n    if (isMenuOpen()) {\n      closeMenu();\n      event.stopImmediatePropagation();\n      event.preventDefault();\n      return;\n    }\n    if (settingsOverlayEl.getAttribute(\"data-open\") === \"true\") {\n      closeSettingsOverlay();\n      event.stopImmediatePropagation();\n      event.preventDefault();\n    }\n  }, true);\n\n  // Sync body.map-overlay-open with side-panel state on mobile.\n  function syncSidePanelOverlayClass() {\n    if (!isMobileLayout() || !sidePanelEl) return;\n    const collapsed = sidePanelEl.classList.contains(\"is-collapsed\");\n    if (collapsed && settingsOverlayEl.getAttribute(\"data-open\") !== \"true\") {\n      document.body.classList.remove(\"map-overlay-open\");\n    } else if (!collapsed) {\n      document.body.classList.add(\"map-overlay-open\");\n    }\n  }\n\n  if (sidePanelEl && \"MutationObserver\" in window) {\n    const obs = new MutationObserver(syncSidePanelOverlayClass);\n    obs.observe(sidePanelEl, { attributes: true, attributeFilter: [\"class\"] });\n  }\n\n  mq.addEventListener(\"change\", applyLayoutForMode);\n  applyLayoutForMode();\n}\n", "// @ts-check\n\n// Top-level DOM nodes only. Per-feature queries live inside each feature module's setup().\n// See refactor plan \u00A72.3: avoid the god-registry pattern.\n\n/**\n * @typedef {Object} TopLevelNodes\n * @property {HTMLElement | null} rootEl\n * @property {SVGSVGElement | null} svgNode\n * @property {HTMLElement | null} tooltipRoot\n * @property {HTMLElement | null} hoverCardRoot\n * @property {HTMLElement | null} sidePanelRoot\n * @property {HTMLElement | null} infoModalRoot\n * @property {HTMLElement | null} treemapTooltipRoot\n */\n\n/** @returns {TopLevelNodes} */\nexport function queryTopLevelNodes() {\n  return {\n    rootEl: /** @type {HTMLElement | null} */ (document.getElementById(\"us-ai-map-root\")),\n    svgNode: /** @type {SVGSVGElement | null} */ (document.getElementById(\"us-ai-map-svg\")),\n    tooltipRoot: /** @type {HTMLElement | null} */ (document.querySelector(\"[data-map-tooltip]\")),\n    hoverCardRoot: /** @type {HTMLElement | null} */ (document.querySelector(\"[data-map-hover-card]\")),\n    sidePanelRoot: /** @type {HTMLElement | null} */ (document.querySelector(\"[data-map-side-panel]\")),\n    infoModalRoot: /** @type {HTMLElement | null} */ (document.querySelector(\"[data-map-info-modal]\")),\n    treemapTooltipRoot: /** @type {HTMLElement | null} */ (document.querySelector(\"[data-map-treemap-tooltip]\")),\n  };\n}\n", "// @ts-check\n\n// Entry-point DOM element handles for the map boot path.\n//\n// These are the flat `getElementById` / `querySelector` lookups that\n// us_ai_map.js builds once at boot and threads into the controllers\n// (side panel, top-occupations, treemap nav, zoom, etc.). They were\n// previously inlined at the top of bootMap(); pulling them into a single\n// `queryMapElements()` keeps us_ai_map.js focused on orchestration.\n//\n// This is intentionally a flat one-shot bundle for the *entry point* only \u2014\n// it does NOT replace the per-feature query convention documented in dom.js\n// (\u00A72.3 \"avoid the god-registry pattern\"). Those per-feature queries still\n// live inside each feature module's setup(). This function only relocates the\n// lookups bootMap() was already doing verbatim, with zero behavior change.\n\n/**\n * Query every top-of-boot DOM handle bootMap() consumes (excluding the\n * top-level nodes queried by dom.js's queryTopLevelNodes()). Returns the same\n * element references, looked up at the same time, as the original inline block.\n *\n * @returns {Record<string, HTMLElement | Element | null>}\n */\nexport function queryMapElements() {\n  return {\n    hoverTitleEl: document.getElementById(\"map-hover-title\"),\n    hoverWorkersEl: document.getElementById(\"map-hover-workers\"),\n    hoverWageEl: document.getElementById(\"map-hover-wage\"),\n    selectedTypeEl: document.getElementById(\"selected-type\"),\n    selectedNameEl: document.getElementById(\"selected-name\"),\n    topOccupationsDetailEl: document.getElementById(\"map-top-occupations-detail\"),\n    topOccupationsDetailMetaEl: document.getElementById(\"map-top-occupations-detail-meta\"),\n    topOccupationsStatusEl: document.getElementById(\"map-top-occupations-status\"),\n    topOccupationsTreemapEl: document.getElementById(\"map-top-occupations-treemap\"),\n    topOccupationsTasksEl: document.getElementById(\"map-top-occupations-tasks\"),\n    treemapNavRootEl: document.getElementById(\"map-treemap-nav\"),\n    treemapNavRegionLabelEl: document.getElementById(\"map-treemap-nav-region-label\"),\n    treemapNavIndustryBtnEl: document.getElementById(\"map-treemap-nav-industry-btn\"),\n    treemapNavIndustryLabelEl: document.getElementById(\"map-treemap-nav-industry-label\"),\n    treemapNavJobsBtnEl: document.getElementById(\"map-treemap-nav-jobs-btn\"),\n    treemapNavJobsLabelEl: document.getElementById(\"map-treemap-nav-jobs-label\"),\n    treemapNavIndustryPopoverEl: document.getElementById(\"map-treemap-nav-industry-popover\"),\n    treemapNavIndustrySearchEl: document.getElementById(\"map-treemap-nav-industry-search\"),\n    treemapNavIndustryClearEl: document.getElementById(\"map-treemap-nav-industry-clear\"),\n    treemapNavIndustryListEl: document.getElementById(\"map-treemap-nav-industry-list\"),\n    treemapNavJobsPopoverEl: document.getElementById(\"map-treemap-nav-jobs-popover\"),\n    treemapNavJobsSearchEl: document.getElementById(\"map-treemap-nav-jobs-search\"),\n    treemapNavJobsClearEl: document.getElementById(\"map-treemap-nav-jobs-clear\"),\n    treemapNavJobsListEl: document.getElementById(\"map-treemap-nav-jobs-list\"),\n    sidePanelToggleEl: document.getElementById(\"map-side-panel-toggle\"),\n    panelCloseEl: document.getElementById(\"map-panel-close\"),\n    panelBackTop5El: document.getElementById(\"map-panel-back-top5\"),\n    panelExpandEl: document.getElementById(\"map-panel-expand\"),\n    treemapNavJobsChevronEl: document.getElementById(\"map-treemap-nav-jobs-chevron\"),\n    treemapNavJobsClearJobEl: document.getElementById(\"map-treemap-nav-jobs-clear-job\"),\n    treemapNavIndustryChevronEl: document.getElementById(\"map-treemap-nav-industry-chevron\"),\n    treemapNavIndustryClearIndustryEl: document.getElementById(\"map-treemap-nav-industry-clear-industry\"),\n    // Mobile treemap card hosts (inside the bottom sheet's expanded mount).\n    // These mirror the desktop refs by id; the mobile orchestrator is a\n    // separate instance and never touches the desktop hosts.\n    mobileTreemapDetailEl: document.getElementById(\"map-mobile-treemap-detail\"),\n    mobileTreemapDetailMetaEl: document.getElementById(\"map-mobile-treemap-detail-meta\"),\n    mobileTreemapStatusEl: document.getElementById(\"map-mobile-treemap-status\"),\n    mobileTreemapEl: document.getElementById(\"map-mobile-treemap\"),\n    mobileTreemapTasksEl: document.getElementById(\"map-mobile-treemap-tasks\"),\n    mobileTreemapNavRootEl: document.getElementById(\"map-mobile-treemap-nav\"),\n    mobileTreemapNavRegionLabelEl: document.getElementById(\"map-mobile-treemap-nav-region-label\"),\n    mobileTreemapNavIndustryBtnEl: document.getElementById(\"map-mobile-treemap-nav-industry-btn\"),\n    mobileTreemapNavIndustryLabelEl: document.getElementById(\"map-mobile-treemap-nav-industry-label\"),\n    mobileTreemapNavJobsBtnEl: document.getElementById(\"map-mobile-treemap-nav-jobs-btn\"),\n    mobileTreemapNavJobsLabelEl: document.getElementById(\"map-mobile-treemap-nav-jobs-label\"),\n    mobileTreemapNavIndustryPopoverEl: document.getElementById(\"map-mobile-treemap-nav-industry-popover\"),\n    mobileTreemapNavIndustrySearchEl: document.getElementById(\"map-mobile-treemap-nav-industry-search\"),\n    mobileTreemapNavIndustryClearEl: document.getElementById(\"map-mobile-treemap-nav-industry-clear\"),\n    mobileTreemapNavIndustryListEl: document.getElementById(\"map-mobile-treemap-nav-industry-list\"),\n    mobileTreemapNavJobsPopoverEl: document.getElementById(\"map-mobile-treemap-nav-jobs-popover\"),\n    mobileTreemapNavJobsSearchEl: document.getElementById(\"map-mobile-treemap-nav-jobs-search\"),\n    mobileTreemapNavJobsClearEl: document.getElementById(\"map-mobile-treemap-nav-jobs-clear\"),\n    mobileTreemapNavJobsListEl: document.getElementById(\"map-mobile-treemap-nav-jobs-list\"),\n    mobileTreemapNavJobsChevronEl: document.getElementById(\"map-mobile-treemap-nav-jobs-chevron\"),\n    mobileTreemapNavJobsClearJobEl: document.getElementById(\"map-mobile-treemap-nav-jobs-clear-job\"),\n    mobileTreemapNavIndustryChevronEl: document.getElementById(\"map-mobile-treemap-nav-industry-chevron\"),\n    mobileTreemapNavIndustryClearIndustryEl: document.getElementById(\"map-mobile-treemap-nav-industry-clear-industry\"),\n    layerToggleMountEl: document.getElementById(\"map-layer-toggle\"),\n    infoModalDialogEl: document.querySelector(\"#map-info-modal .map-info-modal__dialog\"),\n    homeIconEl: document.getElementById(\"map-home-icon\"),\n    zoomControlsEl: document.getElementById(\"map-zoom-controls\"),\n    // Selected-region stat readouts (were queried lower in bootMap, after the\n    // hover/zoom helpers; relocated here so all entry-point handles live in one\n    // place \u2014 the lookups are order-independent pure DOM reads).\n    selectedTotalWorkforceEl: document.getElementById(\"selected-total-workforce\"),\n    selectedTotalWageBillEl: document.getElementById(\"selected-total-wage-bill\"),\n    selectedExposedWageBillEl: document.getElementById(\"selected-exposed-wage-bill\"),\n    selectedExposedWorkforceEl: document.getElementById(\"selected-exposed-workforce\"),\n    selectedWorkforceGaugeValueEl: document.getElementById(\"selected-workforce-gauge-value\"),\n    selectedWorkforceGaugeProgressEl: document.getElementById(\"selected-workforce-gauge-progress\"),\n    selectedWageBillGaugeValueEl: document.getElementById(\"selected-wage-bill-gauge-value\"),\n    selectedWageBillGaugeProgressEl: document.getElementById(\"selected-wage-bill-gauge-progress\"),\n  };\n}\n", "// @ts-check\n\nimport { createGradientLegend } from \"../map/legend.js\";\n\n// Builds the combined layer/metric/legend panel scaffold that hosts the\n// LayerToggle widget, the MetricToggle widget, and the gradient legend.\n//\n// This is the DOM-construction block that previously lived inline at the top\n// of us_ai_map.js's init(): it clears the mount, builds the\n// `.map-layer-toggle--combined` section (a top row with a layer host + metric\n// host, plus a legend group below), mounts the legend, and returns the two\n// host elements the toggle widgets render into. Behavior is identical to the\n// original inline block \u2014 only relocated.\n\n/**\n * @param {HTMLElement | null} layerToggleMountEl\n * @returns {{ layerToggleHostEl: HTMLElement | null, metricToggleHostEl: HTMLElement | null }}\n */\nexport function buildLayerTogglePanel(layerToggleMountEl) {\n  // When the mount is absent the original code left both hosts at their\n  // initial values (layer host = the (null) mount, metric host = null) and\n  // skipped legend creation. Preserve that exactly.\n  let layerToggleHostEl = layerToggleMountEl;\n  let metricToggleHostEl = null;\n\n  if (layerToggleMountEl) {\n    layerToggleMountEl.innerHTML = \"\";\n    const combinedPanel = document.createElement(\"section\");\n    combinedPanel.className = \"map-layer-toggle map-layer-toggle--combined\";\n\n    const topRow = document.createElement(\"div\");\n    topRow.className = \"map-layer-toggle--combined-top-row\";\n\n    const layerHost = document.createElement(\"div\");\n    layerHost.className = \"map-layer-toggle--combined-group\";\n\n    const metricHost = document.createElement(\"div\");\n    metricHost.className = \"map-layer-toggle--combined-group\";\n\n    const legendHost = document.createElement(\"div\");\n    legendHost.className = \"map-layer-toggle--legend-group\";\n\n    topRow.appendChild(layerHost);\n    topRow.appendChild(metricHost);\n\n    combinedPanel.appendChild(topRow);\n    combinedPanel.appendChild(legendHost);\n    layerToggleMountEl.appendChild(combinedPanel);\n\n    layerToggleHostEl = layerHost;\n    metricToggleHostEl = metricHost;\n    createGradientLegend(legendHost);\n  }\n\n  return { layerToggleHostEl, metricToggleHostEl };\n}\n", "// @ts-check\n\nimport { currentSelection } from \"./state/store.js\";\nimport { getRegionMetrics, nation } from \"./state/caches.js\";\n\n// Region-snapshot helpers for the mobile bottom sheet.\n//\n// Two cohesive functions, relocated verbatim from us_ai_map.js's init():\n//   - showUsMobilePreview(): dock the sheet at peek with US-wide nation stats.\n//   - restoreMobileSheetPreview(): re-show the sheet for whatever the user\n//     currently has selected (used when re-entering the mobile breakpoint so a\n//     state/MSA selection isn't clobbered by the default US-wide preview).\n//\n// `nation`, `currentSelection`, and `getRegionMetrics` are module-level state\n// (caches.js / store.js) and imported directly so the single source of truth\n// is preserved. `isMobileLayout` and `mobileSheet` are boot-time closures and\n// injected so this module shares the orchestrator's instances rather than\n// duplicating them.\n\n/**\n * @param {{\n *   isMobileLayout: () => boolean,\n *   mobileSheet: { show: (meta: any) => void },\n * }} deps\n * @returns {{\n *   showUsMobilePreview: () => void,\n *   restoreMobileSheetPreview: () => void,\n * }}\n */\nexport function createRegionSnapshot({ isMobileLayout, mobileSheet }) {\n  function showUsMobilePreview() {\n    if (!isMobileLayout()) return;\n    mobileSheet.show({\n      name: \"United States\",\n      type: \"Nation\",\n      totalWorkers: nation.totalWorkforce,\n      wageBill: nation.totalWageBill,\n      exposureStats: nation.exposure,\n    });\n  }\n\n  // Re-show the sheet for whatever the user currently has selected.\n  // Used when re-entering the mobile breakpoint so a state/MSA selection\n  // doesn't get clobbered by a default US-wide preview while\n  // currentSelection still points at the region.\n  function restoreMobileSheetPreview() {\n    if (!isMobileLayout()) return;\n    const selection = currentSelection.get();\n    if (!selection || selection.kind === \"nation\") {\n      showUsMobilePreview();\n      return;\n    }\n    // nation is handled above; every remaining selection.kind is one of the 6\n    // region kinds (the old else branch was the nonmetro case), so delegating\n    // to getRegionMetrics returns identical raw values.\n    const { totalWorkers, wageBill, exposureStats } = getRegionMetrics(\n      selection.kind,\n      selection.code,\n    );\n    mobileSheet.show({\n      name: selection.name,\n      type: selection.label,\n      totalWorkers,\n      wageBill,\n      exposureStats,\n    });\n  }\n\n  return { showUsMobilePreview, restoreMobileSheetPreview };\n}\n", "// @ts-check\n\nimport { selectedLayer } from \"./state/store.js\";\n\n// \"Locate me\" geolocation flow, relocated verbatim from us_ai_map.js's init().\n//\n// Self-contained unit: given a browser geolocation fix, it finds the map\n// feature (state/province in state mode, nonmetro/CA area in area mode) that\n// contains the point and synthesizes a click on it so the normal selection\n// path runs. A transient status pill reports unsupported/denied/off-map cases.\n//\n// `d3` is the global from the CDN bundle (same as us_ai_map.js \u2014 it is not an\n// ES import anywhere in this codebase). `svgNode` is injected because the\n// hit-test queries live SVG paths owned by the orchestrator. The\n// #map-locate-status element and the hide timer are local to this flow, so the\n// lookup + mutable timer live inside this factory's closure.\n\n/* global d3 */\n\n/**\n * @param {{ svgNode: SVGSVGElement }} deps\n * @returns {{ locateUserAndSelect: (btn: HTMLButtonElement) => void }}\n */\nexport function createGeolocate({ svgNode }) {\n  function findFeatureAtLngLat(lngLat) {\n    const layerMode = selectedLayer.get();\n    // In state mode the click handlers live on .states-layer/.provinces-layer\n    // paths; in area mode they live on .nonmetros-layer/.ca-areas-layer paths\n    // (which together cover US metro/nonmetro and Canadian CMA/rest areas).\n    const selector = layerMode === \"state\"\n      ? \".states-layer path, .provinces-layer path\"\n      : \".nonmetros-layer path, .ca-areas-layer path\";\n    const nodes = svgNode.querySelectorAll(selector);\n    for (const node of nodes) {\n      const feature = /** @type {any} */ (node).__data__;\n      if (feature && d3.geoContains(feature, lngLat)) {\n        return node;\n      }\n    }\n    return null;\n  }\n\n  const locateStatusEl = document.getElementById(\"map-locate-status\");\n  let locateStatusHideTimer = null;\n  function showLocateStatus(message) {\n    if (!locateStatusEl) return;\n    locateStatusEl.textContent = message;\n    locateStatusEl.hidden = false;\n    // Force reflow before adding the class so the transition runs.\n    void locateStatusEl.offsetWidth;\n    locateStatusEl.classList.add(\"is-visible\");\n    if (locateStatusHideTimer) window.clearTimeout(locateStatusHideTimer);\n    locateStatusHideTimer = window.setTimeout(() => {\n      locateStatusEl.classList.remove(\"is-visible\");\n      window.setTimeout(() => {\n        if (!locateStatusEl.classList.contains(\"is-visible\")) {\n          locateStatusEl.hidden = true;\n        }\n      }, 200);\n    }, 5000);\n  }\n\n  // Bounding longitudes/latitudes are loose \u2014 they only need to disambiguate\n  // \"user is in AK/HI/PR\" from \"user is somewhere else off-map\" so the\n  // message can be specific. Tighter geofencing isn't required.\n  function isInUnmappedUsTerritory(lngLat) {\n    const [lng, lat] = lngLat;\n    const inAlaska = lng >= -180 && lng <= -130 && lat >= 51 && lat <= 72;\n    const inHawaii = lng >= -161 && lng <= -154 && lat >= 18 && lat <= 23;\n    const inPuertoRico = lng >= -68 && lng <= -65 && lat >= 17 && lat <= 19;\n    return inAlaska || inHawaii || inPuertoRico;\n  }\n\n  function locateUserAndSelect(btn) {\n    if (!navigator.geolocation) {\n      showLocateStatus(\"Geolocation isn't supported by your browser.\");\n      return;\n    }\n    btn.disabled = true;\n    btn.classList.add(\"is-loading\");\n    navigator.geolocation.getCurrentPosition(\n      (position) => {\n        btn.disabled = false;\n        btn.classList.remove(\"is-loading\");\n        const lngLat = [position.coords.longitude, position.coords.latitude];\n        const node = findFeatureAtLngLat(lngLat);\n        if (!node) {\n          const msg = isInUnmappedUsTerritory(lngLat)\n            ? \"This map covers the contiguous U.S. and Canada \u2014 Alaska, Hawaii, and Puerto Rico aren't included.\"\n            : \"Your location doesn't appear to be within the mapped regions.\";\n          showLocateStatus(msg);\n          return;\n        }\n        node.dispatchEvent(new MouseEvent(\"click\", { bubbles: true, cancelable: true }));\n      },\n      (error) => {\n        btn.disabled = false;\n        btn.classList.remove(\"is-loading\");\n        const msg = error.code === error.PERMISSION_DENIED\n          ? \"Location permission denied.\"\n          : \"Unable to determine your location.\";\n        showLocateStatus(msg);\n      },\n      { enableHighAccuracy: false, timeout: 10000, maximumAge: 60000 },\n    );\n  }\n\n  return { locateUserAndSelect };\n}\n", "// @ts-check\nimport { FALLBACK_COLORS, LUCIDE_HOME_ICON, MOBILE_QUERY, LAYER_MODE_STATE, LAYER_MODE_AREA, LAYER_MODE_COUNTRY } from \"./config.js\";\nimport { updateGradientLegend } from \"./map/legend.js\";\nimport { createZoomController } from \"./map/zoom.js\";\nimport { computeMapViewport } from \"./map/viewport.js\";\nimport {\n  ensureStatesLoaded as ensureStatesLoadedData,\n  getStatesFeatures,\n  getUsCountryFeature,\n  getUsStateBorders,\n} from \"./data/states.js\";\nimport {\n  ensureMsaMetricsLoaded as ensureMsaMetricsLoadedData,\n  ensureMsasTopologyLoaded as ensureMsasTopologyLoadedData,\n  getMsaFeatures,\n} from \"./data/msas.js\";\nimport {\n  ensureNonmetrosLoaded as ensureNonmetrosLoadedData,\n  getDetailAreaFeatures,\n} from \"./data/nonmetros.js\";\nimport {\n  ensureProvincesLoaded as ensureProvincesLoadedData,\n  getProvinceFeatures,\n  getCaCountryFeature,\n  getCaProvinceBorders,\n} from \"./data/provinces.js\";\nimport {\n  ensureCaAreasLoaded as ensureCaAreasLoadedData,\n  getCaAreaFeatures,\n} from \"./data/ca_areas.js\";\nimport {\n  ensureWorldLoaded as ensureWorldLoadedData,\n  getWorldLandFeature,\n  getWorldCountryBorders,\n} from \"./data/world.js\";\nimport { bustStaleClientCachesIfNeeded } from \"./data/cache-version.js\";\nimport {\n  ensureCountyBordersLoaded as ensureCountyBordersLoadedData,\n  getCountyBorders,\n} from \"./data/counties.js\";\nimport {\n  ensureCaCdBordersLoaded as ensureCaCdBordersLoadedData,\n  getCaCdBorders,\n} from \"./data/ca_census_divisions.js\";\nimport { ensureNationLoaded as ensureNationLoadedData } from \"./data/nation.js\";\nimport {\n  ensureGeoUrlsLoaded,\n  keyForPath,\n  urlForKey,\n} from \"./state/geo_urls.js\";\nimport { ServiceUnavailableError } from \"./data/fetch.js\";\nimport {\n  normalizeMsaCode,\n  normalizeAreaCode,\n  normalizeCmaCode,\n  normalizeProvinceCode,\n  getStateCode,\n  getMsaCode,\n  getProvinceCode,\n} from \"./util/normalize.js\";\nimport { LayerToggle, COUNTRY_CA, COUNTRY_US } from \"./ui/layer-toggle.js\";\nimport { MetricToggle } from \"./ui/metric-toggle.js\";\nimport { createInfoModal } from \"./ui/info-modal.js\";\nimport { installEscapeArbiter } from \"./ui/keyboard.js\";\nimport { createHoverTooltip } from \"./ui/tooltip.js\";\nimport { createSelectionController } from \"./map/selection.js\";\nimport { createLayersController } from \"./map/layers.js\";\nimport { createRenderController } from \"./map/render.js\";\nimport { setupPostLoadHandlers } from \"./map/post-load.js\";\nimport { selectedLayer, selectedMetric, currentSelection } from \"./state/store.js\";\nimport {\n  stateMetricsByCode,\n  msaMetricsByCode,\n  nonmetroMetricsByCode,\n  provinceMetricsByCode,\n  cmaMetricsByCode,\n  caNonmetroMetricsByCode,\n  nation,\n  nationCa,\n} from \"./state/caches.js\";\nimport {\n  getStatesColorScale,\n  getMsasColorScale,\n  getNonmetroColorScale,\n  getMetricValue,\n  rebuildColorScales,\n} from \"./map/colors.js\";\nimport { createSidePanelController } from \"./panel/side-panel.js\";\nimport { createMobileSheet } from \"./panel/mobile-sheet.js\";\nimport { createTopOccupationsController } from \"./panel/top-occupations/index.js\";\nimport { createMobileTopOccupationsController } from \"./panel/top-occupations/mobile.js\";\nimport { setupMobileShell } from \"./ui/mobile-shell.js\";\nimport { queryTopLevelNodes } from \"./dom.js\";\nimport { queryMapElements } from \"./els.js\";\nimport { buildLayerTogglePanel } from \"./ui/layer-toggle-panel.js\";\nimport { createRegionSnapshot } from \"./regionSnapshot.js\";\nimport { createGeolocate } from \"./geolocate.js\";\nimport { measureAsync } from \"./util/perf.js\";\n\n// Single cached MediaQueryList for the mobile-layout media query. `isMobileLayout()`\n// is hot (called on every resize tick plus several user-event paths), and\n// allocating a fresh MQL per call is wasteful even though browsers de-dupe\n// internally on the same query string.\nconst MOBILE_MQ = window.matchMedia(MOBILE_QUERY);\n\n/** @type {import(\"./types.js\").Cfg} */\n// @ts-ignore window.US_AI_MAP_CONFIG global\nconst cfg = window.US_AI_MAP_CONFIG || {};\nbustStaleClientCachesIfNeeded(cfg);\nif (window.d3 && window.topojson) {\n  bootMap();\n}\n\nfunction bootMap() {\n  const topNodes = queryTopLevelNodes();\n  const rootEl = topNodes.rootEl;\n  const svgNode = topNodes.svgNode;\n  const tooltipEl = topNodes.tooltipRoot;\n  const treemapTooltipEl = topNodes.treemapTooltipRoot;\n  const hoverCardEl = topNodes.hoverCardRoot;\n  const sidePanelEl = topNodes.sidePanelRoot;\n  const infoModalEl = topNodes.infoModalRoot;\n\n  // Entry-point DOM handles. Relocated to els.js (queryMapElements) \u2014 same\n  // getElementById/querySelector lookups, same time, destructured back into the\n  // local names the rest of bootMap() uses. See els.js for the not-a-god-\n  // registry rationale.\n  const {\n    hoverTitleEl,\n    hoverWorkersEl,\n    hoverWageEl,\n    selectedTypeEl,\n    selectedNameEl,\n    topOccupationsDetailEl,\n    topOccupationsDetailMetaEl,\n    topOccupationsStatusEl,\n    topOccupationsTreemapEl,\n    topOccupationsTasksEl,\n    treemapNavRootEl,\n    treemapNavRegionLabelEl,\n    treemapNavIndustryBtnEl,\n    treemapNavIndustryLabelEl,\n    treemapNavJobsBtnEl,\n    treemapNavJobsLabelEl,\n    treemapNavIndustryPopoverEl,\n    treemapNavIndustrySearchEl,\n    treemapNavIndustryClearEl,\n    treemapNavIndustryListEl,\n    treemapNavJobsPopoverEl,\n    treemapNavJobsSearchEl,\n    treemapNavJobsClearEl,\n    treemapNavJobsListEl,\n    sidePanelToggleEl,\n    panelCloseEl,\n    panelBackTop5El,\n    panelExpandEl,\n    treemapNavJobsChevronEl,\n    treemapNavJobsClearJobEl,\n    treemapNavIndustryChevronEl,\n    treemapNavIndustryClearIndustryEl,\n    mobileTreemapDetailEl,\n    mobileTreemapDetailMetaEl,\n    mobileTreemapStatusEl,\n    mobileTreemapEl,\n    mobileTreemapTasksEl,\n    mobileTreemapNavRootEl,\n    mobileTreemapNavRegionLabelEl,\n    mobileTreemapNavIndustryBtnEl,\n    mobileTreemapNavIndustryLabelEl,\n    mobileTreemapNavJobsBtnEl,\n    mobileTreemapNavJobsLabelEl,\n    mobileTreemapNavIndustryPopoverEl,\n    mobileTreemapNavIndustrySearchEl,\n    mobileTreemapNavIndustryClearEl,\n    mobileTreemapNavIndustryListEl,\n    mobileTreemapNavJobsPopoverEl,\n    mobileTreemapNavJobsSearchEl,\n    mobileTreemapNavJobsClearEl,\n    mobileTreemapNavJobsListEl,\n    mobileTreemapNavJobsChevronEl,\n    mobileTreemapNavJobsClearJobEl,\n    mobileTreemapNavIndustryChevronEl,\n    mobileTreemapNavIndustryClearIndustryEl,\n    layerToggleMountEl,\n    infoModalDialogEl,\n    homeIconEl,\n    zoomControlsEl,\n    selectedTotalWorkforceEl,\n    selectedTotalWageBillEl,\n    selectedExposedWageBillEl,\n    selectedExposedWorkforceEl,\n    selectedWorkforceGaugeValueEl,\n    selectedWorkforceGaugeProgressEl,\n    selectedWageBillGaugeValueEl,\n    selectedWageBillGaugeProgressEl,\n  } = queryMapElements();\n  const gatedUiElements = [tooltipEl, hoverCardEl, sidePanelToggleEl, layerToggleMountEl, sidePanelEl, zoomControlsEl];\n  const infoModal = createInfoModal({\n    modalEl: infoModalEl,\n    dialogEl: /** @type {HTMLElement | null} */ (infoModalDialogEl),\n  });\n  const hoverTooltip = createHoverTooltip({\n    hoverCardEl,\n    hoverTitleEl,\n    hoverWorkersEl,\n    hoverWageEl,\n    tooltipEl,\n  });\n  const openMapInfoModal = infoModal.open;\n  const setupMapInfoModal = infoModal.setup;\n  const showTooltip = hoverTooltip.show;\n  const hideTooltip = hoverTooltip.hide;\n  const positionTooltip = hoverTooltip.position;\n\n  let resizeRaf = null;\n  let currentTransform = d3.zoomIdentity;\n  let userHasInteractedWithZoom = false;\n  let hoveredFeatureElement = null;\n  let hasRevealedBaseMap = false;\n  let hasRevealedDataLayers = false;\n  let mapColors = {\n    noData: FALLBACK_COLORS.noData,\n    noDataNonmetro: FALLBACK_COLORS.noDataNonmetro,\n    worldLand: FALLBACK_COLORS.worldLand,\n    worldOcean: FALLBACK_COLORS.worldOcean,\n  };\n\n  const svg = d3.select(svgNode);\n  const mapRoot = svg.append(\"g\").attr(\"class\", \"map-root\");\n  const worldLayer = mapRoot.append(\"g\").attr(\"class\", \"world-layer\");\n  const dataLayers = mapRoot.append(\"g\").attr(\"class\", \"map-data-layers\");\n  const statesLayer = dataLayers.append(\"g\").attr(\"class\", \"states-layer\");\n  // Country fill layer (whole-country polygons for the LAYER_MODE_COUNTRY view).\n  // Placed low in the stack \u2014 before the borders and selection outline groups \u2014\n  // so those overlays always paint on top. Hidden until country mode is active.\n  const countryLayer = dataLayers.append(\"g\").attr(\"class\", \"country-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const provincesLayer = dataLayers.append(\"g\").attr(\"class\", \"provinces-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const msasLayer = dataLayers.append(\"g\").attr(\"class\", \"msas-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const nonmetrosLayer = dataLayers.append(\"g\").attr(\"class\", \"nonmetros-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const caAreasLayer = dataLayers.append(\"g\").attr(\"class\", \"ca-areas-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const countyBordersLayer = dataLayers.append(\"g\").attr(\"class\", \"county-borders-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const caCdBordersLayer = dataLayers.append(\"g\").attr(\"class\", \"ca-cd-borders-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const metroNonmetroBordersLayer = dataLayers.append(\"g\").attr(\"class\", \"metro-nonmetro-borders-layer\").style(\"opacity\", 0).style(\"pointer-events\", \"none\");\n  const selectionOutlineLayer = dataLayers.append(\"g\").attr(\"class\", \"selection-outline-layer\").style(\"pointer-events\", \"none\");\n\n  const projection = d3.geoNaturalEarth1().rotate([100, 0]);\n  let pathGenerator = d3.geoPath(projection);\n\n  /** @type {any} */\n  let sidePanelController = null;\n  /** @type {import(\"./ui/layer-toggle.js\").LayerToggle | null} */\n  let layerToggle = null;\n  /** @type {any} */\n  let topOccupationsController = null;\n  /** @type {any} */\n  let mobileTopOccupationsController = null;\n\n  function getCssColorVariable(name, fallback) {\n    const rootStyles = window.getComputedStyle(document.documentElement);\n    const rawValue = rootStyles.getPropertyValue(name);\n    const value = rawValue ? rawValue.trim() : \"\";\n    return value || fallback;\n  }\n\n  function readMapColorsFromCss() {\n    return {\n      noData: getCssColorVariable(\"--map-no-data\", FALLBACK_COLORS.noData),\n      noDataNonmetro: getCssColorVariable(\"--map-no-data-nonmetro\", FALLBACK_COLORS.noDataNonmetro),\n      worldLand: getCssColorVariable(\"--map-world-land\", FALLBACK_COLORS.worldLand),\n      worldOcean: getCssColorVariable(\"--map-world-ocean\", FALLBACK_COLORS.worldOcean),\n    };\n  }\n\n  function getStateFeatureFill(feature) {\n    const code = getStateCode(feature);\n    const metrics = stateMetricsByCode.get(code);\n    const metricValue = getMetricValue(metrics);\n    return metricValue == null ? mapColors.noData : getStatesColorScale()(metricValue);\n  }\n\n  function getMsaFeatureFill(feature) {\n    const code = getMsaCode(feature);\n    const metrics = msaMetricsByCode.get(code);\n    const metricValue = getMetricValue(metrics);\n    return metricValue == null ? mapColors.noData : getMsasColorScale()(metricValue);\n  }\n\n  function getAreaFeatureFill(feature) {\n    const areaInfo = feature && feature.properties ? feature.properties : null;\n    if (!areaInfo) {\n      return mapColors.noData;\n    }\n    const areaCode = String(areaInfo.area_code || \"\").trim();\n    if (areaInfo.area_type === \"metro\") {\n      const metrics = msaMetricsByCode.get(normalizeMsaCode(areaCode));\n      const metricValue = getMetricValue(metrics);\n      return metricValue == null ? mapColors.noData : getMsasColorScale()(metricValue);\n    }\n    const metrics = nonmetroMetricsByCode.get(normalizeAreaCode(areaCode));\n    const metricValue = getMetricValue(metrics);\n    return metricValue == null ? mapColors.noDataNonmetro : getNonmetroColorScale()(metricValue);\n  }\n\n  function getProvinceFeatureFill(feature) {\n    const code = getProvinceCode(feature);\n    const metrics = provinceMetricsByCode.get(code);\n    const metricValue = getMetricValue(metrics);\n    // Same scale as US states \u2014 getStatesColorScale() is built from the\n    // combined state+province domain (map/colors.js).\n    return metricValue == null ? mapColors.noData : getStatesColorScale()(metricValue);\n  }\n\n  function getCaAreaFeatureFill(feature) {\n    const areaInfo = feature && feature.properties ? feature.properties : null;\n    if (!areaInfo) {\n      return mapColors.noData;\n    }\n    const areaCode = String(areaInfo.area_code || \"\").trim();\n    if (areaInfo.area_type === \"cma\") {\n      const metrics = cmaMetricsByCode.get(normalizeCmaCode(areaCode));\n      const metricValue = getMetricValue(metrics);\n      return metricValue == null ? mapColors.noData : getMsasColorScale()(metricValue);\n    }\n    const metrics = caNonmetroMetricsByCode.get(normalizeProvinceCode(areaCode));\n    const metricValue = getMetricValue(metrics);\n    return metricValue == null ? mapColors.noDataNonmetro : getNonmetroColorScale()(metricValue);\n  }\n\n  // Country fill: the nation's aggregate metric run through the same scale US\n  // states/provinces use (getStatesColorScale is built from the combined\n  // state+province domain \u2014 map/colors.js), so a country reads as comparable to\n  // its own regions. The nation metric triple is [theoretical, current,\n  // calibrated] (data/nation.js), matching getMetricValue's index mapping.\n  function getCountryFeatureFill(feature) {\n    const code = feature && feature.properties ? feature.properties.country : \"\";\n    const holder = code === COUNTRY_CA ? nationCa : nation;\n    const metricValue = getMetricValue(holder.metrics);\n    return metricValue == null ? mapColors.noData : getStatesColorScale()(metricValue);\n  }\n\n  // Country click \u2192 select that nation (national totals panel). Mirrors a state\n  // click: it selects the entity, outlines it, recenters, and STAYS in the\n  // current (country) layer. Deliberately does NOT route through\n  // resetSelectionToNation: that helper's Canada branch calls focusCanadaNation,\n  // which switches to state-layer mode and would drop the user out of the\n  // country layer \u2014 an asymmetry with the US branch (which stays put). Keeping\n  // the layer mode fixed here makes US and Canada clicks behave symmetrically.\n  // Hoisted so it can be threaded into createRenderController below; it is only\n  // invoked at click time, after every dep it reads has been assigned.\n  function onCountrySelect(country, feature) {\n    clearHoverHighlight();\n    hideTooltip();\n    const isCanada = country === COUNTRY_CA;\n    const label = isCanada ? \"Canada\" : \"United States\";\n    currentSelection.set({ kind: \"nation\", code: country, label, name: label });\n    syncSelectionUrl(\"nation\", country);\n    updateSelectionOutline(feature, `nation:${country}`);\n    // Paint the panel from whatever aggregate is already cached, then refresh\n    // again once the summary lands \u2014 but only if this country is still selected.\n    sidePanelController.refreshSelectionPanel();\n    ensureNationLoadedData({ cfg, country })\n      .then(() => {\n        const selection = currentSelection.get();\n        if (selection && selection.kind === \"nation\" && selection.code === country) {\n          sidePanelController.refreshSelectionPanel();\n          // The country fill may have been no-data grey before its aggregate\n          // loaded; repaint now that the metric triple is present.\n          renderController.refreshFills();\n        }\n      })\n      .catch((err) => console.warn(\"Unable to load nation summary for the selected country.\", err));\n    if (isMobileLayout()) {\n      // The mobile sheet renders US-wide preview stats today (same limitation as\n      // focusCanadaNation); keep it open at peek rather than dismissing.\n      showUsMobilePreview();\n      return;\n    }\n    const transform = isCanada ? getInitialCanadaTransform() : getInitialUsTransform();\n    if (transform) {\n      setZoomTransformAnimated(transform);\n    }\n  }\n\n  function refreshLegend() {\n    updateGradientLegend();\n  }\n\n  function syncMapVisualsFromCss() {\n    mapColors = readMapColorsFromCss();\n    svg.style(\"background\", mapColors.worldOcean);\n    rebuildColorScales();\n    if (renderController) renderController.refreshFills();\n    refreshLegend();\n    if (sidePanelController) sidePanelController.refreshSelectionPanel();\n  }\n\n  function setupHomeIconUi() {\n    if (!homeIconEl) {\n      return;\n    }\n    homeIconEl.innerHTML = LUCIDE_HOME_ICON;\n  }\n\n  // Thin wrapper over map/viewport.js \u2014 keeps the call sites\n  // (getViewport callbacks, focus math, resize) unchanged while the\n  // measurement logic lives in its own DOM-only module.\n  function getMapViewport(collapsedOverride = null) {\n    return computeMapViewport({ svgNode, sidePanelEl }, collapsedOverride);\n  }\n\n  function enterUnavailableOverlay() {\n    setMapVisible(true);\n    setMapUiReady(false);\n    // Surface the failure UI (previously the map just went blank with no\n    // message). Null-safe so a missing node never throws inside the boot catch.\n    const overlayEl = document.getElementById(\"map-unavailable-overlay\");\n    if (overlayEl) {\n      overlayEl.classList.remove(\"is-hidden\");\n    }\n  }\n\n  function setMapVisible(visible) {\n    if (!svgNode) {\n      return;\n    }\n    svgNode.classList.toggle(\"is-visible\", visible);\n  }\n\n  function revealBaseMap() {\n    if (hasRevealedBaseMap) {\n      return;\n    }\n    hasRevealedBaseMap = true;\n    window.requestAnimationFrame(() => {\n      setMapVisible(true);\n    });\n  }\n\n  function revealDataLayers() {\n    if (hasRevealedDataLayers) {\n      return;\n    }\n    hasRevealedDataLayers = true;\n    window.requestAnimationFrame(() => {\n      dataLayers.classed(\"is-visible\", true);\n    });\n  }\n\n  function getFeatureName(feature, fallbackPrefix) {\n    const props = feature && feature.properties ? feature.properties : {};\n    return (\n      props.name ||\n      props.NAME ||\n      props.state_name ||\n      props.msa_name ||\n      props.province_name ||\n      props.area_name ||\n      `${fallbackPrefix}`\n    );\n  }\n\n\n  function setMapUiReady(ready) {\n    for (const element of gatedUiElements) {\n      if (!element) {\n        continue;\n      }\n      element.classList.toggle(\"map-ui-hidden\", !ready);\n      element.classList.toggle(\"map-ui-ready\", ready);\n    }\n\n    if (!ready) {\n      clearHoverHighlight();\n      hideTooltip();\n      // topOccupationsController is assigned during init() before any data-load\n      // await, so the guard here covers only the pre-init window (before init\n      // runs at module load). Do not reorder: setMapUiReady(false) from\n      // enterUnavailableOverlay() relies on the controller being live.\n      if (topOccupationsController) topOccupationsController.hideTreemapTooltip();\n      if (mobileTopOccupationsController) mobileTopOccupationsController.hideTreemapTooltip();\n    }\n  }\n\n  function setHoveredFeatureElement(element) {\n    if (hoveredFeatureElement === element) {\n      return;\n    }\n    if (hoveredFeatureElement) {\n      hoveredFeatureElement.classList.remove(\"is-hovered\");\n    }\n    hoveredFeatureElement = element || null;\n    if (hoveredFeatureElement) {\n      hoveredFeatureElement.classList.add(\"is-hovered\");\n    }\n  }\n\n  function clearHoverHighlight() {\n    setHoveredFeatureElement(null);\n  }\n\n  function applyTransform(transform) {\n    currentTransform = transform || d3.zoomIdentity;\n    mapRoot.attr(\"transform\", currentTransform.toString());\n  }\n\n  const zoomController = createZoomController({\n    svg,\n    getProjection: () => projection,\n    getPathGenerator: () => pathGenerator,\n    setPathGenerator: (p) => { pathGenerator = p; },\n    applyTransform,\n    onUserInteract: () => { userHasInteractedWithZoom = true; },\n    ensureSelectionOutlineVisible: () => ensureSelectionOutlineVisible(),\n    getViewport: (collapsedOverride) => getMapViewport(collapsedOverride),\n    getProvinceFeatures,\n  });\n  const getInitialUsTransform = zoomController.getInitialUsTransform;\n  const getInitialCanadaTransform = zoomController.getInitialCanadaTransform;\n  const setZoomTransform = zoomController.setZoomTransform;\n  const setZoomTransformAnimated = zoomController.setZoomTransformAnimated;\n  const focusFeatureInViewport = zoomController.focusFeatureInViewport;\n  const setupZoomBehavior = zoomController.setupZoomBehavior;\n  const fitProjection = zoomController.fitProjection;\n  const refreshZoomExtent = zoomController.refreshZoomExtent;\n  const zoomByStep = zoomController.zoomBy;\n\n  const selectionController = createSelectionController({\n    selectionOutlineLayer,\n    getPathGenerator: () => pathGenerator,\n    focusFeatureInViewport,\n    getSidePanelEl: () => sidePanelEl,\n    setPanelCollapsed: (collapsed) => sidePanelController.setPanelCollapsed(collapsed),\n    handleLayoutChange: (reason) => sidePanelController.handleLayoutChange(reason),\n    schedulePanelLayoutRecompute: (reason, onDone) =>\n      sidePanelController.schedulePanelLayoutRecompute(reason, onDone),\n  });\n  const updateSelectionOutline = selectionController.updateSelectionOutline;\n  const ensureSelectionOutlineVisible = selectionController.ensureSelectionOutlineVisible;\n  const focusSelectionFeature = selectionController.focusSelectionFeature;\n\n\n  // Several deps below (showTooltip, hideTooltip, setPanelCollapsed, etc.) are\n  // wrapped in arrow fns to defer name resolution past their declarations\n  // further down in init(). Do not \"simplify\" to bare references without\n  // verifying declaration order first.\n  const renderController = createRenderController({\n    statesLayer,\n    msasLayer,\n    nonmetrosLayer,\n    provincesLayer,\n    caAreasLayer,\n    worldLayer,\n    countryLayer,\n    countyBordersLayer,\n    caCdBordersLayer,\n    metroNonmetroBordersLayer,\n    selectionOutlineLayer,\n    getPathGenerator: () => pathGenerator,\n    getStatesFeatures,\n    getMsaFeatures,\n    getDetailAreaFeatures,\n    getProvinceFeatures,\n    getCaAreaFeatures,\n    getUsCountryFeature,\n    getCaCountryFeature,\n    getUsStateBorders,\n    getCaProvinceBorders,\n    getWorldLandFeature,\n    getWorldCountryBorders,\n    getCountyBorders,\n    getCaCdBorders,\n    getStateFeatureFill,\n    getMsaFeatureFill,\n    getAreaFeatureFill,\n    getProvinceFeatureFill,\n    getCaAreaFeatureFill,\n    getCountryFeatureFill,\n    onCountrySelect,\n    setHoveredFeatureElement,\n    clearHoverHighlight,\n    showTooltip: (event, name, totalWorkers, wageBill) =>\n      showTooltip(event, name, totalWorkers, wageBill),\n    positionTooltip: (event) => positionTooltip(event),\n    hideTooltip: () => hideTooltip(),\n    updateSelection: (...args) => sidePanelController.updateSelection(...args),\n    updateSelectionOutline,\n    focusSelectionFeature,\n    focusFeatureInViewport,\n    ensureSelectionOutlineVisible,\n    getFeatureName,\n    isMobileLayout,\n    showMobilePreview: (meta) => mobileSheet.show(meta),\n  });\n  const renderWorld = renderController.renderWorld;\n  const renderStates = renderController.renderStates;\n  const renderProvinces = renderController.renderProvinces;\n  const renderMsas = renderController.renderMsas;\n  const renderNonmetros = renderController.renderNonmetros;\n  const renderCaAreas = renderController.renderCaAreas;\n  const renderCountry = renderController.renderCountry;\n  const renderMetroNonmetroBorders = renderController.renderMetroNonmetroBorders;\n  const renderCountyBorders = renderController.renderCountyBorders;\n  const renderCaCdBorders = renderController.renderCaCdBorders;\n  const updateFeaturePaths = renderController.updateFeaturePaths;\n  // URL <-> state sync (plan unit E): shared commit path for deep-link/popstate.\n  const selectByKindCode = renderController.selectByKindCode;\n  const setApplyingHistory = renderController.setApplyingHistory;\n  const isApplyingHistory = renderController.isApplyingHistory;\n  const syncSelectionUrl = renderController.syncSelectionUrl;\n\n  sidePanelController = createSidePanelController({\n    els: {\n      sidePanelEl,\n      sidePanelToggleEl,\n      rootEl,\n      svgNode: /** @type {any} */ (svgNode),\n      selectedTypeEl,\n      selectedNameEl,\n      selectedTotalWorkforceEl,\n      selectedTotalWageBillEl,\n      selectedExposedWageBillEl,\n      selectedExposedWorkforceEl,\n      selectedWorkforceGaugeValueEl,\n      selectedWorkforceGaugeProgressEl,\n      selectedWageBillGaugeValueEl,\n      selectedWageBillGaugeProgressEl,\n    },\n    mapOps: {\n      getMapColors: () => mapColors,\n      getCurrentTransform: () => currentTransform,\n      getProjection: () => projection,\n      getMapViewport: (collapsedOverride) => getMapViewport(collapsedOverride),\n      fitProjection,\n      refreshZoomExtent,\n      updateFeaturePaths,\n      ensureSelectionOutlineVisible: () => ensureSelectionOutlineVisible(),\n      setZoomTransform,\n      setZoomTransformAnimated,\n      getInitialUsTransform,\n      userHasInteractedWithZoom: () => userHasInteractedWithZoom,\n    },\n    refreshTopOccupationsPanel: () => {\n      topOccupationsController.refreshTopOccupationsPanel();\n      // Mobile controller no-ops when not on the mobile breakpoint, so\n      // calling unconditionally is cheap and keeps the wiring simple.\n      if (mobileTopOccupationsController) {\n        mobileTopOccupationsController.refreshTopOccupationsPanel();\n      }\n    },\n  });\n\n  topOccupationsController = createTopOccupationsController({\n    cfg,\n    els: {\n      sidePanelEl,\n      topOccupationsDetailEl,\n      topOccupationsDetailMetaEl,\n      topOccupationsStatusEl,\n      topOccupationsTreemapEl,\n      topOccupationsTasksEl,\n      treemapTooltipEl,\n      panelBackTop5El,\n      panelExpandEl,\n    },\n    treemapNavEls: {\n      rootEl: treemapNavRootEl,\n      regionLabelEl: treemapNavRegionLabelEl,\n      industryBtnEl: treemapNavIndustryBtnEl,\n      industryLabelEl: treemapNavIndustryLabelEl,\n      jobsBtnEl: treemapNavJobsBtnEl,\n      jobsLabelEl: treemapNavJobsLabelEl,\n      industryPopoverEl: treemapNavIndustryPopoverEl,\n      industrySearchEl: /** @type {HTMLInputElement | null} */ (treemapNavIndustrySearchEl),\n      industryClearEl: treemapNavIndustryClearEl,\n      industryListEl: treemapNavIndustryListEl,\n      jobsPopoverEl: treemapNavJobsPopoverEl,\n      jobsSearchEl: /** @type {HTMLInputElement | null} */ (treemapNavJobsSearchEl),\n      jobsClearEl: treemapNavJobsClearEl,\n      jobsListEl: treemapNavJobsListEl,\n      jobsChevronEl: treemapNavJobsChevronEl,\n      jobsClearJobEl: treemapNavJobsClearJobEl,\n      industryChevronEl: treemapNavIndustryChevronEl,\n      industryClearIndustryEl: treemapNavIndustryClearIndustryEl,\n    },\n    mapOps: {\n      getMapColors: () => mapColors,\n      getCurrentTransform: () => currentTransform,\n    },\n    panelOps: {\n      setPanelCollapsed: (c) => sidePanelController.setPanelCollapsed(c),\n      handleLayoutChange: (r) => sidePanelController.handleLayoutChange(r),\n      schedulePanelLayoutRecompute: (r, onDone) =>\n        sidePanelController.schedulePanelLayoutRecompute(r, onDone),\n      clearSelectionDisplay: (name) => sidePanelController.clearSelectionDisplay(name),\n    },\n    selectionOps: {\n      focusFeatureInViewport,\n      ensureSelectionOutlineVisible: () => ensureSelectionOutlineVisible(),\n    },\n  });\n\n  mobileTopOccupationsController = createMobileTopOccupationsController({\n    cfg,\n    els: {\n      topOccupationsDetailEl: mobileTreemapDetailEl,\n      topOccupationsDetailMetaEl: mobileTreemapDetailMetaEl,\n      topOccupationsStatusEl: mobileTreemapStatusEl,\n      topOccupationsTreemapEl: mobileTreemapEl,\n      topOccupationsTasksEl: mobileTreemapTasksEl,\n      treemapTooltipEl,\n      cardEl: mobileTreemapEl ? mobileTreemapEl.closest(\".map-mobile-treemap-card\") : null,\n    },\n    treemapNavEls: {\n      rootEl: mobileTreemapNavRootEl,\n      regionLabelEl: mobileTreemapNavRegionLabelEl,\n      industryBtnEl: mobileTreemapNavIndustryBtnEl,\n      industryLabelEl: mobileTreemapNavIndustryLabelEl,\n      jobsBtnEl: mobileTreemapNavJobsBtnEl,\n      jobsLabelEl: mobileTreemapNavJobsLabelEl,\n      industryPopoverEl: mobileTreemapNavIndustryPopoverEl,\n      industrySearchEl: /** @type {HTMLInputElement | null} */ (mobileTreemapNavIndustrySearchEl),\n      industryClearEl: mobileTreemapNavIndustryClearEl,\n      industryListEl: mobileTreemapNavIndustryListEl,\n      jobsPopoverEl: mobileTreemapNavJobsPopoverEl,\n      jobsSearchEl: /** @type {HTMLInputElement | null} */ (mobileTreemapNavJobsSearchEl),\n      jobsClearEl: mobileTreemapNavJobsClearEl,\n      jobsListEl: mobileTreemapNavJobsListEl,\n      jobsChevronEl: mobileTreemapNavJobsChevronEl,\n      jobsClearJobEl: mobileTreemapNavJobsClearJobEl,\n      industryChevronEl: mobileTreemapNavIndustryChevronEl,\n      industryClearIndustryEl: mobileTreemapNavIndustryClearIndustryEl,\n    },\n    mapOps: {\n      getMapColors: () => mapColors,\n    },\n    isMobileLayout,\n  });\n\n  const layersController = createLayersController({\n    statesLayer,\n    msasLayer,\n    nonmetrosLayer,\n    provincesLayer,\n    caAreasLayer,\n    countryLayer,\n    countyBordersLayer,\n    caCdBordersLayer,\n    metroNonmetroBordersLayer,\n    ensureStatesLoaded: () => ensureStatesLoadedData({ cfg }),\n    ensureMsaMetricsLoaded: () => ensureMsaMetricsLoadedData({ cfg }),\n    ensureMsasTopologyLoaded: () => ensureMsasTopologyLoadedData({ cfg }),\n    ensureNonmetrosLoaded: () => ensureNonmetrosLoadedData({ cfg }),\n    ensureProvincesLoaded: () => ensureProvincesLoadedData({ cfg }),\n    ensureCaAreasLoaded: () => ensureCaAreasLoadedData({ cfg }),\n    // Country mode's fills come from both nation aggregates; its polygons come\n    // from the states + provinces topologies (loaded via needsCountryData in\n    // applyLayerVisibility). A US or CA failure only leaves that country grey.\n    ensureCountryDataLoaded: () => Promise.all([\n      ensureNationLoadedData({ cfg, country: COUNTRY_US }),\n      ensureNationLoadedData({ cfg, country: COUNTRY_CA }),\n    ]),\n    renderCountry,\n    refreshLegend,\n    refreshSelectionPanel: () => sidePanelController.refreshSelectionPanel(),\n    ensureSelectionOutlineVisible: () => ensureSelectionOutlineVisible(),\n  });\n  const setLayerMode = layersController.setLayerMode;\n  const setMetricMode = layersController.setMetricMode;\n  const applyLayerVisibility = layersController.applyLayerVisibility;\n\n  // selectedMetric reaction chain: subscribers fire in registration order, so\n  // anything that needs fresh color scales (refreshFills, legend, panel) must\n  // be wired AFTER rebuildColorScales below. Keep this block contiguous.\n  selectedMetric.subscribe(() => {\n    // No cache clearing on metric change: the shared job-families singleton\n    // (data/job-families.js) caches one metric-agnostic limit=500 payload per\n    // region and re-sorts client-side for the active metric, so a metric\n    // toggle re-renders from cache with zero refetch. The re-render chain\n    // (second subscriber \u2192 refreshSelectionPanel + both refreshTopOccupations\n    // panels + mobileSheet.refresh()) repaints with the new metric field.\n    rebuildColorScales();\n  });\n  renderController.subscribeToMetricChanges();\n  selectedMetric.subscribe(() => {\n    refreshLegend();\n    sidePanelController.refreshSelectionPanel();\n    mobileSheet.refresh();\n  });\n\n  setupPostLoadHandlers({\n    renderWorld,\n    renderStates,\n    renderProvinces,\n    renderMsas,\n    renderNonmetros,\n    renderCaAreas,\n    renderCountry,\n    renderMetroNonmetroBorders,\n    renderCountyBorders,\n    renderCaCdBorders,\n    updateFeaturePaths,\n    applyLayerVisibility,\n  });\n\n  // Function declarations (hoisted) so they're usable in createRenderController\n  // deps further up. Used by render.js click handlers to swap full-overlay\n  // open for the docked preview card on small viewports.\n  function isMobileLayout() {\n    return MOBILE_MQ.matches;\n  }\n\n  // Prepare the map so a code-driven selection (deep-link / popstate) reproduces\n  // EXACTLY what a click of the same geography produces (plan unit E). A click\n  // is only reachable when that geography's layer is both loaded AND the active\n  // visible layer, so we must reconcile two things the click path takes for\n  // granted:\n  //   1. Layer MODE. state/province are only clickable in \"state\" mode;\n  //      msa/nonmetro/cma/ca_nonmetro only in \"area\" mode. Setting the wrong\n  //      mode would paint the selection outline over a mismatched fill layer\n  //      (e.g. a state outline atop metro fills) \u2014 visually impossible via\n  //      click. setLayerMode also runs applyLayerVisibility, which lazily loads\n  //      whichever layer the mode needs.\n  //   2. DATA. We still await the specific ensure* explicitly so the by-code\n  //      feature/outline indexes selectByKindCode reads are populated before it\n  //      runs, regardless of whether applyLayerVisibility or boot started the\n  //      same loader first.\n  // Every ensure*/setLayerMode is idempotent (loaded-signal + in-flight-promise\n  // guards; mode set is a no-op when already in that mode), so this is safe\n  // regardless of what boot already kicked off or the user's current mode.\n  /**\n   * @param {string} kind\n   * @returns {Promise<void>}\n   */\n  async function ensureLayerLoadedForKind(kind) {\n    // Set mode AND keep the toggle's radio in sync (notify:false so we don't\n    // re-enter setLayerMode via its onChange). setLayerMode is a no-op when\n    // already in that mode, so the common area-mode deep-link costs nothing.\n    const applyMode = async (mode) => {\n      await setLayerMode(mode);\n      if (layerToggle) layerToggle.setValue(mode, false);\n    };\n    if (kind === \"state\") {\n      await applyMode(LAYER_MODE_STATE);\n      await ensureStatesLoadedData({ cfg });\n    } else if (kind === \"province\") {\n      await applyMode(LAYER_MODE_STATE);\n      await ensureProvincesLoadedData({ cfg });\n    } else if (kind === \"cma\" || kind === \"ca_nonmetro\") {\n      await applyMode(LAYER_MODE_AREA);\n      await ensureCaAreasLoadedData({ cfg });\n    } else {\n      // msa / nonmetro \u2014 the US composites layer (the default area mode).\n      await applyMode(LAYER_MODE_AREA);\n      await ensureNonmetrosLoadedData({ cfg });\n    }\n  }\n\n  const mobileSheet = createMobileSheet({\n    getMapColors: () => mapColors,\n    bodyDrag: !!cfg.mobileSheetBodyDrag,\n    eventLogUrl: cfg.sheetEventLogUrl,\n  });\n\n  // Region-snapshot (mobile-sheet preview) helpers. Relocated to\n  // regionSnapshot.js; instantiated here \u2014 after isMobileLayout (hoisted) and\n  // mobileSheet exist \u2014 so the returned functions share the orchestrator's\n  // single mobileSheet instance. They're invoked only from inside init() (and\n  // via setupMobileShell), exactly as before.\n  const { showUsMobilePreview, restoreMobileSheetPreview } = createRegionSnapshot({\n    isMobileLayout,\n    mobileSheet,\n  });\n\n  // \"Locate me\" geolocation flow. Relocated to geolocate.js; svgNode is the\n  // live hit-test target it queries.\n  const { locateUserAndSelect } = createGeolocate({\n    svgNode: /** @type {SVGSVGElement} */ (svgNode),\n  });\n\n  // Edge-detect breakpoint crossings so cross-mode UI state (open desktop\n  // side panel bleeding into mobile, expanded mobile sheet bleeding into\n  // desktop) gets reset exactly once on the transition rather than every\n  // resize tick.\n  let wasMobileLayout = isMobileLayout();\n\n  function handleResize() {\n    if (resizeRaf) {\n      cancelAnimationFrame(resizeRaf);\n    }\n\n    resizeRaf = requestAnimationFrame(() => {\n      const nowMobileLayout = isMobileLayout();\n      if (nowMobileLayout !== wasMobileLayout) {\n        // Collapse the desktop side panel on any breakpoint crossing \u2014\n        // mobile-shell.js's applyLayoutForMode handles the mobile sheet,\n        // menu, and settings overlay, but doesn't touch #map-side-panel.\n        sidePanelController.setPanelCollapsed(true);\n        wasMobileLayout = nowMobileLayout;\n      }\n      const collapsedState = sidePanelEl ? sidePanelEl.classList.contains(\"is-collapsed\") : true;\n      sidePanelController.handleLayoutChange(\"resize\");\n      sidePanelController.updateTogglePosition(collapsedState);\n      if (topOccupationsController) topOccupationsController.refreshTopOccupationsPanel();\n      if (mobileTopOccupationsController) mobileTopOccupationsController.refreshTopOccupationsPanel();\n    });\n  }\n\n  async function init() {\n    syncMapVisualsFromCss();\n    setupHomeIconUi();\n    setupMapInfoModal();\n    topOccupationsController.clearTopOccupationsPanel();\n    mobileTopOccupationsController.clearTopOccupationsPanel();\n    setMapUiReady(false);\n    setMapVisible(false);\n    fitProjection();\n    renderWorld();\n    updateFeaturePaths();\n    setupZoomBehavior();\n    setZoomTransform(getInitialUsTransform());\n\n    const { layerToggleHostEl, metricToggleHostEl } =\n      buildLayerTogglePanel(layerToggleMountEl);\n\n    // Retained (not fire-and-forget) so the deep-link / popstate path can keep\n    // the toggle's visible radio state in sync when it switches layer mode\n    // programmatically (plan unit E) \u2014 the toggle holds its own value and does\n    // not subscribe to selectedLayer, so a silent setLayerMode would leave the\n    // radio showing the wrong mode.\n    // The Layers control offers a third \"Country\" granularity below Metro/States.\n    // It is now a real fill layer (LAYER_MODE_COUNTRY): picking it shows the\n    // whole-country choropleth (US + Canada polygons filled by their national\n    // aggregate). Its option carries layerValue LAYER_MODE_COUNTRY, so \u2014 exactly\n    // like Metro/States \u2014 setLayerMode drives it and applyLayerVisibility lazily\n    // loads the states + provinces topologies (for the polygons) and both nation\n    // aggregates (for the fills). Clicking a country selects that nation\n    // (onCountrySelect). Switching US<->Canada is handled separately (map click /\n    // geolocation / deep-link URL).\n    layerToggle = new LayerToggle({\n      mountEl: layerToggleHostEl,\n      value: selectedLayer.get(),\n      onChange: (visualValue) => {\n        setLayerMode(visualValue);\n      },\n    });\n    layerToggle.render();\n\n    new MetricToggle({\n      mountEl: metricToggleHostEl,\n      value: selectedMetric.get(),\n      onChange: (nextValue) => {\n        setMetricMode(nextValue);\n      },\n    }).render();\n\n    if (layerToggleMountEl && rootEl) {\n      const syncLayerToggleWidth = () => {\n        const w = layerToggleMountEl.offsetWidth || 0;\n        rootEl.style.setProperty(\"--map-layer-toggle-width\", `${w}px`);\n      };\n      syncLayerToggleWidth();\n      if (typeof ResizeObserver !== \"undefined\") {\n        // Coalesce resize bursts and defer the style write out of the\n        // ResizeObserver callback (avoids layout thrash + RO-loop warnings).\n        let rafId = 0;\n        new ResizeObserver(() => {\n          if (rafId) return;\n          rafId = requestAnimationFrame(() => {\n            rafId = 0;\n            syncLayerToggleWidth();\n          });\n        }).observe(layerToggleMountEl);\n      }\n    }\n\n    const panelInfoEl = document.getElementById(\"map-panel-info\");\n    if (panelInfoEl) {\n      panelInfoEl.addEventListener(\"click\", () => openMapInfoModal(panelInfoEl));\n    }\n\n    sidePanelController.setPanelCollapsed(true);\n\n    if (sidePanelToggleEl) {\n      sidePanelToggleEl.addEventListener(\"click\", () => {\n        const currentlyCollapsed = sidePanelEl ? sidePanelEl.classList.contains(\"is-collapsed\") : true;\n        sidePanelController.setPanelCollapsed(!currentlyCollapsed);\n        sidePanelController.schedulePanelLayoutRecompute(\"panel-toggle\");\n      });\n    }\n\n    if (panelCloseEl) {\n      panelCloseEl.addEventListener(\"click\", () => {\n        // Closing the region panel now also DESELECTS (matches the zoom-reset\n        // button): onPanelClose() does the top-occupations sub-view cleanup;\n        // resetSelectionToNation() then clears the selection and recenters \u2014\n        // country-aware (plan unit E FIX \u2460), so closing the panel while a\n        // Canadian geography is selected rewinds to the Canada nation view\n        // (/us-ai-map/ca/ + Canada-fit) instead of jumping to the US. The\n        // collapsePanel intent preserves the prior X-collapses-the-panel\n        // contract (map.spec.js:166). onPanelClose runs first so its deferred\n        // re-focus-the-selected-feature step no-ops (the outline is cleared by\n        // the orchestrator). The recenter is owned by the orchestrator now (it\n        // used to be a separate resetMapView() that always recentered on the US,\n        // which would clobber the Canada-fit transform).\n        topOccupationsController.onPanelClose();\n        resetSelectionToNation({ collapsePanel: true });\n      });\n    }\n\n    if (panelBackTop5El) {\n      panelBackTop5El.addEventListener(\"click\", () => topOccupationsController.handleBackToTop5());\n    }\n\n    if (panelExpandEl) {\n      panelExpandEl.addEventListener(\"click\", () => topOccupationsController.setTopOccupationsViewMode(\"expanded\"));\n    }\n\n    const zoomInBtn = document.getElementById(\"map-zoom-in\");\n    const zoomOutBtn = document.getElementById(\"map-zoom-out\");\n    const zoomResetBtn = document.getElementById(\"map-zoom-reset\");\n    if (zoomInBtn) zoomInBtn.addEventListener(\"click\", () => zoomByStep(1.6));\n    if (zoomOutBtn) zoomOutBtn.addEventListener(\"click\", () => zoomByStep(1 / 1.6));\n    if (zoomResetBtn) {\n      zoomResetBtn.addEventListener(\"click\", () => {\n        // Country-aware deselect (plan unit E FIX \u2460): collapse the panel and\n        // reset to the nation view. The orchestrator owns the recenter so a\n        // Canadian selection rewinds to /us-ai-map/ca/ + Canada-fit instead of\n        // the old unconditional US resetMapView().\n        resetSelectionToNation({ collapsePanel: true });\n      });\n    }\n\n    const locateMeBtn = document.getElementById(\"map-locate-me\");\n    if (locateMeBtn) {\n      locateMeBtn.addEventListener(\"click\", () => locateUserAndSelect(locateMeBtn));\n    }\n\n    // The unavailable-overlay retry simply reloads the page \u2014 a fresh boot is\n    // the cleanest recovery from a transient origin/503 stall.\n    const mapUnavailableRetryBtn = document.getElementById(\"map-unavailable-retry\");\n    if (mapUnavailableRetryBtn) {\n      mapUnavailableRetryBtn.addEventListener(\"click\", () => window.location.reload());\n    }\n\n    // showUsMobilePreview / restoreMobileSheetPreview now come from\n    // createRegionSnapshot (regionSnapshot.js); the geolocation flow\n    // (findFeatureAtLngLat / showLocateStatus / isInUnmappedUsTerritory /\n    // locateUserAndSelect) now comes from createGeolocate (geolocate.js).\n    // Both were instantiated above, before init().\n\n    function clearMapSelection() {\n      clearHoverHighlight();\n      hideTooltip();\n      updateSelectionOutline(null, null);\n      currentSelection.set({\n        kind: \"nation\",\n        code: \"us\",\n        label: \"United States\",\n        name: \"United States\",\n      });\n      // Rewind the slug to the nation root (/us-ai-map/) so deselecting via\n      // background-click / Escape / zoom-reset never leaves a stale region path.\n      // No-ops under the popstate applyingHistory bracket (the browser is\n      // already at the popped URL), so back/forward to \"/us-ai-map/\" is unaffected.\n      syncSelectionUrl(\"nation\", \"us\");\n      sidePanelController.refreshSelectionPanel();\n      // On mobile, keep the bottom sheet open at peek with US-wide stats\n      // instead of dismissing \u2014 the sheet is the primary way to read totals.\n      if (isMobileLayout()) {\n        showUsMobilePreview();\n      } else {\n        mobileSheet.hide();\n      }\n    }\n\n    // Focus the Canada nation view: provinces layer (states-layer mode) + select\n    // the Canada nation aggregate + nation summary + panel refresh + fit to\n    // Canada's bounds. Shared by the bootstrap deep-link block and the popstate\n    // restore so the two paths can't drift. Uses currentSelection.set (not\n    // commitSelection) so no history entry is written \u2014 callers preserve the\n    // /us-ai-map/ca/ URL already in the address bar / popped from history.\n    async function focusCanadaNation() {\n      // \"province\" \u2192 states-layer mode + ensureProvincesLoaded; the loaded\n      // province features back getInitialCanadaTransform's bounds fit.\n      await ensureLayerLoadedForKind(\"province\");\n      currentSelection.set({\n        kind: \"nation\",\n        code: \"ca\",\n        label: \"Canada\",\n        name: \"Canada\",\n      });\n      await ensureNationLoadedData({ cfg, country: \"ca\" });\n      sidePanelController.refreshSelectionPanel();\n      // getInitialCanadaTransform is documented to return null (province topology\n      // not loaded / degenerate bounds / projection not ready). Passing null into\n      // setZoomTransformAnimated reaches d3's zoomBehavior.transform, which reads\n      // .k/.x/.y off the transform and throws. Guard it: only animate when the\n      // transform is truthy; otherwise log and continue (selection + panel still\n      // apply, leaving a sane un-fitted view rather than throwing).\n      const canadaTransform = getInitialCanadaTransform();\n      if (canadaTransform) {\n        setZoomTransformAnimated(canadaTransform);\n      } else {\n        console.warn(\"Canada initial transform unavailable; leaving current map view.\");\n      }\n      showUsMobilePreview();\n    }\n\n    // Is the CURRENT selection a Canadian geography? Used to make the user-facing\n    // deselect paths country-aware (plan unit E FIX \u2460) so deselecting while\n    // exploring Canada rewinds to the Canada nation view (/us-ai-map/ca/) rather\n    // than jumping to the US (/us-ai-map/). Treats every Canadian entity kind\n    // (province / cma / ca_nonmetro) plus the Canada nation aggregate as Canadian.\n    function isCanadianSelection(selection) {\n      if (!selection) return false;\n      const { kind, code } = selection;\n      if (kind === \"province\" || kind === \"cma\" || kind === \"ca_nonmetro\") return true;\n      if (kind === \"nation\" && code === \"ca\") return true;\n      return false;\n    }\n\n    // Single deselect orchestrator (plan unit E FIX \u2460). Every USER deselect entry\n    // point \u2014 ocean/background click, Escape, zoom-reset, panel X, mobile reset \u2014\n    // routes through here so the reset is consistently country-aware. We derive\n    // the country from currentSelection BEFORE clearing, then:\n    //   - Canada: focusCanadaNation() (Canada nation selection + panel + its own\n    //     guarded Canada-fit transform) + URL \"/us-ai-map/ca/\". focusCanadaNation\n    //     owns the recenter, so we MUST NOT also run the US recenter (it would\n    //     clobber the Canada transform). That is why the orchestrator \u2014 not the\n    //     caller \u2014 owns the recenter for both branches.\n    //   - US: the existing nation:us reset (selection + URL \"/us-ai-map/\" + panel\n    //     refresh + mobile preview) + the US-fit recenter.\n    // `openPanel` / `collapsePanel` preserve each caller's panel intent (ocean\n    // click opens the desktop panel; zoom-reset / panel X / mobile reset collapse\n    // it). syncSelectionUrl is a no-op under applyingHistory, so this never writes\n    // history during a popstate/deep-link restore. NOTE: the popstate handler is\n    // already country-aware and drives focusCanadaNation itself; it does NOT route\n    // through this orchestrator (it calls clearMapSelection for its US/root\n    // branches), so there is no double-handling.\n    // `forceCountry` (\"us\" | \"ca\" | null) lets a caller pick the destination\n    // country explicitly instead of deriving it from the current selection. The\n    // ocean/background click uses this to choose the summary by the latitude\n    // under the pointer (above Toronto -> Canada, below -> US). When null we\n    // keep the selection-derived behavior every other caller relies on.\n    async function resetSelectionToNation({ openPanel = false, collapsePanel = false, forceCountry = null } = {}) {\n      const wasCanadian = forceCountry\n        ? forceCountry === \"ca\"\n        : isCanadianSelection(currentSelection.get());\n      clearHoverHighlight();\n      hideTooltip();\n      updateSelectionOutline(null, null);\n\n      if (wasCanadian) {\n        // Open the desktop panel BEFORE the Canada reset so focusCanadaNation's\n        // bounds-fit measures the open-panel viewport (mirrors the US open-then-\n        // recenter sequence). On collapse-intent callers we collapse first.\n        if (openPanel && !isMobileLayout() && sidePanelEl && sidePanelEl.classList.contains(\"is-collapsed\")) {\n          sidePanelController.setPanelCollapsed(false);\n        } else if (collapsePanel) {\n          sidePanelController.setPanelCollapsed(true);\n        }\n        // focusCanadaNation sets nation:ca via currentSelection.set (no history),\n        // refreshes the panel, and applies the guarded Canada-fit transform. The\n        // explicit syncSelectionUrl then rewinds the slug to /us-ai-map/ca/ (a\n        // no-op under applyingHistory).\n        await focusCanadaNation();\n        syncSelectionUrl(\"nation\", \"ca\");\n        return;\n      }\n\n      // US-side deselect: reuse clearMapSelection for the shared selection/URL/\n      // panel/mobile work (single source of truth \u2014 the popstate US/root/fallback\n      // branches call the same helper), then keep only the recenter sequencing\n      // here. clearMapSelection re-runs clearHoverHighlight/hideTooltip/\n      // updateSelectionOutline, which we already did above; those are idempotent\n      // no-ops against the now-cleared state, so behavior is unchanged.\n      clearMapSelection();\n\n      const recenterOnUs = () => setZoomTransformAnimated(getInitialUsTransform());\n      if (openPanel && !isMobileLayout() && sidePanelEl && sidePanelEl.classList.contains(\"is-collapsed\")) {\n        // Opening the panel changes the viewport width, so defer the recenter\n        // until the panel transition settles (otherwise getInitialUsTransform\n        // measures a mid-animation panel rect). Mirrors focusSelectionFeature.\n        sidePanelController.setPanelCollapsed(false);\n        sidePanelController.schedulePanelLayoutRecompute(\"panel-toggle\", recenterOnUs);\n      } else {\n        if (collapsePanel) sidePanelController.setPanelCollapsed(true);\n        recenterOnUs();\n      }\n    }\n\n    setupMobileShell({\n      sidePanelEl,\n      mobileSheet,\n      // Country-aware deselect orchestrator (plan unit E FIX \u2460) for the mobile\n      // reset button, replacing the former clearMapSelection + explicit US\n      // recenter (which always jumped to the US even from a Canadian selection).\n      resetMapToNation: () => resetSelectionToNation(),\n      showUsMobilePreview,\n      restoreMobileSheetPreview,\n      isMobileLayout,\n      openMapInfoModal,\n    });\n\n    // Latitude of Toronto (43.65\u00B0N) \u2014 the dividing line for ocean-click country\n    // selection: a background click above it shows the Canada summary, below it\n    // the US summary.\n    const TORONTO_LATITUDE = 43.65;\n\n    // Geographic latitude under a pointer event, accounting for the live zoom\n    // transform (pan/scale) and the Natural Earth projection. d3.pointer gives\n    // screen coords relative to the svg; currentTransform.invert undoes the\n    // pan/zoom to projection space; projection.invert unprojects to [lng, lat].\n    // Returns null if the point can't be unprojected (defensive \u2014 Natural Earth\n    // covers the whole sphere, so in practice this always resolves).\n    function clickLatitude(event) {\n      const point = currentTransform.invert(d3.pointer(event, svgNode));\n      const lngLat = projection.invert(point);\n      if (!lngLat || !Number.isFinite(lngLat[1])) return null;\n      return lngLat[1];\n    }\n\n    svg.on(\"click\", (event) => {\n      // A click that reaches the svg missed every feature (the feature click\n      // handlers in map/render.js call stopPropagation), so this is a click on\n      // the ocean/world background. Reset to the nation view and open the\n      // desktop side panel (it starts collapsed and is otherwise only\n      // uncollapsed as a side effect of selecting a region, so without this the\n      // nation stats stay hidden and the click looks like a no-op). The recenter\n      // is country-aware (plan unit E FIX \u2460) and owned by the orchestrator: for\n      // the US path it opens the panel then defers the US-fit recenter until the\n      // panel transition settles (so getInitialUsTransform measures the settled\n      // panel rect, not a mid-animation one); for a Canadian selection it rewinds\n      // to /us-ai-map/ca/ + the guarded Canada-fit transform instead of jumping\n      // to the US. openPanel preserves this handler's \"ocean click opens the\n      // panel\" intent.\n      //\n      // The country is chosen by the latitude under the click (above Toronto ->\n      // Canada, below -> US) rather than the prior selection, so an ocean click\n      // up north opens the Canada summary even from a US selection and vice\n      // versa. If the latitude can't be resolved we fall back to the\n      // selection-derived country (forceCountry: null).\n      const lat = clickLatitude(event);\n      const forceCountry = lat === null ? null : (lat >= TORONTO_LATITUDE ? \"ca\" : \"us\");\n      resetSelectionToNation({ openPanel: true, forceCountry });\n    });\n\n    // Single arbitrated document Escape handler (replaces the four formerly\n    // independent document-level Escape listeners across info-modal, treemap\n    // nav, mobile-sheet, and this boot). It dispatches Escape to the innermost\n    // open overlay only \u2014 modal > treemap popovers > mobile sheet > map reset \u2014\n    // so one keypress can no longer cascade (e.g. close a popover AND reset the\n    // map). Treemap popovers live behind two lazily-booted controllers\n    // (desktop + mobile); only one is ever active, and the predicate is false\n    // until that controller's nav is booted, so OR-ing both is safe.\n    installEscapeArbiter({\n      infoModal: {\n        isOpen: () => infoModal.isOpen(),\n        close: () => infoModal.close(),\n      },\n      treemapNav: {\n        hasOpenPopovers: () =>\n          Boolean(topOccupationsController && topOccupationsController.hasOpenTreemapPopovers()) ||\n          Boolean(mobileTopOccupationsController && mobileTopOccupationsController.hasOpenTreemapPopovers()),\n        closePopovers: () => {\n          if (topOccupationsController) topOccupationsController.closeTreemapPopovers();\n          if (mobileTopOccupationsController) mobileTopOccupationsController.closeTreemapPopovers();\n        },\n      },\n      mobileSheet: {\n        // The mobile sheet only claims Escape when there is nothing to clear:\n        // i.e. it's showing but the current selection is already the nation\n        // (US peek). When a REGION is selected the sheet is also showing, but\n        // Escape must fall through to the map-reset branch \u2014 clearMapSelection()\n        // re-docks the sheet at peek with US-wide stats (showUsMobilePreview),\n        // which is the expected \"return to US peek\" behavior. Pre-PR-9b this\n        // worked because the map's own document Escape listener always ran\n        // clearMapSelection() alongside the sheet's; the arbiter's single\n        // dispatch otherwise short-circuits at the sheet and the selection\n        // never resets (regression on the mobile-safari touch path).\n        isShowing: () => {\n          if (!mobileSheet.isShowing()) return false;\n          const selection = currentSelection.get();\n          // No selection or already at the nation peek \u2192 nothing to clear, so\n          // the sheet legitimately owns Escape and dismisses itself.\n          return !selection || selection.kind === \"nation\";\n        },\n        hideForEscape: () => mobileSheet.hideForEscape(),\n      },\n      // Country-aware map-default reset (plan unit E FIX \u2460). Collapses nothing\n      // (Escape from the map default keeps whatever panel state the user had \u2014\n      // matching the prior behavior where clearMapSelection didn't force a\n      // collapse) and lets the orchestrator own the recenter so a Canadian\n      // selection rewinds to /us-ai-map/ca/ + Canada-fit rather than the US.\n      resetMapToNation: () => resetSelectionToNation(),\n    });\n\n    // Back/forward history sync (plan unit E). When the user navigates with the\n    // browser's back/forward (or any programmatic history pop), restore the\n    // geography the popped URL encodes. We resolve the pathname to {kind, code}\n    // via keyForPath and route through the SAME selection path a click uses, so\n    // the restored view (focus/zoom + panel + outline) is identical. The\n    // applyingHistory bracket guarantees the restore itself does NOT write a new\n    // history entry (which would corrupt the back/forward stack):\n    //   - entity kinds: selectByKindCode(..., {fromHistory:true}) sets the flag.\n    //   - nation root (\"/us-ai-map/\"): clearMapSelection() sets currentSelection\n    //     directly (no commitSelection), so it can't write URL on its own, but\n    //     we bracket with setApplyingHistory defensively in case that path ever\n    //     starts routing through commitSelection.\n    // The handler is async only to await the layer-load for kinds that may not\n    // be loaded yet; the await resolves immediately once a layer is ready.\n    window.addEventListener(\"popstate\", async (event) => {\n      const key = keyForPath(window.location.pathname);\n      setApplyingHistory(true);\n      try {\n        if (!key || key.kind === \"nation\") {\n          // Nation branch is country-aware: a pop to /us-ai-map/ca/ re-fits the\n          // Canada view (shared focusCanadaNation helper, same as the bootstrap\n          // deep-link), while the bare root / /us-ai-map/us/ keeps the existing\n          // US reset. setApplyingHistory (already set above) brackets the restore\n          // so focusCanadaNation's currentSelection.set can't write history.\n          if (key && key.kind === \"nation\" && key.code === \"ca\") {\n            await focusCanadaNation();\n            return;\n          }\n          clearMapSelection();\n          setZoomTransformAnimated(getInitialUsTransform());\n          return;\n        }\n        await ensureLayerLoadedForKind(key.kind);\n        const ok = selectByKindCode(key.kind, key.code, { fromHistory: true });\n        if (!ok) {\n          // Popped to an entity we can't resolve (not in render set / load\n          // failed): degrade to the nation view rather than leaving the map in\n          // a stale state inconsistent with the URL.\n          clearMapSelection();\n          setZoomTransformAnimated(getInitialUsTransform());\n        }\n      } catch (popError) {\n        console.warn(\"Unable to restore geography from history; resetting to nation view.\", popError);\n        clearMapSelection();\n        setZoomTransformAnimated(getInitialUsTransform());\n      } finally {\n        setApplyingHistory(false);\n      }\n    });\n\n    try {\n      await measureAsync(\"map:init:world\", () => ensureWorldLoadedData({ cfg }));\n      revealBaseMap();\n      // MSA metrics, US composites, and Canada composites are independent\n      // fetches. The default area layer should reveal US + Canada together when\n      // all three are healthy, so start them concurrently and wait for Canada\n      // before first reveal. The MSA *topology* is NOT fetched here: it feeds\n      // only the metros-only fallback layer and is pulled lazily by\n      // applyLayerVisibility if the composites layer fails.\n      //\n      // Use allSettled rather than Promise.all so that when both reject the\n      // catch below makes a deterministic 503-vs-overlay decision: Promise.all\n      // surfaces whichever rejection lands first, so a mixed failure (one\n      // endpoint 503s, the other times out) would land the silent-return vs\n      // unavailable-overlay branch at random. We rethrow a ServiceUnavailableError\n      // preferentially so a 503 anywhere in the pair is treated as \"service\n      // unavailable\" (silent return) regardless of fetch ordering.\n      const dataLayerResults = await measureAsync(\"map:init:data-layers\", () =>\n        Promise.allSettled([\n          ensureMsaMetricsLoadedData({ cfg }),\n          ensureNonmetrosLoadedData({ cfg }),\n          ensureCaAreasLoadedData({ cfg }),\n        ]),\n      );\n      const dataLayerRejections = dataLayerResults\n        .slice(0, 2)\n        .filter((result) => result.status === \"rejected\");\n      if (dataLayerRejections.length) {\n        throw (\n          dataLayerRejections.find(\n            (result) => result.reason instanceof ServiceUnavailableError,\n          )?.reason ?? dataLayerRejections[0].reason\n        );\n      }\n      const caAreasResult = dataLayerResults[2];\n      if (caAreasResult && caAreasResult.status === \"rejected\") {\n        console.warn(\"Unable to load Canadian area data; map will render without it.\", caAreasResult.reason);\n      }\n      updateFeaturePaths();\n      // The reveal must never be gated on a rejecting follow-up: if\n      // applyLayerVisibility throws (e.g. a non-fatal layer load failed), the\n      // base data layers still have to fade in or the map stays blank.\n      try {\n        await applyLayerVisibility();\n      } finally {\n        revealDataLayers();\n      }\n      sidePanelController.updateTogglePosition(true);\n      setMapUiReady(true);\n\n      // Prefetch state-layer data in the background so the layer toggle is\n      // instant. Deferred until after the default metro view is interactive\n      // so it doesn't block first paint. Provinces ride along for the same\n      // reason (they render in the same layer mode).\n      ensureStatesLoadedData({ cfg }).catch((statesError) => {\n        console.warn(\"Unable to prefetch state-level data; will retry on demand.\", statesError);\n      });\n      ensureProvincesLoadedData({ cfg }).catch((provincesError) => {\n        console.warn(\"Unable to prefetch province-level data; will retry on demand.\", provincesError);\n      });\n\n      // Fetch the URL<->geography slug table (plan unit E) so commitSelection can\n      // write canonical URLs on click and popstate can resolve a pathname back\n      // to a selection. Fire-and-forget here for the click path (a click before\n      // it lands simply writes the nation-root fallback URL); the deep-link\n      // block below awaits it explicitly so the initial URL reconciles. Failure\n      // degrades URL sync to no-op and is non-fatal.\n      const geoUrlsReady = ensureGeoUrlsLoaded(cfg).catch((geoUrlsError) => {\n        console.warn(\"Unable to load geo-url table; URL deep-linking disabled this session.\", geoUrlsError);\n      });\n\n      // Geo-urls load-race correction (plan unit E FIX \u2461). The slug table loads\n      // async; a region click BEFORE it resolves makes urlForKey(kind,code)\n      // return undefined, so syncSelectionUrl writes the \"/us-ai-map/\" fallback\n      // for a REAL selection (a wrong/stale slug). Once the table resolves,\n      // re-sync the CURRENT selection's URL so that early-click slug is\n      // corrected to the canonical entity path. Guards:\n      //   - Skip while a deep-link / popstate restore is mid-flight\n      //     (isApplyingHistory) \u2014 those paths intentionally suppress URL writes\n      //     and the browser is already at the right URL.\n      //   - Only act on a non-nation entity selection (nation URLs are written\n      //     by the deselect orchestrator and don't depend on the slug table).\n      //   - Only write when urlForKey now RESOLVES to a real slug. If it's still\n      //     undefined (entity absent from the table \u2014 e.g. a deep-linked entity\n      //     the table doesn't cover) we leave the address bar untouched rather\n      //     than clobbering a correct deep-link URL with the \"/us-ai-map/\"\n      //     fallback. This makes the correction strictly additive: it can only\n      //     replace a fallback with the right slug, never the reverse.\n      geoUrlsReady.then(() => {\n        if (isApplyingHistory()) return;\n        const sel = currentSelection.get();\n        if (!sel || sel.kind === \"nation\" || !sel.code) return;\n        if (!urlForKey(sel.kind, sel.code)) return;\n        syncSelectionUrl(sel.kind, sel.code);\n      });\n\n      // Deep-link focus (plan unit E): if the page was loaded at a per-entity\n      // URL, the server set cfg.initialSelection = {kind, code}. Reproduce the\n      // exact selection a click would produce (focus/zoom + panel + outline) by\n      // routing through the shared selectByKindCode path with fromHistory:true\n      // (so commitSelection does NOT overwrite the URL the browser already\n      // navigated to). We MUST ensure the relevant layer's data is loaded first\n      // \u2014 the click path only fires after a layer is visible, but a deep-link\n      // can target a layer that boot prefetches fire-and-forget\n      // (states/provinces) or doesn't load at all by default (Canadian\n      // composites). On resolution failure (entity absent from the render set,\n      // or load error) we fall through to the nation default below.\n      //\n      // This is deliberately OUTSIDE / BEFORE the nation-summary load: the\n      // deep-link depends only on its own layer's data, never on the nation\n      // aggregate, so a slow/failing /api/map/drilldown for the nation must not\n      // suppress focusing the requested geography.\n      let deepLinked = false;\n      const initialSelection = cfg.initialSelection;\n      if (initialSelection && initialSelection.kind === \"nation\") {\n        // Country hub (/us-ai-map/<country>/). BOTH hubs must open the desktop\n        // side panel: it ships collapsed (map-side-panel is-collapsed) and is\n        // otherwise only uncollapsed as a side effect of selecting a region or an\n        // ocean-click reset, so a bare country-hub load left the country summary\n        // hidden \u2014 the reported \"/us/ shows no US panel\" bug (and the symmetric\n        // latent /us-ai-map/ca/ case). Opening is desktop-only and independent of\n        // the nation drilldown fetch (a slow/failing fetch must not keep the\n        // panel collapsed); the panel content is filled by the branches below.\n        const openNationPanelOnDesktop =\n          !isMobileLayout() &&\n          sidePanelEl &&\n          sidePanelEl.classList.contains(\"is-collapsed\");\n        if (initialSelection.code === \"ca\") {\n          try {\n            await geoUrlsReady;\n            // Open the panel first so focusCanadaNation's guarded Canada-fit\n            // measures the open-panel viewport (mirrors the ocean-click Canada\n            // path). Shared with the popstate nation branch so deep-link and\n            // back/forward produce the identical Canada view (provinces layer +\n            // Canada nation selection + nation summary + guarded bounds fit +\n            // mobile preview). currentSelection.set inside writes no history, so\n            // the loaded /us-ai-map/ca/ URL is preserved.\n            if (openNationPanelOnDesktop) sidePanelController.setPanelCollapsed(false);\n            await focusCanadaNation();\n            deepLinked = true;\n          } catch (canadaError) {\n            console.warn(\"Unable to focus the Canada country view; falling back to nation default.\", canadaError);\n          }\n        } else if (openNationPanelOnDesktop) {\n          // \"us\": open the desktop panel, then fall through (deepLinked stays\n          // false) to the nation-default block below, which loads the aggregate,\n          // selects nation:us, and refreshes the panel \u2014 all it lacked was this\n          // open. Opening the panel changes the map viewport width, so defer the\n          // US-fit recenter until the transition settles (mirrors the ocean-click\n          // US path / focusSelectionFeature); otherwise getInitialUsTransform\n          // would measure a mid-animation panel rect.\n          sidePanelController.setPanelCollapsed(false);\n          sidePanelController.schedulePanelLayoutRecompute(\"panel-toggle\", () =>\n            setZoomTransformAnimated(getInitialUsTransform()),\n          );\n        }\n      } else if (initialSelection && initialSelection.kind && initialSelection.code) {\n        try {\n          // Wait for both the slug table (so a subsequent click writes the\n          // right URL) and the target layer's data before resolving.\n          await geoUrlsReady;\n          await ensureLayerLoadedForKind(initialSelection.kind);\n          deepLinked = selectByKindCode(initialSelection.kind, initialSelection.code, {\n            fromHistory: true,\n          });\n        } catch (deepLinkError) {\n          console.warn(\"Unable to focus deep-linked geography; falling back to nation view.\", deepLinkError);\n        }\n        if (deepLinked) {\n          // The deep-link committed the selection (panel + outline + focus);\n          // still surface the mobile preview sheet so totals are visible.\n          showUsMobilePreview();\n        }\n      }\n\n      // Default to US-wide metrics when no region is selected. The backend\n      // drilldown endpoint already serves an aggregate across all states\n      // (refresh_map_cache._refresh_nation_payload); loading it populates the\n      // `nation` holders that refreshSelectionPanel reads for kind=\"nation\".\n      // Skipped when a deep-link already committed a selection.\n      try {\n        if (!deepLinked) {\n          await ensureNationLoadedData({ cfg });\n          const selection = currentSelection.get();\n          if (!selection) {\n            currentSelection.set({\n              kind: \"nation\",\n              code: \"us\",\n              label: \"United States\",\n              name: \"United States\",\n            });\n            sidePanelController.refreshSelectionPanel();\n          } else if (selection.kind === \"nation\") {\n            sidePanelController.refreshSelectionPanel();\n          }\n          // Open the half-collapsed sheet by default on mobile so the US\n          // statistics are visible without requiring a tap.\n          showUsMobilePreview();\n        }\n      } catch (nationError) {\n        console.warn(\"Unable to load nation summary; side panel will remain empty until a region is selected.\", nationError);\n      }\n    } catch (error) {\n      // A 503 (service temporarily unavailable) used to return silently with no\n      // UI or log, leaving the map blank and undiagnosable. Both branches now\n      // land the unavailable overlay; only the log level differs so a transient\n      // 503 is distinguishable from a hard failure in production logs.\n      if (error instanceof ServiceUnavailableError) {\n        console.warn(\"Map service temporarily unavailable (503).\", error);\n      } else {\n        console.error(\"Unable to load state map data.\", error);\n      }\n      enterUnavailableOverlay();\n    } finally {\n      // County-border mesh is an ornamental 822 KB topojson with no API\n      // dependency. Deferred to here (was started early, outside the try)\n      // so it doesn't compete for bandwidth with the critical data fetches\n      // (world + msas + nonmetros) that gate first paint \u2014 kicked off only\n      // after the success path reveals the data layers / sets map UI ready,\n      // or after the catch path lands the unavailable overlay. The fetch is\n      // fire-and-forget; its late arrival is handled by the\n      // countyBordersLoaded signal \u2192 map/post-load.js subscriber \u2192\n      // applyLayerVisibility re-check, so a render that ran before the mesh\n      // arrived re-evaluates county-border visibility when it does. Failure\n      // is silent \u2014 the map renders without county detail.\n      ensureCountyBordersLoadedData({ cfg }).catch((countyError) => {\n        console.warn(\"Unable to load county borders; map will render without them.\", countyError);\n      });\n      // The Canadian census-division mesh follows the identical contract\n      // (ornamental static asset, caCdBordersLoaded signal \u2192 post-load\n      // subscriber \u2192 applyLayerVisibility re-check; failure is silent).\n      ensureCaCdBordersLoadedData({ cfg }).catch((cdError) => {\n        console.warn(\"Unable to load census-division borders; map will render without them.\", cdError);\n      });\n    }\n  }\n\n  window.addEventListener(\"resize\", handleResize);\n  init();\n}\n"],
  "mappings": "ukBA8KO,SAASA,GAAiB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REGION_METRIC_MAPS", "getRegionAccentColor", "mapColors", "getMetricValue", "getColorScale", "spec", "REGION_ACCENT_SPEC", "metricValue", "stateMetricsByCode", "msaMetricsByCode", "nonmetroMetricsByCode", "provinceMetricsByCode", "cmaMetricsByCode", "caNonmetroMetricsByCode", "stateTotalsByCode", "msaTotalsByCode", "nonmetroTotalsByCode", "provinceTotalsByCode", "cmaTotalsByCode", "caNonmetroTotalsByCode", "stateWagesByCode", "msaWagesByCode", "nonmetroWagesByCode", "provinceWagesByCode", "cmaWagesByCode", "caNonmetroWagesByCode", "stateExposureByCode", "msaExposureByCode", "nonmetroExposureByCode", "provinceExposureByCode", "cmaExposureByCode", "caNonmetroExposureByCode", "nation", "nationCa", "msaFeatureByCode", "areaOutlineFeatureByKey", "metricDomainCache", "statesLoaded", "msaMetricsLoaded", "msaTopologyLoaded", "provincesLoaded", "caAreasLoaded", "nonmetrosLoaded", "worldLoaded", "countyBordersLoaded", "caCdBordersLoaded", "nationLoaded", "nationCaLoaded", "init_caches", "__esmMin", "init_signal", "signal", "normalizeLayerMode", "value", "LAYER_MODE_AREA", "LAYER_MODE_COUNTRY", "LAYER_MODE_STATE", "normalizeMetricMode", "METRIC_MODE_AI_EXPOSURE", "METRIC_MODE_CALIBRATED", "METRIC_MODE_AI_ABILITIES", "normalizeStateCode", "raw", "normalizeMsaCode", "normalizeAreaCode", "normalizeCountyCode", "normalizeProvinceCode", "normalizeCmaCode", "getProvinceCode", "feature", "props", "getStateCode", "getMsaCode", "getAreaKey", "init_normalize", "__esmMin", "init_config", "getStatesColorScale", "statesColorScale", "getMsasColorScale", "areaColorScale", "getNonmetroColorScale", "getColorScaleForKey", "scaleKey", "getSelectedMetricIndex", "selectedMetric", "METRIC_MODE_AI_EXPOSURE", "METRIC_MODE_CALIBRATED", "getMetricValue", "metrics", "metricValue", "getMetricValueByIndex", "metricIndex", "getMetricDomain", "dataMap", "values", "min", "d3", "max", "setMetricDomainCacheEntry", "cacheKey", "abilityDomain", "exposureDomain", "calibratedDomain", "metricDomainCache", "METRIC_MODE_AI_ABILITIES", "updateCombinedAreaDomainCache", "metricMode", "domains", "key", "mins", "d", "value", "maxes", "updateCombinedStateDomainCache", "buildExposureScale", "fallback", "finite", "constantColor", "MAP_AI_SEQUENTIAL_INTERPOLATOR", "scale", "buildSequentialScaleFromDomain", "domain", "rebuildColorScales", "stateMetricsByCode", "provinceMetricsByCode", "combined", "msaMetricsByCode", "nonmetroMetricsByCode", "cmaMetricsByCode", "caNonmetroMetricsByCode", "getLegendGradient", "interpolator", "stop", "t", "init_colors", "__esmMin", "init_store", "init_caches", "init_normalize", "init_config", "updateGradientLegend", "legendWrapEl", "legendScaleEl", "legendLowEl", "legendHighEl", "getLegendGradient", "createGradientLegend", "container", "labels", "init_legend", "__esmMin", "init_colors", "createZoomController", "deps", "svg", "getProjection", "getPathGenerator", "setPathGenerator", "applyTransform", "onUserInteract", "ensureSelectionOutlineVisible", "getViewport", "getProvinceFeatures", "zoomBehavior", "isProgrammaticZoom", "getZoomScaleFactor", "collapsedOverride", "vp", "w", "effMin", "c", "effMax", "effInit", "BREAKPOINT_PHONE_MAX_PX", "MOBILE_INITIAL_ZOOM_MULTIPLIER", "getInitialUsTransform", "viewport", "initialCenterLonLat", "projectedUsCenter", "d3", "k", "tx", "ty", "getInitialCanadaTransform", "features", "computeFitZoomTransformForFeature", "setZoomTransform", "nextTransform", "zoomBy", "factor", "duration", "setZoomTransformAnimated", "feature", "pathGenerator", "padding", "FIT_PADDING_MAX_PX", "bounds", "x0", "y0", "x1", "y1", "bw", "bh", "cx", "cy", "availW", "availH", "focusFeatureInViewport", "targetScale", "preferFit", "keepScale", "fitTransform", "projection", "projectedCenter", "geoCenter", "scale", "current", "rescaledTarget", "setupZoomBehavior", "event", "fitProjection", "fitTarget", "refreshZoomExtent", "init_zoom", "__esmMin", "init_config", "computeMapViewport", "svgNode", "sidePanelEl", "collapsedOverride", "rect", "width", "height", "pad", "left", "right", "top", "bottom", "MIN_MAP_HEIGHT", "sheetEl", "handleH", "peekContentEl", "peekContentH", "peekHeight", "sheetState", "reservedSheetHeight", "isCollapsed", "panelRight", "MIN_MAP_WIDTH", "init_viewport", "__esmMin", "getTopoFeatures", "topology", "preferredObjectNames", "object", "getTopoObjectByNames", "objects", "objectNames", "selectedName", "name", "mergeTopoToFeature", "properties", "meshTopoObject", "init_topo", "__esmMin", "appendMapCacheVersion", "baseUrl", "cfg", "version", "sep", "init_api_url", "__esmMin", "deriveCalibratedMetric", "item", "totEmp", "direct", "normalizeFiniteNumber", "exposedCalibrated", "populateGeographyCaches", "items", "metricsMap", "totalsMap", "wagesMap", "exposureMap", "codeField", "normalizeCode", "code", "exposedTheoretical", "exposedCurrent", "theoretical", "current", "calibrated", "wageBill", "normalizeNullableFiniteNumber", "init_populate", "__esmMin", "init_format", "createMemoizedLoader", "signal", "load", "onFailure", "loadingPromise", "err", "init_createMemoizedLoader", "__esmMin", "getStatesFeatures", "statesFeatures", "getUsCountryFeature", "usCountryFeature", "getUsStateBorders", "usStateBorders", "ensureStatesLoaded", "cfg", "pendingCfg", "loadStates", "init_states", "__esmMin", "init_normalize", "init_topo", "init_caches", "init_fetch", "init_api_url", "init_populate", "init_createMemoizedLoader", "createMemoizedLoader", "statesLoaded", "statePayload", "statesTopology", "fetchJson", "appendMapCacheVersion", "fetchJsonWithFallback", "populateGeographyCaches", "stateMetricsByCode", "stateTotalsByCode", "stateWagesByCode", "stateExposureByCode", "normalizeStateCode", "getTopoFeatures", "mergeTopoToFeature", "meshTopoObject", "getMsaFeatures", "msaFeatures", "ensureMsaMetricsLoaded", "cfg", "pendingMetricsCfg", "loadMsaMetrics", "ensureMsasTopologyLoaded", "pendingTopologyCfg", "loadMsasTopology", "init_msas", "__esmMin", "init_normalize", "init_topo", "init_caches", "init_fetch", "init_api_url", "init_populate", "init_createMemoizedLoader", "createMemoizedLoader", "msaMetricsLoaded", "msaPayload", "fetchJson", "appendMapCacheVersion", "populateGeographyCaches", "msaMetricsByCode", "msaTotalsByCode", "msaWagesByCode", "msaExposureByCode", "normalizeMsaCode", "msaTopologyLoaded", "msaTopology", "fetchJsonWithFallback", "getTopoFeatures", "msaFeatureByCode", "feature", "code", "getMsaCode", "formatAreaName", "name", "getDetailAreaFeatures", "detailAreaFeatures", "buildAreaOutlineFeaturesFromCountyTopology", "countiesTopology", "countyMapPayload", "result", "areaByCounty", "objects", "countyObjectName", "countyObject", "countyGeometries", "geometriesByArea", "geometry", "props", "countyCode", "normalizeCountyCode", "areaInfo", "areaType", "normalizedAreaCode", "normalizeMsaCode", "normalizeAreaCode", "areaKey", "entry", "mergedGeometry", "normalizeAreaFeature", "feature", "loadCountyOutlineFallback", "cfg", "fetchJsonWithFallback", "fetchJson", "appendMapCacheVersion", "ensureNonmetrosLoaded", "pendingCfg", "loadNonmetros", "init_nonmetros", "__esmMin", "init_normalize", "init_topo", "init_caches", "init_fetch", "init_api_url", "init_populate", "init_createMemoizedLoader", "createMemoizedLoader", "nonmetrosLoaded", "nonmetroPayload", "areaCompositesTopology", "populateGeographyCaches", "nonmetroMetricsByCode", "nonmetroTotalsByCode", "nonmetroWagesByCode", "nonmetroExposureByCode", "precomputedAreaFeatures", "getTopoFeatures", "scrubOwnedOutlineKeys", "key", "areaOutlineFeatureByKey", "outlines", "getProvinceFeatures", "provinceFeatures", "getCaCountryFeature", "caCountryFeature", "getCaProvinceBorders", "caProvinceBorders", "ensureProvincesLoaded", "cfg", "pendingCfg", "loadProvinces", "init_provinces", "__esmMin", "init_normalize", "init_topo", "init_caches", "init_fetch", "init_api_url", "init_populate", "init_createMemoizedLoader", "createMemoizedLoader", "provincesLoaded", "provincePayload", "provincesTopology", "fetchJson", "appendMapCacheVersion", "fetchJsonWithFallback", "populateGeographyCaches", "provinceMetricsByCode", "provinceTotalsByCode", "provinceWagesByCode", "provinceExposureByCode", "normalizeProvinceCode", "getTopoFeatures", "mergeTopoToFeature", "meshTopoObject", "getCaAreaFeatures", "caAreaFeatures", "normalizeCaAreaFeature", "feature", "props", "areaType", "normalizedAreaCode", "normalizeCmaCode", "normalizeProvinceCode", "areaKey", "ensureCaAreasLoaded", "cfg", "pendingCfg", "loadCaAreas", "init_ca_areas", "__esmMin", "init_normalize", "init_topo", "init_caches", "init_fetch", "init_api_url", "init_populate", "init_createMemoizedLoader", "createMemoizedLoader", "caAreasLoaded", "cmaPayload", "caNonmetroPayload", "compositesTopology", "fetchJson", "appendMapCacheVersion", "fetchJsonWithFallback", "populateGeographyCaches", "cmaMetricsByCode", "cmaTotalsByCode", "cmaWagesByCode", "cmaExposureByCode", "caNonmetroMetricsByCode", "caNonmetroTotalsByCode", "caNonmetroWagesByCode", "caNonmetroExposureByCode", "getTopoFeatures", "areaOutlineFeatureByKey", "getWorldLandFeature", "worldLandFeature", "getWorldCountryBorders", "worldCountryBorders", "ensureWorldLoaded", "cfg", "worldLoaded", "loadingPromise", "worldTopology", "fetchJsonWithFallback", "worldObjects", "landObjectName", "name", "a", "b", "init_world", "__esmMin", "init_fetch", "init_caches", "cacheKey", "scope", "code", "evictIfNeeded", "familiesCache", "MAX_CACHED_REGIONS", "victim", "key", "PINNED_KEY", "loadJobFamilies", "cfg", "existing", "entry", "params", "FAMILY_FETCH_LIMIT", "version", "payload", "fetchJson", "families", "error", "peekJobFamilies", "sortFamiliesForDisplay", "metricField", "num", "v", "arr", "a", "b", "topFamilies", "limit", "sorted", "clearJobFamiliesCache", "init_job_families", "__esmMin", "init_fetch", "createTopOccupationsCaches", "caches", "activeCaches", "clearAllOccupationTasksCaches", "init_caches", "__esmMin", "resetNationLoaders", "country", "loadingPromises", "holderForCountry", "nationCa", "nation", "loadedSignalForCountry", "nationCaLoaded", "nationLoaded", "ensureNationLoaded", "cfg", "holder", "params", "payload", "fetchJson", "appendMapCacheVersion", "summary", "totalWorkforce", "totalWageBill", "normalizeFiniteNumber", "normalizeNullableFiniteNumber", "deriveCalibratedMetric", "err", "init_nation", "__esmMin", "init_format", "init_caches", "init_fetch", "init_populate", "init_api_url", "clearMetricDomainCache", "metricDomainCache", "resetAllGeographyLoaders", "stateMetricsByCode", "msaMetricsByCode", "nonmetroMetricsByCode", "provinceMetricsByCode", "cmaMetricsByCode", "caNonmetroMetricsByCode", "stateTotalsByCode", "msaTotalsByCode", "nonmetroTotalsByCode", "provinceTotalsByCode", "cmaTotalsByCode", "caNonmetroTotalsByCode", "stateWagesByCode", "msaWagesByCode", "nonmetroWagesByCode", "provinceWagesByCode", "cmaWagesByCode", "caNonmetroWagesByCode", "stateExposureByCode", "msaExposureByCode", "nonmetroExposureByCode", "provinceExposureByCode", "cmaExposureByCode", "caNonmetroExposureByCode", "nation", "nationCa", "resetNationLoaders", "statesLoaded", "msaMetricsLoaded", "provincesLoaded", "caAreasLoaded", "nonmetrosLoaded", "nationLoaded", "nationCaLoaded", "init_geography_reset", "__esmMin", "init_caches", "init_nation", "registerNationalExposureReset", "reset", "resetNationalExposureHooks", "bustStaleClientCachesIfNeeded", "cfg", "version", "previous", "STORAGE_KEY", "clearJobFamiliesCache", "clearAllOccupationTasksCaches", "clearExplanationCache", "resetAllGeographyLoaders", "resetNationalExposure", "init_cache_version", "__esmMin", "init_job_families", "init_caches", "init_task_explanation", "init_geography_reset", "getCountyBorders", "countyBorders", "ensureCountyBordersLoaded", "cfg", "countyBordersLoaded", "loadingPromise", "countiesTopology", "fetchJsonWithFallback", "objects", "countyObjectName", "name", "a", "b", "init_counties", "__esmMin", "init_fetch", "init_caches", "getCaCdBorders", "caCdBorders", "ensureCaCdBordersLoaded", "cfg", "caCdBordersLoaded", "loadingPromise", "topology", "fetchJsonWithFallback", "objects", "objectName", "name", "a", "b", "init_ca_census_divisions", "__esmMin", "init_fetch", "init_caches", "normalizePath", "pathname", "NATION_PATH", "path", "ensureGeoUrlsLoaded", "cfg", "loaded", "loadingPromise", "url", "response", "table", "nextForward", "nextReverse", "key", "sep", "kind", "code", "forwardMap", "reverseMap", "err", "urlForKey", "keyForPath", "hubCode", "NATION_HUB_PATHS", "init_geo_urls", "__esmMin", "COUNTRY_US", "COUNTRY_CA", "LAYER_VISUAL_COUNTRY", "LayerToggle", "init_layer_toggle", "__esmMin", "init_config", "LAYER_MODE_COUNTRY", "mountEl", "value", "LAYER_MODE_AREA", "onChange", "LAYER_MODE_STATE", "MOBILE_QUERY", "panel", "title", "optionsWrap", "option", "optionRow", "input", "inputId", "label", "marker", "text", "segmented", "optionEl", "nextValue", "notify", "normalized", "nextVisualValue", "visualValue", "active", "MetricToggle", "init_metric_toggle", "__esmMin", "init_config", "init_normalize", "mountEl", "value", "METRIC_MODE_AI_EXPOSURE", "onChange", "normalizeMetricMode", "MOBILE_QUERY", "METRIC_MODE_CALIBRATED", "METRIC_MODE_AI_ABILITIES", "panel", "header", "title", "optionsWrap", "option", "optionRow", "input", "inputId", "label", "marker", "text", "segmented", "optionEl", "nextValue", "notify", "normalized", "visualValue", "active", "createInfoModal", "modalEl", "dialogEl", "lastFocused", "currentTrigger", "isOpen", "open", "triggerEl", "close", "activateTab", "tabId", "tabs", "panels", "tab", "selected", "panel", "setup", "event", "target", "tabBtn", "idx", "nextIdx", "nextTab", "init_info_modal", "__esmMin", "isTextEntryTarget", "target", "el", "handleEscape", "deps", "infoModal", "treemapNav", "mobileSheet", "resetMapToNation", "installEscapeArbiter", "doc", "onKeyDown", "event", "init_keyboard", "__esmMin", "hoverCardTransform", "event", "HOVER_CARD_OFFSET_PX", "createHoverTooltip", "hoverCardEl", "hoverTitleEl", "hoverWorkersEl", "hoverWageEl", "tooltipEl", "show", "title", "totalWorkers", "wageBill", "formatWorkers", "getTotalWorkers", "formatWage", "position", "hide", "init_tooltip", "__esmMin", "init_format", "createSelectionController", "deps", "selectionOutlineLayer", "getPathGenerator", "focusFeatureInViewport", "getSidePanelEl", "setPanelCollapsed", "schedulePanelLayoutRecompute", "renderSelectionOutline", "pathGenerator", "feature", "key", "selectedOutline", "outlineData", "entry", "updateSelectionOutline", "outlineKey", "ensureSelectionOutlineVisible", "focusSelectionFeature", "targetScale", "duration", "runFocus", "sidePanelEl", "init_selection", "__esmMin", "init_store", "canMeasure", "measureSync", "name", "fn", "seq", "measureSeq", "start", "end", "measureAsync", "afterInputPaint", "init_perf", "__esmMin", "resolveVisibleLayers", "mode", "normalizedMode", "normalizeLayerMode", "inCountryMode", "LAYER_MODE_COUNTRY", "showStateLayer", "LAYER_MODE_STATE", "showCountryLayer", "statesLoaded", "provincesLoaded", "showAreaCompositeLayer", "nonmetrosLoaded", "showMsaFallbackLayer", "msaTopologyLoaded", "showStateAreaBorders", "showProvincesLayer", "showCaAreasLayer", "caAreasLoaded", "showCountyBorders", "countyBordersLoaded", "showCaCdBorders", "caCdBordersLoaded", "createLayersController", "deps", "statesLayer", "msasLayer", "nonmetrosLayer", "provincesLayer", "caAreasLayer", "countryLayer", "countyBordersLayer", "caCdBordersLayer", "metroNonmetroBordersLayer", "ensureStatesLoaded", "ensureMsaMetricsLoaded", "ensureMsasTopologyLoaded", "ensureNonmetrosLoaded", "ensureProvincesLoaded", "ensureCaAreasLoaded", "ensureCountryDataLoaded", "renderCountry", "refreshLegend", "refreshSelectionPanel", "ensureSelectionOutlineVisible", "LAYER_FADE_DURATION_MS", "LAYER_FADE_MODE_CHANGE_MS", "fadeLayer", "layer", "visible", "interactive", "slow", "duration", "transition", "applyLayerVisibility", "visibility", "selectedLayer", "err", "caAreasReady", "msaMetricsReady", "nonmetrosReady", "nonmetroError", "topoError", "resolvedVisibility", "setLayerMode", "nextLayerMode", "measureAsync", "setMetricMode", "nextMetricMode", "selectedMetric", "normalizeMetricMode", "init_layers", "__esmMin", "init_store", "init_caches", "init_normalize", "init_config", "init_perf", "createRenderController", "deps", "statesLayer", "msasLayer", "nonmetrosLayer", "provincesLayer", "caAreasLayer", "worldLayer", "countryLayer", "countyBordersLayer", "caCdBordersLayer", "metroNonmetroBordersLayer", "selectionOutlineLayer", "getPathGenerator", "getStatesFeatures", "getMsaFeatures", "getDetailAreaFeatures", "getProvinceFeatures", "getCaAreaFeatures", "getUsCountryFeature", "getCaCountryFeature", "getUsStateBorders", "getCaProvinceBorders", "getWorldLandFeature", "getWorldCountryBorders", "getCountyBorders", "getCaCdBorders", "getStateFeatureFill", "getMsaFeatureFill", "getAreaFeatureFill", "getProvinceFeatureFill", "getCaAreaFeatureFill", "getCountryFeatureFill", "onCountrySelect", "setHoveredFeatureElement", "clearHoverHighlight", "showTooltip", "positionTooltip", "hideTooltip", "updateSelection", "updateSelectionOutline", "focusSelectionFeature", "focusFeatureInViewport", "ensureSelectionOutlineVisible", "getFeatureName", "isMobileLayout", "showMobilePreview", "applyingHistory", "setApplyingHistory", "value", "isApplyingHistory", "selectionCommitSeq", "syncSelectionUrl", "kind", "code", "urlForKey", "commitSelection", "label", "name", "snap", "feature", "outlineKey", "measureSync", "commitSeq", "shouldSyncUrl", "currentSelection", "afterInputPaint", "getFeatureSnapshot", "getRegionMetrics", "areaName", "fallback", "resolveKindCode", "fallbackFeature", "f", "getStateCode", "getProvinceCode", "msaFeatureByCode", "areaOutlineFeatureByKey", "selectByKindCode", "fromHistory", "resolved", "prevApplyingHistory", "renderSimpleFeatureLayer", "cfg", "layer", "featureClass", "scope", "namePrefix", "getFeatures", "getCode", "getFill", "event", "hoverCapableMQ", "worldDatumToPath", "pathGenerator", "updateFeaturePaths", "renderWorld", "worldFeatures", "worldLandFeature", "worldCountryBorders", "renderCompositeAreaLayer", "resolveSubKind", "resolveOutlineFeature", "getAreaKey", "areaInfo", "getCountryFeatures", "features", "usFeature", "caFeature", "countryCode", "getCountryEdgeGeometries", "edges", "usEdges", "caEdges", "renderCountry", "holder", "nationCa", "nation", "renderStates", "renderMsas", "getMsaCode", "renderProvinces", "renderNonmetros", "isMetro", "normalizeMsaCode", "normalizeAreaCode", "renderCaAreas", "isCma", "normalizeCmaCode", "normalizeProvinceCode", "renderMetroNonmetroBorders", "renderCountyBorders", "mesh", "data", "renderCaCdBorders", "refreshFills", "subscribeToMetricChanges", "selectedMetric", "init_render", "__esmMin", "init_normalize", "init_store", "init_caches", "init_media_queries", "init_geo_urls", "init_perf", "setupPostLoadHandlers", "deps", "renderWorld", "renderStates", "renderProvinces", "renderMsas", "renderNonmetros", "renderCaAreas", "renderCountry", "renderMetroNonmetroBorders", "renderCountyBorders", "renderCaCdBorders", "updateFeaturePaths", "applyLayerVisibility", "worldLoaded", "loaded", "statesLoaded", "setMetricDomainCacheEntry", "stateMetricsByCode", "updateCombinedStateDomainCache", "rebuildColorScales", "provincesLoaded", "updateGradientLegend", "provinceMetricsByCode", "msaMetricsLoaded", "msaMetricsByCode", "updateCombinedAreaDomainCache", "nonmetrosLoaded", "caAreasLoaded", "msaTopologyLoaded", "nonmetroMetricsByCode", "cmaMetricsByCode", "caNonmetroMetricsByCode", "countyBordersLoaded", "caCdBordersLoaded", "nationLoaded", "nationCaLoaded", "init_post_load", "__esmMin", "init_caches", "init_colors", "init_legend", "createSidePanelController", "deps", "els", "mapOps", "refreshTopOccupationsPanel", "sidePanelEl", "sidePanelToggleEl", "rootEl", "svgNode", "selectedTypeEl", "selectedNameEl", "selectedTotalWorkforceEl", "selectedTotalWageBillEl", "selectedExposedWageBillEl", "selectedExposedWorkforceEl", "selectedWorkforceGaugeValueEl", "selectedWorkforceGaugeProgressEl", "selectedWageBillGaugeValueEl", "selectedWageBillGaugeProgressEl", "getMapColors", "getCurrentTransform", "getProjection", "getMapViewport", "fitProjection", "refreshZoomExtent", "updateFeaturePaths", "ensureSelectionOutlineVisible", "setZoomTransform", "setZoomTransformAnimated", "getInitialUsTransform", "userHasInteractedWithZoom", "updateCircularGauge", "progressEl", "valueEl", "ratio", "gaugeEl", "radius", "circumference", "clampedRatio", "clamp01", "formatGaugePercentage", "setGaugeAccentColor", "color", "lab", "getSelectionAccentColor", "selection", "currentSelection", "getRegionAccentColor", "getMetricValue", "getColorScaleForKey", "resolveExposureMetrics", "exposureStats", "metric", "selectedMetric", "entry", "METRIC_MODE_AI_EXPOSURE", "METRIC_MODE_CALIBRATED", "normalizeNullableFiniteNumber", "clearSelectionDisplay", "name", "updateSelection", "type", "totalWorkers", "wageBill", "exposure", "normalizedTotalWorkers", "getTotalWorkers", "workforceRatio", "calculateExposureRatio", "wageBillRatio", "selectionAccentColor", "formatRoundedCount", "formatRoundedWage", "refreshSelectionPanel", "holder", "nationCa", "nation", "REGION_KINDS", "metrics", "getRegionMetrics", "updateTogglePosition", "collapsed", "containerRect", "left", "top", "panelRect", "setPanelCollapsed", "captureViewportGeoCenter", "viewport", "mapCoordinates", "geo", "handleLayoutChange", "reason", "geoCenterBeforeResize", "currentScale", "projectedCenter", "tx", "ty", "shouldPreserveView", "pendingRecompute", "PANEL_TRANSITION_FALLBACK_MS", "schedulePanelLayoutRecompute", "onDone", "fire", "done", "onTransitionEnd", "event", "init_side_panel", "__esmMin", "init_config", "init_store", "init_caches", "init_colors", "init_format", "velocityFromSamples", "samples", "releaseTime", "windowMs", "last", "cutoff", "i", "first", "dt", "prev", "dtRaw", "projectFlingDistance", "velocity", "decelerationRate", "decideSheetTarget", "currentHeight", "startHeight", "detents", "commitPx", "ladder", "nearestIdx", "h", "bi", "bd", "d", "projectedHeight", "targetIdx", "startIdx", "downTravel", "init_sheet_snap", "__esmMin", "createMobileSheet", "deps", "getMapColors", "bodyDrag", "eventLogUrl", "reduceMotionMQL", "cardEl", "titleEl", "typeEl", "workersEl", "wageEl", "handleEl", "peekEl", "expandedEl", "pendingHideOnEnd", "clearPendingHide", "setSheetTranslate", "px", "getSheetHeight", "snapForState", "state", "h", "bottomInset", "setState", "lastMeta", "resolveExposure", "exposureStats", "metric", "selectedMetric", "entry", "METRIC_MODE_AI_EXPOSURE", "METRIC_MODE_CALIBRATED", "normalizeNullableFiniteNumber", "getMobileAccentColor", "selection", "currentSelection", "getRegionAccentColor", "getMetricValue", "getColorScaleForKey", "renderStatWithPercent", "el", "countsText", "ratio", "countsEl", "pctEl", "formatPenetrationPercentRounded", "renderMeta", "meta", "total", "getTotalWorkers", "wage", "exposedWorkforce", "exposedWageBill", "workforceRatio", "calculateExposureRatio", "wageRatio", "formatRoundedCount", "formatRoundedWage", "accent", "show", "name", "type", "totalWorkers", "wageBill", "wasClosed", "hide", "wasOpen", "onEnd", "ev", "isShowing", "hideForEscape", "reportSheetEvent", "dragStartY", "dragStartHeight", "dragCurrentHeight", "dragDetents", "pendingMaxHeight", "maxHeightRaf", "dragSamples", "dragging", "dragMoved", "lastGestureOrigin", "pendingBodyDrag", "bodyStartY", "writeMaxHeight", "scheduleMaxHeight", "next", "flushMaxHeight", "clearMaxHeightSchedule", "method", "fromState", "toState", "payload", "blob", "getMaxSheetHeight", "vh", "getDetentHeights", "handleH", "peekH", "expandedH", "max", "beginDrag", "clientY", "timeStamp", "pointerId", "captureEl", "origin", "startH", "onPointerDown", "e", "measureSync", "onPointerMove", "dy", "onPointerUp", "currentH", "detents", "releaseT", "velocity", "velocityFromSamples", "target", "decideSheetTarget", "cycleStateForward", "s", "BODY_DRAG_TAKEOVER_PX", "onBodyPointerDown", "onBodyPointerMove", "onBodyPointerUp", "vvRaf", "refresh", "init_mobile_sheet", "__esmMin", "init_config", "init_store", "init_caches", "init_colors", "init_format", "init_sheet_snap", "init_perf", "clearTreemapModuleCache", "cached", "cachedTreemapVersion", "inflight", "loadTreemap", "exposureMod", "occupationsMod", "navMod", "mods", "err", "showLoadError", "clearTaskViewModuleCache", "taskCached", "taskInflight", "loadTaskView", "setTreemapErrorBanner", "target", "onRetry", "errorBannerTarget", "errorBannerOnRetry", "clearErrorBanner", "host", "banner", "msg", "btn", "e", "init_treemap", "__esmMin", "init_constants", "createTreemapTooltip", "tooltipEl", "hide", "position", "clientX", "clientY", "pad", "offset", "tw", "th", "x", "y", "show", "event", "lineStrings", "lines", "s", "titleNode", "i", "row", "init_tooltip", "__esmMin", "createNationalExposureLoader", "cfg", "byLabel", "loadPromise", "lastFailureAt", "ensureLoaded", "NATIONAL_RETRY_COOLDOWN_MS", "families", "loadJobFamilies", "family", "labelKey", "getJobFamilyLookupKey", "error", "getValue", "item", "key", "getExposureValue", "hasData", "values", "reset", "init_national_exposure", "__esmMin", "init_job_families", "init_shared", "createExposureColorScales", "nationalExposure", "getMapColors", "buildNationalExposureFillScale", "values", "family", "getExposureValue", "value", "scale", "buildExposureScale", "item", "getLocalExposureColorScale", "items", "getOccupationExposureColor", "clamped", "clamp01", "MAP_AI_SEQUENTIAL_INTERPOLATOR", "init_color_scales", "__esmMin", "init_colors", "init_shared", "init_format", "createDrilldownState", "mode", "selectedOccupationKey", "selectedOccupationData", "topSerial", "taskSerial", "next", "data", "key", "serial", "init_drilldown", "__esmMin", "createTreemapBoot", "deps", "cfg", "els", "treemapNavEls", "tooltip", "drilldown", "getOccupationExposureColor", "getNationalExposureValue", "getSelectionPayload", "loadJobFamilies", "updateBackToTop5Visibility", "syncNavChrome", "setViewMode", "refreshTopOccupationsPanel", "refreshTaskTreemapPanel", "resetTopOccupationsTaskState", "handleBackToTop5", "onOccupationClick", "onOccupationIntent", "getOverviewViewMode", "mountOverviewToggle", "exposureCtrl", "taskCtrl", "taskCtrlUiVersion", "occupationsCtrl", "navCtrl", "navTeardown", "ensureReady", "mods", "loadTreemap", "m", "data", "key", "occs", "family", "ensureTaskReady", "taskMods", "loadTaskView", "teardownNav", "init_treemap_boot", "__esmMin", "init_treemap", "init_constants", "selectionToPayload", "selection", "DRILLDOWN_SCOPES", "init_selection_scope", "__esmMin", "createTopOccupationsCore", "deps", "cfg", "els", "caches", "drilldown", "nationalExposure", "scales", "treemapBoot", "getSelectionPayload", "getSelectionKey", "getCurrentSelection", "getOverviewLimit", "getOverviewStatusText", "forceCompactTileLabels", "renderOverviewMeta", "beforeTaskRender", "resetTaskState", "syncNavChrome", "updateOverviewChrome", "selectIndustry", "clearTopOccupationsPanel", "shouldRefresh", "beforeRefresh", "unavailableMessage", "fetchJson", "topOccupationsDetailEl", "topOccupationsDetailMetaEl", "topOccupationsStatusEl", "topOccupationsTreemapEl", "inFlightTaskFetch", "abortInFlightTaskFetch", "cancelPendingTreemapPaints", "exposureCtrl", "taskCtrl", "fetchOccupationTasks", "selectionPayload", "occupation", "signal", "params", "getOccupationKey", "appendMapCacheVersion", "refreshTaskTreemapPanel", "selection", "sel", "occupationData", "cacheKey", "occupationTasksCacheKey", "cached", "tasksSatisfyCurrentMetric", "selectedMetric", "requestSerial", "controller", "payload", "tasks", "OCCUPATION_TASKS_MAX_CACHED", "oldest", "error", "renderTopOccupationsPanel", "occupations", "mods", "occupationsCtrl", "selectionKey", "treemapFamilyData", "items", "selectionLabel", "displayItems", "topFamilies", "getTopOccupationsMetricField", "industryFillAccessor", "formatWorkers", "formatPenetrationPercentRounded", "item", "getEmploymentValue", "refreshTopOccupationsPanel", "peeked", "peekJobFamilies", "loadJobFamilies", "init_core", "__esmMin", "init_fetch", "init_api_url", "init_job_families", "init_format", "init_shared", "init_store", "createOverviewViewToggle", "getMode", "onChange", "root", "treemapBtn", "tableBtn", "sync", "isTable", "mount", "container", "detach", "createTopOccupationsController", "deps", "cfg", "els", "treemapNavEls", "mapOps", "panelOps", "selectionOps", "sidePanelEl", "topOccupationsDetailEl", "topOccupationsDetailMetaEl", "topOccupationsStatusEl", "topOccupationsTreemapEl", "treemapTooltipEl", "panelBackTop5El", "panelExpandEl", "getMapColors", "getCurrentTransform", "setPanelCollapsed", "schedulePanelLayoutRecompute", "clearSelectionDisplay", "focusFeatureInViewport", "ensureSelectionOutlineVisible", "tooltip", "createTreemapTooltip", "overviewViewMode", "overviewToggle", "mode", "refreshTopOccupationsPanel", "setTreemapErrorBanner", "caches", "createTopOccupationsCaches", "nationalExposure", "createNationalExposureLoader", "registerNationalExposureReset", "scales", "createExposureColorScales", "drilldown", "createDrilldownState", "getTopOccupationsSelectionPayload", "selection", "currentSelection", "selectionToPayload", "getTopOccupationsSelectionKey", "payload", "updateBackToTop5Visibility", "topOccupationsViewMode", "updateExpandButtonVisibility", "resetTopOccupationsTaskState", "selectedTreemapFamilyData", "syncNavChrome", "navCtrl", "treemapBoot", "hasOpenTreemapPopovers", "closeTreemapPopovers", "selectIndustryAndRenderOccupations", "item", "pendingViewModeTimerId", "pendingViewModeRafId", "pendingTransitioningEl", "setTopOccupationsViewMode", "nextMode", "rerender", "suppressLayout", "normalizedMode", "changed", "contentEl", "applyMode", "outlineFeature", "selectedOutline", "currentTransform", "k", "FADE_OUT_MS", "MAX_WAIT_MS", "oldTreemapChild", "start", "tick", "newChild", "treemapReady", "timedOut", "loadTreemapNavJobFamilies", "loadJobFamilies", "createTreemapBoot", "value", "refreshTaskTreemapPanel", "handleBackToTop5", "getOccupationKey", "pillsEl", "clearTopOccupationsPanel", "message", "keepSelectionDisplay", "core", "renderOverviewMeta", "displayItems", "formatWorkers", "formatPenetrationPercentRounded", "renderIndustryOverviewMeta", "getEmploymentValue", "getTopOccupationsExposureLabel", "createTopOccupationsCore", "TOP_OCCUPATIONS_EXPANDED_LIMIT", "TOP_OCCUPATIONS_COMPACT_LIMIT", "onPanelClose", "hideTreemapTooltip", "init_top_occupations", "__esmMin", "init_store", "init_job_families", "init_cache_version", "init_treemap", "init_shared", "init_tooltip", "init_detail_meta_pills", "init_caches", "init_national_exposure", "init_color_scales", "init_drilldown", "init_treemap_boot", "init_selection_scope", "init_core", "createMobileTopOccupationsController", "deps", "cfg", "els", "treemapNavEls", "mapOps", "isMobileLayout", "topOccupationsDetailEl", "topOccupationsDetailMetaEl", "topOccupationsStatusEl", "topOccupationsTreemapEl", "treemapTooltipEl", "getMapColors", "tooltip", "createTreemapTooltip", "caches", "createTopOccupationsCaches", "nationalExposure", "createNationalExposureLoader", "registerNationalExposureReset", "scales", "createExposureColorScales", "drilldown", "createDrilldownState", "viewModePinned", "pinViewModeExpanded", "topOccupationsViewMode", "getSelectionPayload", "selection", "currentSelection", "selectionToPayload", "getSelectionKey", "payload", "resetTaskState", "selectedTreemapFamilyData", "syncNavChrome", "navCtrl", "treemapBoot", "hasOpenTreemapPopovers", "closeTreemapPopovers", "selectIndustryAndRenderOccupations", "item", "refreshTopOccupationsPanel", "setViewMode", "loadNavJobFamilies", "loadJobFamilies", "createTreemapBoot", "value", "refreshTaskTreemapPanel", "getOccupationKey", "clearTopOccupationsPanel", "message", "core", "createTopOccupationsCore", "MOBILE_TOP_LIMIT", "hideTreemapTooltip", "init_mobile", "__esmMin", "init_store", "init_job_families", "init_cache_version", "init_shared", "init_tooltip", "init_caches", "init_national_exposure", "init_color_scales", "init_drilldown", "init_treemap_boot", "init_selection_scope", "init_core", "setupMobileShell", "deps", "sidePanelEl", "mobileSheet", "resetMapToNation", "showUsMobilePreview", "restoreMobileSheetPreview", "isMobileLayout", "openMapInfoModal", "menuToggleEl", "menuEl", "settingsFabEl", "infoFabEl", "settingsOverlayEl", "settingsOverlayCloseEl", "settingsSlotEl", "resetBtnEl", "layerToggleEl", "layerToggleDesktopParent", "layerToggleDesktopNext", "mq", "MOBILE_QUERY", "applyLayoutForMode", "closeMenu", "closeSettingsOverlay", "menuFocusables", "setMenuTabbable", "tabbable", "el", "openMenu", "isMenuOpen", "e", "target", "settingsOverlayLastFocused", "getSettingsFocusables", "trapSettingsTab", "event", "focusables", "first", "last", "active", "openSettingsOverlay", "focusTarget", "backLinkEl", "syncSidePanelOverlayClass", "collapsed", "init_mobile_shell", "__esmMin", "init_config", "queryTopLevelNodes", "init_dom", "__esmMin", "queryMapElements", "init_els", "__esmMin", "buildLayerTogglePanel", "layerToggleMountEl", "layerToggleHostEl", "metricToggleHostEl", "combinedPanel", "topRow", "layerHost", "metricHost", "legendHost", "createGradientLegend", "init_layer_toggle_panel", "__esmMin", "init_legend", "createRegionSnapshot", "isMobileLayout", "mobileSheet", "showUsMobilePreview", "nation", "restoreMobileSheetPreview", "selection", "currentSelection", "totalWorkers", "wageBill", "exposureStats", "getRegionMetrics", "init_regionSnapshot", "__esmMin", "init_store", "init_caches", "createGeolocate", "svgNode", "findFeatureAtLngLat", "lngLat", "selector", "selectedLayer", "nodes", "node", "feature", "locateStatusEl", "locateStatusHideTimer", "showLocateStatus", "message", "isInUnmappedUsTerritory", "lng", "lat", "inAlaska", "inHawaii", "inPuertoRico", "locateUserAndSelect", "btn", "position", "msg", "error", "init_geolocate", "__esmMin", "init_store", "require_us_ai_map", "__commonJSMin", "init_config", "init_legend", "init_zoom", "init_viewport", "init_states", "init_msas", "init_nonmetros", "init_provinces", "init_ca_areas", "init_world", "init_cache_version", "init_counties", "init_ca_census_divisions", "init_nation", "init_geo_urls", "init_fetch", "init_normalize", "init_layer_toggle", "init_metric_toggle", "init_info_modal", "init_keyboard", "init_tooltip", "init_selection", "init_layers", "init_render", "init_post_load", "init_store", "init_caches", "init_colors", "init_side_panel", "init_mobile_sheet", "init_top_occupations", "init_mobile", "init_mobile_shell", "init_dom", "init_els", "init_layer_toggle_panel", "init_regionSnapshot", "init_geolocate", "init_perf", "MOBILE_MQ", "MOBILE_QUERY", "cfg", "bustStaleClientCachesIfNeeded", "bootMap", "topNodes", "queryTopLevelNodes", "rootEl", "svgNode", "tooltipEl", "treemapTooltipEl", "hoverCardEl", "sidePanelEl", "infoModalEl", "hoverTitleEl", "hoverWorkersEl", "hoverWageEl", "selectedTypeEl", "selectedNameEl", "topOccupationsDetailEl", "topOccupationsDetailMetaEl", "topOccupationsStatusEl", "topOccupationsTreemapEl", "topOccupationsTasksEl", "treemapNavRootEl", "treemapNavRegionLabelEl", "treemapNavIndustryBtnEl", "treemapNavIndustryLabelEl", "treemapNavJobsBtnEl", "treemapNavJobsLabelEl", "treemapNavIndustryPopoverEl", "treemapNavIndustrySearchEl", "treemapNavIndustryClearEl", "treemapNavIndustryListEl", "treemapNavJobsPopoverEl", "treemapNavJobsSearchEl", "treemapNavJobsClearEl", "treemapNavJobsListEl", "sidePanelToggleEl", "panelCloseEl", "panelBackTop5El", "panelExpandEl", "treemapNavJobsChevronEl", "treemapNavJobsClearJobEl", "treemapNavIndustryChevronEl", "treemapNavIndustryClearIndustryEl", "mobileTreemapDetailEl", "mobileTreemapDetailMetaEl", "mobileTreemapStatusEl", "mobileTreemapEl", "mobileTreemapTasksEl", "mobileTreemapNavRootEl", "mobileTreemapNavRegionLabelEl", "mobileTreemapNavIndustryBtnEl", "mobileTreemapNavIndustryLabelEl", "mobileTreemapNavJobsBtnEl", "mobileTreemapNavJobsLabelEl", "mobileTreemapNavIndustryPopoverEl", "mobileTreemapNavIndustrySearchEl", "mobileTreemapNavIndustryClearEl", "mobileTreemapNavIndustryListEl", "mobileTreemapNavJobsPopoverEl", "mobileTreemapNavJobsSearchEl", "mobileTreemapNavJobsClearEl", "mobileTreemapNavJobsListEl", "mobileTreemapNavJobsChevronEl", "mobileTreemapNavJobsClearJobEl", "mobileTreemapNavIndustryChevronEl", "mobileTreemapNavIndustryClearIndustryEl", "layerToggleMountEl", "infoModalDialogEl", "homeIconEl", "zoomControlsEl", "selectedTotalWorkforceEl", "selectedTotalWageBillEl", "selectedExposedWageBillEl", "selectedExposedWorkforceEl", "selectedWorkforceGaugeValueEl", "selectedWorkforceGaugeProgressEl", "selectedWageBillGaugeValueEl", "selectedWageBillGaugeProgressEl", "queryMapElements", "gatedUiElements", "infoModal", "createInfoModal", "hoverTooltip", "createHoverTooltip", "openMapInfoModal", "setupMapInfoModal", "showTooltip", "hideTooltip", "positionTooltip", "resizeRaf", "currentTransform", "userHasInteractedWithZoom", "hoveredFeatureElement", "hasRevealedBaseMap", "hasRevealedDataLayers", "mapColors", "FALLBACK_COLORS", "svg", "mapRoot", "worldLayer", "dataLayers", "statesLayer", "countryLayer", "provincesLayer", "msasLayer", "nonmetrosLayer", "caAreasLayer", "countyBordersLayer", "caCdBordersLayer", "metroNonmetroBordersLayer", "selectionOutlineLayer", "projection", "pathGenerator", "sidePanelController", "layerToggle", "topOccupationsController", "mobileTopOccupationsController", "getCssColorVariable", "name", "fallback", "rawValue", "readMapColorsFromCss", "getStateFeatureFill", "feature", "code", "getStateCode", "metrics", "stateMetricsByCode", "metricValue", "getMetricValue", "getStatesColorScale", "getMsaFeatureFill", "getMsaCode", "msaMetricsByCode", "getMsasColorScale", "getAreaFeatureFill", "areaInfo", "areaCode", "normalizeMsaCode", "nonmetroMetricsByCode", "normalizeAreaCode", "getNonmetroColorScale", "getProvinceFeatureFill", "getProvinceCode", "provinceMetricsByCode", "getCaAreaFeatureFill", "cmaMetricsByCode", "normalizeCmaCode", "caNonmetroMetricsByCode", "normalizeProvinceCode", "getCountryFeatureFill", "holder", "COUNTRY_CA", "nationCa", "nation", "onCountrySelect", "country", "clearHoverHighlight", "isCanada", "label", "currentSelection", "syncSelectionUrl", "updateSelectionOutline", "ensureNationLoaded", "selection", "renderController", "err", "isMobileLayout", "showUsMobilePreview", "transform", "getInitialCanadaTransform", "getInitialUsTransform", "setZoomTransformAnimated", "refreshLegend", "updateGradientLegend", "syncMapVisualsFromCss", "rebuildColorScales", "setupHomeIconUi", "LUCIDE_HOME_ICON", "getMapViewport", "collapsedOverride", "computeMapViewport", "enterUnavailableOverlay", "setMapVisible", "setMapUiReady", "overlayEl", "visible", "revealBaseMap", "revealDataLayers", "getFeatureName", "fallbackPrefix", "props", "ready", "element", "setHoveredFeatureElement", "applyTransform", "zoomController", "createZoomController", "p", "ensureSelectionOutlineVisible", "getProvinceFeatures", "setZoomTransform", "focusFeatureInViewport", "setupZoomBehavior", "fitProjection", "refreshZoomExtent", "zoomByStep", "selectionController", "createSelectionController", "collapsed", "reason", "onDone", "focusSelectionFeature", "createRenderController", "getStatesFeatures", "getMsaFeatures", "getDetailAreaFeatures", "getCaAreaFeatures", "getUsCountryFeature", "getCaCountryFeature", "getUsStateBorders", "getCaProvinceBorders", "getWorldLandFeature", "getWorldCountryBorders", "getCountyBorders", "getCaCdBorders", "event", "totalWorkers", "wageBill", "args", "meta", "mobileSheet", "renderWorld", "renderStates", "renderProvinces", "renderMsas", "renderNonmetros", "renderCaAreas", "renderCountry", "renderMetroNonmetroBorders", "renderCountyBorders", "renderCaCdBorders", "updateFeaturePaths", "selectByKindCode", "setApplyingHistory", "isApplyingHistory", "createSidePanelController", "createTopOccupationsController", "c", "r", "createMobileTopOccupationsController", "layersController", "createLayersController", "ensureStatesLoaded", "ensureMsaMetricsLoaded", "ensureMsasTopologyLoaded", "ensureNonmetrosLoaded", "ensureProvincesLoaded", "ensureCaAreasLoaded", "COUNTRY_US", "setLayerMode", "setMetricMode", "applyLayerVisibility", "selectedMetric", "setupPostLoadHandlers", "ensureLayerLoadedForKind", "kind", "applyMode", "mode", "LAYER_MODE_STATE", "LAYER_MODE_AREA", "createMobileSheet", "restoreMobileSheetPreview", "createRegionSnapshot", "locateUserAndSelect", "createGeolocate", "wasMobileLayout", "handleResize", "nowMobileLayout", "collapsedState", "init", "layerToggleHostEl", "metricToggleHostEl", "buildLayerTogglePanel", "LayerToggle", "selectedLayer", "visualValue", "MetricToggle", "nextValue", "syncLayerToggleWidth", "w", "rafId", "panelInfoEl", "currentlyCollapsed", "resetSelectionToNation", "zoomInBtn", "zoomOutBtn", "zoomResetBtn", "locateMeBtn", "mapUnavailableRetryBtn", "clearMapSelection", "focusCanadaNation", "canadaTransform", "isCanadianSelection", "openPanel", "collapsePanel", "forceCountry", "wasCanadian", "recenterOnUs", "setupMobileShell", "TORONTO_LATITUDE", "clickLatitude", "point", "lngLat", "lat", "installEscapeArbiter", "key", "keyForPath", "popError", "measureAsync", "ensureWorldLoaded", "dataLayerResults", "dataLayerRejections", "result", "ServiceUnavailableError", "caAreasResult", "statesError", "provincesError", "geoUrlsReady", "ensureGeoUrlsLoaded", "geoUrlsError", "sel", "urlForKey", "deepLinked", "initialSelection", "openNationPanelOnDesktop", "canadaError", "deepLinkError", "nationError", "error", "ensureCountyBordersLoaded", "countyError", "ensureCaCdBordersLoaded", "cdError"]
}
