text paste
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Post-Sumerian Biopolitical, Plague &amp; IVC Reference Atlas (2004 BCE – 642 CE)</title>
<style>
  :root {
    --bg: #0b0e14;
    --panel: #131822;
    --panel-border: #252e42;
    --text: #e6ecf5;
    --muted: #8b98b0;
    --accent: #f59e0b;
    --accent-soft: rgba(245, 158, 11, 0.16);
    --plague: #f43f5e;
    --cattle: #eab308;
    --pregnancy: #d946ef;
    --cyan: #38bdf8;
    --emerald: #10b981;
  }
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    background: var(--bg);
    color: var(--text);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;
  }
  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 9px 16px;
    background: var(--panel);
    border-bottom: 1px solid var(--panel-border);
    gap: 10px;
    flex-wrap: wrap;
  }
  .title-block h1 {
    font-size: 14.5px;
    font-weight: 700;
    letter-spacing: 0.3px;
    color: #fff;
  }
  .title-block p {
    font-size: 11px;
    color: var(--muted);
    margin-top: 2px;
  }
  .controls {
    display: flex;
    align-items: center;
    gap: 7px;
    flex-wrap: wrap;
  }
  button {
    background: #1c2434;
    color: var(--text);
    border: 1px solid var(--panel-border);
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 11.5px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.15s ease;
  }
  button:hover { background: #263147; border-color: #3b4a69; }
  button.primary {
    background: var(--accent);
    color: #0b0e14;
    border-color: var(--accent);
  }
  button.primary:hover { background: #fbbf24; }
  .filter-bar {
    display: flex;
    align-items: center;
    background: #0f141d;
    border: 1px solid var(--panel-border);
    border-radius: 6px;
    padding: 2px;
    gap: 2px;
  }
  .filter-btn {
    border: none;
    background: transparent;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    color: var(--muted);
  }
  .filter-btn.active {
    background: #232d42;
    color: #fff;
  }
  .filter-btn.f-plague.active { background: rgba(244, 63, 94, 0.22); color: #fda4af; border: 1px solid rgba(244,63,94,0.45); }
  .filter-btn.f-cattle.active { background: rgba(234, 179, 8, 0.22); color: #fde047; border: 1px solid rgba(234,179,8,0.45); }
  .filter-btn.f-preg.active { background: rgba(217, 70, 239, 0.22); color: #f0abfc; border: 1px solid rgba(217,70,239,0.45); }
  .zoom-group {
    display: flex;
    align-items: center;
    background: #161c28;
    border: 1px solid var(--panel-border);
    border-radius: 6px;
    overflow: hidden;
  }
  .zoom-group button {
    border: none;
    border-radius: 0;
    padding: 5px 9px;
    font-size: 12.5px;
  }
  .zoom-label {
    padding: 0 7px;
    font-size: 11px;
    color: var(--muted);
    font-variant-numeric: tabular-nums;
  }
  main {
    display: grid;
    grid-template-columns: 1fr 385px;
    flex: 1;
    min-height: 0;
  }
  .map-wrap {
    position: relative;
    width: 100%;
    height: 100%;
    background: #070b12;
    overflow: hidden;
    cursor: grab;
  }
  .map-wrap:active { cursor: grabbing; }
  canvas {
    display: block;
    width: 100%;
    height: 100%;
  }
  .hud-top-left {
    position: absolute;
    top: 12px;
    left: 12px;
    background: rgba(13, 18, 28, 0.9);
    backdrop-filter: blur(8px);
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 9px 12px;
    pointer-events: none;
    max-width: 365px;
  }
  .epoch-badge {
    display: inline-block;
    font-size: 11px;
    font-weight: 700;
    color: var(--accent);
    background: var(--accent-soft);
    padding: 2px 7px;
    border-radius: 4px;
    margin-bottom: 4px;
    letter-spacing: 0.4px;
  }
  .epoch-title {
    font-size: 13.5px;
    font-weight: 700;
    color: #fff;
  }
  .map-tooltip {
    position: absolute;
    display: none;
    background: rgba(11, 14, 20, 0.96);
    border: 1px solid var(--accent);
    border-radius: 7px;
    padding: 9px 11px;
    max-width: 285px;
    font-size: 11.5px;
    line-height: 1.42;
    color: #e2e8f0;
    pointer-events: none;
    z-index: 20;
    box-shadow: 0 8px 24px rgba(0,0,0,0.65);
  }
  .map-tooltip .tt-head {
    font-weight: 700;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 3px;
  }
  .hud-hint {
    position: absolute;
    bottom: 12px;
    left: 12px;
    background: rgba(13, 18, 28, 0.85);
    border: 1px solid var(--panel-border);
    border-radius: 6px;
    padding: 5px 10px;
    font-size: 11px;
    color: var(--muted);
    pointer-events: none;
  }
  .sidebar {
    background: var(--panel);
    border-left: 1px solid var(--panel-border);
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    padding: 12px;
    gap: 11px;
  }
  .card {
    background: #0f141d;
    border: 1px solid var(--panel-border);
    border-radius: 8px;
    padding: 10px 11px;
  }
  .card h3 {
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.7px;
    color: var(--muted);
    margin-bottom: 7px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .ivc-box {
    background: rgba(16, 185, 129, 0.09);
    border: 1px solid rgba(16, 185, 129, 0.35);
    border-left: 3px solid #10b981;
    border-radius: 6px;
    padding: 8px 9px;
    font-size: 11.5px;
    line-height: 1.44;
    color: #d1fae5;
  }
  .ivc-box strong { color: #6ee7b7; }
  .narrative {
    font-size: 12px;
    line-height: 1.5;
    color: #d5deed;
  }
  .narrative strong { color: #fff; }
  .bio-list, .verb-list {
    display: flex;
    flex-direction: column;
    gap: 6px;
    font-size: 11.5px;
  }
  .bio-card {
    padding: 7px 9px;
    border-radius: 6px;
    background: #141b27;
    border-left: 3px solid var(--plague);
    line-height: 1.4;
  }
  .bio-card.plague { border-left-color: var(--plague); background: rgba(244, 63, 94, 0.08); }
  .bio-card.cattle { border-left-color: var(--cattle); background: rgba(234, 179, 8, 0.08); }
  .bio-card.pregnancy { border-left-color: var(--pregnancy); background: rgba(217, 70, 239, 0.08); }
  .bio-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 700;
    font-size: 10.5px;
    text-transform: uppercase;
    letter-spacing: 0.45px;
    margin-bottom: 3px;
  }
  .bio-card.plague .bio-head { color: #fda4af; }
  .bio-card.cattle .bio-head { color: #fde047; }
  .bio-card.pregnancy .bio-head { color: #f0abfc; }
  .bio-loc {
    font-size: 10px;
    color: var(--muted);
    font-weight: 600;
  }
  .verb-pill {
    padding: 6px 8px;
    border-radius: 6px;
    background: #151c29;
    border-left: 3px solid var(--accent);
    line-height: 1.38;
  }
  .verb-pill span.vtag {
    font-weight: 700;
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    display: block;
    margin-bottom: 2px;
  }
  .toggle-list {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  .toggle-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 11.5px;
    color: #d5deed;
    cursor: pointer;
    padding: 3px 5px;
    border-radius: 5px;
  }
  .toggle-item:hover { background: rgba(255,255,255,0.05); }
  .toggle-left {
    display: flex;
    align-items: center;
    gap: 7px;
  }
  .swatch {
    width: 10px;
    height: 10px;
    border-radius: 3px;
    display: inline-block;
  }
  footer {
    background: var(--panel);
    border-top: 1px solid var(--panel-border);
    padding: 8px 16px 10px;
  }
  .timeline-track-wrap {
    position: relative;
    margin-bottom: 7px;
  }
  .timeline-pips {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 6px;
    margin-bottom: 4px;
    padding: 0 54px;
  }
  .pip-cluster {
    display: flex;
    justify-content: center;
    gap: 4px;
    font-size: 10px;
  }
  .pip {
    padding: 1px 5px;
    border-radius: 10px;
    font-weight: 700;
    cursor: pointer;
    border: 1px solid transparent;
  }
  .pip.plague { background: rgba(244,63,94,0.2); color: #fda4af; border-color: rgba(244,63,94,0.4); }
  .pip.cattle { background: rgba(234,179,8,0.2); color: #fde047; border-color: rgba(234,179,8,0.4); }
  .pip.pregnancy { background: rgba(217,70,239,0.2); color: #f0abfc; border-color: rgba(217,70,239,0.4); }
  .timeline-row {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  input[type="range"] {
    flex: 1;
    accent-color: var(--accent);
    cursor: pointer;
    height: 6px;
  }
  .stage-buttons {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    gap: 6px;
  }
  .stage-btn {
    text-align: left;
    padding: 5px 7px;
    background: #0f141d;
    border: 1px solid var(--panel-border);
    border-radius: 6px;
    font-size: 11px;
  }
  .stage-btn.active {
    border-color: var(--accent);
    background: var(--accent-soft);
  }
  .stage-btn .yr {
    display: block;
    font-weight: 700;
    color: var(--accent);
    font-size: 11px;
  }
  .stage-btn .lbl {
    display: block;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-top: 1px;
  }
  @media (max-width: 980px) {
    main { grid-template-columns: 1fr; grid-template-rows: 54vh 1fr; }
    .stage-buttons, .timeline-pips { grid-template-columns: repeat(3, 1fr); padding: 0; }
  }
</style>
</head>
<body>

<header>
  <div class="title-block">
    <h1>Post-Sumerian Biopolitical, Plague &amp; Static IVC Reference Atlas</h1>
    <p>Static IVC Zone (c. 3300–1300 BCE) · Geographic coastline &amp; modern borders · Dynamic post-Sumerian polygons &amp; bio-shocks</p>
  </div>
  <div class="controls">
    <button id="playBtn" class="primary">▶ Play Timeline</button>
    <div class="filter-bar" title="Highlight specific biological attrition vectors">
      <button class="filter-btn active" data-filter="all">All Bio-Shocks</button>
      <button class="filter-btn f-plague" data-filter="plague">☠ Plagues</button>
      <button class="filter-btn f-cattle" data-filter="cattle">🐂 Cattle Death</button>
      <button class="filter-btn f-preg" data-filter="pregnancy">🧬 Pregnancy Failures</button>
    </div>
    <div class="zoom-group">
      <button id="zoomOutBtn" title="Zoom Out">−</button>
      <span class="zoom-label" id="zoomLabel">0.85×</span>
      <button id="zoomInBtn" title="Zoom In">+</button>
      <button id="resetViewBtn" title="Reset View">Reset</button>
    </div>
    <button id="macroBtn" title="Zoom out to full Nile–IVC–Steppe view">Macro View</button>
  </div>
</header>

<main>
  <div class="map-wrap" id="mapWrap">
    <canvas id="mapCanvas"></canvas>
    <div class="hud-top-left">
      <div class="epoch-badge" id="hudYear">2004 BCE</div>
      <div class="epoch-title" id="hudTitle">Elam Sacks Ur &amp; Audits the Ghee Ledger</div>
    </div>
    <div class="map-tooltip" id="mapTooltip"></div>
    <div class="hud-hint">Static Green Zone = Indus Valley Civilization (3300–1300 BCE) · Scroll to zoom · Drag to pan</div>
  </div>

  <aside class="sidebar">
    <div class="card">
      <h3>
        <span>Static Reference: Indus Valley Zone</span>
        <span style="color:#34d399;font-weight:700">3300–1300 BCE</span>
      </h3>
      <div class="ivc-box">
        <strong>When:</strong> Early Harappan <strong>c. 3300–2600 BCE</strong> · Mature Urban Phase <strong>2600–1900 BCE</strong> (contemporary with Sumer Ur III &amp; Elam) · Late Harappan <strong>1900–1300 BCE</strong>.<br>
        <strong>Where:</strong> Indus &amp; Ghaggar-Hakra basins across modern <strong>Pakistan, NW India &amp; NE Afghanistan</strong>—from <em>Sutkagen Dor</em> (Makran coast) and <em>Dholavira/Lothal</em> (Gujarat) north to <em>Harappa, Rakhigarhi, Manda</em> &amp; <em>Shortugai</em>.
      </div>
    </div>

    <div class="card">
      <h3>
        <span>Plague, Cattle &amp; Gestational Ledger</span>
        <span id="bioCountBadge" style="color:var(--accent)">3 Active</span>
      </h3>
      <div class="bio-list" id="bioList"></div>
    </div>

    <div class="card">
      <h3>Epoch Geopolitical &amp; Forensic Brief</h3>
      <div class="narrative" id="epochNarrative"></div>
    </div>

    <div class="card">
      <h3>Spatial Action Verbs &amp; Vectors</h3>
      <div class="verb-list" id="verbList"></div>
    </div>

    <div class="card">
      <h3>Map &amp; Overlay Layers</h3>
      <div class="toggle-list">
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:rgba(16,185,129,0.5);border:1px solid #10b981"></span>Static IVC Zone (3300–1300 BCE)</span>
          <input type="checkbox" id="chkIVC" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#f43f5e"></span>Bio-Shock Hazard Rings (Plague / Cattle / Gestation)</span>
          <input type="checkbox" id="chkBio" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#334155;border:1px solid #64748b"></span>Modern Country Borders &amp; Labels</span>
          <input type="checkbox" id="chkBorders" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#1e293b"></span>Mountain Relief (Zagros, Taurus, Hindu Kush)</span>
          <input type="checkbox" id="chkTerrain" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#38bdf8"></span>Major Rivers (Nile, Tigris, Euphrates, Indus, Hakra)</span>
          <input type="checkbox" id="chkRivers" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#f59e0b"></span>Dynamic Empire Polygons</span>
          <input type="checkbox" id="chkPolygons" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#ef4444"></span>Action Vectors (Sack, Audit, Shield, Ration)</span>
          <input type="checkbox" id="chkVectors" checked>
        </label>
        <label class="toggle-item">
          <span class="toggle-left"><span class="swatch" style="background:#e2e8f0"></span>Ancient Cities &amp; Modern Capitals</span>
          <input type="checkbox" id="chkCities" checked>
        </label>
      </div>
    </div>
  </aside>
</main>

<footer>
  <div class="timeline-track-wrap">
    <div class="timeline-pips" id="timelinePips"></div>
    <div class="timeline-row">
      <span style="font-size:11px;color:var(--muted);font-weight:700;min-width:64px;">2004 BCE</span>
      <input type="range" id="timeSlider" min="0" max="500" value="0">
      <span style="font-size:11px;color:var(--muted);font-weight:700;min-width:54px;text-align:right;">642 CE</span>
    </div>
  </div>
  <div class="stage-buttons" id="stageButtons"></div>
</footer>

<script>
const canvas = document.getElementById('mapCanvas');
const ctx = canvas.getContext('2d');
const mapWrap = document.getElementById('mapWrap');
const tooltipEl = document.getElementById('mapTooltip');

// Extended eastward to 78E so the entire IVC (Rakhigarhi, Lothal, Harappa, Shortugai) fits cleanly
const GEO = { minLon: 22, maxLon: 78, minLat: 11, maxLat: 43 };

let cam = {
  zoom: 0.88,
  panX: 0,
  panY: 0,
  dragging: false,
  lastX: 0,
  lastY: 0,
  mouseX: -1000,
  mouseY: -1000
};

let activeBioFilter = 'all';
let screenBioNodes = [];

const LANDMASSES = [
  [
    [22.0, 32.8], [25.2, 31.6], [27.5, 31.2], [29.9, 31.2], [31.9, 31.5],
    [32.4, 30.0], [33.8, 28.0], [34.5, 29.5], [34.9, 28.5], [35.6, 26.0],
    [37.2, 24.0], [39.1, 21.5], [41.2, 18.0], [42.8, 15.0], [43.4, 12.6],
    [45.0, 12.8], [48.5, 14.0], [51.2, 15.2], [54.0, 16.9], [56.5, 18.5],
    [58.8, 20.5], [59.8, 22.5], [58.5, 23.6], [56.4, 25.0], [56.2, 26.3],
    [55.2, 25.2], [54.0, 24.2], [51.6, 24.1], [51.5, 25.9], [50.8, 25.8],
    [50.1, 26.5], [49.5, 27.5], [48.2, 29.4], [48.0, 30.0], [48.8, 30.1],
    [49.8, 29.5], [50.8, 28.8], [52.5, 27.5], [54.8, 26.6], [56.3, 27.1],
    [57.2, 25.8], [60.5, 25.3], [63.5, 25.2], [66.8, 24.8], [68.2, 23.8],
    [69.0, 22.4], [70.2, 22.5], [72.2, 21.6], [72.8, 22.3], [72.8, 20.5],
    [74.5, 18.0], [78.0, 18.0], [78.0, 43.0], [54.0, 43.0],
    [53.2, 41.5], [53.8, 39.5], [53.9, 37.2], [51.5, 36.7], [49.2, 37.5],
    [48.8, 39.2], [49.8, 40.4], [48.5, 42.0], [47.5, 43.0], [41.5, 43.0],
    [41.6, 41.6], [39.5, 41.0], [36.5, 41.3], [35.0, 42.0], [32.0, 41.5],
    [29.0, 41.2], [26.5, 40.5], [26.2, 39.2], [27.0, 37.5], [27.5, 36.7],
    [30.5, 36.8], [32.5, 36.2], [34.8, 36.8], [36.0, 36.8], [35.8, 35.5],
    [35.5, 33.9], [35.0, 32.8], [34.6, 31.5], [34.2, 31.2], [32.4, 31.3],
    [31.5, 31.5], [30.0, 31.2], [27.0, 31.4], [24.0, 32.1], [22.0, 32.8]
  ],
  [[32.3, 35.1], [33.0, 35.4], [34.5, 35.6], [33.9, 35.0], [33.0, 34.7], [32.4, 34.9]],
  [[23.5, 35.5], [26.2, 35.3], [26.1, 35.0], [23.6, 35.2]]
];

// Static Indus Valley Civilization (IVC) Geographic Polygon (c. 3300–1300 BCE; Mature 2600–1900 BCE)
const IVC_STATIC_ZONE = {
  name: 'INDUS VALLEY CIVILIZATION (IVC)',
  span: 'c. 3300–1300 BCE (Mature: 2600–1900 BCE)',
  pts: [
    [61.8, 25.2], // Sutkagen Dor (Makran coast)
    [65.5, 28.8], // Mehrgarh / Bolan Pass
    [69.8, 33.8], // Taxila / Bannu northern fringe
    [70.3, 36.9], // Shortugai (Oxus / Badakhshan outpost)
    [74.7, 32.9], // Manda (Jammu / Chenab foothills)
    [76.6, 30.9], // Ropar (Sutlej)
    [77.4, 29.2], // Alamgirpur (Upper Yamuna–Ganga Doab)
    [76.1, 29.3], // Rakhigarhi (Haryana)
    [74.2, 29.4], // Kalibangan (Ghaggar-Hakra)
    [72.3, 23.0], // Lothal (Gulf of Khambhat, Gujarat)
    [70.2, 23.9], // Dholavira (Rann of Kutch)
    [68.1, 24.2], // Indus Delta / Allahdino
    [66.5, 25.0]  // Balakot / Sonmiani
  ]
};

const MODERN_BORDERS = [
  [[25.0, 31.6], [25.0, 22.0]],
  [[22.0, 22.0], [36.8, 22.0]],
  [[34.2, 31.2], [34.9, 29.5]],
  [[35.6, 33.2], [35.5, 31.2], [35.0, 29.5]],
  [[35.9, 34.6], [36.5, 34.2], [35.8, 33.3]],
  [[36.0, 36.8], [38.0, 36.9], [40.5, 37.1], [42.3, 37.1]],
  [[42.3, 37.1], [41.2, 35.0], [38.8, 33.3]],
  [[35.8, 32.7], [37.0, 32.3], [38.8, 33.3]],
  [[35.0, 29.5], [36.2, 29.2], [38.0, 30.0], [37.5, 31.5], [39.0, 32.1]],
  [[39.0, 32.1], [41.5, 31.2], [44.5, 29.2], [46.5, 29.1], [47.7, 30.0]],
  [[46.5, 29.1], [47.7, 30.0], [48.0, 29.1], [47.4, 28.5], [46.5, 29.1]],
  [[42.3, 37.1], [43.5, 37.3], [44.8, 37.1]],
  [[44.8, 37.1], [45.8, 35.5], [45.5, 34.0], [46.2, 33.0], [47.7, 31.0], [48.0, 30.0]],
  [[42.8, 16.4], [45.0, 17.4], [48.0, 18.2], [52.0, 19.0], [53.1, 16.6]],
  [[53.1, 16.6], [55.0, 20.0], [55.2, 22.6], [56.0, 24.2]],
  [[51.6, 24.1], [54.0, 22.8], [55.2, 22.6], [56.3, 25.0]],
  [[54.0, 37.9], [58.5, 37.5], [61.2, 35.6], [60.6, 33.5], [60.9, 31.5], [61.8, 29.8], [63.2, 27.2], [61.5, 25.2]],
  [[61.8, 29.8], [66.3, 30.0], [69.3, 32.0], [70.0, 34.0], [71.5, 36.8]],
  [[68.2, 23.8], [71.0, 24.5], [70.5, 26.8], [73.8, 29.8], [74.5, 32.5]]
];

const COUNTRY_LABELS = [
  { name: 'EGYPT', lon: 29.2, lat: 26.8 },
  { name: 'SAUDI ARABIA', lon: 44.2, lat: 23.8 },
  { name: 'YEMEN', lon: 47.5, lat: 15.5 },
  { name: 'OMAN', lon: 56.8, lat: 21.2 },
  { name: 'IRAQ', lon: 43.3, lat: 33.0 },
  { name: 'SYRIA', lon: 38.4, lat: 35.0 },
  { name: 'JORDAN', lon: 36.7, lat: 31.0 },
  { name: 'TURKEY', lon: 34.5, lat: 39.0 },
  { name: 'IRAN', lon: 53.8, lat: 32.6 },
  { name: 'AFGHANISTAN', lon: 65.5, lat: 33.8 },
  { name: 'PAKISTAN', lon: 67.5, lat: 29.6 },
  { name: 'INDIA', lon: 75.5, lat: 24.5 }
];

const RIVERS = [
  { name: 'Nile', pts: [[31.2, 31.4], [31.2, 30.0], [31.0, 28.0], [32.6, 25.7], [32.9, 24.1], [31.5, 22.0]], dash: [] },
  { name: 'Euphrates', pts: [[39.0, 38.5], [38.0, 36.8], [39.0, 35.9], [40.5, 35.0], [42.5, 34.1], [44.4, 32.5], [46.0, 31.0], [47.4, 31.0], [48.0, 30.0]], dash: [] },
  { name: 'Tigris', pts: [[40.2, 37.9], [42.4, 37.1], [43.1, 36.3], [43.3, 35.4], [44.4, 33.3], [45.8, 32.2], [47.4, 31.0]], dash: [] },
  { name: 'Karun', pts: [[50.8, 32.3], [49.0, 31.8], [48.5, 31.3], [48.2, 30.4]], dash: [] },
  { name: 'Indus', pts: [[74.5, 35.5], [72.2, 33.5], [71.2, 31.2], [69.5, 28.8], [68.2, 26.8], [67.8, 24.2]], dash: [] },
  { name: 'Ghaggar-Hakra', pts: [[76.8, 30.7], [74.5, 29.5], [72.0, 28.5], [70.2, 27.5], [69.2, 25.2]], dash: [3, 3] }
];

const MOUNTAIN_RANGES = [
  { name: 'ZAGROS MTS', pts: [[45.5, 36.5], [47.5, 34.5], [49.8, 32.5], [52.2, 30.3], [55.0, 28.2]] },
  { name: 'TAURUS MTS', pts: [[31.0, 37.2], [34.5, 37.5], [38.0, 38.0], [41.5, 38.3]] },
  { name: 'ELBURZ MTS', pts: [[49.5, 37.0], [52.5, 36.3], [56.0, 36.7]] },
  { name: 'HINDU KUSH', pts: [[66.0, 34.8], [69.5, 35.6], [72.5, 36.5]] }
];

const CITIES = [
  { name: 'Ur', lon: 46.1, lat: 30.96, type: 'ancient' },
  { name: 'Babylon', lon: 44.42, lat: 32.54, type: 'ancient' },
  { name: 'Baghdad', lon: 44.36, lat: 33.31, type: 'modern' },
  { name: 'Mari', lon: 40.89, lat: 34.55, type: 'ancient' },
  { name: 'Assur', lon: 43.26, lat: 35.45, type: 'ancient' },
  { name: 'Nineveh', lon: 43.15, lat: 36.36, type: 'ancient' },
  { name: 'Susa', lon: 48.25, lat: 32.19, type: 'ancient' },
  { name: 'Anshan', lon: 52.89, lat: 29.93, type: 'ancient' },
  { name: 'Tehran', lon: 51.39, lat: 35.69, type: 'modern' },
  { name: 'Damascus', lon: 36.29, lat: 33.51, type: 'modern' },
  { name: 'Mecca / Hijaz', lon: 39.82, lat: 21.42, type: 'ancient' },
  { name: 'Riyadh (Najd)', lon: 46.72, lat: 24.71, type: 'modern' },
  { name: 'Memphis / Cairo', lon: 31.23, lat: 30.04, type: 'modern' },
  { name: 'Taxila', lon: 72.80, lat: 33.74, type: 'ancient' },
  // Key IVC Cities
  { name: 'Harappa', lon: 72.87, lat: 30.63, type: 'ivc' },
  { name: 'Mohenjo-daro', lon: 68.14, lat: 27.32, type: 'ivc' },
  { name: 'Rakhigarhi', lon: 76.11, lat: 29.29, type: 'ivc' },
  { name: 'Dholavira', lon: 70.21, lat: 23.89, type: 'ivc' },
  { name: 'Lothal', lon: 72.25, lat: 22.52, type: 'ivc' },
  { name: 'Sutkagen Dor', lon: 61.85, lat: 25.49, type: 'ivc' }
];

const EPOCHS = [
  {
    year: '2004 BCE',
    title: 'Elam Sacks Ur & Audits the Ghee Ledger',
    narrative: 'King <strong>Kindattu</strong> of Elam descends from the Zagros highlands, sacks <strong>Ur</strong>, captures Ibbi-Sin, and confiscates the Ur III palace ledgers (while the <strong>Mature IVC</strong> thrives contemporaneously across the Indus–Hakra basin). Auditing the Ur tablets exposes how salinized floodplain cattle murrain, siege pestilence, and palace <em>ì-nun</em> (ghee) retinoid overload rotted Sumer’s ruling bloodline from inside.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PLAGUE & SIEGE PESTILENCE',
        title: 'Ur III Siege Pestilence (Lamentation over Ur)',
        location: 'Ur & Nippur (S. Iraq)',
        lon: 46.1, lat: 30.96,
        detail: 'Cuneiform laments record acute epidemic mortality ("corpses piled at the city gates") as irrigation breakdown and siege crowding triggered waterborne & zoonotic fever waves.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'CATTLE DEATH & SALINIZATION',
        title: 'Drehem / Puzrish-Dagan Herd Murrain & Marsh Ghee',
        location: 'Lower Euphrates Marshes',
        lon: 45.2, lat: 31.85,
        detail: 'Ur III livestock tablets document massive cattle die-offs (murṣu) from salinized pastures; rendering fat from stressed marsh cattle concentrated lipophilic toxins & retinoids into palace ì-nun (ghee).'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'PREGNANCY & NURSERY FAILURE',
        title: 'Gipar Retinoid Overload & Wet-Nurse Swap',
        location: 'Ur Royal Gipar Quarters',
        lon: 46.6, lat: 30.4,
        detail: 'Excess preformed retinol in clarified butter disrupted embryonic neural/axis patterning while wet-nurse stipends (um-me-ga-lá) severed maternal exosomal telemetry; Elam purged both after sacking Ur.'
      }
    ],
    verbs: [
      { tag: 'SACK & OCCUPY', color: '#a855f7', text: 'Elam marches from Susa/Anshan to sack Ur (2004 BCE) & seize Ur III archives.' },
      { tag: 'FORENSIC AUDIT', color: '#f59e0b', text: 'Confiscated clay ledgers reveal palace ghee retinoid overload & wet-nurse exosome swaps.' },
      { tag: 'UPHILL SHIELD', color: '#10b981', text: 'Elam marches Ibbi-Sin & source scrolls uphill to Anshan; purges marsh ghee from royal nurseries.' }
    ],
    polygons: [
      { name: 'Sumer (Collapsing Ur III)', color: 'rgba(234,179,8,0.30)', stroke: '#eab308', pts: [[44.2,32.6],[46.6,32.5],[48.0,30.1],[46.2,29.8],[44.5,31.0]] },
      { name: 'Elam (Susa + Anshan Core)', color: 'rgba(168,85,247,0.40)', stroke: '#a855f7', pts: [[47.4,33.6],[51.2,32.8],[54.2,30.2],[53.0,28.5],[49.2,29.8],[47.8,31.2]] },
      { name: 'Amorite Steppe Tribes', color: 'rgba(16,185,129,0.22)', stroke: '#10b981', pts: [[37.0,36.2],[41.8,36.0],[42.5,33.5],[38.2,32.8],[36.5,34.4]] },
      { name: 'Old Assyria (Upper Tigris)', color: 'rgba(239,68,68,0.26)', stroke: '#ef4444', pts: [[41.8,37.0],[44.5,36.8],[44.2,35.0],[42.0,35.1]] },
      { name: 'Middle Kingdom Egypt', color: 'rgba(56,189,248,0.26)', stroke: '#38bdf8', pts: [[29.8,31.3],[32.2,31.2],[32.8,24.5],[31.0,24.5],[30.3,29.5]] }
    ],
    vectors: [
      { from: [48.6, 32.0], to: [46.1, 30.96], label: 'SACK OF UR (2004 BCE)', color: '#a855f7', dashed: false },
      { from: [46.1, 30.96], to: [52.89, 29.93], label: 'AUDIT & UPHILL SHIELD', color: '#f59e0b', dashed: true },
      { from: [39.5, 35.0], to: [43.5, 33.2], label: 'STEPPE INCURSION', color: '#10b981', dashed: true }
    ]
  },
  {
    year: '1760 BCE',
    title: 'Amorite Babylon, Mari Quarantines & Late IVC Transition',
    narrative: 'Semi-nomadic <strong>Amorites</strong> capture Babylon and Mari—enforcing strict palace plague quarantines while codifying <em>Atra-Hasis</em> population-attrition theology—just as the <strong>IVC</strong> enters its Late Harappan de-urbanization phase (1900–1300 BCE) following Ghaggar-Hakra hydrological shifts.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PLAGUE & QUARANTINE PROTOCOL',
        title: 'Mari Royal Archives Mūtānu Epidemic Isolation',
        location: 'Mari & Terqa (Syria/Iraq Border)',
        lon: 40.89, lat: 34.55,
        detail: 'King Zimri-Lim’s letters enforce strict palace quarantine ("no one shall drink from her cup or sit on her chair") during contagious mūtānu outbreaks in Terqa while letting lower towns absorb the wave.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'CATTLE DEATH & FODDER TOXINS',
        title: 'Euphrates Valley Cattle Plague & Steppe Herd Split',
        location: 'Middle Euphrates / Babylon',
        lon: 44.42, lat: 32.54,
        detail: 'Alluvial cattle murrains and granary mycotoxins devastate sedentary herds; Amorite elites keep clean steppe sheep/goat milk while rationing omega-6 sesame oil & barley to laborers.'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'PREGNANCY FAILURE POLITICS',
        title: 'Atra-Hasis Codified Barrenness & Pāšittu Infant Loss',
        location: 'Babylon & Sippar',
        lon: 44.25, lat: 33.1,
        detail: 'Old Babylonian state theology explicitly frames plagues, female barrenness (ša lā alādi), and neonatal death (pāšittu) as administrative population-control levers over lower-caste labor.'
      }
    ],
    verbs: [
      { tag: 'CAPTURE & CODIFY', color: '#10b981', text: 'Amorites seize Babylon & Mari; publish transparent statutory law vs. temple omen guilds.' },
      { tag: 'RATION WEAPONRY', color: '#ef4444', text: 'Standardized barley + omega-6 sesame oil rations institutionalize compliant lowland labor.' },
      { tag: 'HIGHLAND BUFFER', color: '#a855f7', text: 'Elam rotates royal pregnancies uphill to Anshan; avoids irrigated floodplain cattle ghee.' }
    ],
    polygons: [
      { name: 'Amorite Babylon & Mari', color: 'rgba(16,185,129,0.34)', stroke: '#10b981', pts: [[38.0,36.2],[43.2,35.6],[47.5,31.0],[46.0,29.8],[43.5,31.8],[39.5,33.6]] },
      { name: 'Elam (Sukkalmah Empire)', color: 'rgba(168,85,247,0.36)', stroke: '#a855f7', pts: [[47.3,34.0],[51.8,33.0],[54.8,29.8],[53.2,28.2],[48.8,29.8],[47.7,31.3]] },
      { name: 'Assyrian Trade Axis', color: 'rgba(239,68,68,0.28)', stroke: '#ef4444', pts: [[41.5,37.2],[44.8,37.0],[44.5,35.1],[41.8,35.2]] },
      { name: 'Egypt (Late Middle Kingdom)', color: 'rgba(56,189,248,0.26)', stroke: '#38bdf8', pts: [[29.8,31.3],[32.3,31.2],[33.0,23.5],[31.0,23.5],[30.2,29.5]] }
    ],
    vectors: [
      { from: [40.89, 34.55], to: [44.42, 32.54], label: 'PASTORAL DYNASTY CAPTURE', color: '#10b981', dashed: false },
      { from: [48.25, 32.19], to: [52.89, 29.93], label: 'GESTATION QUARANTINE', color: '#a855f7', dashed: true },
      { from: [44.42, 32.54], to: [46.1, 30.96], label: 'GRAIN/OIL LABOR RATIONS', color: '#ef4444', dashed: true }
    ]
  },
  {
    year: '1155 BCE',
    title: 'Shutruk-Nahhunte’s Sack, Bronze Age Plagues & Egyptian Inbreeding',
    narrative: 'Elamite king <strong>Shutruk-Nahhunte</strong> sacks Babylon (1155 BCE) and hauls legal/medical source texts to Susa amid the Late Bronze Age Collapse. Megadroughts trigger cattle plagues across the Fertile Crescent, while Egypt’s royal bloodlines rot from mandatory sibling inbreeding and lead-antimony cosmetics.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PLAGUE & BRONZE AGE COLLAPSE',
        title: 'Levant–Mesopotamia Erra / Namtar Pestilence Wave',
        location: 'Syria / Upper Euphrates Corridor',
        lon: 38.4, lat: 35.0,
        detail: 'Late Bronze Age trade collapse and refugee movements trigger severe epidemic fevers across Levantine and Babylonian cities, collapsing urban garrison densities.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'CATTLE DEATH & MEGADROUGHT',
        title: 'Anatolian–Mesopotamian Livestock Die-Off',
        location: 'Upper Tigris & N. Syria',
        lon: 41.8, lat: 36.6,
        detail: 'Severe 12th-century BCE aridification causes mass cattle and grain failures across Hittite and Kassite territories, driving nomadic pastoralist incursions.'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'DYNASTIC GESTATIONAL COLLAPSE',
        title: 'Egyptian Sibling Inbreeding & Lead/Antimony Kohl',
        location: 'Thebes / Memphis (Egypt)',
        lon: 31.23, lat: 28.5,
        detail: 'Late 18th–20th Dynasty sibling marriages plus chronic lead/antimony cosmetic toxicity produce severe congenital bone necrosis, cleft palate, stillbirths, and immune fragility.'
      }
    ],
    verbs: [
      { tag: 'ARCHIVE EXTRACTION', color: '#a855f7', text: 'Shutruk-Nahhunte sacks Babylon (1155 BCE) & hauls legal/medical source texts to Susa.' },
      { tag: 'MILITARIZE CORE', color: '#ef4444', text: 'Middle Assyria locks down Upper Tigris iron logistics & capital laws against pregnancy tampering.' },
      { tag: 'CLOSED INBREEDING', color: '#38bdf8', text: 'Egyptian dynasties compound sibling inbreeding, lead cosmetics & priestly hoarding.' }
    ],
    polygons: [
      { name: 'Elam (Post-Babylon Sack)', color: 'rgba(168,85,247,0.42)', stroke: '#a855f7', pts: [[44.2,33.5],[48.5,34.2],[52.5,32.6],[55.0,29.6],[52.8,28.2],[48.2,30.0],[45.5,31.5]] },
      { name: 'Middle Assyria', color: 'rgba(239,68,68,0.34)', stroke: '#ef4444', pts: [[40.2,37.4],[44.8,37.2],[45.2,34.6],[41.2,34.8]] },
      { name: 'Early Arabian Camel Clans', color: 'rgba(249,115,22,0.26)', stroke: '#f97316', pts: [[37.5,28.5],[44.5,28.0],[47.0,22.0],[41.0,19.5],[38.0,24.0]] },
      { name: 'New Kingdom Egypt', color: 'rgba(56,189,248,0.32)', stroke: '#38bdf8', pts: [[29.6,31.4],[34.5,31.2],[34.8,29.6],[33.2,22.5],[31.0,22.5],[30.0,29.5]] }
    ],
    vectors: [
      { from: [48.25, 32.19], to: [44.42, 32.54], label: 'SACK OF BABYLON (1155 BCE)', color: '#a855f7', dashed: false },
      { from: [44.42, 32.54], to: [48.25, 32.19], label: 'CONFISCATE TEXTS & STELAE', color: '#f59e0b', dashed: true },
      { from: [41.5, 23.0], to: [38.5, 29.5], label: 'CAMEL PASTORAL EXPANSION', color: '#f97316', dashed: true }
    ]
  },
  {
    year: '647 BCE',
    title: 'Neo-Assyrian Deportation Plagues & Mutagen Polypharmacy',
    narrative: '<strong>Ashurbanipal</strong> sacks Susa (647 BCE) and hoards medical texts in Nineveh—institutionalizing a lethal two-tier split: mechanical surgery for kings vs. licorice (<em>šūšu</em>), mandrake, and lead pastes for deportees, while forced marches spread epidemics and livestock die-offs.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PLAGUE & DEPORTATION CORRIDORS',
        title: 'Neo-Assyrian Mūtānu Garrison & Deportee Epidemics',
        location: 'Nineveh & Kalhu (N. Iraq)',
        lon: 43.15, lat: 36.36,
        detail: 'Court astrological/medical tablets report recurring mūtānu plagues erupting along forced-deportation columns and overcrowded provincial garrisons, bleeding Assyria’s core manpower.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'CATTLE CONFISCATION & MURRAIN',
        title: 'Imperial Herd Seizure & Susiana Livestock Collapse',
        location: 'Susa / Khuzestan Plain',
        lon: 48.25, lat: 32.19,
        detail: 'Assyria strips prime highland cattle and horses as tribute for its military elite while scorched-earth campaigns trigger epizootic herd collapses across Elam and Babylonia.'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'MUTAGEN PHARMACOLOGY & HPA HIJACK',
        title: 'Licorice (Šūšu) Cortisol Flood & Mandrake Pastes',
        location: 'Babylon & Nineveh Lower Towns',
        lon: 44.42, lat: 32.54,
        detail: 'Nineveh formularies pack glycyrrhizin-heavy licorice (blocking placental 11β-HSD2), mandrake alkaloids, and lead/antimony pastes into common remedies—inducing fetal HPA-axis damage and teratogenic drift.'
      }
    ],
    verbs: [
      { tag: 'SACK & CONSOLIDATE', color: '#ef4444', text: 'Assyria sacks Susa (647 BCE), deporting populations & hoarding texts in Nineveh.' },
      { tag: 'MUTAGEN POLYPHARMACY', color: '#f59e0b', text: 'Two-tier split: mechanical surgery for kings vs. licorice/mandrake/mineral pastes for masses.' },
      { tag: 'UPHILL PERSIAN PIVOT', color: '#a855f7', text: 'Elamite scribal DNA survives in highland Anshan, seeding the Achaemenid Persian state.' }
    ],
    polygons: [
      { name: 'Neo-Assyrian Hyper-Empire', color: 'rgba(239,68,68,0.42)', stroke: '#ef4444', pts: [[30.0,31.2],[35.5,36.8],[43.5,37.6],[48.5,34.5],[48.8,30.2],[44.5,30.5],[36.5,31.2],[34.5,29.5],[32.8,24.5],[30.5,24.5]] },
      { name: 'Highland Anshan (Proto-Persia)', color: 'rgba(168,85,247,0.36)', stroke: '#a855f7', pts: [[50.2,32.5],[55.5,31.2],[56.2,28.0],[51.8,28.2]] },
      { name: 'Arabian Steppe Confederations', color: 'rgba(249,115,22,0.32)', stroke: '#f97316', pts: [[36.5,30.2],[45.5,29.2],[50.5,24.5],[48.5,17.5],[41.5,17.0],[37.5,23.5]] }
    ],
    vectors: [
      { from: [43.15, 36.36], to: [48.25, 32.19], label: 'SACK OF SUSA (647 BCE)', color: '#ef4444', dashed: false },
      { from: [48.25, 32.19], to: [43.15, 36.36], label: 'MASS DEPORTATIONS & TEXTS', color: '#f59e0b', dashed: true },
      { from: [43.15, 36.36], to: [31.23, 30.04], label: 'IMPERIAL OVERSTRETCH', color: '#ef4444', dashed: true }
    ]
  },
  {
    year: '522 BCE',
    title: 'Achaemenid Satrapies vs. Arabian Bādiya Desert Firewall',
    narrative: '<strong>Darius I</strong> builds an empire from the Nile into the northern Indus zone (Gandhara/Taxila)—projecting Aramaic/Kharosthi orthographic control while keeping Persian princes sequestered in highland estates. Across the desert, Arabian elites institutionalize <strong><em>bādiya</em> Bedouin fostering</strong> to escape urban plagues and wet-nurse/apothecary attrition.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PLAGUE & CANAL-ZONE ENDEMICS',
        title: 'Nile Delta & Babylonian Canal-Grid Endemic Fevers',
        location: 'Memphis / Lower Nile & Babylon',
        lon: 31.23, lat: 30.04,
        detail: 'Dense irrigated river hubs suffer chronic malaria, schistosomiasis, and garrison plagues, while Persian vispuhrān princes and Bedouin clans stay insulated in high/arid ecological zones.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'LIVESTOCK RESILIENCE SPLIT',
        title: 'Alluvial Cattle Murrain vs. Desert Camel/Goat Immunity',
        location: 'Hijaz & Najd Steppe (Arabia)',
        lon: 43.5, lat: 24.5,
        detail: 'Lowland river herds remain vulnerable to seasonal murrains and aflatoxin fodder, whereas decentralized Arabian camel and desert-goat herds provide clean, unboiled lactoferrin-rich milk.'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'ANTI-URBAN GESTATIONAL SHIELD',
        title: 'Bādiya Desert Fostering vs. Urban Electuaries',
        location: 'Mecca / Hijaz Desert Frontier',
        lon: 39.82, lat: 21.42,
        detail: 'Arabian nobility deliberately sends infants to Bedouin foster-mothers (mustarḍiʿāt) to prevent urban polypharmacy exposure, wet-nurse stress-cortisol swaps, and early-childhood mortality.'
      }
    ],
    verbs: [
      { tag: 'IMPERIAL OVERLAY', color: '#a855f7', text: 'Achaemenids fuse Elamite highland security with Assyrian Aramaic bureaucracy to Taxila.' },
      { tag: 'BĀDIYA FOSTERING', color: '#f97316', text: 'Arabian elites send infants to desert foster-mothers for clean camel milk & zero urban drugs.' },
      { tag: 'COLONIAL EXTRACTION', color: '#38bdf8', text: 'Egypt reduced to a taxed satrapy while priestly castes hoard decaying temple medicine.' }
    ],
    polygons: [
      { name: 'Achaemenid Persian Empire', color: 'rgba(168,85,247,0.36)', stroke: '#a855f7', pts: [[29.8,31.3],[35.8,36.8],[44.5,38.0],[55.0,37.2],[68.5,35.5],[72.8,33.7],[68.0,25.2],[56.5,27.0],[48.2,30.0],[36.2,31.2],[33.0,23.5],[30.5,23.5]] },
      { name: 'Arabian Bādiya Heartland', color: 'rgba(249,115,22,0.38)', stroke: '#f97316', pts: [[36.2,30.2],[46.5,29.0],[54.5,23.5],[53.0,15.5],[43.5,14.5],[38.0,21.5]] }
    ],
    vectors: [
      { from: [52.89, 29.93], to: [72.8, 33.74], label: 'ARAMAIC / KHAROSTHI VECTOR', color: '#a855f7', dashed: true },
      { from: [39.82, 21.42], to: [44.5, 25.5], label: 'BĀDIYA DESERT SHIELD', color: '#f97316', dashed: false },
      { from: [52.89, 29.93], to: [31.23, 30.04], label: 'SATRAPY TRIBUTE DRAIN', color: '#38bdf8', dashed: true }
    ]
  },
  {
    year: '642 CE',
    title: 'Justinianic/Amwas Plagues & Collapse of Hollowed-Out Egypt',
    narrative: 'Recurrent waves of the <strong>Plague of Justinian</strong> (541–640s CE) and the <strong>Plague of Amwas</strong> (639 CE), paired with Nile cattle murrains and centuries of Ptolemaic–Byzantine inbreeding and lead/grain attrition, leave Egypt and Sasanian Iraq demographically hollow before the high-vitality Arabian expansion.',
    bioEvents: [
      {
        type: 'plague',
        icon: '☠',
        tag: 'PANDEMIC COLLAPSE (YERSINIA PESTIS)',
        title: 'Plague of Justinian & Plague of Amwas (638–639 CE)',
        location: 'Pelusium / Alexandria & Levant',
        lon: 32.3, lat: 31.0,
        detail: 'Originating through Pelusium in Egypt (541 CE) with recurring waves through 639 CE (Amwas), bubonic plague gutted dense Byzantine & Sasanian urban tax bases while decentralized tribal networks rebounded fast.'
      },
      {
        type: 'cattle',
        icon: '🐂',
        tag: 'NILE MURRAIN & AGRARIAN CRASH',
        title: 'Late-Byzantine Egyptian Cattle Plague & Silt Failure',
        location: 'Nile Valley (Egypt)',
        lon: 31.1, lat: 27.5,
        detail: '6th–7th century epizootic cattle die-offs wiped out draft oxen across Byzantine Egypt, collapsing irrigation maintenance and starving the imperial grain-tribute engine.'
      },
      {
        type: 'pregnancy',
        icon: '🧬',
        tag: 'CUMULATIVE DEMOGRAPHIC EXHAUSTION',
        title: 'Multi-Century Urban Attrition vs. Bādiya Kin Vitality',
        location: 'Cairo / Fustat & Ctesiphon',
        lon: 44.58, lat: 33.09,
        detail: 'Centuries of Ptolemaic/Roman extraction, heavy-metal cosmetics, and urban polypharmacy left river-valley populations depleted—allowing mobile, desert-fostered Arabian clans to take Egypt (639–642 CE) with minimal resistance.'
      }
    ],
    verbs: [
      { tag: 'COLLAPSE OF HOLLOW CORE', color: '#38bdf8', text: 'Internally exhausted Egypt falls rapidly to Amr ibn al-As (639–642 CE) without local defense.' },
      { tag: 'VITALITY EXPANSION', color: '#f97316', text: 'Decentralized Arabian networks absorb both Sasanian Iran/Iraq and Byzantine Levant/Egypt.' },
      { tag: 'TWO-TIER CONTINUUM', color: '#f59e0b', text: 'Caliphal elites keep Bedouin fostering while scaling urban Qarābādīn polypharmacy manuals.' }
    ],
    polygons: [
      { name: 'Early Caliphate (High-Vitality Expansion)', color: 'rgba(249,115,22,0.40)', stroke: '#f97316', pts: [[25.0,31.6],[32.2,31.3],[36.2,36.6],[44.5,37.4],[54.5,36.8],[61.5,35.0],[61.0,25.5],[56.2,26.8],[54.5,23.5],[53.0,15.5],[43.5,14.5],[38.0,21.5],[34.5,29.5],[32.8,23.0],[29.5,23.0]] }
    ],
    vectors: [
      { from: [39.82, 21.42], to: [31.23, 30.04], label: 'CONQUEST OF EGYPT (639–642 CE)', color: '#f97316', dashed: false },
      { from: [44.5, 25.5], to: [44.36, 33.31], label: 'FALL OF SASANIAN IRAQ', color: '#f97316', dashed: false },
      { from: [44.36, 33.31], to: [41.5, 24.0], label: 'NOBLE BĀDIYA NURSERY LOOP', color: '#10b981', dashed: true }
    ]
  }
];

let currentSlider = 0;
let playing = false;
let animPhase = 0;

const stageButtonsEl = document.getElementById('stageButtons');
const timelinePipsEl = document.getElementById('timelinePips');

EPOCHS.forEach((ep, idx) => {
  const btn = document.createElement('button');
  btn.className = 'stage-btn' + (idx === 0 ? ' active' : '');
  btn.innerHTML = `<span class="yr">${ep.year}</span><span class="lbl">${ep.title.split('&')[0].trim()}</span>`;
  btn.addEventListener('click', () => jumpToStage(idx, 'all'));
  stageButtonsEl.appendChild(btn);

  const cluster = document.createElement('div');
  cluster.className = 'pip-cluster';
  ep.bioEvents.forEach(ev => {
    const pip = document.createElement('span');
    pip.className = `pip ${ev.type}`;
    pip.textContent = ev.icon;
    pip.title = `${ep.year} — ${ev.title}`;
    pip.addEventListener('click', () => jumpToStage(idx, ev.type));
    cluster.appendChild(pip);
  });
  timelinePipsEl.appendChild(cluster);
});

function jumpToStage(idx, filterType) {
  playing = false;
  updatePlayBtn();
  currentSlider = idx * 100;
  document.getElementById('timeSlider').value = currentSlider;
  if (filterType) setBioFilter(filterType);
  updateSidebar(idx);
}

function setBioFilter(filterType) {
  activeBioFilter = filterType;
  document.querySelectorAll('.filter-btn').forEach(b => {
    b.classList.toggle('active', b.dataset.filter === filterType);
  });
  updateSidebar(Math.round(currentSlider / 100));
}

document.querySelectorAll('.filter-btn').forEach(btn => {
  btn.addEventListener('click', () => setBioFilter(btn.dataset.filter));
});

function updatePlayBtn() {
  document.getElementById('playBtn').textContent = playing ? '⏸ Pause' : '▶ Play Timeline';
}

document.getElementById('playBtn').addEventListener('click', () => {
  playing = !playing;
  if (playing && currentSlider >= 500) currentSlider = 0;
  updatePlayBtn();
});

document.getElementById('timeSlider').addEventListener('input', (e) => {
  playing = false;
  updatePlayBtn();
  currentSlider = Number(e.target.value);
  updateSidebar(Math.round(currentSlider / 100));
});

function setZoom(newZoom) {
  cam.zoom = Math.max(0.55, Math.min(3.5, newZoom));
  document.getElementById('zoomLabel').textContent = cam.zoom.toFixed(2) + '×';
}

document.getElementById('zoomOutBtn').addEventListener('click', () => setZoom(cam.zoom * 0.8));
document.getElementById('zoomInBtn').addEventListener('click', () => setZoom(cam.zoom * 1.25));
document.getElementById('resetViewBtn').addEventListener('click', () => {
  cam.zoom = 0.88; cam.panX = 0; cam.panY = 0;
  document.getElementById('zoomLabel').textContent = cam.zoom.toFixed(2) + '×';
});
document.getElementById('macroBtn').addEventListener('click', () => {
  cam.zoom = 0.62; cam.panX = 0; cam.panY = 0;
  document.getElementById('zoomLabel').textContent = cam.zoom.toFixed(2) + '×';
});

mapWrap.addEventListener('wheel', (e) => {
  e.preventDefault();
  setZoom(cam.zoom * (e.deltaY > 0 ? 0.88 : 1.14));
}, { passive: false });

mapWrap.addEventListener('mousedown', (e) => {
  cam.dragging = true;
  cam.lastX = e.clientX;
  cam.lastY = e.clientY;
});

window.addEventListener('mousemove', (e) => {
  const rect = mapWrap.getBoundingClientRect();
  cam.mouseX = e.clientX - rect.left;
  cam.mouseY = e.clientY - rect.top;

  if (cam.dragging) {
    cam.panX += (e.clientX - cam.lastX);
    cam.panY += (e.clientY - cam.lastY);
    cam.lastX = e.clientX;
    cam.lastY = e.clientY;
    tooltipEl.style.display = 'none';
    return;
  }

  let hit = null;
  for (const node of screenBioNodes) {
    if (Math.hypot(cam.mouseX - node.x, cam.mouseY - node.y) <= 22) {
      hit = node;
      break;
    }
  }
  if (hit) {
    const colorMap = { plague: '#fda4af', cattle: '#fde047', pregnancy: '#f0abfc' };
    tooltipEl.style.display = 'block';
    tooltipEl.style.left = Math.min(rect.width - 295, Math.max(12, hit.x + 16)) + 'px';
    tooltipEl.style.top = Math.min(rect.height - 135, Math.max(12, hit.y - 20)) + 'px';
    tooltipEl.style.borderColor = colorMap[hit.ev.type];
    tooltipEl.innerHTML = `
      <div class="tt-head" style="color:${colorMap[hit.ev.type]}">${hit.ev.icon} ${hit.ev.tag}</div>
      <div style="font-weight:700;color:#fff;margin-bottom:3px">${hit.ev.title} (${hit.ev.location})</div>
      <div>${hit.ev.detail}</div>
    `;
  } else {
    tooltipEl.style.display = 'none';
  }
});

window.addEventListener('mouseup', () => { cam.dragging = false; });

function updateSidebar(stageIdx) {
  const ep = EPOCHS[stageIdx];
  document.getElementById('hudYear').textContent = ep.year;
  document.getElementById('hudTitle').textContent = ep.title;
  document.getElementById('epochNarrative').innerHTML = ep.narrative;

  const filteredBios = ep.bioEvents.filter(ev => activeBioFilter === 'all' || ev.type === activeBioFilter);
  document.getElementById('bioCountBadge').textContent = `${filteredBios.length} Highlighted`;
  document.getElementById('bioList').innerHTML = filteredBios.map(ev => `
    <div class="bio-card ${ev.type}">
      <div class="bio-head">
        <span>${ev.icon} ${ev.tag}</span>
        <span class="bio-loc">${ev.location}</span>
      </div>
      <div style="font-weight:700;color:#fff;margin-bottom:2px">${ev.title}</div>
      <div style="color:#cbd5e1">${ev.detail}</div>
    </div>
  `).join('');

  document.getElementById('verbList').innerHTML = ep.verbs.map(v => `
    <div class="verb-pill" style="border-left-color:${v.color}">
      <span class="vtag" style="color:${v.color}">${v.tag}</span>
      ${v.text}
    </div>
  `).join('');

  document.querySelectorAll('.stage-btn').forEach((b, i) => {
    b.classList.toggle('active', i === stageIdx);
  });
}

function geoToScreen(lon, lat, w, h) {
  const midLatRad = ((GEO.minLat + GEO.maxLat) / 2) * Math.PI / 180;
  const cosLat = Math.cos(midLatRad);
  const geoW = (GEO.maxLon - GEO.minLon) * cosLat;
  const geoH = (GEO.maxLat - GEO.minLat);
  const baseScale = Math.min(w / geoW, h / geoH) * 0.94;
  const centerLon = (GEO.minLon + GEO.maxLon) / 2;
  const centerLat = (GEO.minLat + GEO.maxLat) / 2;
  const x = (w / 2) + ((lon - centerLon) * cosLat * baseScale * cam.zoom) + cam.panX;
  const y = (h / 2) - ((lat - centerLat) * baseScale * cam.zoom) + cam.panY;
  return [x, y];
}

function drawPolygon(pts, w, h, fill, stroke, lineWidth = 1.5, dash = []) {
  if (!pts || pts.length < 3) return;
  ctx.save();
  ctx.beginPath();
  pts.forEach(([lon, lat], i) => {
    const [x, y] = geoToScreen(lon, lat, w, h);
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  });
  ctx.closePath();
  if (fill) { ctx.fillStyle = fill; ctx.fill(); }
  if (stroke) {
    ctx.setLineDash(dash);
    ctx.strokeStyle = stroke;
    ctx.lineWidth = lineWidth;
    ctx.stroke();
  }
  ctx.restore();
}

function drawPolyline(pts, w, h, stroke, lineWidth = 1.2, dash = []) {
  if (!pts || pts.length < 2) return;
  ctx.save();
  ctx.beginPath();
  pts.forEach(([lon, lat], i) => {
    const [x, y] = geoToScreen(lon, lat, w, h);
    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  });
  ctx.setLineDash(dash);
  ctx.strokeStyle = stroke;
  ctx.lineWidth = lineWidth;
  ctx.stroke();
  ctx.restore();
}

function drawArrowVector(v, w, h, phase) {
  const [x1, y1] = geoToScreen(v.from[0], v.from[1], w, h);
  const [x2, y2] = geoToScreen(v.to[0], v.to[1], w, h);
  const dx = x2 - x1, dy = y2 - y1;
  const len = Math.hypot(dx, dy);
  if (len < 12) return;

  const nx = -dy / len, ny = dx / len;
  const curve = Math.min(28, len * 0.16);
  const cx = (x1 + x2) / 2 + nx * curve;
  const cy = (y1 + y2) / 2 + ny * curve;

  ctx.save();
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.quadraticCurveTo(cx, cy, x2, y2);
  ctx.strokeStyle = v.color;
  ctx.lineWidth = 2.2;
  if (v.dashed) {
    ctx.setLineDash([7, 5]);
    ctx.lineDashOffset = -phase * 24;
  }
  ctx.stroke();

  const t = phase % 1;
  const px = (1 - t) * (1 - t) * x1 + 2 * (1 - t) * t * cx + t * t * x2;
  const py = (1 - t) * (1 - t) * y1 + 2 * (1 - t) * t * cy + t * t * y2;
  ctx.setLineDash([]);
  ctx.beginPath();
  ctx.arc(px, py, 3.5, 0, Math.PI * 2);
  ctx.fillStyle = '#fff';
  ctx.fill();

  const angle = Math.atan2(y2 - cy, x2 - cx);
  const headLen = 8.5;
  ctx.beginPath();
  ctx.moveTo(x2, y2);
  ctx.lineTo(x2 - headLen * Math.cos(angle - Math.PI / 6), y2 - headLen * Math.sin(angle - Math.PI / 6));
  ctx.lineTo(x2 - headLen * Math.cos(angle + Math.PI / 6), y2 - headLen * Math.sin(angle + Math.PI / 6));
  ctx.closePath();
  ctx.fillStyle = v.color;
  ctx.fill();

  const lx = 0.25 * x1 + 0.5 * cx + 0.25 * x2;
  const ly = 0.25 * y1 + 0.5 * cy + 0.25 * y2;
  ctx.font = 'bold 9.5px -apple-system, BlinkMacSystemFont, sans-serif';
  const tw = ctx.measureText(v.label).width;
  ctx.fillStyle = 'rgba(11, 14, 20, 0.85)';
  ctx.fillRect(lx - tw / 2 - 4, ly - 7, tw + 8, 14);
  ctx.strokeStyle = v.color;
  ctx.lineWidth = 1;
  ctx.strokeRect(lx - tw / 2 - 4, ly - 7, tw + 8, 14);
  ctx.fillStyle = '#fff';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(v.label, lx, ly);
  ctx.restore();
}

function drawBioHazardNode(ev, w, h, phase) {
  const [x, y] = geoToScreen(ev.lon, ev.lat, w, h);
  screenBioNodes.push({ x, y, ev });

  const colorCfg = {
    plague: { main: '#f43f5e', glow: 'rgba(244, 63, 94, 0.35)', text: '#fda4af' },
    cattle: { main: '#eab308', glow: 'rgba(234, 179, 8, 0.35)', text: '#fde047' },
    pregnancy: { main: '#d946ef', glow: 'rgba(217, 70, 239, 0.35)', text: '#f0abfc' }
  }[ev.type];

  const pulse = (phase * 1.4) % 1;
  const rOuter = 12 + pulse * 24;

  ctx.save();
  ctx.beginPath();
  ctx.arc(x, y, rOuter, 0, Math.PI * 2);
  ctx.strokeStyle = colorCfg.main;
  ctx.globalAlpha = Math.max(0, 1 - pulse) * 0.85;
  ctx.lineWidth = 2;
  ctx.stroke();

  ctx.globalAlpha = 1;
  ctx.beginPath();
  ctx.arc(x, y, 13, 0, Math.PI * 2);
  ctx.fillStyle = colorCfg.glow;
  ctx.fill();
  ctx.strokeStyle = colorCfg.main;
  ctx.lineWidth = 2;
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(x, y, 9.5, 0, Math.PI * 2);
  ctx.fillStyle = '#0b0e14';
  ctx.fill();
  ctx.font = '11px sans-serif';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(ev.icon, x, y + 0.5);

  const label = `${ev.type.toUpperCase()}: ${ev.location.split('(')[0].trim()}`;
  ctx.font = 'bold 9.5px sans-serif';
  const tw = ctx.measureText(label).width;
  ctx.fillStyle = 'rgba(11, 14, 20, 0.92)';
  ctx.fillRect(x - tw / 2 - 5, y + 15, tw + 10, 14);
  ctx.strokeStyle = colorCfg.main;
  ctx.lineWidth = 1;
  ctx.strokeRect(x - tw / 2 - 5, y + 15, tw + 10, 14);
  ctx.fillStyle = colorCfg.text;
  ctx.fillText(label, x, y + 22);
  ctx.restore();
}

function render() {
  const dpr = window.devicePixelRatio || 1;
  const rect = mapWrap.getBoundingClientRect();
  if (canvas.width !== Math.floor(rect.width * dpr) || canvas.height !== Math.floor(rect.height * dpr)) {
    canvas.width = Math.floor(rect.width * dpr);
    canvas.height = Math.floor(rect.height * dpr);
  }
  const w = rect.width;
  const h = rect.height;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  screenBioNodes = [];

  // 1. Ocean background
  ctx.fillStyle = '#070d17';
  ctx.fillRect(0, 0, w, h);

  // 2. Graticule
  ctx.save();
  ctx.strokeStyle = 'rgba(148, 163, 184, 0.07)';
  ctx.lineWidth = 1;
  ctx.font = '10px monospace';
  ctx.fillStyle = 'rgba(148, 163, 184, 0.32)';
  for (let lon = 10; lon <= 85; lon += 5) {
    const [x1, y1] = geoToScreen(lon, 5, w, h);
    const [x2, y2] = geoToScreen(lon, 48, w, h);
    ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
    ctx.fillText(`${lon}°E`, x1 + 3, h - 8);
  }
  for (let lat = 10; lat <= 45; lat += 5) {
    const [x1, y1] = geoToScreen(10, lat, w, h);
    const [x2, y2] = geoToScreen(85, lat, w, h);
    ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke();
    ctx.fillText(`${lat}°N`, 8, y1 - 3);
  }
  ctx.restore();

  // 3. Landmasses
  LANDMASSES.forEach(poly => drawPolygon(poly, w, h, '#141c29', '#3b4d6b', 1.4));

  // Water labels
  ctx.save();
  ctx.font = 'italic 11px Georgia, serif';
  ctx.fillStyle = 'rgba(56, 189, 248, 0.30)';
  ctx.textAlign = 'center';
  [
    { name: 'MEDITERRANEAN SEA', lon: 29.5, lat: 33.8 },
    { name: 'RED SEA', lon: 38.2, lat: 20.5 },
    { name: 'PERSIAN GULF', lon: 51.5, lat: 26.8 },
    { name: 'ARABIAN SEA', lon: 61.5, lat: 18.5 },
    { name: 'CASPIAN SEA', lon: 51.2, lat: 40.2 }
  ].forEach(s => {
    const [sx, sy] = geoToScreen(s.lon, s.lat, w, h);
    ctx.fillText(s.name, sx, sy);
  });
  ctx.restore();

  // 4. Static Indus Valley Civilization (IVC) Zone Polygon (Translucent Green)
  if (document.getElementById('chkIVC').checked) {
    drawPolygon(
      IVC_STATIC_ZONE.pts,
      w,
      h,
      'rgba(16, 185, 129, 0.22)',
      '#10b981',
      2.0,
      [6, 4]
    );
    const [ivcX, ivcY] = geoToScreen(71.2, 28.1, w, h);
    ctx.save();
    ctx.font = 'bold 10.5px sans-serif';
    ctx.textAlign = 'center';
    const w1 = ctx.measureText(IVC_STATIC_ZONE.name).width;
    const w2 = ctx.measureText(IVC_STATIC_ZONE.span).width;
    const boxW = Math.max(w1, w2) + 12;
    ctx.fillStyle = 'rgba(6, 28, 22, 0.88)';
    ctx.fillRect(ivcX - boxW / 2, ivcY - 14, boxW, 28);
    ctx.strokeStyle = '#10b981';
    ctx.lineWidth = 1.2;
    ctx.strokeRect(ivcX - boxW / 2, ivcY - 14, boxW, 28);
    ctx.fillStyle = '#6ee7b7';
    ctx.fillText(IVC_STATIC_ZONE.name, ivcX, ivcY - 2);
    ctx.font = '600 9px sans-serif';
    ctx.fillStyle = '#a7f3d0';
    ctx.fillText(IVC_STATIC_ZONE.span, ivcX, ivcY + 10);
    ctx.restore();
  }

  // 5. Mountain relief
  if (document.getElementById('chkTerrain').checked) {
    ctx.save();
    MOUNTAIN_RANGES.forEach(mr => {
      drawPolyline(mr.pts, w, h, 'rgba(148, 163, 184, 0.22)', 8, [3, 5]);
      const mid = mr.pts[Math.floor(mr.pts.length / 2)];
      const [mx, my] = geoToScreen(mid[0], mid[1], w, h);
      ctx.font = 'bold 9.5px sans-serif';
      ctx.fillStyle = 'rgba(203, 213, 225, 0.42)';
      ctx.textAlign = 'center';
      ctx.fillText(`▲ ${mr.name}`, mx, my - 7);
    });
    ctx.restore();
  }

  // 6. Modern borders
  if (document.getElementById('chkBorders').checked) {
    MODERN_BORDERS.forEach(b => drawPolyline(b, w, h, 'rgba(148, 163, 184, 0.34)', 1.1, [4, 4]));
    ctx.save();
    ctx.font = '700 10px sans-serif';
    ctx.fillStyle = 'rgba(148, 163, 184, 0.38)';
    ctx.textAlign = 'center';
    COUNTRY_LABELS.forEach(c => {
      const [cx, cy] = geoToScreen(c.lon, c.lat, w, h);
      ctx.fillText(c.name, cx, cy);
    });
    ctx.restore();
  }

  // 7. Rivers
  if (document.getElementById('chkRivers').checked) {
    RIVERS.forEach(r => drawPolyline(r.pts, w, h, 'rgba(56, 189, 248, 0.52)', 1.6, r.dash || []));
  }

  const stageIdx = Math.min(EPOCHS.length - 1, Math.round(currentSlider / 100));
  const activeEpoch = EPOCHS[stageIdx];

  // 8. Dynamic historical polygons
  if (document.getElementById('chkPolygons').checked) {
    activeEpoch.polygons.forEach(p => {
      drawPolygon(p.pts, w, h, p.color, p.stroke, 1.8);
      let sumLon = 0, sumLat = 0;
      p.pts.forEach(([lo, la]) => { sumLon += lo; sumLat += la; });
      const [lx, ly] = geoToScreen(sumLon / p.pts.length, sumLat / p.pts.length, w, h);
      ctx.save();
      ctx.font = 'bold 10.5px sans-serif';
      ctx.textAlign = 'center';
      ctx.fillStyle = 'rgba(11,14,20,0.72)';
      const tw = ctx.measureText(p.name).width;
      ctx.fillRect(lx - tw / 2 - 4, ly - 7, tw + 8, 14);
      ctx.fillStyle = '#fff';
      ctx.fillText(p.name, lx, ly + 3);
      ctx.restore();
    });
  }

  // 9. Action vectors
  if (document.getElementById('chkVectors').checked) {
    activeEpoch.vectors.forEach(v => drawArrowVector(v, w, h, animPhase));
  }

  // 10. Reference cities (including IVC urban nodes)
  if (document.getElementById('chkCities').checked) {
    ctx.save();
    CITIES.forEach(city => {
      if (city.type === 'ivc' && !document.getElementById('chkIVC').checked) return;
      const [cx, cy] = geoToScreen(city.lon, city.lat, w, h);
      ctx.beginPath();
      ctx.arc(cx, cy, city.type === 'modern' ? 2.5 : 3.2, 0, Math.PI * 2);
      ctx.fillStyle = city.type === 'ivc' ? '#34d399' : (city.type === 'ancient' ? '#fbbf24' : '#cbd5e1');
      ctx.fill();
      ctx.font = city.type === 'modern' ? '9.5px sans-serif' : 'bold 10px sans-serif';
      ctx.fillStyle = city.type === 'ivc' ? '#6ee7b7' : (city.type === 'ancient' ? '#fde68a' : '#94a3b8');
      ctx.textAlign = 'left';
      ctx.fillText(city.name, cx + 5, cy + 3);
    });
    ctx.restore();
  }

  // 11. Bio-Attrition Hazard Rings
  if (document.getElementById('chkBio').checked) {
    activeEpoch.bioEvents
      .filter(ev => activeBioFilter === 'all' || ev.type === activeBioFilter)
      .forEach(ev => drawBioHazardNode(ev, w, h, animPhase));
  }
}

let lastStage = -1;
function tick() {
  animPhase += 0.008;
  if (playing) {
    currentSlider += 0.35;
    if (currentSlider >= 500) {
      currentSlider = 500;
      playing = false;
      updatePlayBtn();
    }
    document.getElementById('timeSlider').value = Math.floor(currentSlider);
  }
  const st = Math.round(currentSlider / 100);
  if (st !== lastStage) {
    lastStage = st;
    updateSidebar(st);
  }
  render();
  requestAnimationFrame(tick);
}

updateSidebar(0);
setZoom(0.88);
requestAnimationFrame(tick);
</script>
</body>
</html>