Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

209 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Excaliflow — Hand-Drawn Diagramming &amp; Live Causal Flow</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;500;600;700&family=Architects+Daughter&family=Caveat:wght@500;700&family=Geist+Mono:wght@400;500;600&family=Geist:wght@400;500;600;700&family=Inter:wght@400;500;600;700&family=Nunito:wght@400;500;600;700&family=Patrick+Hand&display=swap" rel="stylesheet" />
  <style>
    /* Official Excalidraw Web Fonts (Excalifont, Virgil, Cascadia) */
    @font-face {
      font-family: 'Excalifont';
      src: url('https://esm.sh/@excalidraw/[email protected]/dist/prod/fonts/Excalifont/Excalifont-Regular-a88b72a24fb54c9f94e3b5fdaa7481c9.woff2') format('woff2');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Virgil';
      src: url('https://unpkg.com/@excalidraw/[email protected]/dist/excalidraw-assets/Virgil.woff2') format('woff2');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Cascadia';
      src: url('https://unpkg.com/@excalidraw/[email protected]/dist/excalidraw-assets/Cascadia.woff2') format('woff2');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }

    :root {
      --bg-canvas: #ffffff;
      --panel-bg: rgba(255, 255, 255, 0.94);
      --panel-border: rgba(15, 23, 42, 0.09);
      --panel-shadow: 0 4px 20px -2px rgba(15, 23, 42, 0.08), 0 1px 3px rgba(15, 23, 42, 0.05);
      --text-primary: #1b1b1f;
      --text-secondary: #495057;
      --text-muted: #868e96;
      --surface-hover: #f1f0ff;
      --surface-subtle: #f8f9fa;
      --surface-active: #e0dfff;
      --accent: #6965db;
      --accent-strong: #5753d0;
      --selection-blue: #6965db;
      --danger: #e03131;
      --emerald: #10b981;
      --divider: rgba(15, 23, 42, 0.08);
      --font-sans: 'Assistant', 'Nunito', 'Geist', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      --font-mono: 'Cascadia', 'Geist Mono', monospace;
      --font-hand: 'Excalifont', 'Virgil', 'Patrick Hand', 'Architects Daughter', 'Caveat', cursive;
    }

    body.dark-canvas {
      --bg-canvas: #000000;
      --panel-bg: rgba(22, 22, 27, 0.92);
      --panel-border: rgba(255, 255, 255, 0.11);
      --panel-shadow: 0 8px 28px -4px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(255, 255, 255, 0.06);
      --text-primary: #f1f5f9;
      --text-secondary: #cbd5e1;
      --text-muted: #64748b;
      --surface-hover: rgba(165, 162, 255, 0.12);
      --surface-subtle: rgba(255, 255, 255, 0.05);
      --surface-active: rgba(105, 101, 219, 0.28);
      --accent: #a5a2ff;
      --accent-strong: #8b87ff;
      --selection-blue: #8b87ff;
      --divider: rgba(255, 255, 255, 0.09);
    }

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      user-select: none;
      -webkit-user-select: none;
    }

    html, body {
      width: 100%;
      height: 100%;
      overflow: hidden;
      background-color: var(--bg-canvas);
      font-family: var(--font-sans);
      color: var(--text-primary);
      -webkit-font-smoothing: antialiased;
    }

    /* Dual-Layer Retina Canvas Pipeline */
    #canvasStage {
      position: fixed;
      inset: 0;
      width: 100vw;
      height: 100vh;
      overflow: hidden;
      background-color: var(--bg-canvas);
      transition: background-color 0.16s ease;
    }

    #staticCanvas,
    #interactiveCanvas {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: block;
    }

    #staticCanvas {
      z-index: 1;
      pointer-events: none;
    }

    #interactiveCanvas {
      z-index: 2;
      touch-action: none;
      cursor: default;
    }

    /* Clean Excaliflow Floating Islands */
    .glass-panel {
      background: var(--panel-bg);
      backdrop-filter: blur(14px) saturate(160%);
      -webkit-backdrop-filter: blur(14px) saturate(160%);
      border: 1px solid var(--panel-border);
      box-shadow: var(--panel-shadow);
      border-radius: 10px;
      color: var(--text-primary);
    }

    /* Top Bar Layout */
    #topHeaderBar {
      position: fixed;
      top: 12px;
      left: 12px;
      right: 12px;
      z-index: 20;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      pointer-events: none;
    }

    .header-group {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 6px;
      pointer-events: auto;
    }

    .brand-badge {
      display: flex;
      align-items: center;
      gap: 7px;
      padding: 2px 8px 2px 4px;
      font-weight: 700;
      font-size: 14px;
      letter-spacing: -0.02em;
      color: var(--text-primary);
    }

    .brand-icon {
      width: 24px;
      height: 24px;
      border-radius: 6px;
      background: #6965db;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-family: var(--font-hand);
      font-size: 15px;
      font-weight: 700;
    }

    .v-divider {
      width: 1px;
      height: 20px;
      background: var(--divider);
      margin: 0 3px;
    }

    /* Multi-Canvas Tab Bar & Top Canvas Switcher */
    #bottomCanvasDock {
      position: fixed;
      bottom: 14px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 22;
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 6px;
      pointer-events: auto;
      max-width: calc(100vw - 340px);
    }

    .canvas-tab-strip {
      display: flex;
      align-items: center;
      gap: 4px;
      max-width: calc(100vw - 470px);
      overflow-x: auto;
      scrollbar-width: none;
      padding: 2px;
      background: var(--surface-subtle);
      border: 1px solid var(--divider);
      border-radius: 8px;
    }

    .canvas-tab-strip::-webkit-scrollbar {
      display: none;
    }

    .canvas-tab-pill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      height: 28px;
      padding: 0 9px;
      border: 1px solid var(--divider);
      border-radius: 6px;
      background: var(--panel-bg);
      color: var(--text-secondary);
      font-family: var(--font-sans);
      font-size: 12px;
      font-weight: 500;
      cursor: pointer;
      white-space: nowrap;
      flex-shrink: 0;
      max-width: 210px;
      transition: background 0.12s ease, color 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;
    }

    .canvas-tab-pill:hover {
      background: var(--surface-hover);
      color: var(--text-primary);
      border-color: rgba(105, 101, 219, 0.3);
    }

    .canvas-tab-pill.active {
      background: #6965db;
      color: #ffffff;
      font-weight: 600;
      border-color: #5753d0;
      box-shadow: 0 2px 6px rgba(105, 101, 219, 0.34);
    }

    .tab-num-badge {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 16px;
      height: 16px;
      padding: 0 4px;
      border-radius: 4px;
      font-family: var(--font-mono);
      font-size: 10px;
      font-weight: 600;
      background: rgba(15, 23, 42, 0.07);
      color: var(--text-muted);
      pointer-events: none;
    }

    body.dark-canvas .tab-num-badge {
      background: rgba(255, 255, 255, 0.1);
      color: var(--text-secondary);
    }

    .canvas-tab-pill.active .tab-num-badge {
      background: rgba(255, 255, 255, 0.22);
      color: #ffffff;
    }

    .canvas-tab-pill .tab-label {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 145px;
      pointer-events: none;
    }

    .canvas-tab-pill .tab-close {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 16px;
      height: 16px;
      border-radius: 4px;
      font-size: 12px;
      line-height: 1;
      opacity: 0.6;
      transition: opacity 0.12s ease, background 0.12s ease, color 0.12s ease;
    }

    .canvas-tab-pill.active .tab-close {
      color: #ffffff;
      opacity: 0.8;
    }

    .canvas-tab-pill:hover .tab-close {
      opacity: 0.95;
    }

    .canvas-tab-pill .tab-close:hover {
      opacity: 1;
      background: rgba(224, 49, 49, 0.22);
      color: #ff6b6b;
    }

    .tab-rename-input {
      width: 120px;
      height: 22px;
      padding: 0 6px;
      border: 1.5px solid #ffffff;
      border-radius: 4px;
      background: var(--panel-bg);
      color: var(--text-primary);
      font-family: var(--font-sans);
      font-size: 12px;
      font-weight: 600;
      outline: none;
    }

    .tab-action-btn {
      height: 28px;
      padding: 0 8px;
      font-size: 12px;
      font-weight: 600;
      flex-shrink: 0;
    }

    #canvasSwitcherBtn {
      background: var(--surface-subtle);
      border: 1px solid var(--divider);
      font-weight: 600;
      color: var(--text-primary);
      padding: 0 10px;
      max-width: 210px;
    }

    #canvasSwitcherBtn:hover {
      background: var(--surface-hover);
      border-color: rgba(105, 101, 219, 0.35);
    }

    .switcher-count-badge {
      font-family: var(--font-mono);
      font-size: 10px;
      font-weight: 600;
      padding: 1px 5px;
      border-radius: 4px;
      background: var(--surface-active);
      color: var(--accent);
    }

    .ui-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 5px;
      height: 32px;
      padding: 0 10px;
      border: 1px solid transparent;
      border-radius: 7px;
      background: transparent;
      color: var(--text-secondary);
      font-family: var(--font-sans);
      font-size: 12px;
      font-weight: 500;
      cursor: pointer;
      transition: background 0.12s ease, color 0.12s ease, transform 0.08s ease;
      white-space: nowrap;
    }

    .ui-btn:hover {
      background: var(--surface-hover);
      color: var(--text-primary);
    }

    .ui-btn:active {
      transform: scale(0.97);
    }

    .ui-btn:focus-visible {
      outline: 2px solid var(--accent);
      outline-offset: 1px;
    }

    .ui-btn.active {
      background: var(--surface-active);
      color: var(--accent);
      font-weight: 600;
    }

    .ui-btn.primary {
      background: #6965db;
      color: #ffffff;
      font-weight: 600;
    }

    .ui-btn.primary:hover {
      background: #5753d0;
      color: #ffffff;
    }

    .ui-btn:disabled {
      opacity: 0.35;
      pointer-events: none;
    }

    .ui-btn.danger:hover {
      background: rgba(224, 49, 49, 0.12);
      color: var(--danger);
    }

    /* Excaliflow Top-Center Iconic Tool Island */
    #bottomToolDock {
      display: flex;
      align-items: center;
      gap: 2px;
      padding: 4px;
      pointer-events: auto;
    }

    .dock-tool-btn {
      position: relative;
      width: 36px;
      height: 36px;
      border: 1px solid transparent;
      border-radius: 8px;
      background: transparent;
      color: var(--text-secondary);
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      transition: background 0.12s ease, color 0.12s ease, transform 0.08s ease;
    }

    .dock-tool-btn svg {
      width: 17px;
      height: 17px;
      stroke: currentColor;
      stroke-width: 1.85;
      fill: none;
      stroke-linecap: round;
      stroke-linejoin: round;
    }

    .dock-tool-btn:hover {
      background: var(--surface-hover);
      color: var(--text-primary);
    }

    .dock-tool-btn:active {
      transform: scale(0.94);
    }

    .dock-tool-btn.active {
      background: var(--surface-active);
      color: var(--accent);
    }

    .dock-key {
      position: absolute;
      bottom: 2px;
      right: 3.5px;
      font-family: var(--font-sans);
      font-size: 8.5px;
      font-weight: 600;
      opacity: 0.58;
      line-height: 1;
      pointer-events: none;
    }

    /* Master Flow Pill */
    #masterFlowPill {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 0 4px;
    }

    .flow-status-dot {
      width: 7px;
      height: 7px;
      border-radius: 50%;
      background: #10b981;
      box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
      animation: flowPulseDot 1.8s infinite;
    }

    .flow-status-dot.paused {
      background: #94a3b8;
      box-shadow: none;
      animation: none;
    }

    @keyframes flowPulseDot {
      0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.65); }
      70% { box-shadow: 0 0 0 6px rgba(16, 185, 129, 0); }
      100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }

    .flow-badge-meta {
      font-family: var(--font-mono);
      font-size: 10px;
      font-weight: 600;
      color: var(--accent);
      padding: 2px 6px;
      border-radius: 5px;
      background: var(--surface-active);
    }

    /* Dropdown Popover Menu (Export / Share & Templates) */
    .dropdown-wrap {
      position: relative;
      display: inline-flex;
    }

    .dropdown-menu {
      position: absolute;
      top: calc(100% + 8px);
      right: 0;
      min-width: 196px;
      padding: 6px;
      display: none;
      flex-direction: column;
      gap: 2px;
      z-index: 35;
    }

    .dropdown-menu.align-left {
      right: auto;
      left: 0;
    }

    .dropdown-menu.open {
      display: flex;
    }

    .menu-item {
      width: 100%;
      justify-content: space-between;
      height: 31px;
      padding: 0 10px;
      font-size: 12px;
      border-radius: 6px;
    }

    .menu-sep {
      height: 1px;
      background: var(--divider);
      margin: 4px 2px;
    }

    /* Left Properties Panel (#leftSidebar) - Clean Excaliflow Inspector */
    #leftSidebar {
      position: fixed;
      top: 64px;
      left: 12px;
      max-height: calc(100vh - 132px);
      width: 218px;
      z-index: 18;
      padding: 12px;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      gap: 12px;
      transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.16s ease;
    }

    #leftSidebar.collapsed {
      transform: translateX(-240px);
      opacity: 0;
      pointer-events: none;
    }

    #leftSidebar::-webkit-scrollbar {
      width: 4px;
    }

    #leftSidebar::-webkit-scrollbar-thumb {
      background: var(--divider);
      border-radius: 4px;
    }

    .sidebar-section {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .section-title {
      font-size: 11px;
      font-weight: 500;
      color: var(--text-secondary);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .grid-2x2 {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 4px;
    }

    .segmented-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(34px, 1fr));
      gap: 3px;
      background: var(--surface-subtle);
      padding: 3px;
      border-radius: 8px;
      border: 1px solid var(--divider);
    }

    .seg-btn {
      height: 26px;
      border: none;
      border-radius: 6px;
      background: transparent;
      color: var(--text-secondary);
      font-family: var(--font-sans);
      font-size: 11px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.12s ease;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 3px;
    }

    .seg-btn:hover {
      color: var(--text-primary);
      background: var(--surface-hover);
    }

    .seg-btn.active {
      background: var(--surface-active);
      color: var(--accent);
      font-weight: 600;
    }

    /* Color Swatches */
    .swatch-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 4px;
      padding: 2px 0;
    }

    .color-swatch {
      width: 22px;
      height: 22px;
      border-radius: 6px;
      border: 1.5px solid rgba(0, 0, 0, 0.12);
      cursor: pointer;
      transition: transform 0.12s ease, box-shadow 0.12s ease;
    }

    .color-swatch:hover {
      transform: scale(1.1);
    }

    .color-swatch.active {
      box-shadow: 0 0 0 2px var(--bg-canvas), 0 0 0 3.5px var(--accent);
    }

    /* Floating Contextual Selection Toolbar (#quickHud) */
    #quickHud {
      position: fixed;
      z-index: 25;
      display: none;
      align-items: center;
      gap: 4px;
      padding: 4px 7px;
      transform: translate(-50%, -100%);
      pointer-events: auto;
      white-space: nowrap;
    }

    #quickHud.visible {
      display: inline-flex;
    }

    .hud-dot {
      width: 16px;
      height: 16px;
      border-radius: 4px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      cursor: pointer;
      transition: transform 0.1s ease;
    }

    .hud-dot:hover,
    .hud-dot.active {
      transform: scale(1.16);
      box-shadow: 0 0 0 2px var(--accent);
    }

    /* Bottom-Left Undo/Redo & Bottom-Right Zoom Pill */
    #bottomLeftBar {
      position: fixed;
      bottom: 14px;
      left: 14px;
      z-index: 20;
      display: flex;
      align-items: center;
      gap: 2px;
      padding: 3px 5px;
    }

    #zoomPill {
      position: fixed;
      bottom: 14px;
      right: 14px;
      z-index: 20;
      display: flex;
      align-items: center;
      gap: 2px;
      padding: 3px 5px;
    }

    /* Subtle Onboarding Hint Pill */
    #canvasHintPill {
      position: fixed;
      bottom: 16px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 15;
      padding: 5px 12px;
      font-size: 11.5px;
      color: var(--text-muted);
      pointer-events: none;
      display: flex;
      align-items: center;
      gap: 10px;
      border-radius: 999px;
    }

    .hint-key {
      font-family: var(--font-mono);
      font-size: 10px;
      padding: 1px 5px;
      border-radius: 4px;
      background: var(--surface-subtle);
      border: 1px solid var(--divider);
      color: var(--text-secondary);
    }

    /* Inline Textarea Editor */
    #inlineEditorWrap {
      position: fixed;
      z-index: 30;
      display: none;
      pointer-events: auto;
    }

    #inlineTextEditor {
      min-width: 80px;
      min-height: 30px;
      padding: 4px 8px;
      border: 1.5px solid var(--accent);
      border-radius: 6px;
      background: var(--panel-bg);
      color: var(--text-primary);
      text-align: center;
      resize: none;
      outline: none;
      overflow: hidden;
      line-height: 1.3;
      box-shadow: 0 4px 16px rgba(105, 101, 219, 0.22);
    }

    /* Toast status notification */
    #studioToast {
      position: fixed;
      bottom: 60px;
      left: 50%;
      transform: translateX(-50%) translateY(8px);
      z-index: 40;
      padding: 6px 14px;
      font-size: 12px;
      font-weight: 500;
      opacity: 0;
      pointer-events: none;
      transition: all 0.18s ease;
    }

    #studioToast.show {
      opacity: 1;
      transform: translateX(-50%) translateY(0);
    }
  </style>
</head>
<body>
  <!-- Dual-Layer Retina Canvas Pipeline -->
  <div id="canvasStage">
    <canvas id="staticCanvas"></canvas>
    <canvas id="interactiveCanvas"></canvas>
  </div>

  <!-- Top Bar: Left Brand/Templates | Center Excaliflow Tool Island | Right Flow/Theme/Export -->
  <header id="topHeaderBar">
    <!-- Left Island: Brand + Active Canvas Switcher + Templates -->
    <div class="header-group glass-panel">
      <button id="sidebarToggleBtn" class="ui-btn" title="Toggle Properties Panel (⌘\)">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="15" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
      </button>
      <div class="brand-badge">
        <span class="brand-icon">E</span>
        <span>Excaliflow</span>
      </div>
      <div class="v-divider"></div>
      <button id="prevCanvasBtn" class="ui-btn tab-action-btn" title="Previous Canvas (⌥[)">‹</button>
      <div class="dropdown-wrap">
        <button id="canvasSwitcherBtn" class="ui-btn" title="Switch or Manage Canvases">
          <span id="activeCanvasLabel">AI Agent Swarm</span>
          <span id="activeCanvasCount" class="switcher-count-badge">1/1</span>
          <span style="font-size:9px;opacity:0.65">▾</span>
        </button>
        <div id="canvasesDropdown" class="dropdown-menu align-left glass-panel" style="min-width:240px"></div>
      </div>
      <button id="nextCanvasBtn" class="ui-btn tab-action-btn" title="Next Canvas (⌥])">›</button>
      <button id="addCanvasTabBtn" class="ui-btn tab-action-btn" title="New Blank Canvas Tab (⌥T)">+ New</button>
      <button id="forkCanvasTabBtn" class="ui-btn tab-action-btn" title="Duplicate Active Canvas Tab">⧉</button>
      <div class="v-divider"></div>
      <div class="dropdown-wrap">
        <button id="templatesMenuBtn" class="ui-btn" title="Starter Architecture Templates">
          <span>Templates</span>
          <span style="font-size:9px;opacity:0.65">▾</span>
        </button>
        <div id="templatesDropdown" class="dropdown-menu align-left glass-panel">
          <button class="ui-btn menu-item" data-template="AI Agent Swarm"><span>AI Agent Swarm</span><span style="opacity:0.5">5 nodes</span></button>
          <button class="ui-btn menu-item" data-template="How Browsers Work"><span>How Browsers Work</span><span style="opacity:0.5">5 nodes</span></button>
          <button class="ui-btn menu-item" data-template="RAG Pipeline"><span>RAG Pipeline</span><span style="opacity:0.5">5 nodes</span></button>
          <button class="ui-btn menu-item" data-template="Microservices"><span>Microservices</span><span style="opacity:0.5">6 nodes</span></button>
        </div>
      </div>
    </div>

    <!-- Center Island: Iconic Excaliflow Tool Dock -->
    <nav id="bottomToolDock" class="glass-panel" aria-label="Drawing Tools">
      <button id="toolLockBtn" class="dock-tool-btn" title="Keep selected tool active after drawing (Q)">
        <svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
        <span class="dock-key">Q</span>
      </button>
      <div class="v-divider"></div>
      <button class="dock-tool-btn active" data-tool="select" title="Selection — Move, resize, bend arrows (V or 1)">
        <svg viewBox="0 0 24 24"><path d="M4 4l7.07 17 2.51-7.39L21 11.07z"/></svg>
        <span class="dock-key">1</span>
      </button>
      <button class="dock-tool-btn" data-tool="hand" title="Hand — Pan canvas (H or Space)">
        <svg viewBox="0 0 24 24"><path d="M18 11V6a2 2 0 0 0-4 0v4"/><path d="M14 10V4a2 2 0 0 0-4 0v6"/><path d="M10 10.5V6a2 2 0 0 0-4 0v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></svg>
        <span class="dock-key">H</span>
      </button>
      <button class="dock-tool-btn" data-tool="rectangle" title="Rectangle (R or 2)">
        <svg viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="3"/></svg>
        <span class="dock-key">2</span>
      </button>
      <button class="dock-tool-btn" data-tool="diamond" title="Diamond / Decision (D or 3)">
        <svg viewBox="0 0 24 24"><path d="M12 3l9 9-9 9-9-9z"/></svg>
        <span class="dock-key">3</span>
      </button>
      <button class="dock-tool-btn" data-tool="ellipse" title="Ellipse / Circle (O or 4)">
        <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></svg>
        <span class="dock-key">4</span>
      </button>
      <button class="dock-tool-btn" data-tool="arrow" title="Causal Flow Arrow (A or 5)">
        <svg viewBox="0 0 24 24"><line x1="5" y1="19" x2="19" y2="5"/><polyline points="9 5 19 5 19 15"/></svg>
        <span class="dock-key">5</span>
      </button>
      <button class="dock-tool-btn" data-tool="freedraw" title="Draw Freehand (P or 7)">
        <svg viewBox="0 0 24 24"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/></svg>
        <span class="dock-key">7</span>
      </button>
      <button class="dock-tool-btn" data-tool="text" title="Text (T or 8)">
        <svg viewBox="0 0 24 24"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>
        <span class="dock-key">8</span>
      </button>
      <button class="dock-tool-btn" data-tool="sticky" title="Sticky Note (N or 9)">
        <svg viewBox="0 0 24 24"><path d="M15.5 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z"/><polyline points="14 3 14 9 21 9"/></svg>
        <span class="dock-key">9</span>
      </button>
      <button class="dock-tool-btn" data-tool="laser" title="Laser Pointer (K)">
        <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.93 4.93l2.12 2.12M16.95 16.95l2.12 2.12M19.07 4.93l-2.12 2.12M7.05 16.95l-2.12 2.12"/></svg>
        <span class="dock-key">K</span>
      </button>
      <button class="dock-tool-btn" data-tool="eraser" title="Eraser (E or 0)">
        <svg viewBox="0 0 24 24"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>
        <span class="dock-key">0</span>
      </button>
    </nav>

    <!-- Right Island: Live Flow Pill + Canvas Theme + Share/Export -->
    <div class="header-group glass-panel">
      <div id="masterFlowPill">
        <span id="flowStatusDot" class="flow-status-dot"></span>
        <button id="masterFlowBtn" class="ui-btn active" title="Toggle Live 60fps Causal Data Flow">Flow: ON</button>
        <span id="flowBadgeText" class="flow-badge-meta">COMETS · 1X</span>
      </div>
      <div class="v-divider"></div>
      <button id="bgWhiteBtn" class="ui-btn active" title="Pure White Canvas (#ffffff)">☀</button>
      <button id="bgBlackBtn" class="ui-btn" title="Pitch-Black Neon Canvas (#000000)">☾</button>
      <div class="v-divider"></div>
      <button id="btnSavePng" class="ui-btn primary" title="Export Cropped 2x Retina PNG">Export PNG</button>
      <div class="dropdown-wrap">
        <button id="exportMenuBtn" class="ui-btn" title="More Export &amp; Scene Actions">⋯</button>
        <div id="exportDropdown" class="dropdown-menu glass-panel">
          <button id="btnCopyPng" class="ui-btn menu-item"><span>Copy 2x PNG</span><span>⌘⇧C</span></button>
          <button id="btnRecordVideo" class="ui-btn menu-item"><span>Record 60fps Video</span><span>.webm</span></button>
          <div class="menu-sep"></div>
          <button id="btnSaveJson" class="ui-btn menu-item"><span>Save Scene</span><span>JSON</span></button>
          <button id="btnLoadJson" class="ui-btn menu-item"><span>Load Scene</span><span>Open</span></button>
          <input type="file" id="jsonFileInput" accept=".json,.excaliflow,.excalidraw" style="display:none" />
          <div class="menu-sep"></div>
          <button id="btnClearScene" class="ui-btn menu-item danger"><span>Clear Canvas</span><span>⌫</span></button>
        </div>
      </div>
    </div>
  </header>

  <!-- Left Properties Inspector (#leftSidebar) -->
  <aside id="leftSidebar" class="glass-panel">
    <!-- Stroke Color Swatches -->
    <div class="sidebar-section">
      <div class="section-title"><span>Stroke</span></div>
      <div class="swatch-row" id="sidebarSwatches">
        <button class="color-swatch active" data-color="#171717" title="Carbon (#171717)" style="background:#171717"></button>
        <button class="color-swatch" data-color="#0070f3" title="Blue (#0070f3)" style="background:#0070f3"></button>
        <button class="color-swatch" data-color="#7928ca" title="Purple (#7928ca)" style="background:#7928ca"></button>
        <button class="color-swatch" data-color="#10b981" title="Emerald (#10b981)" style="background:#10b981"></button>
        <button class="color-swatch" data-color="#f59e0b" title="Amber (#f59e0b)" style="background:#f59e0b"></button>
        <button class="color-swatch" data-color="#ef4444" title="Rose (#ef4444)" style="background:#ef4444"></button>
        <button class="color-swatch" data-color="#06b6d4" title="Cyan (#06b6d4)" style="background:#06b6d4"></button>
      </div>
    </div>

    <!-- Fill Style -->
    <div class="sidebar-section">
      <div class="section-title"><span>Fill</span></div>
      <div class="segmented-row" id="fillStyleRow">
        <button class="seg-btn active" data-fill-style="hachure" title="Hachure Sketch Fill">Sketch</button>
        <button class="seg-btn" data-fill-style="cross-hatch" title="Cross-Hatch Fill">Cross</button>
        <button class="seg-btn" data-fill-style="solid" title="Solid Tint Fill">Solid</button>
        <button class="seg-btn" data-fill-style="none" title="Outline Only">None</button>
      </div>
    </div>

    <!-- Stroke Width & Style -->
    <div class="sidebar-section">
      <div class="section-title"><span>Stroke Width &amp; Style</span></div>
      <div class="segmented-row" id="strokeWidthRow">
        <button class="seg-btn" data-stroke-width="1.5">Thin</button>
        <button class="seg-btn active" data-stroke-width="2.2">Bold</button>
        <button class="seg-btn" data-stroke-width="3.6">Heavy</button>
      </div>
      <div class="segmented-row" id="strokeStyleRow">
        <button class="seg-btn active" data-stroke-style="solid">Solid</button>
        <button class="seg-btn" data-stroke-style="dashed">Dashed</button>
        <button class="seg-btn" data-stroke-style="dotted">Dotted</button>
      </div>
    </div>

    <!-- Sloppiness & Arrow Type -->
    <div class="sidebar-section">
      <div class="section-title"><span>Sloppiness &amp; Arrow</span></div>
      <div class="segmented-row" id="roughnessRow">
        <button class="seg-btn" data-roughness="0">Clean</button>
        <button class="seg-btn active" data-roughness="0.85">Artist</button>
        <button class="seg-btn" data-roughness="1.75">Cartoon</button>
      </div>
      <div class="segmented-row" id="curveTypeRow">
        <button class="seg-btn active" data-curve-type="curved">Curved</button>
        <button class="seg-btn" data-curve-type="elbow">Elbow</button>
        <button class="seg-btn" data-curve-type="straight">Straight</button>
      </div>
    </div>

    <!-- Typography -->
    <div class="sidebar-section">
      <div class="section-title"><span>Typography</span></div>
      <div class="segmented-row" id="fontFamilyRow">
        <button class="seg-btn active" data-font-family="hand" style="font-family:var(--font-hand);font-size:13px">Hand</button>
        <button class="seg-btn" data-font-family="sans">Normal</button>
        <button class="seg-btn" data-font-family="code" style="font-family:var(--font-mono);font-size:10.5px">Code</button>
      </div>
      <div class="segmented-row" id="fontSizeRow">
        <button class="seg-btn" data-font-size="13">S</button>
        <button class="seg-btn active" data-font-size="15">M</button>
        <button class="seg-btn" data-font-size="19">L</button>
        <button class="seg-btn" data-font-size="24">XL</button>
      </div>
    </div>

    <!-- Live Flow Animation -->
    <div class="sidebar-section">
      <div class="section-title"><span>Flow Animation</span></div>
      <div class="grid-2x2" id="flowModeGrid">
        <button class="seg-btn active" data-flow-mode="comets">☄ Comets</button>
        <button class="seg-btn" data-flow-mode="pulses">◎ Pulses</button>
        <button class="seg-btn" data-flow-mode="neon">⚡ Neon</button>
        <button class="seg-btn" data-flow-mode="dashed">⋯ Stream</button>
      </div>
      <div class="segmented-row" id="flowSpeedRow">
        <button class="seg-btn" data-flow-speed="0.6">0.6x</button>
        <button class="seg-btn active" data-flow-speed="1">1x</button>
        <button class="seg-btn" data-flow-speed="1.8">1.8x</button>
      </div>
    </div>

    <!-- Quick Insert / Chain -->
    <div class="sidebar-section">
      <div class="section-title"><span>Quick Chain</span></div>
      <div class="grid-2x2">
        <button class="seg-btn" data-quick-add="rectangle">+ Box</button>
        <button class="seg-btn" data-quick-add="ellipse">+ Circle</button>
        <button class="seg-btn" data-quick-add="diamond">+ Decision</button>
        <button class="seg-btn" data-quick-add="sticky">+ Sticky</button>
      </div>
    </div>
  </aside>

  <!-- Floating Contextual Selection Toolbar (#quickHud) -->
  <div id="quickHud" class="glass-panel">
    <div id="hudColorDots" style="display:inline-flex;align-items:center;gap:4px"></div>
    <div class="v-divider"></div>
    <div id="hudFontGroup" style="display:inline-flex;align-items:center;gap:2px">
      <button class="ui-btn" data-hud-font="hand" title="Hand-drawn font">Hand</button>
      <button class="ui-btn" data-hud-font="sans" title="Normal font">Sans</button>
      <button class="ui-btn" data-hud-font="code" title="Code font">Code</button>
    </div>
    <div class="v-divider"></div>
    <!-- Node-specific morph & flow actions -->
    <div id="hudNodeControls" style="display:inline-flex;align-items:center;gap:2px">
      <button class="ui-btn" data-hud-morph="rectangle" title="Morph to Box">▭</button>
      <button class="ui-btn" data-hud-morph="ellipse" title="Morph to Circle">◯</button>
      <button class="ui-btn" data-hud-morph="diamond" title="Morph to Decision">◇</button>
      <button id="hudPulseBtn" class="ui-btn" title="Send Pulse Burst">⚡ Pulse</button>
      <button id="hudNextBtn" class="ui-btn" title="Chain Next Node (Tab)">+ Next</button>
    </div>
    <!-- Arrow-specific actions -->
    <div id="hudArrowControls" style="display:none;align-items:center;gap:2px">
      <button class="ui-btn" data-hud-curve="curved">Curved</button>
      <button class="ui-btn" data-hud-curve="elbow">Elbow</button>
      <button class="ui-btn" data-hud-curve="straight">Straight</button>
      <button id="hudArrowFlowBtn" class="ui-btn">Flow ON</button>
      <button id="hudFlipArrowBtn" class="ui-btn" title="Reverse Arrow Direction">⇄</button>
    </div>
    <div class="v-divider"></div>
    <button id="hudDuplicateBtn" class="ui-btn" title="Duplicate (⌘D)">⧉</button>
    <button id="hudDeleteBtn" class="ui-btn danger" title="Delete (⌫)">✕</button>
  </div>

  <!-- Bottom-Left Undo/Redo Pill (Excaliflow Standard Placement) -->
  <div id="bottomLeftBar" class="glass-panel">
    <button id="btnUndo" class="ui-btn" title="Undo (⌘Z)">↶</button>
    <button id="btnRedo" class="ui-btn" title="Redo (⇧⌘Z)">↷</button>
  </div>

  <!-- Bottom-Center Multi-Canvas Tab Bar (Figma / Excalidraw Pages Style) -->
  <div id="bottomCanvasDock" class="glass-panel">
    <div id="canvasTabStrip" class="canvas-tab-strip" role="tablist" aria-label="Canvas Tabs"></div>
    <div class="v-divider"></div>
    <button id="bottomAddTabBtn" class="ui-btn tab-action-btn" title="New Blank Canvas Tab (⌥T)">+ Canvas</button>
    <button id="bottomForkTabBtn" class="ui-btn tab-action-btn" title="Duplicate Current Canvas">⧉</button>
  </div>

  <!-- Bottom-Right Zoom Pill -->
  <div id="zoomPill" class="glass-panel">
    <button id="zoomOutBtn" class="ui-btn" title="Zoom Out">−</button>
    <button id="zoomResetBtn" class="ui-btn" title="Reset Zoom to 100%">100%</button>
    <button id="zoomInBtn" class="ui-btn" title="Zoom In">+</button>
    <div class="v-divider"></div>
    <button id="zoomFitBtn" class="ui-btn" title="Fit Diagram to Screen">Fit</button>
  </div>

  <!-- Inline Text Editor -->
  <div id="inlineEditorWrap">
    <textarea id="inlineTextEditor" rows="1" spellcheck="false"></textarea>
  </div>

  <!-- Toast Status Pill -->
  <div id="studioToast" class="glass-panel"></div>

  <script>
    /* =========================================================================
     * EXCALIFLOW — ZERO-DEPENDENCY HAND-DRAWN DIAGRAMMING & 60FPS FLOW ENGINE
     * ========================================================================= */

    const SEMANTIC_COLORS = [
      { hex: '#171717', name: 'Carbon', lightFill: 'rgba(23, 23, 23, 0.07)', darkFill: 'rgba(248, 250, 252, 0.14)', darkStroke: '#f8fafc' },
      { hex: '#0070f3', name: 'Blue',   lightFill: 'rgba(0, 112, 243, 0.12)', darkFill: 'rgba(56, 189, 248, 0.20)', darkStroke: '#38bdf8' },
      { hex: '#7928ca', name: 'Purple', lightFill: 'rgba(121, 40, 202, 0.12)', darkFill: 'rgba(192, 132, 252, 0.22)', darkStroke: '#c084fc' },
      { hex: '#10b981', name: 'Emerald',lightFill: 'rgba(16, 185, 129, 0.13)', darkFill: 'rgba(52, 211, 153, 0.20)', darkStroke: '#34d399' },
      { hex: '#f59e0b', name: 'Amber',  lightFill: 'rgba(245, 158, 11, 0.15)', darkFill: 'rgba(251, 191, 36, 0.22)', darkStroke: '#fbbf24' },
      { hex: '#ef4444', name: 'Rose',   lightFill: 'rgba(239, 68, 68, 0.13)',  darkFill: 'rgba(248, 113, 113, 0.22)', darkStroke: '#f87171' },
      { hex: '#06b6d4', name: 'Cyan',   lightFill: 'rgba(6, 182, 212, 0.14)',  darkFill: 'rgba(34, 211, 238, 0.22)', darkStroke: '#22d3ee' }
    ];

    // Matches Excalidraw's FONT_FAMILY (Excalifont / Virgil for hand, Assistant / Nunito for normal, Cascadia for code)
    const FONT_MAP = {
      hand: "'Excalifont', 'Virgil', 'Patrick Hand', 'Architects Daughter', 'Caveat', cursive",
      sans: "'Assistant', 'Nunito', 'Geist', 'Inter', -apple-system, BlinkMacSystemFont, sans-serif",
      code: "'Cascadia', 'Geist Mono', monospace"
    };

    // Excalidraw unitless line-height metric from packages/common/src/font-metadata.ts
    const EXCALIDRAW_LINE_HEIGHT = 1.25;

    function normalizeFontFamily(family) {
      if (!family) return 'hand';
      if (typeof family === 'number') {
        if (family === 3 || family === 8) return 'code';
        if (family === 2 || family === 4 || family === 6 || family === 9 || family === 10) return 'sans';
        return 'hand';
      }
      const f = String(family).toLowerCase();
      if (f === 'hand' || f.includes('excalifont') || f.includes('virgil') || f.includes('patrick') || f.includes('caveat')) return 'hand';
      if (f === 'sans' || f === 'normal' || f.includes('assistant') || f.includes('nunito') || (f.includes('geist') && !f.includes('mono')) || f.includes('inter')) return 'sans';
      if (f === 'code' || f === 'mono' || f.includes('cascadia') || f.includes('mono')) return 'code';
      return 'hand';
    }

    function getFontCss(family, fontSize, weight = null) {
      const key = normalizeFontFamily(family);
      const cssFamily = FONT_MAP[key] || FONT_MAP.hand;
      const sz = Number(fontSize) || 16;
      const resolvedWeight = weight !== null ? weight : (key === 'hand' ? 400 : 500);
      return `${resolvedWeight} ${sz}px ${cssFamily}`;
    }

    function getColorEntry(hex) {
      const norm = (hex || '#171717').toLowerCase();
      return SEMANTIC_COLORS.find(c => c.hex.toLowerCase() === norm) || SEMANTIC_COLORS[0];
    }

    function resolveStrokeColor(hex, canvasBg) {
      const entry = getColorEntry(hex);
      const isDark = (canvasBg || state.canvasBg) === '#000000';
      if (isDark) return entry.darkStroke || entry.hex;
      return entry.hex;
    }

    function resolveFillTint(hex, canvasBg, isSticky = false) {
      const entry = getColorEntry(hex);
      const isDark = (canvasBg || state.canvasBg) === '#000000';
      if (isSticky) {
        if (entry.hex === '#171717') return isDark ? 'rgba(251, 191, 36, 0.20)' : '#fef3c7';
      }
      return isDark ? entry.darkFill : entry.lightFill;
    }

    /* -------------------------------------------------------------------------
     * 1. Deterministic Seeded PRNG (mulberry32)
     * ------------------------------------------------------------------------- */
    function mulberry32(seed) {
      let a = (Number(seed) || 1) >>> 0;
      return function () {
        a |= 0;
        a = (a + 0x6D2B79F5) | 0;
        let t = Math.imul(a ^ (a >>> 15), 1 | a);
        t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
      };
    }

    let idCounter = 1000;
    function nextId(prefix = 'el') {
      idCounter += 1;
      return `${prefix}_${idCounter}_${Math.floor(Math.random() * 9000 + 1000)}`;
    }

    function syncIdCounterWithId(rawId) {
      if (typeof rawId !== 'string') return;
      const m = rawId.match(/_(\d+)_/);
      if (m) {
        const n = Number(m[1]);
        if (Number.isFinite(n) && n > idCounter) idCounter = n;
      }
    }

    /* -------------------------------------------------------------------------
     * 2. Scene State
     * ------------------------------------------------------------------------- */
    const state = {
      tabs: [],
      activeTabId: null,
      editingTabId: null,
      elements: [],
      selectedIds: new Set(),
      hoveredId: null,
      hoveredPort: null,
      hoveredArrowHandle: null,
      hoveredResizeHandle: null,
      splitTargetArrowId: null,
      snapPreview: null,
      activeTool: 'select',
      toolLocked: false,
      canvasBg: '#ffffff',
      scrollX: 0,
      scrollY: 0,
      zoom: 1,
      flowEnabled: true,
      flowMode: 'comets',
      flowSpeed: 1.0,
      activePulses: [],
      laserPoints: [],
      nodeArrivalEnergy: new Map(),
      defaults: {
        strokeColor: '#171717',
        fillStyle: 'hachure',
        fontFamily: 'hand',
        fontSize: 15,
        roughness: 0.85,
        strokeWidth: 2.2,
        strokeStyle: 'solid',
        curveType: 'curved'
      },
      history: {
        undoStack: [],
        redoStack: []
      },
      clipboard: [],
      pasteCount: 0,
      drag: null,
      editingId: null,
      isSpacePanning: false
    };

    /* -------------------------------------------------------------------------
     * 3. Zero-Bleed Analytical Interior Clipping & Procedural Sketch Engine
     * ------------------------------------------------------------------------- */
    function clampPointToShapeInterior(el, px, py, inset = 1.5) {
      const w = Math.max(2, el.width || 0);
      const h = Math.max(2, el.height || 0);
      const cx = el.x + w / 2;
      const cy = el.y + h / 2;
      const ins = Math.min(Math.max(0, inset), Math.min(w, h) * 0.35);

      if (el.type === 'ellipse') {
        const rx = Math.max(1, w / 2 - ins);
        const ry = Math.max(1, h / 2 - ins);
        const ux = (px - cx) / rx;
        const vy = (py - cy) / ry;
        const d2 = ux * ux + vy * vy;
        if (d2 > 0.999) {
          const s = 0.995 / Math.sqrt(d2);
          return [cx + (px - cx) * s, cy + (py - cy) * s];
        }
        return [px, py];
      }

      if (el.type === 'diamond') {
        const hw = Math.max(1, w / 2 - ins);
        const hh = Math.max(1, h / 2 - ins);
        const l1 = Math.abs(px - cx) / hw + Math.abs(py - cy) / hh;
        if (l1 > 0.999) {
          const s = 0.995 / l1;
          return [cx + (px - cx) * s, cy + (py - cy) * s];
        }
        return [px, py];
      }

      const xL = el.x + ins;
      const xR = el.x + w - ins;
      const yT = el.y + ins;
      const yB = el.y + h - ins;
      let nx = Math.max(xL, Math.min(xR, px));
      let ny = Math.max(yT, Math.min(yB, py));
      const r = Math.max(0, Math.min(14, w / 4, h / 4) - ins * 0.5);
      if (r > 0.5) {
        const corners = [
          [xL + r, yT + r, nx < xL + r && ny < yT + r],
          [xR - r, yT + r, nx > xR - r && ny < yT + r],
          [xR - r, yB - r, nx > xR - r && ny > yB - r],
          [xL + r, yB - r, nx < xL + r && ny > yB - r]
        ];
        for (const [kx, ky, inCorner] of corners) {
          if (inCorner) {
            const dx = nx - kx;
            const dy = ny - ky;
            const d = Math.hypot(dx, dy);
            if (d > r * 0.995) {
              const s = (r * 0.99) / d;
              nx = kx + dx * s;
              ny = ky + dy * s;
            }
          }
        }
      }
      return [nx, ny];
    }

    function clipSegmentToShape(el, x1, y1, x2, y2, inset = 1.8) {
      if (!el) return null;
      const w = Number(el.width) || 0;
      const h = Number(el.height) || 0;
      if (w <= 2 || h <= 2) return null;

      const cx = el.x + w / 2;
      const cy = el.y + h / 2;
      const ins = Math.min(Math.max(0, Number(inset) || 0), Math.min(w, h) * 0.35);
      const dx = x2 - x1;
      const dy = y2 - y1;

      if (el.type === 'ellipse') {
        const rx = Math.max(1, w / 2 - ins);
        const ry = Math.max(1, h / 2 - ins);
        const u1 = (x1 - cx) / rx;
        const v1 = (y1 - cy) / ry;
        const du = dx / rx;
        const dv = dy / ry;

        const A = du * du + dv * dv;
        const B = 2 * (u1 * du + v1 * dv);
        const C = u1 * u1 + v1 * v1 - 1;

        if (A < 1e-12) {
          return C <= 0 ? [x1, y1, x2, y2] : null;
        }
        const disc = B * B - 4 * A * C;
        if (disc <= 0) return null;

        const sqrtD = Math.sqrt(disc);
        const t0 = (-B - sqrtD) / (2 * A);
        const t1 = (-B + sqrtD) / (2 * A);
        const tMin = Math.max(0, Math.min(t0, t1));
        const tMax = Math.min(1, Math.max(t0, t1));
        if (tMin >= tMax - 1e-5) return null;

        const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);
        const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);
        return [cx1, cy1, cx2, cy2];
      }

      if (el.type === 'diamond') {
        const hw = Math.max(1, w / 2 - ins);
        const hh = Math.max(1, h / 2 - ins);
        let tMin = 0;
        let tMax = 1;

        const signs = [[1, 1], [1, -1], [-1, 1], [-1, -1]];
        for (let i = 0; i < 4; i++) {
          const sx = signs[i][0];
          const sy = signs[i][1];
          const p = sx * (dx / hw) + sy * (dy / hh);
          const q = 1 - (sx * ((x1 - cx) / hw) + sy * ((y1 - cy) / hh));
          if (Math.abs(p) < 1e-12) {
            if (q < 0) return null;
          } else if (p > 0) {
            tMax = Math.min(tMax, q / p);
          } else {
            tMin = Math.max(tMin, q / p);
          }
          if (tMin >= tMax - 1e-5) return null;
        }

        const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);
        const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);
        return [cx1, cy1, cx2, cy2];
      }

      const xL = el.x + ins;
      const xR = el.x + w - ins;
      const yT = el.y + ins;
      const yB = el.y + h - ins;
      if (xL >= xR || yT >= yB) return null;

      let tMin = 0;
      let tMax = 1;
      const pArr = [-dx, dx, -dy, dy];
      const qArr = [x1 - xL, xR - x1, y1 - yT, yB - y1];
      for (let i = 0; i < 4; i++) {
        const p = pArr[i];
        const q = qArr[i];
        if (Math.abs(p) < 1e-12) {
          if (q < 0) return null;
        } else {
          const r = q / p;
          if (p < 0) tMin = Math.max(tMin, r);
          else tMax = Math.min(tMax, r);
          if (tMin >= tMax - 1e-5) return null;
        }
      }

      const r = el.type === 'sticky' ? 4 : Math.max(0, Math.min(14, w / 4, h / 4) - ins * 0.5);
      if (r > 0.5) {
        const clipCornerCircle = (tVal, isStart) => {
          const px = x1 + tVal * dx;
          const py = y1 + tVal * dy;
          let kx = null;
          let ky = null;
          if (px < xL + r && py < yT + r) { kx = xL + r; ky = yT + r; }
          else if (px > xR - r && py < yT + r) { kx = xR - r; ky = yT + r; }
          else if (px > xR - r && py > yB - r) { kx = xR - r; ky = yB - r; }
          else if (px < xL + r && py > yB - r) { kx = xL + r; ky = yB - r; }
          if (kx === null) return tVal;

          const ox = x1 - kx;
          const oy = y1 - ky;
          if (ox * ox + oy * oy <= r * r && !isStart) return tVal;
          const A = dx * dx + dy * dy;
          const B = 2 * (ox * dx + oy * dy);
          const C = ox * ox + oy * oy - r * r;
          const disc = B * B - 4 * A * C;
          if (disc <= 0 || A < 1e-12) return null;
          const sD = Math.sqrt(disc);
          const ca = (-B - sD) / (2 * A);
          const cb = (-B + sD) / (2 * A);
          return isStart ? Math.max(tVal, Math.min(ca, cb)) : Math.min(tVal, Math.max(ca, cb));
        };

        const ntMin = clipCornerCircle(tMin, true);
        const ntMax = clipCornerCircle(tMax, false);
        if (ntMin === null || ntMax === null || ntMin >= ntMax - 1e-5) return null;
        tMin = ntMin;
        tMax = ntMax;
      }

      const [cx1, cy1] = clampPointToShapeInterior(el, x1 + tMin * dx, y1 + tMin * dy, ins);
      const [cx2, cy2] = clampPointToShapeInterior(el, x1 + tMax * dx, y1 + tMax * dy, ins);
      return [cx1, cy1, cx2, cy2];
    }

    function roughEdge(path, x1, y1, x2, y2, rng, roughness = 0.85) {
      const r = Number(roughness) || 0;
      if (r <= 0.001) {
        path.moveTo(x1, y1);
        path.lineTo(x2, y2);
        return;
      }
      const dx = x2 - x1;
      const dy = y2 - y1;
      const len = Math.hypot(dx, dy) || 1;
      const nx = -dy / len;
      const ny = dx / len;
      const isCartoon = r > 1.2;
      const passes = isCartoon ? 3 : 2;
      const endJit = isCartoon ? 4.8 : 1.6 * r;
      const bowMag = isCartoon
        ? Math.min(11.0, Math.max(4.8, len * 0.055))
        : Math.min(4.8, Math.max(2.2, len * 0.025)) * r;

      for (let pass = 0; pass < passes; pass++) {
        const sign = pass === 0 ? 1 : (pass === 1 ? -0.9 : 0.55);
        const overshoot = isCartoon ? (pass === 0 ? 3.5 : -2.0) : 0;
        const ux = dx / len;
        const uy = dy / len;
        const sx = x1 - ux * overshoot + (rng() - 0.5) * endJit;
        const sy = y1 - uy * overshoot + (rng() - 0.5) * endJit;
        const ex = x2 + ux * overshoot + (rng() - 0.5) * endJit;
        const ey = y2 + uy * overshoot + (rng() - 0.5) * endJit;
        const bow1 = sign * bowMag * (0.75 + rng() * 0.5);
        const bow2 = (isCartoon && pass === 2 ? -sign : sign) * bowMag * (0.65 + rng() * 0.5);
        const cp1x = x1 + dx * 0.33 + nx * bow1;
        const cp1y = y1 + dy * 0.33 + ny * bow1;
        const cp2x = x1 + dx * 0.67 + nx * bow2;
        const cp2y = y1 + dy * 0.67 + ny * bow2;
        path.moveTo(sx, sy);
        path.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, ex, ey);
      }
    }

    function buildCleanRoundRectPath(path, x, y, w, h, r) {
      const cr = Math.max(0, Math.min(r, w / 2, h / 2));
      path.moveTo(x + cr, y);
      path.lineTo(x + w - cr, y);
      path.quadraticCurveTo(x + w, y, x + w, y + cr);
      path.lineTo(x + w, y + h - cr);
      path.quadraticCurveTo(x + w, y + h, x + w - cr, y + h);
      path.lineTo(x + cr, y + h);
      path.quadraticCurveTo(x, y + h, x, y + h - cr);
      path.lineTo(x, y + cr);
      path.quadraticCurveTo(x, y, x + cr, y);
      path.closePath();
    }

    function roughRoundRect(path, x, y, w, h, r, rng, roughness = 0.85) {
      const cr = Math.max(0, Math.min(r, w / 4, h / 4));
      if (!roughness || roughness <= 0.001) {
        buildCleanRoundRectPath(path, x, y, w, h, cr);
        return;
      }
      const isCartoon = roughness > 1.2;
      const passes = isCartoon ? 3 : 2;
      for (let p = 0; p < passes; p++) {
        const sign = p === 0 ? 1 : (p === 1 ? -0.95 : 0.6);
        const jit = isCartoon ? 4.5 : 1.6 * roughness;
        const bow = (isCartoon ? 9.5 : 3.8 * roughness) * sign;
        const j = () => (rng() - 0.5) * jit;
        const b = () => bow * (0.75 + rng() * 0.5);

        const t1x = x + cr + j(), t1y = y + j();
        const t2x = x + w - cr + j(), t2y = y + j();
        const r1x = x + w + j(), r1y = y + cr + j();
        const r2x = x + w + j(), r2y = y + h - cr + j();
        const b1x = x + w - cr + j(), b1y = y + h + j();
        const b2x = x + cr + j(), b2y = y + h + j();
        const l1x = x + j(), l1y = y + h - cr + j();
        const l2x = x + j(), l2y = y + cr + j();

        path.moveTo(t1x, t1y);
        path.quadraticCurveTo((t1x + t2x) / 2 + j(), (t1y + t2y) / 2 - b(), t2x, t2y);
        path.quadraticCurveTo(x + w + j(), y + j(), r1x, r1y);
        path.quadraticCurveTo((r1x + r2x) / 2 + b(), (r1y + r2y) / 2 + j(), r2x, r2y);
        path.quadraticCurveTo(x + w + j(), y + h + j(), b1x, b1y);
        path.quadraticCurveTo((b1x + b2x) / 2 + j(), (b1y + b2y) / 2 + b(), b2x, b2y);
        path.quadraticCurveTo(x + j(), y + h + j(), l1x, l1y);
        path.quadraticCurveTo((l1x + l2x) / 2 - b(), (l1y + l2y) / 2 + j(), l2x, l2y);
        path.quadraticCurveTo(x + j(), y + j(), t1x, t1y);
      }
    }

    function roughEllipse(path, cx, cy, rx, ry, rng, roughness = 0.85) {
      if (!roughness || roughness <= 0.001) {
        path.ellipse(cx, cy, Math.max(1, rx), Math.max(1, ry), 0, 0, Math.PI * 2);
        return;
      }
      const isCartoon = roughness > 1.2;
      const steps = 16;
      const passes = isCartoon ? 3 : 2;
      for (let pass = 0; pass < passes; pass++) {
        const sign = pass === 0 ? 1 : (pass === 1 ? -1 : 0.65);
        const waveAmp = isCartoon ? 5.8 : 2.4 * roughness;
        const jitAmp = isCartoon ? 3.6 : 1.2 * roughness;
        const phase = rng() * Math.PI * 2 + pass * 1.7;
        const cxShift = sign * (isCartoon ? 2.4 : 0.9 * roughness);
        const cyShift = -sign * (isCartoon ? 2.0 : 0.8 * roughness);
        const pts = [];
        for (let i = 0; i < steps; i++) {
          const theta = (i / steps) * Math.PI * 2;
          const radialWave = Math.sin(theta * 2 + phase) * waveAmp * sign;
          const curRx = Math.max(2, rx + radialWave);
          const curRy = Math.max(2, ry - radialWave * 0.75);
          const px = cx + cxShift + Math.cos(theta) * curRx + (rng() - 0.5) * jitAmp;
          const py = cy + cyShift + Math.sin(theta) * curRy + (rng() - 0.5) * jitAmp;
          pts.push([px, py]);
        }
        const firstMidX = (pts[steps - 1][0] + pts[0][0]) / 2;
        const firstMidY = (pts[steps - 1][1] + pts[0][1]) / 2;
        path.moveTo(firstMidX, firstMidY);
        const totalSteps = isCartoon && pass === 0 ? steps + 1 : steps;
        for (let i = 0; i < totalSteps; i++) {
          const curr = pts[i % steps];
          const next = pts[(i + 1) % steps];
          const midX = (curr[0] + next[0]) / 2;
          const midY = (curr[1] + next[1]) / 2;
          path.quadraticCurveTo(curr[0], curr[1], midX, midY);
        }
      }
    }

    const ShapeCache = {
      cache: new Map(),

      keyFor(el) {
        return [
          el.id,
          el.type,
          Math.round(el.x * 10) / 10,
          Math.round(el.y * 10) / 10,
          Math.round((el.width || 0) * 10) / 10,
          Math.round((el.height || 0) * 10) / 10,
          el.seed || 1,
          el.versionNonce || 1,
          el.roughness ?? 0.85,
          el.fillStyle || 'hachure',
          el.strokeWidth || 2.2
        ].join('|');
      },

      generate(el) {
        const rng = mulberry32((Number(el.seed) || 1) ^ (Number(el.versionNonce) || 1));
        const fillPath = new Path2D();
        const strokePath = new Path2D();
        const hachurePath = new Path2D();

        const x = Number(el.x) || 0;
        const y = Number(el.y) || 0;
        const w = Math.max(2, Number(el.width) || 0);
        const h = Math.max(2, Number(el.height) || 0);
        const cx = x + w / 2;
        const cy = y + h / 2;
        const roughness = el.roughness ?? 0.85;

        if (el.type === 'ellipse') {
          const rx = Math.max(1, w / 2);
          const ry = Math.max(1, h / 2);
          fillPath.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);
          roughEllipse(strokePath, cx, cy, rx, ry, rng, roughness);
        } else if (el.type === 'diamond') {
          const top = [cx, y];
          const right = [x + w, cy];
          const bottom = [cx, y + h];
          const left = [x, cy];
          fillPath.moveTo(top[0], top[1]);
          fillPath.lineTo(right[0], right[1]);
          fillPath.lineTo(bottom[0], bottom[1]);
          fillPath.lineTo(left[0], left[1]);
          fillPath.closePath();

          roughEdge(strokePath, top[0], top[1], right[0], right[1], rng, roughness);
          roughEdge(strokePath, right[0], right[1], bottom[0], bottom[1], rng, roughness);
          roughEdge(strokePath, bottom[0], bottom[1], left[0], left[1], rng, roughness);
          roughEdge(strokePath, left[0], left[1], top[0], top[1], rng, roughness);
        } else if (el.type === 'rectangle' || el.type === 'sticky') {
          const r = el.type === 'sticky' ? 4 : Math.min(14, w / 4, h / 4);
          buildCleanRoundRectPath(fillPath, x, y, w, h, r);
          roughRoundRect(strokePath, x, y, w, h, r, rng, el.type === 'sticky' ? roughness * 0.65 : roughness);
        }

        const fillStyle = el.fillStyle || 'hachure';
        if ((fillStyle === 'hachure' || fillStyle === 'cross-hatch') &&
            (el.type === 'rectangle' || el.type === 'ellipse' || el.type === 'diamond' || el.type === 'sticky')) {
          const isCartoon = roughness > 1.2;
          const spacing = roughness <= 0.001 ? 8.0 : (isCartoon ? 11.0 : 8.5);
          const inset = Math.max(2.2, (Number(el.strokeWidth) || 2) * 0.9);
          const diag = w + h;
          const hatchBow = roughness <= 0.001 ? 0 : (isCartoon ? 12.0 : roughness * 4.5);

          const addClippedHatchSegment = (rawX1, rawY1, rawX2, rawY2) => {
            const clipped = clipSegmentToShape(el, rawX1, rawY1, rawX2, rawY2, inset);
            if (!clipped) return;
            const [cx1, cy1, cx2, cy2] = clipped;
            if (Math.hypot(cx2 - cx1, cy2 - cy1) <= 1.5) return;
            if (hatchBow <= 0.001) {
              hachurePath.moveTo(cx1, cy1);
              hachurePath.lineTo(cx2, cy2);
              return;
            }
            const sign = rng() > 0.5 ? 1 : -1;
            const rawMx = (cx1 + cx2) / 2 + sign * hatchBow * (0.6 + rng() * 0.4);
            const rawMy = (cy1 + cy2) / 2 - sign * hatchBow * (0.6 + rng() * 0.4);
            const [mx, my] = clampPointToShapeInterior(el, rawMx, rawMy, inset);
            hachurePath.moveTo(cx1, cy1);
            hachurePath.quadraticCurveTo(mx, my, cx2, cy2);
          };

          for (let d = -diag; d <= diag; d += spacing) {
            const jStep = isCartoon ? (rng() - 0.5) * 3.5 : 0;
            addClippedHatchSegment(x + d + jStep, y + h, x + d + h + jStep, y);
          }

          if (fillStyle === 'cross-hatch') {
            for (let d = -diag; d <= diag; d += spacing * 1.05) {
              const jStep = isCartoon ? (rng() - 0.5) * 3.5 : 0;
              addClippedHatchSegment(x + d + jStep, y, x + d + h + jStep, y + h);
            }
          }
        }

        return { fillPath, strokePath, hachurePath };
      },

      get(el) {
        const key = this.keyFor(el);
        let entry = this.cache.get(el.id);
        if (!entry || entry.key !== key) {
          const paths = this.generate(el);
          entry = { key, paths };
          this.cache.set(el.id, entry);
        }
        return entry.paths;
      },

      invalidate(el) {
        if (!el) return;
        const id = typeof el === 'string' ? el : el.id;
        if (typeof el === 'object' && el !== null) {
          el.versionNonce = (Number(el.versionNonce) || 1) + 1;
        }
        this.cache.delete(id);
      },

      clear() {
        this.cache.clear();
      }
    };

    /* -------------------------------------------------------------------------
     * 4. Perimeter Sliding (focusAngle) & Arrow Geometry Engine
     * ------------------------------------------------------------------------- */
    function isNodeElement(el) {
      return el && (el.type === 'rectangle' || el.type === 'ellipse' || el.type === 'diamond' || el.type === 'sticky' || el.type === 'text');
    }

    function angleToSide(angle) {
      if (typeof angle !== 'number' || Number.isNaN(angle)) return 'right';
      const deg = (angle * 180) / Math.PI;
      if (deg >= -45 && deg <= 45) return 'right';
      if (deg > 45 && deg < 135) return 'bottom';
      if (deg >= -135 && deg < -45) return 'top';
      return 'left';
    }

    function computeBindingForShape(shape, worldPt) {
      if (!shape || !worldPt) return null;
      const cx = shape.x + shape.width / 2;
      const cy = shape.y + shape.height / 2;
      const dx = worldPt.x - cx;
      const dy = worldPt.y - cy;
      const rx = Math.max(1, shape.width / 2);
      const ry = Math.max(1, shape.height / 2);
      const normDist = Math.hypot(dx / rx, dy / ry);

      let focusAngle = null;
      if (normDist >= 0.35 || (Math.abs(dx) > 0.001 || Math.abs(dy) > 0.001)) {
        focusAngle = Math.atan2(dy, dx);
      }
      const coreCenter = normDist < 0.35;
      return {
        elementId: shape.id,
        focusAngle,
        coreCenter,
        side: angleToSide(focusAngle ?? 0),
        gap: 4
      };
    }

    function getBindingBoundaryPoint(shape, binding, fallbackRefPt, gap = 4) {
      if (!shape) return fallbackRefPt || { x: 0, y: 0 };
      const cx = shape.x + shape.width / 2;
      const cy = shape.y + shape.height / 2;

      let theta = 0;
      if (binding && typeof binding.focusAngle === 'number' && !Number.isNaN(binding.focusAngle) && !binding.coreCenter) {
        theta = binding.focusAngle;
      } else if (fallbackRefPt && (Math.abs(fallbackRefPt.x - cx) > 0.01 || Math.abs(fallbackRefPt.y - cy) > 0.01)) {
        theta = Math.atan2(fallbackRefPt.y - cy, fallbackRefPt.x - cx);
      } else if (binding && typeof binding.focusAngle === 'number') {
        theta = binding.focusAngle;
      }

      const ux = Math.cos(theta);
      const uy = Math.sin(theta);
      const g = (binding && typeof binding.gap === 'number') ? binding.gap : (Number(gap) || 0);
      const hw = Math.max(1, shape.width / 2 + g);
      const hh = Math.max(1, shape.height / 2 + g);

      if (shape.type === 'ellipse') {
        const denom = Math.hypot(ux / hw, uy / hh) || 1;
        const t = 1 / denom;
        return { x: cx + t * ux, y: cy + t * uy, angle: theta };
      }

      if (shape.type === 'diamond') {
        const denom = (Math.abs(ux) / hw + Math.abs(uy) / hh) || 1;
        const t = 1 / denom;
        return { x: cx + t * ux, y: cy + t * uy, angle: theta };
      }

      const tx = Math.abs(ux) > 1e-9 ? hw / Math.abs(ux) : Infinity;
      const ty = Math.abs(uy) > 1e-9 ? hh / Math.abs(uy) : Infinity;
      const t = Math.min(tx, ty);
      return { x: cx + t * ux, y: cy + t * uy, angle: theta };
    }

    function distanceToShapeBoundary(shape, wx, wy) {
      if (!shape) return Infinity;
      const cx = shape.x + shape.width / 2;
      const cy = shape.y + shape.height / 2;
      const hw = Math.max(1, shape.width / 2);
      const hh = Math.max(1, shape.height / 2);
      const dx = wx - cx;
      const dy = wy - cy;

      if (shape.type === 'ellipse') {
        const norm = Math.hypot(dx / hw, dy / hh);
        if (norm <= 1) return 0;
        const theta = Math.atan2(dy, dx);
        const bx = cx + Math.cos(theta) * hw;
        const by = cy + Math.sin(theta) * hh;
        return Math.hypot(wx - bx, wy - by);
      }

      if (shape.type === 'diamond') {
        const l1 = Math.abs(dx) / hw + Math.abs(dy) / hh;
        if (l1 <= 1) return 0;
        const pt = getBindingBoundaryPoint(shape, { focusAngle: Math.atan2(dy, dx), gap: 0 }, null, 0);
        return Math.hypot(wx - pt.x, wy - pt.y);
      }

      const clampedX = Math.max(shape.x, Math.min(shape.x + shape.width, wx));
      const clampedY = Math.max(shape.y, Math.min(shape.y + shape.height, wy));
      return Math.hypot(wx - clampedX, wy - clampedY);
    }

    function findMagneticShape(wx, wy, excludeId = null) {
      const snapRadius = 42 / (state.zoom || 1);
      let bestShape = null;
      let bestScore = Infinity;

      for (let i = state.elements.length - 1; i >= 0; i--) {
        const el = state.elements[i];
        if (!isNodeElement(el) || el.id === excludeId) continue;
        const d = distanceToShapeBoundary(el, wx, wy);
        if (d <= snapRadius && d < bestScore) {
          bestScore = d;
          bestShape = el;
        }
      }
      return bestShape;
    }

    function getElementMap(elements = state.elements) {
      const map = new Map();
      for (const el of elements) map.set(el.id, el);
      return map;
    }

    function getArrowGeometry(el, elementsMap = null) {
      const map = elementsMap || getElementMap();
      const startShape = el.startBinding?.elementId ? map.get(el.startBinding.elementId) : null;
      const endShape = el.endBinding?.elementId ? map.get(el.endBinding.elementId) : null;

      let rawP0 = { x: Number(el.x) || 0, y: Number(el.y) || 0 };
      let rawP1 = {
        x: typeof el.x2 === 'number' ? el.x2 : (rawP0.x + (Number(el.width) || 120)),
        y: typeof el.y2 === 'number' ? el.y2 : (rawP0.y + (Number(el.height) || 0))
      };

      const startCenter = startShape
        ? { x: startShape.x + startShape.width / 2, y: startShape.y + startShape.height / 2 }
        : rawP0;
      const endCenter = endShape
        ? { x: endShape.x + endShape.width / 2, y: endShape.y + endShape.height / 2 }
        : rawP1;

      if (startShape && el.startBinding && typeof el.startBinding.focusAngle === 'number') {
        const natAng = Math.atan2(endCenter.y - startCenter.y, endCenter.x - startCenter.x);
        const diff = Math.abs(Math.atan2(Math.sin(natAng - el.startBinding.focusAngle), Math.cos(natAng - el.startBinding.focusAngle)));
        if (diff > Math.PI * 0.55) {
          el.startBinding.focusAngle = natAng;
          el.startBinding.side = angleToSide(natAng);
        }
      }
      if (endShape && el.endBinding && typeof el.endBinding.focusAngle === 'number') {
        const natAng = Math.atan2(startCenter.y - endCenter.y, startCenter.x - endCenter.x);
        const diff = Math.abs(Math.atan2(Math.sin(natAng - el.endBinding.focusAngle), Math.cos(natAng - el.endBinding.focusAngle)));
        if (diff > Math.PI * 0.55) {
          el.endBinding.focusAngle = natAng;
          el.endBinding.side = angleToSide(natAng);
        }
      }

      let p0 = startShape
        ? getBindingBoundaryPoint(startShape, el.startBinding, endShape ? endCenter : rawP1, 4)
        : rawP0;
      let p1 = endShape
        ? getBindingBoundaryPoint(endShape, el.endBinding, startShape ? startCenter : p0, 4)
        : rawP1;

      const curveType = el.curveType || 'curved';
      const curveOffset = curveType === 'straight' ? 0 : (Number(el.curveOffset) || 0);

      const N = 40;
      const samples = [];
      const cumLenArr = [0];
      let totalLen = 0;
      let waypoints = [p0, p1];
      let elbowAxis = 'x';

      if (curveType === 'elbow') {
        const dx = endCenter.x - startCenter.x;
        const dy = endCenter.y - startCenter.y;
        const shw = startShape ? startShape.width / 2 + 4 : 0;
        const shh = startShape ? startShape.height / 2 + 4 : 0;
        const ehw = endShape ? endShape.width / 2 + 4 : 0;
        const ehh = endShape ? endShape.height / 2 + 4 : 0;

        const normDx = Math.abs(dx) / Math.max(40, shw + ehw);
        const normDy = Math.abs(dy) / Math.max(40, shh + ehh);
        const verticalFirst = normDy > normDx * 1.15;

        const p0H = startShape
          ? getBindingBoundaryPoint(startShape, { focusAngle: dx >= 0 ? 0 : Math.PI, gap: 4 }, endCenter, 4)
          : rawP0;
        const p0V = startShape
          ? getBindingBoundaryPoint(startShape, { focusAngle: dy >= 0 ? Math.PI / 2 : -Math.PI / 2, gap: 4 }, endCenter, 4)
          : rawP0;
        var elbowBaseMid = { x: (p0H.x + p1.x) / 2, y: (p0V.y + p1.y) / 2 };

        let rawWaypoints;
        let handlePt;
        if (verticalFirst) {
          elbowAxis = 'y';
          p0 = p0V;
          const midY0 = (p0.y + p1.y) / 2;
          const rawElbowY = midY0 + curveOffset * 0.5;
          const goesIntoStart = startShape && (dy >= 0 ? rawElbowY < p0.y + 8 : rawElbowY > p0.y - 8);

          if (goesIntoStart && Math.abs(p1.x - p0H.x) > 12) {
            p0 = p0H;
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: p1.x, y: p0.y },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: (p0.x + p1.x) / 2, y: p0.y };
          } else if (Math.abs(rawElbowY - p1.y) < 16 && Math.abs(p1.x - p0.x) > 14) {
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: p0.x, y: p1.y },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: p0.x, y: p1.y };
          } else {
            let elbowY = rawElbowY;
            if (startShape) {
              elbowY = dy >= 0 ? Math.max(p0.y + 12, elbowY) : Math.min(p0.y - 12, elbowY);
            }
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: p0.x, y: elbowY },
              { x: p1.x, y: elbowY },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: (p0.x + p1.x) / 2, y: elbowY };
          }
        } else {
          elbowAxis = 'x';
          p0 = p0H;
          const midX0 = (p0.x + p1.x) / 2;
          const rawElbowX = midX0 + curveOffset * 0.5;
          const goesIntoStart = startShape && (dx >= 0 ? rawElbowX < p0.x + 8 : rawElbowX > p0.x - 8);

          if (goesIntoStart && Math.abs(p1.y - p0V.y) > 12) {
            p0 = p0V;
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: p0.x, y: p1.y },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: p0.x, y: (p0.y + p1.y) / 2 };
          } else if (Math.abs(rawElbowX - p1.x) < 16 && Math.abs(p1.y - p0.y) > 14) {
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: p1.x, y: p0.y },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: p1.x, y: (p0.y + p1.y) / 2 };
          } else {
            let elbowX = rawElbowX;
            if (startShape) {
              elbowX = dx >= 0 ? Math.max(p0.x + 12, elbowX) : Math.min(p0.x - 12, elbowX);
            }
            rawWaypoints = [
              { x: p0.x, y: p0.y },
              { x: elbowX, y: p0.y },
              { x: elbowX, y: p1.y },
              { x: p1.x, y: p1.y }
            ];
            handlePt = { x: elbowX, y: (p0.y + p1.y) / 2 };
          }
        }

        el.x = p0.x;
        el.y = p0.y;
        el.x2 = p1.x;
        el.y2 = p1.y;
        el.width = p1.x - p0.x;
        el.height = p1.y - p0.y;

        waypoints = [rawWaypoints[0]];
        for (let i = 1; i < rawWaypoints.length; i++) {
          const prev = waypoints[waypoints.length - 1];
          const curr = rawWaypoints[i];
          if (Math.hypot(curr.x - prev.x, curr.y - prev.y) > 0.5) {
            waypoints.push(curr);
          }
        }
        if (waypoints.length < 2) {
          waypoints = [{ x: p0.x, y: p0.y }, { x: p1.x, y: p1.y }];
        } else {
          waypoints[waypoints.length - 1] = { x: p1.x, y: p1.y };
        }
        var elbowHandleOverride = handlePt;
      }

      el.x = p0.x;
      el.y = p0.y;
      el.x2 = p1.x;
      el.y2 = p1.y;
      el.width = p1.x - p0.x;
      el.height = p1.y - p0.y;

      const chordDx = p1.x - p0.x;
      const chordDy = p1.y - p0.y;
      const chordLen = Math.hypot(chordDx, chordDy) || 1;
      const nx = -chordDy / chordLen;
      const ny = chordDx / chordLen;
      const midX = (p0.x + p1.x) / 2;
      const midY = (p0.y + p1.y) / 2;
      let tipAngle = Math.atan2(chordDy, chordDx);

      const cp = {
        x: midX + nx * curveOffset,
        y: midY + ny * curveOffset
      };
      const curveHandlePt = curveType === 'elbow' && elbowHandleOverride
        ? elbowHandleOverride
        : {
            x: midX + nx * (curveOffset * 0.5),
            y: midY + ny * (curveOffset * 0.5)
          };

      if (curveType === 'elbow') {

        const segs = [];
        let polyLen = 0;
        for (let i = 0; i < waypoints.length - 1; i++) {
          const a = waypoints[i];
          const b = waypoints[i + 1];
          const sl = Math.hypot(b.x - a.x, b.y - a.y);
          if (sl > 1e-6) {
            segs.push({ a, b, sl, tx: (b.x - a.x) / sl, ty: (b.y - a.y) / sl });
            polyLen += sl;
          }
        }

        if (segs.length === 0) {
          const tx = chordDx / chordLen;
          const ty = chordDy / chordLen;
          samples.push({ x: p0.x, y: p0.y, tx, ty });
          samples.push({ x: p1.x, y: p1.y, tx, ty });
          cumLenArr.push(chordLen);
          totalLen = chordLen;
          tipAngle = Math.atan2(ty, tx);
        } else {
          for (let s = 0; s < segs.length; s++) {
            const seg = segs[s];
            const steps = Math.max(2, Math.round((seg.sl / Math.max(1, polyLen)) * N));
            const startStep = s === 0 ? 0 : 1;
            for (let k = startStep; k <= steps; k++) {
              const localT = k / steps;
              const pt = {
                x: seg.a.x + (seg.b.x - seg.a.x) * localT,
                y: seg.a.y + (seg.b.y - seg.a.y) * localT,
                tx: seg.tx,
                ty: seg.ty
              };
              if (samples.length > 0) {
                const prev = samples[samples.length - 1];
                totalLen += Math.hypot(pt.x - prev.x, pt.y - prev.y);
                cumLenArr.push(totalLen);
              }
              samples.push(pt);
            }
          }
          const lastSeg = segs[segs.length - 1];
          tipAngle = Math.atan2(lastSeg.ty, lastSeg.tx);
        }
      } else {
        for (let i = 0; i <= N; i++) {
          const t = i / N;
          const mt = 1 - t;
          const x = mt * mt * p0.x + 2 * mt * t * cp.x + t * t * p1.x;
          const y = mt * mt * p0.y + 2 * mt * t * cp.y + t * t * p1.y;
          const dxdt = 2 * mt * (cp.x - p0.x) + 2 * t * (p1.x - cp.x);
          const dydt = 2 * mt * (cp.y - p0.y) + 2 * t * (p1.y - cp.y);
          const dLen = Math.hypot(dxdt, dydt) || 1;
          const pt = { x, y, tx: dxdt / dLen, ty: dydt / dLen };
          if (i > 0) {
            totalLen += Math.hypot(x - samples[i - 1].x, y - samples[i - 1].y);
            cumLenArr.push(totalLen);
          }
          samples.push(pt);
        }
        const endSample = samples[samples.length - 1];
        tipAngle = Math.atan2(endSample.ty, endSample.tx);
      }

      const cumLen = Float64Array.from(cumLenArr);
      const midDist = totalLen * 0.5;
      const labelPt = pointAtArcLength({ samples, cumLen, totalLen }, midDist);

      // Arrows are always unbroken and clean — no text or gaps cut in between them
      return {
        p0,
        p1,
        cp,
        curveHandlePt,
        waypoints,
        elbowAxis,
        elbowBaseMid: elbowBaseMid || { x: midX, y: midY },
        tipAngle,
        samples,
        cumLen,
        totalLen: Math.max(1, totalLen),
        labelPt,
        labelBox: null,
        gapStartDist: -1,
        gapEndDist: -1
      };
    }

    function pointAtArcLength(geom, dist) {
      const samples = geom.samples;
      const cumLen = geom.cumLen;
      const N = samples.length - 1;
      if (N <= 0) return { x: 0, y: 0, tx: 1, ty: 0 };
      const clamped = Math.max(0, Math.min(geom.totalLen, dist));
      let lo = 0;
      let hi = N;
      while (lo < hi) {
        const mid = (lo + hi) >> 1;
        if (cumLen[mid] < clamped) lo = mid + 1;
        else hi = mid;
      }
      const idx = Math.max(1, lo);
      const d0 = cumLen[idx - 1];
      const d1 = cumLen[idx];
      const seg = d1 - d0;
      const f = seg > 1e-6 ? (clamped - d0) / seg : 0;
      const a = samples[idx - 1];
      const b = samples[idx];
      return {
        x: a.x + (b.x - a.x) * f,
        y: a.y + (b.y - a.y) * f,
        tx: a.tx + (b.tx - a.tx) * f,
        ty: a.ty + (b.ty - a.ty) * f
      };
    }

    /* -------------------------------------------------------------------------
     * 5. Causal Topological Wave Timing (BFS computeGraphDepths) & Node Pulses
     * ------------------------------------------------------------------------- */
    function computeGraphDepths(elements = state.elements) {
      const nodeDepths = new Map();
      const arrowDepths = new Map();
      const adj = new Map();
      const inDeg = new Map();

      const nodes = elements.filter(isNodeElement);
      const arrows = elements.filter(e => e.type === 'arrow');

      for (const n of nodes) {
        adj.set(n.id, []);
        inDeg.set(n.id, 0);
      }

      for (const arr of arrows) {
        const u = arr.startBinding?.elementId;
        const v = arr.endBinding?.elementId;
        if (u && v && adj.has(u) && adj.has(v)) {
          adj.get(u).push({ target: v, arrowId: arr.id });
          inDeg.set(v, (inDeg.get(v) || 0) + 1);
        }
      }

      const queue = [];
      for (const n of nodes) {
        if ((inDeg.get(n.id) || 0) === 0) {
          nodeDepths.set(n.id, 0);
          queue.push(n.id);
        }
      }

      if (queue.length === 0 && nodes.length > 0) {
        nodeDepths.set(nodes[0].id, 0);
        queue.push(nodes[0].id);
      }

      let head = 0;
      while (head < queue.length) {
        const u = queue[head++];
        const d = nodeDepths.get(u) || 0;
        const edges = adj.get(u) || [];
        for (const edge of edges) {
          arrowDepths.set(edge.arrowId, d);
          if (!nodeDepths.has(edge.target)) {
            nodeDepths.set(edge.target, d + 1);
            queue.push(edge.target);
          }
        }
      }

      for (const n of nodes) {
        if (!nodeDepths.has(n.id)) nodeDepths.set(n.id, 0);
      }
      for (const arr of arrows) {
        if (!arrowDepths.has(arr.id)) {
          const u = arr.startBinding?.elementId;
          arrowDepths.set(arr.id, u && nodeDepths.has(u) ? nodeDepths.get(u) : 0);
        }
      }

      return { nodeDepths, arrowDepths };
    }

    function triggerNodePulse(nodeId) {
      const targetIds = nodeId ? [nodeId] : Array.from(state.selectedIds);
      let spawned = 0;
      const now = performance.now() / 1000;

      for (const id of targetIds) {
        const outgoing = state.elements.filter(
          el => el.type === 'arrow' && el.startBinding?.elementId === id
        );
        const targetArrows = outgoing.length > 0
          ? outgoing
          : state.elements.filter(el => el.type === 'arrow' && el.id === id);

        for (const arr of targetArrows) {
          for (let b = 0; b < 3; b++) {
            state.activePulses.push({
              id: nextId('pulse'),
              arrowId: arr.id,
              progress: -b * 0.14,
              speed: 1.35,
              color: arr.strokeColor || '#0070f3',
              createdAt: now
            });
            spawned++;
          }
        }
      }
      return spawned;
    }

    /* -------------------------------------------------------------------------
     * 6. Multi-Pass Occlusion-Free Rendering Engine
     * ------------------------------------------------------------------------- */
    // Exact Excalidraw dash array formulas from packages/element/src/shape.ts
    function applyDashStyle(ctx, strokeStyle, strokeWidth) {
      const sw = Number(strokeWidth) || 2;
      if (strokeStyle === 'dashed') {
        ctx.setLineDash([8, 8 + sw]);
      } else if (strokeStyle === 'dotted') {
        ctx.setLineDash([1.5, 6 + sw]);
      } else {
        ctx.setLineDash([]);
      }
    }

    function drawStaticElement(ctx, el, opts = {}) {
      if (!el || el.type === 'arrow') return;
      const canvasBg = opts.canvasBg || state.canvasBg;
      const strokeColor = resolveStrokeColor(el.strokeColor, canvasBg);
      const fillTint = resolveFillTint(el.strokeColor, canvasBg, el.type === 'sticky');
      const sw = Number(el.strokeWidth) || 2.2;

      ctx.save();
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';

      const auraEnergy = state.nodeArrivalEnergy.get(el.id) || 0;
      if (auraEnergy > 0.02 && isNodeElement(el) && el.type !== 'text') {
        ctx.save();
        ctx.shadowColor = strokeColor;
        ctx.shadowBlur = 16 * auraEnergy;
        ctx.strokeStyle = strokeColor;
        ctx.globalAlpha = Math.min(0.45, auraEnergy * 0.45);
        ctx.lineWidth = sw + 2;
        const paths = ShapeCache.get(el);
        ctx.stroke(paths.fillPath);
        ctx.restore();
      }

      if (el.type === 'freedraw') {
        const pts = el.points || [];
        if (pts.length > 0) {
          ctx.strokeStyle = strokeColor;
          ctx.lineWidth = sw;
          applyDashStyle(ctx, el.strokeStyle, sw);
          ctx.beginPath();
          ctx.moveTo(el.x + pts[0][0], el.y + pts[0][1]);
          for (let i = 1; i < pts.length; i++) {
            const pPrev = pts[i - 1];
            const pCurr = pts[i];
            const mx = el.x + (pPrev[0] + pCurr[0]) / 2;
            const my = el.y + (pPrev[1] + pCurr[1]) / 2;
            ctx.quadraticCurveTo(el.x + pPrev[0], el.y + pPrev[1], mx, my);
          }
          const last = pts[pts.length - 1];
          ctx.lineTo(el.x + last[0], el.y + last[1]);
          ctx.stroke();
        }
        ctx.restore();
        return;
      }

      if (el.type === 'text') {
        ctx.restore();
        return;
      }

      const paths = ShapeCache.get(el);
      const fillStyle = el.fillStyle || 'hachure';

      if (fillStyle !== 'none') {
        ctx.save();
        ctx.fillStyle = fillTint;
        if (el.type === 'sticky') {
          ctx.shadowColor = 'rgba(0, 0, 0, 0.14)';
          ctx.shadowBlur = 12;
          ctx.shadowOffsetY = 4;
        }
        ctx.fill(paths.fillPath);
        ctx.restore();
      }

      if (fillStyle === 'hachure' || fillStyle === 'cross-hatch') {
        ctx.save();
        ctx.clip(paths.fillPath);
        ctx.strokeStyle = strokeColor;
        ctx.globalAlpha = canvasBg === '#000000' ? 0.44 : 0.36;
        // Excalidraw shape.ts: fillWeight = element.strokeWidth / 2
        ctx.lineWidth = Math.max(1.0, sw * 0.5);
        ctx.setLineDash([]);
        ctx.stroke(paths.hachurePath);
        ctx.restore();
      }

      ctx.strokeStyle = strokeColor;
      // Excalidraw shape.ts: for non-solid strokes, increase width by +0.5
      ctx.lineWidth = (el.strokeStyle && el.strokeStyle !== 'solid') ? sw + 0.5 : sw;
      applyDashStyle(ctx, el.strokeStyle, sw);
      ctx.stroke(paths.strokePath);

      ctx.restore();
    }

    function drawArrowAndParticles(ctx, el, geom, depth, timeSec, opts = {}) {
      const canvasBg = opts.canvasBg || state.canvasBg;
      const isSplitTarget = state.splitTargetArrowId === el.id;
      const strokeColor = isSplitTarget ? '#10b981' : resolveStrokeColor(el.strokeColor, canvasBg);
      const baseSw = Number(el.strokeWidth) || 2.2;
      const sw = isSplitTarget ? Math.max(3.2, baseSw + 1.2) : baseSw;

      ctx.save();
      ctx.lineCap = 'round';
      ctx.lineJoin = 'round';
      ctx.strokeStyle = strokeColor;
      ctx.lineWidth = (el.strokeStyle && el.strokeStyle !== 'solid') ? sw + 0.5 : sw;
      applyDashStyle(ctx, el.strokeStyle, sw);

      if (isSplitTarget) {
        ctx.shadowColor = '#10b981';
        ctx.shadowBlur = 12;
      }

      const curveType = el.curveType || 'curved';
      const roughness = Number(el.roughness ?? 0.85);
      const isCartoon = roughness > 1.2;
      const samples = geom.samples;

      const strokeShaftPass = (offsetX, offsetY, cpBowOffset) => {
        ctx.beginPath();
        if (curveType === 'elbow' && geom.waypoints && geom.waypoints.length >= 2) {
          const pts = geom.waypoints;
          ctx.moveTo(pts[0].x + offsetX * 0.3, pts[0].y + offsetY * 0.3);
          for (let i = 1; i < pts.length - 1; i++) {
            const prev = pts[i - 1];
            const curr = pts[i];
            const next = pts[i + 1];
            const d1 = Math.hypot(curr.x - prev.x, curr.y - prev.y);
            const d2 = Math.hypot(next.x - curr.x, next.y - curr.y);
            const cornerR = Math.min(8, d1 * 0.35, d2 * 0.35);
            const cx = curr.x + offsetX;
            const cy = curr.y + offsetY;
            if (cornerR > 1.5 && typeof ctx.arcTo === 'function') {
              ctx.arcTo(cx, cy, next.x + offsetX, next.y + offsetY, cornerR);
            } else {
              ctx.lineTo(cx, cy);
            }
          }
          const lastPt = pts[pts.length - 1];
          ctx.lineTo(lastPt.x, lastPt.y);
        } else if (curveType === 'straight' || Math.abs(Number(el.curveOffset) || 0) < 0.5) {
          if (Math.abs(cpBowOffset) < 0.05) {
            ctx.moveTo(geom.p0.x, geom.p0.y);
            ctx.lineTo(geom.p1.x, geom.p1.y);
          } else {
            const dx = geom.p1.x - geom.p0.x;
            const dy = geom.p1.y - geom.p0.y;
            const len = Math.hypot(dx, dy) || 1;
            const nx = -dy / len;
            const ny = dx / len;
            const midX = (geom.p0.x + geom.p1.x) / 2 + nx * cpBowOffset;
            const midY = (geom.p0.y + geom.p1.y) / 2 + ny * cpBowOffset;
            ctx.moveTo(geom.p0.x + offsetX * 0.3, geom.p0.y + offsetY * 0.3);
            ctx.quadraticCurveTo(midX, midY, geom.p1.x, geom.p1.y);
          }
        } else {
          const dx = geom.p1.x - geom.p0.x;
          const dy = geom.p1.y - geom.p0.y;
          const len = Math.hypot(dx, dy) || 1;
          const nx = -dy / len;
          const ny = dx / len;
          ctx.moveTo(geom.p0.x + offsetX * 0.3, geom.p0.y + offsetY * 0.3);
          ctx.quadraticCurveTo(
            geom.cp.x + nx * cpBowOffset + offsetX,
            geom.cp.y + ny * cpBowOffset + offsetY,
            geom.p1.x,
            geom.p1.y
          );
        }
        ctx.stroke();
      };

      strokeShaftPass(0, 0, 0);

      if (roughness > 0.01 && (!el.strokeStyle || el.strokeStyle === 'solid')) {
        const rng = mulberry32((Number(el.seed) || 1) + 77);
        const extraPasses = isCartoon ? 2 : 1;
        ctx.save();
        ctx.lineWidth = Math.max(1.2, sw * (isCartoon ? 0.9 : 0.8));
        ctx.globalAlpha = isCartoon ? 0.88 : 0.72;
        for (let p = 0; p < extraPasses; p++) {
          const sign = p === 0 ? 1 : -1;
          const off = (isCartoon ? 3.2 : 1.4) * sign;
          const bow = (isCartoon ? 6.5 : 2.6) * sign * (0.7 + rng() * 0.5);
          strokeShaftPass(off * (rng() - 0.2), -off * (rng() - 0.2), bow);
        }
        ctx.restore();
      }

      // Excalidraw solid arrowhead cap (~25 degree spread)
      ctx.setLineDash([]);
      const endSample = samples[samples.length - 1] || { tx: 1, ty: 0 };
      const tipAngle = typeof geom.tipAngle === 'number'
        ? geom.tipAngle
        : Math.atan2(endSample.ty, endSample.tx);
      const headLen = Math.max(11, sw * 4.6);
      const spread = 0.44;
      ctx.beginPath();
      ctx.moveTo(
        geom.p1.x - headLen * Math.cos(tipAngle - spread),
        geom.p1.y - headLen * Math.sin(tipAngle - spread)
      );
      ctx.lineTo(geom.p1.x, geom.p1.y);
      ctx.lineTo(
        geom.p1.x - headLen * Math.cos(tipAngle + spread),
        geom.p1.y - headLen * Math.sin(tipAngle + spread)
      );
      ctx.stroke();

      if (isCartoon) {
        ctx.save();
        ctx.lineWidth = Math.max(1.2, sw * 0.85);
        ctx.globalAlpha = 0.82;
        ctx.beginPath();
        ctx.moveTo(
          geom.p1.x - (headLen + 2.5) * Math.cos(tipAngle - spread - 0.08),
          geom.p1.y - (headLen + 2.5) * Math.sin(tipAngle - spread - 0.08)
        );
        ctx.lineTo(geom.p1.x + 1.5, geom.p1.y - 1.5);
        ctx.lineTo(
          geom.p1.x - (headLen + 2.5) * Math.cos(tipAngle + spread + 0.08),
          geom.p1.y - (headLen + 2.5) * Math.sin(tipAngle + spread + 0.08)
        );
        ctx.stroke();
        ctx.restore();
      }

      const arrowFlowActive = state.flowEnabled && (el.flowEnabled !== false);
      if (arrowFlowActive && geom.totalLen > 24) {
        const packetCount = Math.max(1, Math.min(4, Math.round(geom.totalLen / 150)));
        const speed = (Number(state.flowSpeed) || 1.0) * 0.55;
        const hopOffset = -(Number(depth) || 0) * 0.38;
        const mode = state.flowMode || 'comets';

        for (let k = 0; k < packetCount; k++) {
          let phase = (timeSec * speed + hopOffset + k / packetCount) % 1;
          if (phase < 0) phase += 1;

          if (phase > 0.82 && el.endBinding?.elementId) {
            const boost = (phase - 0.82) / 0.18;
            const prev = state.nodeArrivalEnergy.get(el.endBinding.elementId) || 0;
            state.nodeArrivalEnergy.set(el.endBinding.elementId, Math.max(prev, Math.sin(boost * Math.PI)));
          }

          const dist = phase * geom.totalLen;
          drawFlowParticleAt(ctx, geom, dist, phase, strokeColor, sw, mode, canvasBg);
        }
      }

      for (let i = state.activePulses.length - 1; i >= 0; i--) {
        const pulse = state.activePulses[i];
        if (pulse.arrowId !== el.id) continue;
        if (pulse.progress >= 0 && pulse.progress <= 1) {
          const dist = pulse.progress * geom.totalLen;
          drawFlowParticleAt(ctx, geom, dist, pulse.progress, strokeColor, sw * 1.45, 'neon', canvasBg, true);
          if (pulse.progress > 0.8 && el.endBinding?.elementId) {
            state.nodeArrivalEnergy.set(el.endBinding.elementId, 1.0);
          }
        }
      }

      ctx.restore();
    }

    function drawFlowParticleAt(ctx, geom, dist, phase, color, sw, mode, canvasBg, isBurst = false) {
      const pt = pointAtArcLength(geom, dist);
      const isDark = canvasBg === '#000000';
      const coreColor = isDark || isBurst ? '#ffffff' : color;

      ctx.save();
      if (mode === 'comets') {
        const tailLen = Math.min(34, geom.totalLen * 0.22);
        const segs = 7;
        for (let s = 0; s < segs; s++) {
          const d0 = Math.max(0, dist - (s / segs) * tailLen);
          const d1 = Math.max(0, dist - ((s + 1) / segs) * tailLen);
          if (d0 <= d1) continue;
          const pA = pointAtArcLength(geom, d0);
          const pB = pointAtArcLength(geom, d1);
          const frac = 1 - s / segs;
          ctx.beginPath();
          ctx.strokeStyle = color;
          ctx.globalAlpha = frac * (isDark ? 0.92 : 0.82);
          ctx.lineWidth = Math.max(1.2, sw * 2.1 * frac);
          ctx.moveTo(pA.x, pA.y);
          ctx.lineTo(pB.x, pB.y);
          ctx.stroke();
        }
        ctx.beginPath();
        ctx.shadowColor = color;
        ctx.shadowBlur = isDark ? 14 : 8;
        ctx.fillStyle = coreColor;
        ctx.arc(pt.x, pt.y, Math.max(2.8, sw * 1.35), 0, Math.PI * 2);
        ctx.fill();
      } else if (mode === 'pulses') {
        const ringExpand = (phase * 4) % 1;
        ctx.beginPath();
        ctx.strokeStyle = color;
        ctx.globalAlpha = (1 - ringExpand) * 0.75;
        ctx.lineWidth = 1.8;
        ctx.arc(pt.x, pt.y, 3 + ringExpand * 11, 0, Math.PI * 2);
        ctx.stroke();

        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.arc(pt.x, pt.y, Math.max(3, sw * 1.3), 0, Math.PI * 2);
        ctx.fill();
      } else if (mode === 'neon') {
        const tailLen = Math.min(28, geom.totalLen * 0.18);
        const pTail = pointAtArcLength(geom, Math.max(0, dist - tailLen));
        ctx.beginPath();
        ctx.shadowColor = color;
        ctx.shadowBlur = isDark ? 18 : 12;
        ctx.strokeStyle = color;
        ctx.lineWidth = sw * 2.6;
        ctx.globalAlpha = 0.85;
        ctx.moveTo(pTail.x, pTail.y);
        ctx.lineTo(pt.x, pt.y);
        ctx.stroke();

        ctx.beginPath();
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = Math.max(1.4, sw * 0.95);
        ctx.globalAlpha = 0.95;
        ctx.moveTo(pTail.x, pTail.y);
        ctx.lineTo(pt.x, pt.y);
        ctx.stroke();
      } else if (mode === 'dashed') {
        const segLen = 10;
        const pBack = pointAtArcLength(geom, Math.max(0, dist - segLen));
        ctx.beginPath();
        ctx.strokeStyle = color;
        ctx.lineWidth = sw * 1.9;
        ctx.moveTo(pBack.x, pBack.y);
        ctx.lineTo(pt.x, pt.y);
        ctx.stroke();
      }
      ctx.restore();
    }

    function drawElementText(ctx, el, opts = {}) {
      // Never render text on arrows
      if (!el || el.type === 'arrow' || !el.text || String(el.text).trim().length === 0) return;
      if (state.editingId === el.id && !opts.forExport) return;

      const canvasBg = opts.canvasBg || state.canvasBg;
      const strokeColor = resolveStrokeColor(el.strokeColor, canvasBg);
      const fontSize = Number(el.fontSize) || 16;
      const lineHeight = Math.round(fontSize * EXCALIDRAW_LINE_HEIGHT);
      const lines = String(el.text).split('\n');

      ctx.save();
      ctx.font = getFontCss(el.fontFamily, fontSize);
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';

      const centerX = el.x + (el.width || 0) / 2;
      const centerY = el.y + (el.height || 0) / 2;
      const totalTextH = lines.length * lineHeight;
      const startY = centerY - totalTextH / 2 + lineHeight / 2;

      ctx.fillStyle = strokeColor;
      for (let i = 0; i < lines.length; i++) {
        ctx.fillText(lines[i], centerX, startY + i * lineHeight);
      }

      ctx.restore();
    }

    function renderScenePasses(ctx, timeSec = 0, opts = {}) {
      const elements = opts.elements || state.elements;
      const elementsMap = getElementMap(elements);
      const { arrowDepths } = computeGraphDepths(elements);

      for (const [nodeId, val] of state.nodeArrivalEnergy.entries()) {
        const nextVal = val * 0.91;
        if (nextVal < 0.01) state.nodeArrivalEnergy.delete(nodeId);
        else state.nodeArrivalEnergy.set(nodeId, nextVal);
      }

      const arrowGeoms = new Map();
      for (const el of elements) {
        if (el.type === 'arrow') {
          arrowGeoms.set(el.id, getArrowGeometry(el, elementsMap));
        }
      }

      for (const el of elements) {
        if (el.type !== 'arrow') {
          drawStaticElement(ctx, el, opts);
        }
      }

      for (const el of elements) {
        if (el.type === 'arrow') {
          const geom = arrowGeoms.get(el.id);
          const depth = arrowDepths.get(el.id) || 0;
          drawArrowAndParticles(ctx, el, geom, depth, timeSec, opts);
        }
      }

      for (const el of elements) {
        if (el.type !== 'arrow') {
          drawElementText(ctx, el, opts);
        }
      }

      return arrowGeoms;
    }

    /* -------------------------------------------------------------------------
     * 7. Hit Testing, 8-Way Resize Handles, Ports & Inline Node Splitting
     * ------------------------------------------------------------------------- */
    function getResizeHandles(el) {
      if (!isNodeElement(el) || el.type === 'text') return [];
      const pad = 6 / (state.zoom || 1);
      const x = el.x - pad;
      const y = el.y - pad;
      const w = (el.width || 0) + pad * 2;
      const h = (el.height || 0) + pad * 2;
      return [
        { dir: 'nw', x: x,         y: y,         cursor: 'nwse-resize' },
        { dir: 'n',  x: x + w / 2, y: y,         cursor: 'ns-resize' },
        { dir: 'ne', x: x + w,     y: y,         cursor: 'nesw-resize' },
        { dir: 'e',  x: x + w,     y: y + h / 2, cursor: 'ew-resize' },
        { dir: 'se', x: x + w,     y: y + h,     cursor: 'nwse-resize' },
        { dir: 's',  x: x + w / 2, y: y + h,     cursor: 'ns-resize' },
        { dir: 'sw', x: x,         y: y + h,     cursor: 'nesw-resize' },
        { dir: 'w',  x: x,         y: y + h / 2, cursor: 'ew-resize' }
      ];
    }

    function hitTestResizeHandles(wx, wy) {
      if (state.selectedIds.size !== 1) return null;
      const id = Array.from(state.selectedIds)[0];
      const el = state.elements.find(e => e.id === id);
      if (!el || !isNodeElement(el) || el.type === 'text') return null;

      const tol = 8 / (state.zoom || 1);
      for (const h of getResizeHandles(el)) {
        if (Math.hypot(wx - h.x, wy - h.y) <= tol) {
          return { elementId: el.id, dir: h.dir, cursor: h.cursor };
        }
      }
      return null;
    }

    function getQuickConnectPorts(el) {
      if (!isNodeElement(el) || el.type === 'text') return [];
      const gap = 18 / (state.zoom || 1);
      const cx = el.x + el.width / 2;
      const cy = el.y + el.height / 2;
      return [
        { dir: 'top',    x: cx,                    y: el.y - gap,              angle: -Math.PI / 2 },
        { dir: 'right',  x: el.x + el.width + gap, y: cy,                      angle: 0 },
        { dir: 'bottom', x: cx,                    y: el.y + el.height + gap,  angle: Math.PI / 2 },
        { dir: 'left',   x: el.x - gap,            y: cy,                      angle: Math.PI }
      ];
    }

    function hitTestQuickPorts(wx, wy) {
      const candidateIds = new Set(state.selectedIds);
      if (state.hoveredId) candidateIds.add(state.hoveredId);
      const hitRadius = 12 / (state.zoom || 1);

      for (const id of candidateIds) {
        const el = state.elements.find(e => e.id === id);
        if (!el || !isNodeElement(el) || el.type === 'text') continue;
        const ports = getQuickConnectPorts(el);
        for (const p of ports) {
          if (Math.hypot(wx - p.x, wy - p.y) <= hitRadius) {
            return { elementId: el.id, dir: p.dir, x: p.x, y: p.y };
          }
        }
      }
      return null;
    }

    function hitTestArrowHandle(wx, wy) {
      const radius = 18 / (state.zoom || 1);
      const elementsMap = getElementMap();

      const arrows = state.elements.filter(e => e.type === 'arrow');
      arrows.sort((a, b) => {
        const aPri = (state.selectedIds.has(a.id) || state.hoveredId === a.id) ? 1 : 0;
        const bPri = (state.selectedIds.has(b.id) || state.hoveredId === b.id) ? 1 : 0;
        return bPri - aPri;
      });

      for (const arr of arrows) {
        const geom = getArrowGeometry(arr, elementsMap);
        if (Math.hypot(wx - geom.p0.x, wy - geom.p0.y) <= radius) {
          return { elementId: arr.id, handle: 'start', point: geom.p0 };
        }
        if (Math.hypot(wx - geom.p1.x, wy - geom.p1.y) <= radius) {
          return { elementId: arr.id, handle: 'end', point: geom.p1 };
        }
        if ((arr.curveType || 'curved') !== 'straight' && Math.hypot(wx - geom.curveHandlePt.x, wy - geom.curveHandlePt.y) <= radius) {
          return { elementId: arr.id, handle: 'curve', point: geom.curveHandlePt };
        }
      }
      return null;
    }

    function distanceToArrowShaft(arrow, wx, wy, elementsMap = null) {
      const geom = getArrowGeometry(arrow, elementsMap);
      let minDist = Infinity;
      const samples = geom.samples;
      for (let i = 0; i < samples.length - 1; i++) {
        const a = samples[i];
        const b = samples[i + 1];
        const dx = b.x - a.x;
        const dy = b.y - a.y;
        const len2 = dx * dx + dy * dy;
        const t = len2 > 1e-6 ? Math.max(0, Math.min(1, ((wx - a.x) * dx + (wy - a.y) * dy) / len2)) : 0;
        const px = a.x + t * dx;
        const py = a.y + t * dy;
        const d = Math.hypot(wx - px, wy - py);
        if (d < minDist) minDist = d;
      }
      return minDist;
    }

    function hitTestElement(wx, wy) {
      const elementsMap = getElementMap();
      const arrowTol = 11 / (state.zoom || 1);

      for (let i = state.elements.length - 1; i >= 0; i--) {
        const el = state.elements[i];
        if (el.type === 'arrow') {
          if (distanceToArrowShaft(el, wx, wy, elementsMap) <= arrowTol) {
            return el;
          }
          continue;
        }
        if (el.type === 'freedraw') {
          const pts = el.points || [];
          for (const p of pts) {
            if (Math.hypot(wx - (el.x + p[0]), wy - (el.y + p[1])) <= 10 / (state.zoom || 1)) {
              return el;
            }
          }
          continue;
        }
        if (el.type === 'ellipse') {
          const cx = el.x + el.width / 2;
          const cy = el.y + el.height / 2;
          const rx = Math.max(4, el.width / 2 + 4);
          const ry = Math.max(4, el.height / 2 + 4);
          if (((wx - cx) / rx) ** 2 + ((wy - cy) / ry) ** 2 <= 1) return el;
          continue;
        }
        if (el.type === 'diamond') {
          const cx = el.x + el.width / 2;
          const cy = el.y + el.height / 2;
          const hw = Math.max(4, el.width / 2 + 4);
          const hh = Math.max(4, el.height / 2 + 4);
          if (Math.abs(wx - cx) / hw + Math.abs(wy - cy) / hh <= 1) return el;
          continue;
        }
        if (wx >= el.x && wx <= el.x + el.width && wy >= el.y && wy <= el.y + el.height) {
          return el;
        }
      }
      return null;
    }

    function findSplitTargetArrow(node) {
      if (!node || !isNodeElement(node) || node.type === 'text') return null;
      const cx = node.x + node.width / 2;
      const cy = node.y + node.height / 2;
      const elementsMap = getElementMap();
      const threshold = Math.min(node.width, node.height) * 0.45;

      for (const el of state.elements) {
        if (el.type !== 'arrow') continue;
        if (el.startBinding?.elementId === node.id || el.endBinding?.elementId === node.id) continue;
        const d = distanceToArrowShaft(el, cx, cy, elementsMap);
        if (d <= threshold) return el;
      }
      return null;
    }

    function trySplitArrowWithNode(node) {
      const arrow = findSplitTargetArrow(node);
      if (!arrow) return false;

      const origEndBinding = arrow.endBinding ? { ...arrow.endBinding } : null;
      const origX2 = arrow.x2;
      const origY2 = arrow.y2;

      const nodeCenter = { x: node.x + node.width / 2, y: node.y + node.height / 2 };
      const geom = getArrowGeometry(arrow);

      arrow.endBinding = computeBindingForShape(node, geom.p0);
      arrow.curveOffset = 0;

      const newArrow = createElement('arrow', {
        x: nodeCenter.x,
        y: nodeCenter.y,
        x2: origX2,
        y2: origY2,
        strokeColor: arrow.strokeColor,
        strokeWidth: arrow.strokeWidth,
        strokeStyle: arrow.strokeStyle,
        curveType: arrow.curveType,
        curveOffset: 0,
        startBinding: computeBindingForShape(node, geom.p1),
        endBinding: origEndBinding,
        flowEnabled: arrow.flowEnabled !== false
      });

      state.elements.push(newArrow);
      state.splitTargetArrowId = null;
      return true;
    }

    /* -------------------------------------------------------------------------
     * 8. Auto-Fitting Multi-Line Text & Element Factory
     * ------------------------------------------------------------------------- */
    let measureCtx = null;
    function getMeasureCtx() {
      if (!measureCtx && typeof document !== 'undefined') {
        const c = document.createElement('canvas');
        measureCtx = c.getContext('2d');
      }
      return measureCtx;
    }

    function autoFitElementToText(el, text) {
      if (!el || el.type === 'arrow') return;
      el.text = text;
      const lines = String(text || '').split('\n');
      const fontSize = Number(el.fontSize) || 15;
      const lineHeight = Math.round(fontSize * EXCALIDRAW_LINE_HEIGHT);

      const mCtx = getMeasureCtx();
      let maxLineW = 0;
      if (mCtx) {
        mCtx.font = getFontCss(el.fontFamily, fontSize);
        for (const line of lines) {
          maxLineW = Math.max(maxLineW, mCtx.measureText(line || ' ').width);
        }
      } else {
        for (const line of lines) {
          maxLineW = Math.max(maxLineW, (line || '').length * fontSize * 0.58);
        }
      }

      const cx = el.x + el.width / 2;
      const cy = el.y + el.height / 2;
      let padX = 32;
      let padY = 28;
      if (el.type === 'diamond') {
        padX = Math.max(56, maxLineW * 0.65);
        padY = Math.max(44, lines.length * lineHeight * 0.65);
      } else if (el.type === 'ellipse') {
        padX = 42;
      }
      const minW = el.type === 'text' ? 40 : 110;
      const minH = el.type === 'text' ? 26 : 54;

      const nextW = Math.max(el.width || minW, minW, Math.ceil(maxLineW + padX));
      const nextH = Math.max(el.height || minH, minH, Math.ceil(lines.length * lineHeight + padY));

      if (nextW !== el.width || nextH !== el.height) {
        el.width = nextW;
        el.height = nextH;
        el.x = cx - nextW / 2;
        el.y = cy - nextH / 2;
        ShapeCache.invalidate(el);
      }
    }

    const DEFAULT_SHAPE_SIZES = {
      sticky: { width: 150, height: 110 },
      diamond: { width: 148, height: 86 },
      default: { width: 144, height: 68 }
    };

    function getDefaultShapeSize(type) {
      return DEFAULT_SHAPE_SIZES[type] || DEFAULT_SHAPE_SIZES.default;
    }

    function createElement(type, props = {}) {
      const d = state.defaults;
      const seed = props.seed || Math.floor(Math.random() * 1000000) + 1;
      const defaultSize = getDefaultShapeSize(type);
      const base = {
        id: props.id || nextId(type),
        type,
        x: props.x ?? 0,
        y: props.y ?? 0,
        width: props.width ?? defaultSize.width,
        height: props.height ?? defaultSize.height,
        strokeColor: props.strokeColor || d.strokeColor,
        fillStyle: props.fillStyle ?? (type === 'sticky' ? 'solid' : d.fillStyle),
        fontFamily: normalizeFontFamily(props.fontFamily || d.fontFamily),
        fontSize: Number(props.fontSize || d.fontSize),
        roughness: props.roughness !== undefined ? Number(props.roughness) : d.roughness,
        strokeWidth: Number(props.strokeWidth || d.strokeWidth),
        strokeStyle: props.strokeStyle || d.strokeStyle,
        curveType: props.curveType || d.curveType,
        curveOffset: Number(props.curveOffset) || 0,
        text: type === 'arrow' ? '' : (props.text ?? ''),
        seed,
        versionNonce: 1,
        flowEnabled: props.flowEnabled !== false,
        startBinding: props.startBinding || null,
        endBinding: props.endBinding || null,
        x2: props.x2,
        y2: props.y2,
        points: props.points || []
      };
      if (base.text && isNodeElement(base)) {
        autoFitElementToText(base, base.text);
      }
      return base;
    }

    /* -------------------------------------------------------------------------
     * 9. History Stack (Undo / Redo)
     * ------------------------------------------------------------------------- */
    function snapshotScene() {
      return JSON.stringify(state.elements);
    }

    function pushHistory(customSnap = null) {
      const snap = customSnap || snapshotScene();
      const stack = state.history.undoStack;
      if (stack.length > 0 && stack[stack.length - 1] === snap) return;
      stack.push(snap);
      if (stack.length > 60) stack.shift();
      state.history.redoStack = [];
      updateHeaderButtons();
    }

    function discardRedundantUndoSnapshot() {
      const stack = state.history.undoStack;
      if (stack.length > 0 && stack[stack.length - 1] === snapshotScene()) {
        stack.pop();
        updateHeaderButtons();
      }
    }

    function undo() {
      const currentSnap = snapshotScene();
      while (state.history.undoStack.length > 0 && state.history.undoStack[state.history.undoStack.length - 1] === currentSnap) {
        state.history.undoStack.pop();
      }
      if (state.history.undoStack.length === 0) {
        updateHeaderButtons();
        return;
      }
      state.history.redoStack.push(currentSnap);
      const prev = state.history.undoStack.pop();
      state.elements = JSON.parse(prev);
      state.selectedIds.clear();
      ShapeCache.clear();
      updateHeaderButtons();
      syncUIWithSelection();
    }

    function redo() {
      if (state.history.redoStack.length === 0) return;
      state.history.undoStack.push(snapshotScene());
      const next = state.history.redoStack.pop();
      state.elements = JSON.parse(next);
      state.selectedIds.clear();
      ShapeCache.clear();
      updateHeaderButtons();
      syncUIWithSelection();
    }

    /* -------------------------------------------------------------------------
     * 10. Quick-Add Chaining, Tab Chaining & Starter Templates
     * ------------------------------------------------------------------------- */
    function chainNodeFrom(sourceNode, dir = 'right', type = null, openEditor = false) {
      pushHistory();
      const targetType = type || (sourceNode.type === 'text' ? 'rectangle' : sourceNode.type);
      const stepX = 220;
      const stepY = 150;
      const scx = sourceNode.x + sourceNode.width / 2;
      const scy = sourceNode.y + sourceNode.height / 2;

      let ncx = scx + stepX;
      let ncy = scy;
      let outAngle = 0;
      let inAngle = Math.PI;

      if (dir === 'left') { ncx = scx - stepX; outAngle = Math.PI; inAngle = 0; }
      else if (dir === 'top') { ncx = scx; ncy = scy - stepY; outAngle = -Math.PI / 2; inAngle = Math.PI / 2; }
      else if (dir === 'bottom') { ncx = scx; ncy = scy + stepY; outAngle = Math.PI / 2; inAngle = -Math.PI / 2; }

      const { width: newW, height: newH } = getDefaultShapeSize(targetType);
      const newNode = createElement(targetType, {
        x: ncx - newW / 2,
        y: ncy - newH / 2,
        width: newW,
        height: newH,
        strokeColor: sourceNode.strokeColor || state.defaults.strokeColor,
        fillStyle: sourceNode.fillStyle || state.defaults.fillStyle,
        fontFamily: sourceNode.fontFamily || state.defaults.fontFamily,
        fontSize: sourceNode.fontSize || state.defaults.fontSize,
        text: 'Next Step'
      });

      const newArrow = createElement('arrow', {
        x: scx,
        y: scy,
        x2: ncx,
        y2: ncy,
        strokeColor: sourceNode.strokeColor || state.defaults.strokeColor,
        startBinding: { elementId: sourceNode.id, focusAngle: outAngle, side: dir, gap: 4 },
        endBinding: { elementId: newNode.id, focusAngle: inAngle, side: angleToSide(inAngle), gap: 4 }
      });

      state.elements.push(newNode, newArrow);
      state.selectedIds.clear();
      state.selectedIds.add(newNode.id);
      syncUIWithSelection();

      if (openEditor) {
        startInlineEditing(newNode);
      }
      return newNode;
    }

    function quickAddShape(type = 'rectangle') {
      const selectedNodes = Array.from(state.selectedIds)
        .map(id => state.elements.find(e => e.id === id))
        .filter(el => el && isNodeElement(el));

      if (selectedNodes.length === 1) {
        return chainNodeFrom(selectedNodes[0], 'right', type, false);
      }

      pushHistory();
      const vw = (typeof window !== 'undefined' ? window.innerWidth : 1280);
      const vh = (typeof window !== 'undefined' ? window.innerHeight : 800);
      const centerWorld = screenToWorld(vw / 2, vh / 2);
      const offset = (state.elements.length % 5) * 24;
      const w = type === 'sticky' ? 156 : (type === 'diamond' ? 150 : 144);
      const h = type === 'sticky' ? 114 : (type === 'diamond' ? 88 : 68);
      const defaultLabels = {
        rectangle: 'Service Node',
        ellipse: 'State / Cache',
        diamond: 'Decision?',
        sticky: 'Architecture Note'
      };
      const el = createElement(type, {
        x: centerWorld.x - w / 2 + offset,
        y: centerWorld.y - h / 2 + offset,
        width: w,
        height: h,
        text: defaultLabels[type] || 'Node'
      });
      state.elements.push(el);
      state.selectedIds.clear();
      state.selectedIds.add(el.id);
      syncUIWithSelection();
      return el;
    }

    function loadTemplate(templateName) {
      pushHistory();
      state.elements = [];
      state.selectedIds.clear();
      state.activePulses = [];
      ShapeCache.clear();

      const addNode = (id, type, x, y, w, h, text, color, fillStyle = 'hachure') => {
        const el = createElement(type, { id, x, y, width: w, height: h, text, strokeColor: color, fillStyle });
        state.elements.push(el);
        return el;
      };

      const addEdge = (fromEl, toEl, curveOffset = 0, color = null) => {
        const fc = { x: fromEl.x + fromEl.width / 2, y: fromEl.y + fromEl.height / 2 };
        const tc = { x: toEl.x + toEl.width / 2, y: toEl.y + toEl.height / 2 };
        const angOut = Math.atan2(tc.y - fc.y, tc.x - fc.x);
        const angIn = Math.atan2(fc.y - tc.y, fc.x - tc.x);
        const arr = createElement('arrow', {
          x: fc.x,
          y: fc.y,
          x2: tc.x,
          y2: tc.y,
          text: '',
          curveOffset,
          curveType: Math.abs(curveOffset) > 1 ? 'curved' : state.defaults.curveType,
          strokeColor: color || fromEl.strokeColor,
          startBinding: { elementId: fromEl.id, focusAngle: angOut, side: angleToSide(angOut), gap: 4 },
          endBinding: { elementId: toEl.id, focusAngle: angIn, side: angleToSide(angIn), gap: 4 }
        });
        state.elements.push(arr);
        return arr;
      };

      if (templateName === 'How Browsers Work') {
        const n1 = addNode('b_url', 'ellipse', 70, 220, 148, 70, 'URL Request\nHTTPS / DNS', '#0070f3');
        const n2 = addNode('b_html', 'rectangle', 295, 125, 156, 70, 'HTML Parser\nDOM Tree', '#7928ca');
        const n3 = addNode('b_css', 'rectangle', 295, 315, 156, 70, 'CSS Parser\nCSSOM', '#06b6d4');
        const n4 = addNode('b_render', 'diamond', 530, 208, 174, 96, 'Render Tree\n& Layout', '#f59e0b');
        const n5 = addNode('b_paint', 'rectangle', 780, 220, 162, 70, 'Composite &\n60fps Paint', '#10b981');
        addEdge(n1, n2, -20, '#0070f3');
        addEdge(n1, n3, 20, '#06b6d4');
        addEdge(n2, n4, 16, '#7928ca');
        addEdge(n3, n4, -16, '#06b6d4');
        addEdge(n4, n5, 0, '#10b981');
      } else if (templateName === 'RAG Pipeline') {
        const n1 = addNode('r_q', 'ellipse', 70, 225, 146, 70, 'User Query', '#0070f3');
        const n2 = addNode('r_emb', 'rectangle', 285, 225, 158, 70, 'Embedding\nEncoder', '#7928ca');
        const n3 = addNode('r_vec', 'diamond', 515, 120, 170, 94, 'Vector DB\nTop-K Search', '#06b6d4');
        const n4 = addNode('r_rerank', 'rectangle', 520, 320, 158, 70, 'Cross-Encoder\nReranker', '#f59e0b');
        const n5 = addNode('r_llm', 'rectangle', 765, 225, 164, 72, 'LLM Context\nSynthesizer', '#10b981');
        addEdge(n1, n2, 0, '#0070f3');
        addEdge(n2, n3, -18, '#7928ca');
        addEdge(n3, n4, 0, '#06b6d4');
        addEdge(n4, n5, 18, '#f59e0b');
        addEdge(n2, n5, -28, '#10b981');
      } else if (templateName === 'Microservices') {
        const n1 = addNode('m_gw', 'diamond', 70, 215, 166, 94, 'API Gateway\nRate Limiter', '#0070f3');
        const n2 = addNode('m_auth', 'rectangle', 315, 100, 152, 68, 'Auth Service\nJWT Verify', '#7928ca');
        const n3 = addNode('m_ord', 'rectangle', 315, 228, 152, 68, 'Order Engine', '#10b981');
        const n4 = addNode('m_pay', 'rectangle', 315, 355, 152, 68, 'Payment Worker', '#f59e0b');
        const n5 = addNode('m_kafka', 'ellipse', 565, 228, 160, 72, 'Event Bus\nKafka Stream', '#ef4444');
        const n6 = addNode('m_db', 'rectangle', 800, 228, 156, 70, 'Read Replica\nAnalytics', '#06b6d4');
        addEdge(n1, n2, -20, '#7928ca');
        addEdge(n1, n3, 0, '#0070f3');
        addEdge(n1, n4, 20, '#f59e0b');
        addEdge(n3, n5, 0, '#10b981');
        addEdge(n4, n5, -18, '#f59e0b');
        addEdge(n5, n6, 0, '#ef4444');
      } else {
        const n1 = addNode('a_user', 'ellipse', 70, 225, 146, 70, 'User Task\nSpec', '#0070f3');
        const n2 = addNode('a_plan', 'diamond', 285, 212, 170, 94, 'Orchestrator\nPlanner', '#7928ca');
        const n3 = addNode('a_code', 'rectangle', 530, 115, 160, 70, 'Coder Agent\nSandbox', '#10b981');
        const n4 = addNode('a_res', 'rectangle', 530, 325, 160, 70, 'Research Agent\nWeb & Docs', '#06b6d4');
        const n5 = addNode('a_ver', 'rectangle', 780, 225, 164, 70, 'Verifier Agent\nTest Runner', '#f59e0b');
        addEdge(n1, n2, 0, '#0070f3');
        addEdge(n2, n3, -20, '#7928ca');
        addEdge(n2, n4, 20, '#7928ca');
        addEdge(n3, n5, 18, '#10b981');
        addEdge(n4, n5, -18, '#06b6d4');
      }

      fitToScreen();
      if (state.tabs.length > 0) {
        const activeTab = state.tabs.find(t => t.id === state.activeTabId);
        if (activeTab) {
          activeTab.name = templateName || 'AI Agent Swarm';
        }
      }
      syncUIWithSelection();
    }

    /* -------------------------------------------------------------------------
     * 11. Camera Transforms & Interactive Overlay Rendering
     * ------------------------------------------------------------------------- */
    function worldToScreen(wx, wy) {
      return {
        x: (wx + state.scrollX) * state.zoom,
        y: (wy + state.scrollY) * state.zoom
      };
    }

    function screenToWorld(sx, sy) {
      return {
        x: sx / state.zoom - state.scrollX,
        y: sy / state.zoom - state.scrollY
      };
    }

    function drawInteractiveOverlay(ctx, arrowGeoms) {
      const zoom = state.zoom || 1;
      const isDark = state.canvasBg === '#000000';
      const accent = isDark ? '#8b87ff' : '#6965db';

      ctx.save();

      const elementsMap = getElementMap();

      // 1. Magnetic snap target outline, center-to-perimeter angle ray & glowing ring
      if (state.snapPreview) {
        const sp = state.snapPreview;
        const targetShape = elementsMap.get(sp.shapeId);
        if (targetShape) {
          const paths = ShapeCache.get(targetShape);
          const scx = targetShape.x + targetShape.width / 2;
          const scy = targetShape.y + targetShape.height / 2;

          ctx.save();
          ctx.strokeStyle = accent;
          ctx.lineWidth = 2.4 / zoom;
          ctx.shadowColor = accent;
          ctx.shadowBlur = 12;
          ctx.stroke(paths.fillPath);

          // Dashed radial guide from shape center to perimeter attachment point
          ctx.beginPath();
          ctx.setLineDash([4 / zoom, 4 / zoom]);
          ctx.lineWidth = 1.3 / zoom;
          ctx.globalAlpha = 0.65;
          ctx.moveTo(scx, scy);
          ctx.lineTo(sp.point.x, sp.point.y);
          ctx.stroke();
          ctx.setLineDash([]);
          ctx.globalAlpha = 1;

          // Glowing perimeter anchor ring
          ctx.beginPath();
          ctx.fillStyle = '#ffffff';
          ctx.strokeStyle = accent;
          ctx.lineWidth = 2.5 / zoom;
          ctx.arc(sp.point.x, sp.point.y, 6.5 / zoom, 0, Math.PI * 2);
          ctx.fill();
          ctx.stroke();
          ctx.restore();
        }
      }

      // 2. Subtle hover cue on hovered unselected node
      if (state.hoveredId && !state.selectedIds.has(state.hoveredId) && !state.drag) {
        const hovEl = elementsMap.get(state.hoveredId);
        if (hovEl && isNodeElement(hovEl) && hovEl.type !== 'text') {
          ctx.save();
          ctx.strokeStyle = accent;
          ctx.globalAlpha = 0.35;
          ctx.lineWidth = 1.5 / zoom;
          const pad = 5 / zoom;
          ctx.strokeRect(hovEl.x - pad, hovEl.y - pad, (hovEl.width || 0) + pad * 2, (hovEl.height || 0) + pad * 2);
          ctx.restore();
        }
      }

      // 3. Selection Bounding Box + 8-Way Resize Handles + Quick-Connect '+' Ports
      const portOwnerIds = new Set(state.selectedIds);
      if (state.hoveredId) portOwnerIds.add(state.hoveredId);

      for (const id of state.selectedIds) {
        const el = elementsMap.get(id);
        if (!el || el.type === 'arrow') continue;
        ctx.save();
        ctx.strokeStyle = accent;
        ctx.lineWidth = 1.4 / zoom;
        const pad = 6 / zoom;
        ctx.strokeRect(el.x - pad, el.y - pad, (el.width || 0) + pad * 2, (el.height || 0) + pad * 2);

        // Draw 8 resize handles when single shape is selected
        if (state.selectedIds.size === 1 && isNodeElement(el) && el.type !== 'text') {
          const hs = 4.2 / zoom;
          for (const h of getResizeHandles(el)) {
            ctx.fillStyle = isDark ? '#1e1e24' : '#ffffff';
            ctx.strokeStyle = accent;
            ctx.lineWidth = 1.5 / zoom;
            ctx.beginPath();
            ctx.rect(h.x - hs, h.y - hs, hs * 2, hs * 2);
            ctx.fill();
            ctx.stroke();
          }
        }
        ctx.restore();
      }

      if (state.activeTool === 'select') {
        for (const id of portOwnerIds) {
          const el = elementsMap.get(id);
          if (!el || !isNodeElement(el) || el.type === 'text') continue;
          const ports = getQuickConnectPorts(el);
          for (const p of ports) {
            const isHoveredPort = state.hoveredPort &&
              state.hoveredPort.elementId === el.id &&
              state.hoveredPort.dir === p.dir;
            const r = (isHoveredPort ? 9.5 : 7.2) / zoom;
            ctx.save();
            ctx.beginPath();
            ctx.fillStyle = isHoveredPort ? accent : (isDark ? '#1e1e26' : '#ffffff');
            ctx.strokeStyle = accent;
            ctx.lineWidth = 1.6 / zoom;
            ctx.arc(p.x, p.y, r, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();

            const arm = 3.3 / zoom;
            ctx.beginPath();
            ctx.strokeStyle = isHoveredPort ? '#ffffff' : accent;
            ctx.lineWidth = 1.6 / zoom;
            ctx.moveTo(p.x - arm, p.y);
            ctx.lineTo(p.x + arm, p.y);
            ctx.moveTo(p.x, p.y - arm);
            ctx.lineTo(p.x, p.y + arm);
            ctx.stroke();
            ctx.restore();
          }
        }
      }

      // 4. Hover-Visible & Selected Arrow Endpoint Handles ('start', 'curve', 'end')
      for (const el of state.elements) {
        if (el.type !== 'arrow') continue;
        const showHandles = state.selectedIds.has(el.id) || state.hoveredId === el.id ||
          (state.hoveredArrowHandle && state.hoveredArrowHandle.elementId === el.id);
        if (!showHandles) continue;

        const geom = arrowGeoms.get(el.id) || getArrowGeometry(el);
        const handles = [
          { name: 'start', pt: geom.p0, bound: Boolean(el.startBinding?.elementId) },
          ...((el.curveType || 'curved') !== 'straight' ? [{ name: 'curve', pt: geom.curveHandlePt, bound: false }] : []),
          { name: 'end',   pt: geom.p1, bound: Boolean(el.endBinding?.elementId) }
        ];

        for (const h of handles) {
          const isHot = state.hoveredArrowHandle &&
            state.hoveredArrowHandle.elementId === el.id &&
            state.hoveredArrowHandle.handle === h.name;
          const r = (isHot ? 7.4 : 5.6) / zoom;
          ctx.save();
          ctx.beginPath();
          ctx.fillStyle = h.bound ? accent : (isDark ? '#18181f' : '#ffffff');
          ctx.strokeStyle = accent;
          ctx.lineWidth = 2 / zoom;
          if (h.name === 'curve') {
            const d = r * 1.15;
            ctx.moveTo(h.pt.x, h.pt.y - d);
            ctx.lineTo(h.pt.x + d, h.pt.y);
            ctx.lineTo(h.pt.x, h.pt.y + d);
            ctx.lineTo(h.pt.x - d, h.pt.y);
            ctx.closePath();
          } else {
            ctx.arc(h.pt.x, h.pt.y, r, 0, Math.PI * 2);
          }
          ctx.fill();
          ctx.stroke();
          ctx.restore();
        }
      }

      // 5. Live Port-Wire Drag Preview
      if (state.drag && state.drag.mode === 'port-wire') {
        const d = state.drag;
        ctx.save();
        ctx.strokeStyle = accent;
        ctx.lineWidth = 2.2 / zoom;
        ctx.setLineDash([6 / zoom, 4 / zoom]);
        ctx.beginPath();
        ctx.moveTo(d.startPt.x, d.startPt.y);
        const mx = (d.startPt.x + d.currPt.x) / 2;
        const my = (d.startPt.y + d.currPt.y) / 2 - 24 / zoom;
        ctx.quadraticCurveTo(mx, my, d.currPt.x, d.currPt.y);
        ctx.stroke();
        ctx.restore();
      }

      // 6. Marquee Selection Box
      if (state.drag && state.drag.mode === 'marquee') {
        const d = state.drag;
        const x = Math.min(d.startX, d.currX);
        const y = Math.min(d.startY, d.currY);
        const w = Math.abs(d.currX - d.startX);
        const h = Math.abs(d.currY - d.startY);
        ctx.save();
        ctx.fillStyle = 'rgba(105, 101, 219, 0.09)';
        ctx.strokeStyle = accent;
        ctx.lineWidth = 1.2 / zoom;
        ctx.fillRect(x, y, w, h);
        ctx.strokeRect(x, y, w, h);
        ctx.restore();
      }

      // 7. Laser Pointer 900ms Decaying Red Glow Trail
      const nowMs = performance.now();
      state.laserPoints = state.laserPoints.filter(p => nowMs - p.t < 900);
      if (state.laserPoints.length > 1) {
        ctx.save();
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        for (let i = 1; i < state.laserPoints.length; i++) {
          const p0 = state.laserPoints[i - 1];
          const p1 = state.laserPoints[i];
          const age = (nowMs - p1.t) / 900;
          const alpha = Math.max(0, 1 - age);
          ctx.beginPath();
          ctx.strokeStyle = '#ef4444';
          ctx.shadowColor = '#ef4444';
          ctx.shadowBlur = 12;
          ctx.globalAlpha = alpha;
          ctx.lineWidth = (4.5 * alpha) / zoom;
          ctx.moveTo(p0.x, p0.y);
          ctx.lineTo(p1.x, p1.y);
          ctx.stroke();
        }
        ctx.restore();
      }

      // 8. Empty Canvas Watermark Guide (when switching to a newly created blank tab)
      if (state.elements.length === 0 && !state.drag) {
        const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
        const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
        const centerW = screenToWorld(vw / 2, vh / 2);
        const activeTab = state.tabs.find(t => t.id === state.activeTabId);
        const tabIdx = Math.max(0, state.tabs.findIndex(t => t.id === state.activeTabId));
        const tabTitle = activeTab ? activeTab.name : `Canvas ${tabIdx + 1}`;
        ctx.save();
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillStyle = isDark ? 'rgba(244, 244, 248, 0.72)' : 'rgba(27, 27, 31, 0.68)';
        ctx.font = `600 ${Math.round(18 / zoom)}px Assistant, system-ui, sans-serif`;
        ctx.fillText(`${tabTitle} — Empty Canvas`, centerW.x, centerW.y - 14 / zoom);
        ctx.fillStyle = isDark ? 'rgba(244, 244, 248, 0.44)' : 'rgba(27, 27, 31, 0.44)';
        ctx.font = `500 ${Math.round(13 / zoom)}px Assistant, system-ui, sans-serif`;
        ctx.fillText('Double-click anywhere to add a node, draw with tools above, or pick a Template', centerW.x, centerW.y + 14 / zoom);
        ctx.restore();
      }

      ctx.restore();
    }

    /* -------------------------------------------------------------------------
     * 12. Pointer Interaction Engine (World-Space & DOM Events)
     * ------------------------------------------------------------------------- */
    function updateInteractiveCursor() {
      if (typeof document === 'undefined') return;
      const ic = document.getElementById('interactiveCanvas');
      if (!ic) return;

      if (state.drag) {
        if (state.drag.mode === 'pan' || state.drag.mode === 'move' || state.drag.mode === 'arrow-handle') {
          ic.style.cursor = 'grabbing';
          return;
        }
        if (state.drag.mode === 'resize') {
          ic.style.cursor = state.drag.cursor || 'nwse-resize';
          return;
        }
      }

      if (state.activeTool === 'hand' || state.isSpacePanning) {
        ic.style.cursor = 'grab';
        return;
      }
      if (state.activeTool !== 'select') {
        ic.style.cursor = 'crosshair';
        return;
      }

      if (state.hoveredResizeHandle) {
        ic.style.cursor = state.hoveredResizeHandle.cursor;
      } else if (state.hoveredPort) {
        ic.style.cursor = 'pointer';
      } else if (state.hoveredArrowHandle) {
        ic.style.cursor = 'grab';
      } else if (state.hoveredId) {
        ic.style.cursor = 'move';
      } else {
        ic.style.cursor = 'default';
      }
    }

    function cloneElementsWithBindings(sourceElements, offsetX = 0, offsetY = 0) {
      if (!Array.isArray(sourceElements) || sourceElements.length === 0) return [];
      const idMap = new Map();
      const clones = [];
      for (const el of sourceElements) {
        const newId = nextId(el.type);
        idMap.set(el.id, newId);
        const copy = JSON.parse(JSON.stringify(el));
        copy.id = newId;
        copy.x = (Number(copy.x) || 0) + offsetX;
        copy.y = (Number(copy.y) || 0) + offsetY;
        if (typeof copy.x2 === 'number') copy.x2 += offsetX;
        if (typeof copy.y2 === 'number') copy.y2 += offsetY;
        copy.seed = Math.floor(Math.random() * 1000000) + 1;
        clones.push(copy);
      }
      for (const c of clones) {
        if (c.startBinding?.elementId && idMap.has(c.startBinding.elementId)) {
          c.startBinding.elementId = idMap.get(c.startBinding.elementId);
        }
        if (c.endBinding?.elementId && idMap.has(c.endBinding.elementId)) {
          c.endBinding.elementId = idMap.get(c.endBinding.elementId);
        }
        state.elements.push(c);
      }
      state.selectedIds = new Set(clones.map(c => c.id));
      return clones;
    }

    function cloneSelectedForAltDrag() {
      const selected = state.elements.filter(el => state.selectedIds.has(el.id));
      cloneElementsWithBindings(selected, 0, 0);
    }

    function pointerDownWorld(wx, wy, opts = {}) {
      if (state.editingId) commitInlineEditor();
      closeAllDropdowns();

      const shiftKey = Boolean(opts.shiftKey);
      const altKey = Boolean(opts.altKey);
      const tool = state.activeTool;

      if (tool === 'hand' || state.isSpacePanning) {
        state.drag = {
          mode: 'pan',
          startScreenX: opts.screenX ?? wx * state.zoom,
          startScreenY: opts.screenY ?? wy * state.zoom,
          origScrollX: state.scrollX,
          origScrollY: state.scrollY
        };
        updateInteractiveCursor();
        return;
      }

      if (tool === 'laser') {
        state.laserPoints.push({ x: wx, y: wy, t: performance.now() });
        state.drag = { mode: 'laser' };
        return;
      }

      if (tool === 'eraser') {
        pushHistory();
        const hit = hitTestElement(wx, wy);
        if (hit) deleteElementById(hit.id);
        state.drag = { mode: 'eraser' };
        return;
      }

      if (tool === 'freedraw') {
        pushHistory();
        const el = createElement('freedraw', {
          x: wx,
          y: wy,
          width: 1,
          height: 1,
          points: [[0, 0]]
        });
        state.elements.push(el);
        state.selectedIds.clear();
        state.selectedIds.add(el.id);
        state.drag = { mode: 'freedraw', element: el };
        return;
      }

      if (tool === 'text' || tool === 'sticky') {
        pushHistory();
        const w = tool === 'sticky' ? 156 : 120;
        const h = tool === 'sticky' ? 112 : 38;
        const el = createElement(tool, {
          x: wx - w / 2,
          y: wy - h / 2,
          width: w,
          height: h,
          text: tool === 'sticky' ? 'Sticky Note' : 'Label'
        });
        state.elements.push(el);
        state.selectedIds.clear();
        state.selectedIds.add(el.id);
        if (!state.toolLocked) setTool('select');
        syncUIWithSelection();
        startInlineEditing(el);
        return;
      }

      if (tool === 'rectangle' || tool === 'ellipse' || tool === 'diamond') {
        pushHistory();
        const el = createElement(tool, {
          x: wx,
          y: wy,
          width: 4,
          height: 4,
          text: ''
        });
        state.elements.push(el);
        state.selectedIds.clear();
        state.selectedIds.add(el.id);
        state.drag = { mode: 'draw-shape', element: el, startX: wx, startY: wy };
        return;
      }

      if (tool === 'arrow') {
        pushHistory();
        const startShape = findMagneticShape(wx, wy, null);
        const startBinding = startShape ? computeBindingForShape(startShape, { x: wx, y: wy }) : null;
        const startPt = startShape
          ? getBindingBoundaryPoint(startShape, startBinding, { x: wx, y: wy }, 4)
          : { x: wx, y: wy };

        const arrow = createElement('arrow', {
          x: startPt.x,
          y: startPt.y,
          x2: wx,
          y2: wy,
          startBinding,
          endBinding: null
        });
        state.elements.push(arrow);
        state.selectedIds.clear();
        state.selectedIds.add(arrow.id);
        state.drag = { mode: 'arrow-handle', arrow, handle: 'end', isNewArrow: true };
        return;
      }

      // SELECT MODE
      // 0. Check 8-Way Resize Handles on selected node
      const resizeHit = hitTestResizeHandles(wx, wy);
      if (resizeHit) {
        const el = state.elements.find(e => e.id === resizeHit.elementId);
        if (el) {
          pushHistory();
          state.drag = {
            mode: 'resize',
            element: el,
            dir: resizeHit.dir,
            cursor: resizeHit.cursor,
            startX: wx,
            startY: wy,
            origX: el.x,
            origY: el.y,
            origW: el.width,
            origH: el.height
          };
          updateInteractiveCursor();
          return;
        }
      }

      // 1. Check Quick-Connect '+' Ports
      const portHit = hitTestQuickPorts(wx, wy);
      if (portHit) {
        const sourceEl = state.elements.find(e => e.id === portHit.elementId);
        if (sourceEl) {
          state.drag = {
            mode: 'port-wire',
            sourceEl,
            dir: portHit.dir,
            startPt: { x: portHit.x, y: portHit.y },
            currPt: { x: wx, y: wy },
            moved: false
          };
          return;
        }
      }

      // 2. Check 1-Click Arrow Endpoint / Curve Handle Grabbing (18px / zoom radius across ALL arrows)
      const handleHit = hitTestArrowHandle(wx, wy);
      if (handleHit) {
        pushHistory();
        const arrow = state.elements.find(e => e.id === handleHit.elementId);
        if (arrow) {
          state.selectedIds.clear();
          state.selectedIds.add(arrow.id);
          syncUIWithSelection();
          state.drag = { mode: 'arrow-handle', arrow, handle: handleHit.handle };
          updateInteractiveCursor();
          return;
        }
      }

      // 3. Hit-test scene elements
      const hitEl = hitTestElement(wx, wy);
      if (hitEl) {
        pushHistory();

        if (hitEl.type === 'arrow' && !altKey) {
          const geom = getArrowGeometry(hitEl);
          const endGrabRadius = 32 / (state.zoom || 1);
          const nearStart = Math.hypot(wx - geom.p0.x, wy - geom.p0.y) <= endGrabRadius;
          const nearEnd = Math.hypot(wx - geom.p1.x, wy - geom.p1.y) <= endGrabRadius;
          const hasStartBind = Boolean(hitEl.startBinding?.elementId);
          const hasEndBind = Boolean(hitEl.endBinding?.elementId);
          const isStraight = (hitEl.curveType || 'curved') === 'straight';

          if (nearStart || nearEnd) {
            state.selectedIds.clear();
            state.selectedIds.add(hitEl.id);
            syncUIWithSelection();
            state.drag = { mode: 'arrow-handle', arrow: hitEl, handle: nearStart ? 'start' : 'end' };
            updateInteractiveCursor();
            return;
          }

          if (hasStartBind && !hasEndBind) {
            state.selectedIds.clear();
            state.selectedIds.add(hitEl.id);
            syncUIWithSelection();
            state.drag = { mode: 'arrow-handle', arrow: hitEl, handle: 'end' };
            updateInteractiveCursor();
            return;
          }

          if (!hasStartBind && hasEndBind) {
            state.selectedIds.clear();
            state.selectedIds.add(hitEl.id);
            syncUIWithSelection();
            state.drag = { mode: 'arrow-handle', arrow: hitEl, handle: 'start' };
            updateInteractiveCursor();
            return;
          }

          if (hasStartBind && hasEndBind) {
            state.selectedIds.clear();
            state.selectedIds.add(hitEl.id);
            syncUIWithSelection();
            if (!isStraight) {
              state.drag = { mode: 'arrow-handle', arrow: hitEl, handle: 'curve' };
            }
            updateInteractiveCursor();
            return;
          }
        }

        if (shiftKey) {
          if (state.selectedIds.has(hitEl.id)) state.selectedIds.delete(hitEl.id);
          else state.selectedIds.add(hitEl.id);
        } else if (!state.selectedIds.has(hitEl.id)) {
          state.selectedIds.clear();
          state.selectedIds.add(hitEl.id);
        }

        if (altKey) {
          cloneSelectedForAltDrag();
        }

        const initialPositions = new Map();
        for (const id of state.selectedIds) {
          const item = state.elements.find(e => e.id === id);
          if (item) {
            initialPositions.set(id, {
              x: item.x,
              y: item.y,
              x2: item.x2,
              y2: item.y2
            });
          }
        }
        syncUIWithSelection();
        state.drag = {
          mode: 'move',
          startX: wx,
          startY: wy,
          initialPositions
        };
        updateInteractiveCursor();
        return;
      }

      // 4. Empty Canvas -> Marquee Selection
      state.selectedIds.clear();
      syncUIWithSelection();
      state.drag = {
        mode: 'marquee',
        startX: wx,
        startY: wy,
        currX: wx,
        currY: wy
      };
    }

    function pointerMoveWorld(wx, wy, opts = {}) {
      if (!state.drag) {
        state.hoveredResizeHandle = hitTestResizeHandles(wx, wy);
        state.hoveredPort = state.hoveredResizeHandle ? null : hitTestQuickPorts(wx, wy);
        state.hoveredArrowHandle = (state.hoveredResizeHandle || state.hoveredPort) ? null : hitTestArrowHandle(wx, wy);
        const elHit = hitTestElement(wx, wy);
        state.hoveredId = elHit ? elHit.id : null;
        updateInteractiveCursor();
        return;
      }

      const d = state.drag;
      if (d.mode === 'pan') {
        const sx = opts.screenX ?? wx * state.zoom;
        const sy = opts.screenY ?? wy * state.zoom;
        state.scrollX = d.origScrollX + (sx - d.startScreenX) / state.zoom;
        state.scrollY = d.origScrollY + (sy - d.startScreenY) / state.zoom;
        updateQuickHudPosition();
        return;
      }

      if (d.mode === 'resize') {
        const el = d.element;
        const dx = wx - d.startX;
        const dy = wy - d.startY;
        const minW = 64;
        const minH = 42;
        let nx = d.origX;
        let ny = d.origY;
        let nw = d.origW;
        let nh = d.origH;

        if (d.dir.includes('e')) nw = Math.max(minW, d.origW + dx);
        if (d.dir.includes('s')) nh = Math.max(minH, d.origH + dy);
        if (d.dir.includes('w')) {
          const possibleW = d.origW - dx;
          if (possibleW >= minW) {
            nw = possibleW;
            nx = d.origX + dx;
          }
        }
        if (d.dir.includes('n')) {
          const possibleH = d.origH - dy;
          if (possibleH >= minH) {
            nh = possibleH;
            ny = d.origY + dy;
          }
        }
        el.x = nx;
        el.y = ny;
        el.width = nw;
        el.height = nh;
        ShapeCache.invalidate(el);
        updateQuickHudPosition();
        return;
      }

      if (d.mode === 'laser') {
        state.laserPoints.push({ x: wx, y: wy, t: performance.now() });
        return;
      }

      if (d.mode === 'eraser') {
        const hit = hitTestElement(wx, wy);
        if (hit) deleteElementById(hit.id);
        return;
      }

      if (d.mode === 'freedraw') {
        const el = d.element;
        el.points.push([wx - el.x, wy - el.y]);
        return;
      }

      if (d.mode === 'draw-shape') {
        const el = d.element;
        el.x = Math.min(d.startX, wx);
        el.y = Math.min(d.startY, wy);
        el.width = Math.max(24, Math.abs(wx - d.startX));
        el.height = Math.max(24, Math.abs(wy - d.startY));
        ShapeCache.invalidate(el);
        return;
      }

      if (d.mode === 'arrow-handle') {
        const arrow = d.arrow;
        if (d.handle === 'start' || d.handle === 'end') {
          const isStart = d.handle === 'start';
          const otherBinding = isStart ? arrow.endBinding : arrow.startBinding;
          const fallbackPt = isStart
            ? { x: arrow.x2 || wx, y: arrow.y2 || wy }
            : { x: arrow.x || wx, y: arrow.y || wy };
          const targetShape = findMagneticShape(wx, wy, otherBinding?.elementId || null);

          let binding = null;
          let endPt = { x: wx, y: wy };
          if (targetShape) {
            binding = computeBindingForShape(targetShape, endPt);
            endPt = getBindingBoundaryPoint(targetShape, binding, fallbackPt, 4);
            state.snapPreview = { shapeId: targetShape.id, point: endPt, angle: binding.focusAngle };
          } else {
            state.snapPreview = null;
          }

          if (otherBinding?.elementId) {
            const otherShape = state.elements.find(e => e.id === otherBinding.elementId);
            if (otherShape) {
              const ocx = otherShape.x + otherShape.width / 2;
              const ocy = otherShape.y + otherShape.height / 2;
              const angleToTarget = Math.atan2(endPt.y - ocy, endPt.x - ocx);
              if (d.isNewArrow && !isStart) {
                otherBinding.focusAngle = angleToTarget;
              } else if (!otherBinding.side && typeof otherBinding.focusAngle === 'number') {
                const diff = Math.abs(Math.atan2(
                  Math.sin(angleToTarget - otherBinding.focusAngle),
                  Math.cos(angleToTarget - otherBinding.focusAngle)
                ));
                if (diff > Math.PI * 0.52) {
                  otherBinding.focusAngle = angleToTarget;
                }
              }
            }
          }

          if (isStart) {
            arrow.startBinding = binding;
            arrow.x = endPt.x;
            arrow.y = endPt.y;
          } else {
            arrow.endBinding = binding;
            arrow.x2 = endPt.x;
            arrow.y2 = endPt.y;
          }
        } else if (d.handle === 'curve') {
          const geom = getArrowGeometry(arrow);
          const { p0, p1 } = geom;
          const mx = (p0.x + p1.x) / 2;
          const my = (p0.y + p1.y) / 2;
          if ((arrow.curveType || 'curved') === 'elbow') {
            const baseMid = geom.elbowBaseMid || { x: mx, y: my };
            arrow.curveOffset = geom.elbowAxis === 'y' ? (wy - baseMid.y) * 2 : (wx - baseMid.x) * 2;
          } else if (arrow.curveType === 'straight') {
            arrow.curveOffset = 0;
          } else {
            const chordDx = p1.x - p0.x;
            const chordDy = p1.y - p0.y;
            const chordLen = Math.hypot(chordDx, chordDy) || 1;
            const nx = -chordDy / chordLen;
            const ny = chordDx / chordLen;
            const proj = (wx - mx) * nx + (wy - my) * ny;
            arrow.curveOffset = proj * 2;
          }
        }
        updateQuickHudPosition();
        return;
      }

      if (d.mode === 'port-wire') {
        d.currPt = { x: wx, y: wy };
        if (Math.hypot(wx - d.startPt.x, wy - d.startPt.y) > 8 / (state.zoom || 1)) {
          d.moved = true;
        }
        const targetShape = findMagneticShape(wx, wy, d.sourceEl.id);
        if (targetShape) {
          const binding = computeBindingForShape(targetShape, { x: wx, y: wy });
          const bPt = getBindingBoundaryPoint(targetShape, binding, d.startPt, 4);
          state.snapPreview = { shapeId: targetShape.id, point: bPt, angle: binding.focusAngle };
        } else {
          state.snapPreview = null;
        }
        return;
      }

      if (d.mode === 'move') {
        const dx = wx - d.startX;
        const dy = wy - d.startY;
        let singleNode = null;

        for (const [id, initPos] of d.initialPositions.entries()) {
          const el = state.elements.find(e => e.id === id);
          if (!el) continue;
          el.x = initPos.x + dx;
          el.y = initPos.y + dy;
          if (el.type === 'arrow') {
            if (!el.startBinding?.elementId && typeof initPos.x === 'number') el.x = initPos.x + dx;
            if (!el.endBinding?.elementId && typeof initPos.x2 === 'number') {
              el.x2 = initPos.x2 + dx;
              el.y2 = initPos.y2 + dy;
            }
          } else {
            ShapeCache.invalidate(el);
            if (d.initialPositions.size === 1 && isNodeElement(el)) {
              singleNode = el;
            }
          }
        }

        // Re-orient unpinned bindings when connected nodes cross past each other
        for (const el of state.elements) {
          if (el.type !== 'arrow') continue;
          const sId = el.startBinding?.elementId;
          const eId = el.endBinding?.elementId;
          if (!sId && !eId) continue;
          if (!d.initialPositions.has(sId) && !d.initialPositions.has(eId)) continue;

          const sShape = sId ? state.elements.find(n => n.id === sId) : null;
          const eShape = eId ? state.elements.find(n => n.id === eId) : null;
          const sCenter = sShape
            ? { x: sShape.x + sShape.width / 2, y: sShape.y + sShape.height / 2 }
            : { x: el.x, y: el.y };
          const eCenter = eShape
            ? { x: eShape.x + eShape.width / 2, y: eShape.y + eShape.height / 2 }
            : { x: el.x2 ?? el.x, y: el.y2 ?? el.y };

          if (sShape && !el.startBinding.side && typeof el.startBinding.focusAngle === 'number') {
            const ang = Math.atan2(eCenter.y - sCenter.y, eCenter.x - sCenter.x);
            const diff = Math.abs(Math.atan2(Math.sin(ang - el.startBinding.focusAngle), Math.cos(ang - el.startBinding.focusAngle)));
            if (diff > Math.PI * 0.52) el.startBinding.focusAngle = ang;
          }
          if (eShape && !el.endBinding.side && typeof el.endBinding.focusAngle === 'number') {
            const ang = Math.atan2(sCenter.y - eCenter.y, sCenter.x - eCenter.x);
            const diff = Math.abs(Math.atan2(Math.sin(ang - el.endBinding.focusAngle), Math.cos(ang - el.endBinding.focusAngle)));
            if (diff > Math.PI * 0.52) el.endBinding.focusAngle = ang;
          }
        }

        if (singleNode) {
          const splitArrow = findSplitTargetArrow(singleNode);
          state.splitTargetArrowId = splitArrow ? splitArrow.id : null;
        } else {
          state.splitTargetArrowId = null;
        }
        updateQuickHudPosition();
        return;
      }

      if (d.mode === 'marquee') {
        d.currX = wx;
        d.currY = wy;
        const x1 = Math.min(d.startX, d.currX);
        const y1 = Math.min(d.startY, d.currY);
        const x2 = Math.max(d.startX, d.currX);
        const y2 = Math.max(d.startY, d.currY);
        state.selectedIds.clear();
        for (const el of state.elements) {
          const ex1 = el.type === 'arrow' ? Math.min(el.x, el.x2 ?? el.x) : el.x;
          const ey1 = el.type === 'arrow' ? Math.min(el.y, el.y2 ?? el.y) : el.y;
          const ex2 = el.type === 'arrow' ? Math.max(el.x, el.x2 ?? el.x) : el.x + (el.width || 0);
          const ey2 = el.type === 'arrow' ? Math.max(el.y, el.y2 ?? el.y) : el.y + (el.height || 0);
          if (ex2 >= x1 && ex1 <= x2 && ey2 >= y1 && ey1 <= y2) {
            state.selectedIds.add(el.id);
          }
        }
        syncUIWithSelection();
      }
    }

    function pointerUpWorld(wx, wy) {
      if (!state.drag) return;
      const d = state.drag;
      state.drag = null;
      state.snapPreview = null;
      updateInteractiveCursor();

      if (d.mode === 'draw-shape') {
        const el = d.element;
        if (el.width < 32 && el.height < 32) {
          el.width = el.type === 'diamond' ? 148 : 144;
          el.height = el.type === 'diamond' ? 86 : 68;
          el.text = el.type === 'diamond' ? 'Decision?' : 'Node';
          ShapeCache.invalidate(el);
        }
        if (!state.toolLocked) setTool('select');
        syncUIWithSelection();
        return;
      }

      if (d.mode === 'arrow-handle') {
        if (!state.toolLocked && state.activeTool === 'arrow') {
          setTool('select');
        }
        discardRedundantUndoSnapshot();
        syncUIWithSelection();
        return;
      }

      if (d.mode === 'port-wire') {
        if (!d.moved) {
          chainNodeFrom(d.sourceEl, d.dir, null, true);
        } else {
          pushHistory();
          const targetShape = findMagneticShape(wx, wy, d.sourceEl.id);
          const sc = { x: d.sourceEl.x + d.sourceEl.width / 2, y: d.sourceEl.y + d.sourceEl.height / 2 };
          const outAng = Math.atan2(wy - sc.y, wx - sc.x);

          if (targetShape) {
            const endBind = computeBindingForShape(targetShape, { x: wx, y: wy });
            const arr = createElement('arrow', {
              x: d.startPt.x,
              y: d.startPt.y,
              x2: wx,
              y2: wy,
              strokeColor: d.sourceEl.strokeColor,
              startBinding: { elementId: d.sourceEl.id, focusAngle: outAng, side: d.dir, gap: 4 },
              endBinding: endBind
            });
            state.elements.push(arr);
            state.selectedIds.clear();
            state.selectedIds.add(arr.id);
          } else {
            const newW = 144;
            const newH = 68;
            const newNode = createElement(d.sourceEl.type === 'text' ? 'rectangle' : d.sourceEl.type, {
              x: wx - newW / 2,
              y: wy - newH / 2,
              width: newW,
              height: newH,
              strokeColor: d.sourceEl.strokeColor,
              text: 'Connected Node'
            });
            const inAng = Math.atan2(sc.y - wy, sc.x - wx);
            const arr = createElement('arrow', {
              x: d.startPt.x,
              y: d.startPt.y,
              x2: wx,
              y2: wy,
              strokeColor: d.sourceEl.strokeColor,
              startBinding: { elementId: d.sourceEl.id, focusAngle: outAng, side: d.dir, gap: 4 },
              endBinding: { elementId: newNode.id, focusAngle: inAng, side: angleToSide(inAng), gap: 4 }
            });
            state.elements.push(newNode, arr);
            state.selectedIds.clear();
            state.selectedIds.add(newNode.id);
            startInlineEditing(newNode);
          }
          syncUIWithSelection();
        }
        return;
      }

      if (d.mode === 'move' || d.mode === 'resize') {
        if (d.mode === 'move' && state.splitTargetArrowId && state.selectedIds.size === 1) {
          const nodeId = Array.from(state.selectedIds)[0];
          const node = state.elements.find(e => e.id === nodeId);
          if (node) trySplitArrowWithNode(node);
        }
        state.splitTargetArrowId = null;
        discardRedundantUndoSnapshot();
        syncUIWithSelection();
      }
    }

    function deleteElementById(id) {
      state.elements = state.elements.filter(el => el.id !== id);
      for (const el of state.elements) {
        if (el.type === 'arrow') {
          if (el.startBinding?.elementId === id) el.startBinding = null;
          if (el.endBinding?.elementId === id) el.endBinding = null;
        }
      }
      state.selectedIds.delete(id);
      ShapeCache.invalidate(id);
      syncUIWithSelection();
    }

    function deleteSelection() {
      if (state.selectedIds.size === 0) return;
      pushHistory();
      const ids = Array.from(state.selectedIds);
      for (const id of ids) deleteElementById(id);
    }

    function duplicateSelection() {
      const selected = state.elements.filter(el => state.selectedIds.has(el.id));
      if (selected.length === 0) return [];
      pushHistory();
      const clones = cloneElementsWithBindings(selected, 28, 28);
      syncUIWithSelection();
      return clones;
    }

    /* -------------------------------------------------------------------------
     * 13. Inline Text Editor & Keyboard Shortcuts
     * ------------------------------------------------------------------------- */
    function startInlineEditing(el) {
      if (!el || el.type === 'arrow' || typeof document === 'undefined') return;
      state.editingId = el.id;
      state.editingPreSnap = snapshotScene();
      const wrap = document.getElementById('inlineEditorWrap');
      const ta = document.getElementById('inlineTextEditor');
      if (!wrap || !ta) return;

      const cx = el.x + (el.width || 0) / 2;
      const cy = el.y + (el.height || 0) / 2;

      const scr = worldToScreen(cx, cy);
      const fontSize = (Number(el.fontSize) || 16) * state.zoom;
      const w = Math.max(120, ((el.width || 120) - 12) * state.zoom);
      const h = Math.max(36, ((el.height || 44) - 8) * state.zoom);

      wrap.style.display = 'block';
      wrap.style.left = `${scr.x - w / 2}px`;
      wrap.style.top = `${scr.y - h / 2}px`;
      ta.style.width = `${w}px`;
      ta.style.height = `${h}px`;
      ta.style.fontFamily = FONT_MAP[normalizeFontFamily(el.fontFamily)];
      ta.style.fontSize = `${fontSize}px`;
      ta.style.color = resolveStrokeColor(el.strokeColor, state.canvasBg);
      ta.value = el.text || '';
      ta.focus?.();
      ta.select?.();
    }

    function commitInlineEditor() {
      if (!state.editingId) return;
      const el = state.elements.find(e => e.id === state.editingId);
      const wrap = typeof document !== 'undefined' ? document.getElementById('inlineEditorWrap') : null;
      const ta = typeof document !== 'undefined' ? document.getElementById('inlineTextEditor') : null;
      if (el && ta) {
        if (state.editingPreSnap && ta.value !== el.text) {
          pushHistory(state.editingPreSnap);
        }
        autoFitElementToText(el, ta.value);
      }
      state.editingId = null;
      state.editingPreSnap = null;
      if (wrap) wrap.style.display = 'none';
    }

    function setTool(tool) {
      state.activeTool = tool;
      if (typeof document === 'undefined') return;
      document.querySelectorAll('#bottomToolDock [data-tool]').forEach(btn => {
        btn.classList.toggle('active', btn.getAttribute('data-tool') === tool);
      });
      updateInteractiveCursor();
    }

    function toggleToolLock(forceVal) {
      state.toolLocked = typeof forceVal === 'boolean' ? forceVal : !state.toolLocked;
      if (typeof document !== 'undefined') {
        const btn = document.getElementById('toolLockBtn');
        if (btn) btn.classList.toggle('active', state.toolLocked);
      }
      return state.toolLocked;
    }

    function handleKeyDown(e) {
      if (state.editingTabId) return;
      const isEditing = Boolean(state.editingId);
      if (isEditing) {
        if (e.key === 'Escape') {
          e.preventDefault?.();
          commitInlineEditor();
          return;
        }
        if (e.key === 'Tab') {
          e.preventDefault?.();
          const editedEl = state.elements.find(el => el.id === state.editingId);
          commitInlineEditor();
          if (editedEl && isNodeElement(editedEl)) {
            chainNodeFrom(editedEl, 'right', null, true);
          }
          return;
        }
        return;
      }

      if (e.key === 'Escape') {
        closeAllDropdowns();
        if (state.selectedIds.size > 0) {
          state.selectedIds.clear();
          syncUIWithSelection();
        }
        if (state.activeTool !== 'select' && !state.toolLocked) {
          setTool('select');
        }
        return;
      }

      const meta = e.metaKey || e.ctrlKey;
      const key = String(e.key || '').toLowerCase();

      if (e.altKey && !meta) {
        if (/^[1-9]$/.test(String(e.key || ''))) {
          const idx = Number(e.key) - 1;
          if (state.tabs[idx]) {
            e.preventDefault?.();
            switchCanvasTab(state.tabs[idx].id);
            return;
          }
        }
        if (e.key === '[' || e.code === 'BracketLeft') {
          e.preventDefault?.();
          stepCanvasTab(-1);
          return;
        }
        if (e.key === ']' || e.code === 'BracketRight') {
          e.preventDefault?.();
          stepCanvasTab(1);
          return;
        }
        if (key === 't' || e.code === 'KeyT') {
          e.preventDefault?.();
          createCanvasTab();
          return;
        }
      }

      if (meta && key === '\\') {
        e.preventDefault?.();
        toggleSidebar();
        return;
      }
      if (meta && key === 'z') {
        e.preventDefault?.();
        if (e.shiftKey) redo();
        else undo();
        return;
      }
      if (meta && key === 'd') {
        e.preventDefault?.();
        duplicateSelection();
        return;
      }
      if (meta && key === 'a') {
        e.preventDefault?.();
        state.selectedIds = new Set(state.elements.map(el => el.id));
        syncUIWithSelection();
        return;
      }
      if (meta && key === 'c') {
        e.preventDefault?.();
        if (e.shiftKey) {
          copy2xPng();
          return;
        }
        state.clipboard = JSON.parse(JSON.stringify(
          state.elements.filter(el => state.selectedIds.has(el.id))
        ));
        state.pasteCount = 0;
        return;
      }
      if (meta && key === 'v') {
        e.preventDefault?.();
        if (state.clipboard.length > 0) {
          pushHistory();
          state.pasteCount += 1;
          const offset = 28 * state.pasteCount;
          cloneElementsWithBindings(state.clipboard, offset, offset);
          syncUIWithSelection();
        }
        return;
      }

      if (e.key === 'Tab') {
        const selectedNodes = Array.from(state.selectedIds)
          .map(id => state.elements.find(el => el.id === id))
          .filter(el => el && isNodeElement(el));
        if (selectedNodes.length === 1) {
          e.preventDefault?.();
          chainNodeFrom(selectedNodes[0], 'right', null, true);
          return;
        }
      }

      if (e.key === 'Backspace' || e.key === 'Delete') {
        e.preventDefault?.();
        deleteSelection();
        return;
      }

      const shortcutMap = {
        '1': 'select',
        'v': 'select',
        'h': 'hand',
        '2': 'rectangle',
        'r': 'rectangle',
        '3': 'diamond',
        'd': 'diamond',
        '4': 'ellipse',
        'o': 'ellipse',
        '5': 'arrow',
        '6': 'arrow',
        'a': 'arrow',
        '7': 'freedraw',
        'p': 'freedraw',
        '8': 'text',
        't': 'text',
        '9': 'sticky',
        'n': 'sticky',
        'k': 'laser',
        '0': 'eraser',
        'e': 'eraser'
      };

      if (key === 'q') {
        e.preventDefault?.();
        toggleToolLock();
        return;
      }

      if (shortcutMap[key]) {
        e.preventDefault?.();
        setTool(shortcutMap[key]);
      }
    }

    /* -------------------------------------------------------------------------
     * 14. Studio Exports (2x Retina PNG, Clipboard, 60fps WebM Video, JSON)
     * ------------------------------------------------------------------------- */
    const ALLOWED_ELEMENT_TYPES = new Set(['rectangle', 'ellipse', 'diamond', 'arrow', 'line', 'freedraw', 'text', 'sticky']);
    const ALLOWED_FLOW_MODES = new Set(['comets', 'pulses', 'neon', 'dashed']);

    function getDiagramExportBounds(padding = 48) {
      if (state.elements.length === 0) {
        return { x: 0, y: 0, width: 800, height: 500 };
      }
      let minX = Infinity;
      let minY = Infinity;
      let maxX = -Infinity;
      let maxY = -Infinity;
      const elementsMap = getElementMap();

      for (const el of state.elements) {
        if (el.type === 'arrow') {
          const geom = getArrowGeometry(el, elementsMap);
          for (const pt of geom.samples) {
            minX = Math.min(minX, pt.x);
            minY = Math.min(minY, pt.y);
            maxX = Math.max(maxX, pt.x);
            maxY = Math.max(maxY, pt.y);
          }
        } else if (el.type === 'freedraw') {
          for (const p of (el.points || [[0, 0]])) {
            minX = Math.min(minX, el.x + p[0]);
            minY = Math.min(minY, el.y + p[1]);
            maxX = Math.max(maxX, el.x + p[0]);
            maxY = Math.max(maxY, el.y + p[1]);
          }
        } else {
          minX = Math.min(minX, el.x);
          minY = Math.min(minY, el.y);
          maxX = Math.max(maxX, el.x + (el.width || 0));
          maxY = Math.max(maxY, el.y + (el.height || 0));
        }
      }

      return {
        x: Math.floor(minX - padding),
        y: Math.floor(minY - padding),
        width: Math.max(120, Math.ceil(maxX - minX + padding * 2)),
        height: Math.max(120, Math.ceil(maxY - minY + padding * 2))
      };
    }

    function renderSceneToExportCtx(offCtx, offCanvas, bounds, scale, timeSec) {
      offCtx.save();
      offCtx.fillStyle = state.canvasBg;
      offCtx.fillRect(0, 0, offCanvas.width, offCanvas.height);
      offCtx.scale(scale, scale);
      offCtx.translate(-bounds.x, -bounds.y);
      renderScenePasses(offCtx, timeSec, { canvasBg: state.canvasBg, forExport: true });
      offCtx.restore();
    }

    function renderCroppedOffscreenCanvas(scale = 2, timeSec = performance.now() / 1000) {
      const bounds = getDiagramExportBounds(48);
      const offCanvas = document.createElement('canvas');
      offCanvas.width = bounds.width * scale;
      offCanvas.height = bounds.height * scale;
      const offCtx = offCanvas.getContext('2d');
      renderSceneToExportCtx(offCtx, offCanvas, bounds, scale, timeSec);
      return offCanvas;
    }

    function downloadBlob(blob, filename) {
      if (!blob || typeof URL === 'undefined' || typeof document === 'undefined') return;
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    }

    function showToast(msg) {
      if (typeof document === 'undefined') return;
      const t = document.getElementById('studioToast');
      if (!t) return;
      t.textContent = msg;
      t.classList.add('show');
      clearTimeout(t._timer);
      t._timer = setTimeout(() => t.classList.remove('show'), 2200);
    }

    function save2xPng() {
      closeAllDropdowns();
      const offCanvas = renderCroppedOffscreenCanvas(2);
      offCanvas.toBlob(blob => {
        if (!blob) return;
        downloadBlob(blob, 'excaliflow-2x.png');
        showToast('Saved 2x Retina PNG (excaliflow-2x.png)');
      }, 'image/png');
    }

    async function copy2xPng() {
      closeAllDropdowns();
      const offCanvas = renderCroppedOffscreenCanvas(2);
      offCanvas.toBlob(async blob => {
        if (!blob) return;
        try {
          await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
          showToast('Copied 2x Retina PNG to Clipboard');
        } catch (err) {
          showToast('Clipboard write unavailable in this context');
        }
      }, 'image/png');
    }

    function recordWebmVideo() {
      closeAllDropdowns();
      if (state.isRecording) {
        showToast('Recording already in progress...');
        return;
      }
      if (typeof MediaRecorder === 'undefined') {
        showToast('MediaRecorder is not supported in this browser');
        return;
      }
      state.isRecording = true;
      const bounds = getDiagramExportBounds(48);
      const scale = 2;
      const offCanvas = document.createElement('canvas');
      offCanvas.width = bounds.width * scale;
      offCanvas.height = bounds.height * scale;
      const offCtx = offCanvas.getContext('2d');

      const stream = offCanvas.captureStream(60);
      const mimeType = MediaRecorder.isTypeSupported('video/webm;codecs=vp9')
        ? 'video/webm;codecs=vp9'
        : 'video/webm';
      const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 8_000_000 });
      const chunks = [];

      recorder.ondataavailable = e => {
        if (e.data && e.data.size > 0) chunks.push(e.data);
      };
      recorder.onerror = () => {
        state.isRecording = false;
      };
      recorder.onstop = () => {
        state.isRecording = false;
        const blob = new Blob(chunks, { type: 'video/webm' });
        downloadBlob(blob, 'excaliflow-flow.webm');
        showToast('Exported 60fps Video Loop (excaliflow-flow.webm)');
      };

      showToast('Recording 4s 60fps WebM Loop...');
      recorder.start();

      const totalFrames = 240;
      let frame = 0;
      const baseTime = performance.now() / 1000;
      const interval = setInterval(() => {
        const simTime = baseTime + frame / 60;
        renderSceneToExportCtx(offCtx, offCanvas, bounds, scale, simTime);

        frame++;
        if (frame >= totalFrames) {
          clearInterval(interval);
          recorder.stop();
        }
      }, 1000 / 60);
    }

    function sanitizeElementsArray(rawElements) {
      if (!Array.isArray(rawElements)) return [];
      const validRaw = rawElements.filter(
        el => el && !el.isDeleted && typeof el.type === 'string' && ALLOWED_ELEMENT_TYPES.has(el.type)
      );
      return validRaw.map(el => {
        syncIdCounterWithId(el.id);
        const normType = el.type === 'line' ? 'arrow' : el.type;
        let resolvedX2 = el.x2;
        let resolvedY2 = el.y2;
        if (normType === 'arrow' && typeof resolvedX2 !== 'number' && Array.isArray(el.points) && el.points.length > 1) {
          const lastPt = el.points[el.points.length - 1];
          if (Array.isArray(lastPt) && lastPt.length >= 2) {
            resolvedX2 = (Number(el.x) || 0) + (Number(lastPt[0]) || 0);
            resolvedY2 = (Number(el.y) || 0) + (Number(lastPt[1]) || 0);
          }
        }
        return createElement(normType, {
          ...el,
          x2: resolvedX2,
          y2: resolvedY2,
          text: normType === 'arrow' ? '' : String(el.text ?? '')
        });
      });
    }

    /* -------------------------------------------------------------------------
     * 14b. Multi-Canvas Workspace Tabs & LocalStorage Auto-Save
     * ------------------------------------------------------------------------- */
    const WORKSPACE_STORAGE_KEY = 'excaliflow_workspace_v1';
    let workspaceSaveTimer = null;

    function getBrowserStorage() {
      try {
        if (typeof window !== 'undefined' && window.localStorage) return window.localStorage;
        if (typeof localStorage !== 'undefined') return localStorage;
      } catch (err) {
        return null;
      }
      return null;
    }

    function syncActiveTabFromState() {
      if (state.tabs.length === 0) return;
      const tab = state.tabs.find(t => t.id === state.activeTabId) || state.tabs[0];
      if (!tab) return;
      state.activeTabId = tab.id;
      tab.elements = state.elements;
      tab.scrollX = state.scrollX;
      tab.scrollY = state.scrollY;
      tab.zoom = state.zoom;
      tab.canvasBg = state.canvasBg;
      tab.flowEnabled = state.flowEnabled;
      tab.flowMode = state.flowMode;
      tab.flowSpeed = state.flowSpeed;
      tab.history = {
        undoStack: [...state.history.undoStack],
        redoStack: [...state.history.redoStack]
      };
    }

    function ensureInitialTab(defaultName = 'AI Agent Swarm') {
      if (state.tabs.length > 0) {
        if (!state.activeTabId || !state.tabs.some(t => t.id === state.activeTabId)) {
          state.activeTabId = state.tabs[0].id;
        }
        return state.tabs.find(t => t.id === state.activeTabId);
      }
      const tab = {
        id: nextId('tab'),
        name: defaultName,
        elements: state.elements,
        scrollX: state.scrollX,
        scrollY: state.scrollY,
        zoom: state.zoom,
        canvasBg: state.canvasBg,
        flowEnabled: state.flowEnabled,
        flowMode: state.flowMode,
        flowSpeed: state.flowSpeed,
        history: {
          undoStack: [...state.history.undoStack],
          redoStack: [...state.history.redoStack]
        }
      };
      state.tabs.push(tab);
      state.activeTabId = tab.id;
      renderCanvasTabs();
      return tab;
    }

    function applyTabToState(tab) {
      if (!tab) return;
      state.activeTabId = tab.id;
      state.elements = Array.isArray(tab.elements) ? tab.elements : [];
      state.scrollX = Number.isFinite(tab.scrollX) ? tab.scrollX : 0;
      state.scrollY = Number.isFinite(tab.scrollY) ? tab.scrollY : 0;
      state.zoom = Number.isFinite(tab.zoom) && tab.zoom > 0 ? tab.zoom : 1;
      state.flowEnabled = tab.flowEnabled !== false;
      state.flowMode = ALLOWED_FLOW_MODES.has(tab.flowMode) ? tab.flowMode : 'comets';
      state.flowSpeed = Number.isFinite(Number(tab.flowSpeed)) && Number(tab.flowSpeed) > 0
        ? Math.max(0.2, Math.min(5.0, Number(tab.flowSpeed)))
        : 1.0;
      state.history = {
        undoStack: Array.isArray(tab.history?.undoStack) ? [...tab.history.undoStack] : [],
        redoStack: Array.isArray(tab.history?.redoStack) ? [...tab.history.redoStack] : []
      };
      state.selectedIds.clear();
      state.activePulses = [];
      ShapeCache.clear();
      setCanvasBackground(tab.canvasBg === '#000000' ? '#000000' : '#ffffff');
      syncZoomReadout();
      if (typeof document !== 'undefined') {
        document.querySelectorAll('#flowModeGrid [data-flow-mode]').forEach(b => {
          b.classList.toggle('active', b.getAttribute('data-flow-mode') === state.flowMode);
        });
        document.querySelectorAll('#flowSpeedRow [data-flow-speed]').forEach(b => {
          b.classList.toggle('active', Number(b.getAttribute('data-flow-speed')) === state.flowSpeed);
        });
      }
      syncUIWithSelection();
      renderCanvasTabs();
    }

    function serializeWorkspace() {
      ensureInitialTab();
      syncActiveTabFromState();
      return {
        type: 'excaliflow',
        version: 2,
        source: 'Excaliflow',
        activeTabId: state.activeTabId,
        elements: state.elements,
        appState: {
          viewBackgroundColor: state.canvasBg,
          scrollX: state.scrollX,
          scrollY: state.scrollY,
          zoom: { value: state.zoom },
          flowEnabled: state.flowEnabled,
          flowMode: state.flowMode,
          flowSpeed: state.flowSpeed
        },
        tabs: state.tabs.map(t => ({
          id: t.id,
          name: t.name,
          elements: t.elements,
          scrollX: t.scrollX,
          scrollY: t.scrollY,
          zoom: t.zoom,
          canvasBg: t.canvasBg,
          flowEnabled: t.flowEnabled,
          flowMode: t.flowMode,
          flowSpeed: t.flowSpeed
        }))
      };
    }

    function saveWorkspaceToStorage() {
      if (state.tabs.length === 0) return false;
      const storage = getBrowserStorage();
      if (!storage || typeof storage.setItem !== 'function') return false;
      try {
        storage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(serializeWorkspace()));
        return true;
      } catch (err) {
        return false;
      }
    }

    function scheduleWorkspaceSave() {
      if (state.tabs.length === 0) return;
      syncActiveTabFromState();
      clearTimeout(workspaceSaveTimer);
      workspaceSaveTimer = setTimeout(() => {
        saveWorkspaceToStorage();
      }, 150);
    }

    function restoreWorkspaceData(data) {
      if (!data || !Array.isArray(data.tabs) || data.tabs.length === 0) return false;
      const restoredTabs = [];
      for (let i = 0; i < data.tabs.length; i++) {
        const rawTab = data.tabs[i];
        if (!rawTab || typeof rawTab !== 'object') continue;
        const tabId = typeof rawTab.id === 'string' && rawTab.id.trim() ? rawTab.id.trim() : nextId('tab');
        syncIdCounterWithId(tabId);
        const name = typeof rawTab.name === 'string' && rawTab.name.trim()
          ? rawTab.name.trim().slice(0, 48)
          : `Canvas ${i + 1}`;
        const elements = sanitizeElementsArray(rawTab.elements || []);
        restoredTabs.push({
          id: tabId,
          name,
          elements,
          scrollX: Number.isFinite(rawTab.scrollX) ? rawTab.scrollX : 0,
          scrollY: Number.isFinite(rawTab.scrollY) ? rawTab.scrollY : 0,
          zoom: Number.isFinite(rawTab.zoom) && rawTab.zoom > 0 ? Math.max(0.25, Math.min(3.0, rawTab.zoom)) : 1,
          canvasBg: rawTab.canvasBg === '#000000' ? '#000000' : '#ffffff',
          flowEnabled: rawTab.flowEnabled !== false,
          flowMode: ALLOWED_FLOW_MODES.has(rawTab.flowMode) ? rawTab.flowMode : 'comets',
          flowSpeed: Number.isFinite(Number(rawTab.flowSpeed)) && Number(rawTab.flowSpeed) > 0
            ? Math.max(0.2, Math.min(5.0, Number(rawTab.flowSpeed)))
            : 1.0,
          history: { undoStack: [], redoStack: [] }
        });
      }
      if (restoredTabs.length === 0) return false;
      state.tabs = restoredTabs;
      const targetActive = restoredTabs.find(t => t.id === data.activeTabId) || restoredTabs[0];
      applyTabToState(targetActive);
      return true;
    }

    function loadWorkspaceFromStorage() {
      const storage = getBrowserStorage();
      if (!storage || typeof storage.getItem !== 'function') return false;
      try {
        const raw = storage.getItem(WORKSPACE_STORAGE_KEY);
        if (!raw) return false;
        const data = JSON.parse(raw);
        return restoreWorkspaceData(data);
      } catch (err) {
        return false;
      }
    }

    let lastRenderedTabSig = '';
    let lastScrolledActiveTabId = null;

    function renderCanvasTabs(force = false) {
      if (typeof document === 'undefined') return;
      const activeIdx = Math.max(0, state.tabs.findIndex(t => t.id === state.activeTabId));
      const activeTab = state.tabs[activeIdx] || state.tabs[0];

      const labelEl = document.getElementById('activeCanvasLabel');
      if (labelEl && activeTab) labelEl.textContent = activeTab.name;
      const countEl = document.getElementById('activeCanvasCount');
      if (countEl) countEl.textContent = `${activeIdx + 1}/${Math.max(1, state.tabs.length)}`;

      const strip = document.getElementById('canvasTabStrip');
      if (!strip || typeof strip.appendChild !== 'function') return;

      const sig = state.tabs.map(t => {
        const elCount = (t.id === state.activeTabId ? state.elements : t.elements)?.length || 0;
        return `${t.id}:${t.name}:${elCount}`;
      }).join('|') + '::' + state.activeTabId + '::' + (state.editingTabId || '');

      if (!force && sig === lastRenderedTabSig && strip.children && strip.children.length === state.tabs.length) {
        return;
      }
      lastRenderedTabSig = sig;

      strip.innerHTML = '';
      if (Array.isArray(strip.children)) strip.children.length = 0;

      for (let i = 0; i < state.tabs.length; i++) {
        const tab = state.tabs[i];
        const isActive = tab.id === state.activeTabId;
        const pill = document.createElement('div');
        pill.className = `canvas-tab-pill${isActive ? ' active' : ''}`;
        pill.setAttribute?.('role', 'tab');
        pill.setAttribute?.('aria-selected', isActive ? 'true' : 'false');
        pill.setAttribute?.('data-tab-id', tab.id);
        pill.title = `${tab.name} (Click to switch · Double-click to rename · ⌥${i + 1})`;

        const numBadge = document.createElement('span');
        numBadge.className = 'tab-num-badge';
        numBadge.textContent = String(i + 1);
        pill.appendChild?.(numBadge);

        if (state.editingTabId === tab.id) {
          const input = document.createElement('input');
          input.type = 'text';
          input.className = 'tab-rename-input';
          input.value = tab.name;
          input.addEventListener?.('click', e => e.stopPropagation?.());
          input.addEventListener?.('keydown', e => {
            e.stopPropagation?.();
            if (e.key === 'Enter') {
              e.preventDefault?.();
              renameCanvasTab(tab.id, input.value);
            } else if (e.key === 'Escape') {
              e.preventDefault?.();
              state.editingTabId = null;
              renderCanvasTabs(true);
            }
          });
          input.addEventListener?.('blur', () => {
            if (state.editingTabId === tab.id) {
              renameCanvasTab(tab.id, input.value);
            }
          });
          pill.appendChild?.(input);
          setTimeout(() => {
            input.focus?.();
            input.select?.();
          }, 0);
        } else {
          const label = document.createElement('span');
          label.className = 'tab-label';
          label.textContent = tab.name;
          pill.appendChild?.(label);

          if (state.tabs.length > 1) {
            const closeBtn = document.createElement('span');
            closeBtn.className = 'tab-close';
            closeBtn.textContent = '×';
            closeBtn.title = `Close ${tab.name}`;
            closeBtn.addEventListener?.('click', e => {
              e.stopPropagation?.();
              closeCanvasTab(tab.id);
            });
            pill.appendChild?.(closeBtn);
          }

          pill.addEventListener?.('click', () => {
            if (state.activeTabId !== tab.id) {
              switchCanvasTab(tab.id);
            }
          });
          pill.addEventListener?.('dblclick', e => {
            e.stopPropagation?.();
            state.editingTabId = tab.id;
            renderCanvasTabs(true);
          });
        }

        strip.appendChild?.(pill);
        if (isActive && state.activeTabId !== lastScrolledActiveTabId) {
          lastScrolledActiveTabId = state.activeTabId;
          setTimeout(() => {
            pill.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
          }, 0);
        }
      }

      // Populate top-left #canvasesDropdown menu for quick vertical switching
      const dropdown = document.getElementById('canvasesDropdown');
      if (dropdown && typeof dropdown.appendChild === 'function') {
        dropdown.innerHTML = '';
        if (Array.isArray(dropdown.children)) dropdown.children.length = 0;
        for (let i = 0; i < state.tabs.length; i++) {
          const tab = state.tabs[i];
          const isActive = tab.id === state.activeTabId;
          const elCount = (isActive ? state.elements : tab.elements)?.length || 0;
          const item = document.createElement('button');
          item.className = `ui-btn menu-item${isActive ? ' active' : ''}`;
          const leftSpan = document.createElement('span');
          leftSpan.textContent = `${i + 1}. ${tab.name}`;
          const rightSpan = document.createElement('span');
          rightSpan.textContent = `${elCount} item${elCount === 1 ? '' : 's'} · ⌥${i + 1}`;
          item.appendChild?.(leftSpan);
          item.appendChild?.(rightSpan);
          item.addEventListener?.('click', e => {
            e.stopPropagation?.();
            closeAllDropdowns();
            if (!isActive) switchCanvasTab(tab.id);
          });
          dropdown.appendChild?.(item);
        }
        const sep = document.createElement('div');
        sep.className = 'menu-sep';
        dropdown.appendChild?.(sep);

        const newBtn = document.createElement('button');
        newBtn.className = 'ui-btn menu-item';
        const nl = document.createElement('span');
        nl.textContent = '+ New Blank Canvas';
        const nr = document.createElement('span');
        nr.textContent = '⌥T';
        newBtn.appendChild?.(nl);
        newBtn.appendChild?.(nr);
        newBtn.addEventListener?.('click', e => {
          e.stopPropagation?.();
          closeAllDropdowns();
          createCanvasTab();
        });
        dropdown.appendChild?.(newBtn);

        const forkBtn = document.createElement('button');
        forkBtn.className = 'ui-btn menu-item';
        const fl = document.createElement('span');
        fl.textContent = '⧉ Duplicate Current Canvas';
        const fr = document.createElement('span');
        fr.textContent = 'Fork';
        forkBtn.appendChild?.(fl);
        forkBtn.appendChild?.(fr);
        forkBtn.addEventListener?.('click', e => {
          e.stopPropagation?.();
          closeAllDropdowns();
          duplicateCanvasTab();
        });
        dropdown.appendChild?.(forkBtn);
      }
    }

    function createCanvasTab(opts = {}) {
      if (state.editingId) commitInlineEditor();
      ensureInitialTab();
      syncActiveTabFromState();
      const nextIndex = state.tabs.length + 1;
      const name = (typeof opts.name === 'string' && opts.name.trim())
        ? opts.name.trim().slice(0, 48)
        : `Canvas ${nextIndex}`;
      const newTab = {
        id: nextId('tab'),
        name,
        elements: Array.isArray(opts.elements) ? sanitizeElementsArray(opts.elements) : [],
        scrollX: Number.isFinite(opts.scrollX) ? opts.scrollX : 0,
        scrollY: Number.isFinite(opts.scrollY) ? opts.scrollY : 0,
        zoom: Number.isFinite(opts.zoom) && opts.zoom > 0 ? opts.zoom : 1,
        canvasBg: opts.canvasBg === '#000000' ? '#000000' : state.canvasBg,
        flowEnabled: opts.flowEnabled !== undefined ? Boolean(opts.flowEnabled) : state.flowEnabled,
        flowMode: ALLOWED_FLOW_MODES.has(opts.flowMode) ? opts.flowMode : state.flowMode,
        flowSpeed: Number.isFinite(Number(opts.flowSpeed)) ? Number(opts.flowSpeed) : state.flowSpeed,
        history: { undoStack: [], redoStack: [] }
      };
      state.tabs.push(newTab);
      applyTabToState(newTab);
      if (opts.templateName) {
        loadTemplate(opts.templateName);
        state.history.undoStack = [];
        updateHeaderButtons();
      }
      renderCanvasTabs(true);
      saveWorkspaceToStorage();
      showToast(`Created "${newTab.name}" (${state.tabs.length}/${state.tabs.length})`);
      return newTab;
    }

    function duplicateCanvasTab(tabId = state.activeTabId) {
      if (state.editingId) commitInlineEditor();
      ensureInitialTab();
      syncActiveTabFromState();
      const sourceIdx = state.tabs.findIndex(t => t.id === tabId);
      const sourceTab = sourceIdx >= 0 ? state.tabs[sourceIdx] : state.tabs[state.tabs.length - 1];
      if (!sourceTab) return null;

      const idMap = new Map();
      const clonedElements = sourceTab.elements.map(el => {
        const newId = nextId(el.type);
        idMap.set(el.id, newId);
        const copy = JSON.parse(JSON.stringify(el));
        copy.id = newId;
        copy.seed = Math.floor(Math.random() * 1000000) + 1;
        return copy;
      });
      for (const c of clonedElements) {
        if (c.startBinding?.elementId && idMap.has(c.startBinding.elementId)) {
          c.startBinding.elementId = idMap.get(c.startBinding.elementId);
        }
        if (c.endBinding?.elementId && idMap.has(c.endBinding.elementId)) {
          c.endBinding.elementId = idMap.get(c.endBinding.elementId);
        }
      }

      const newTab = {
        id: nextId('tab'),
        name: `${sourceTab.name} Copy`.slice(0, 48),
        elements: clonedElements,
        scrollX: sourceTab.scrollX,
        scrollY: sourceTab.scrollY,
        zoom: sourceTab.zoom,
        canvasBg: sourceTab.canvasBg,
        flowEnabled: sourceTab.flowEnabled,
        flowMode: sourceTab.flowMode,
        flowSpeed: sourceTab.flowSpeed,
        history: { undoStack: [], redoStack: [] }
      };
      const insertAt = sourceIdx >= 0 ? sourceIdx + 1 : state.tabs.length;
      state.tabs.splice(insertAt, 0, newTab);
      applyTabToState(newTab);
      renderCanvasTabs(true);
      saveWorkspaceToStorage();
      showToast(`Duplicated "${sourceTab.name}"`);
      return newTab;
    }

    function switchCanvasTab(tabId) {
      if (!tabId || tabId === state.activeTabId) return false;
      if (state.editingId) commitInlineEditor();
      ensureInitialTab();
      syncActiveTabFromState();
      const targetIdx = state.tabs.findIndex(t => t.id === tabId);
      const target = targetIdx >= 0 ? state.tabs[targetIdx] : null;
      if (!target) return false;
      applyTabToState(target);
      renderCanvasTabs(true);
      saveWorkspaceToStorage();
      showToast(`Canvas ${targetIdx + 1}/${state.tabs.length} · ${target.name}`);
      return true;
    }

    function stepCanvasTab(delta = 1) {
      ensureInitialTab();
      if (state.tabs.length <= 1) return false;
      const curIdx = Math.max(0, state.tabs.findIndex(t => t.id === state.activeTabId));
      const nextIdx = (curIdx + delta + state.tabs.length) % state.tabs.length;
      return switchCanvasTab(state.tabs[nextIdx].id);
    }

    function renameCanvasTab(tabId, newName) {
      ensureInitialTab();
      const tab = state.tabs.find(t => t.id === tabId);
      if (!tab) return false;
      const cleaned = String(newName ?? '').trim().slice(0, 48);
      if (cleaned.length > 0) {
        tab.name = cleaned;
      }
      state.editingTabId = null;
      renderCanvasTabs();
      saveWorkspaceToStorage();
      return true;
    }

    function closeCanvasTab(tabId) {
      if (state.editingId) commitInlineEditor();
      ensureInitialTab();
      const idx = state.tabs.findIndex(t => t.id === tabId);
      if (idx === -1) return false;
      if (state.tabs.length <= 1) {
        pushHistory();
        state.elements = [];
        state.selectedIds.clear();
        state.tabs[0].name = 'Canvas 1';
        ShapeCache.clear();
        syncUIWithSelection();
        renderCanvasTabs();
        saveWorkspaceToStorage();
        return true;
      }
      const wasActive = state.activeTabId === tabId;
      state.tabs.splice(idx, 1);
      if (wasActive) {
        const nextTab = state.tabs[Math.min(idx, state.tabs.length - 1)];
        applyTabToState(nextTab);
      } else {
        renderCanvasTabs();
      }
      saveWorkspaceToStorage();
      return true;
    }

    function exportExcalidrawJson() {
      closeAllDropdowns();
      const payload = serializeWorkspace();
      const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
      downloadBlob(blob, 'diagram.excaliflow');
      showToast('Saved diagram.excaliflow');
    }

    function importExcalidrawJson(jsonString) {
      closeAllDropdowns();
      try {
        const data = JSON.parse(jsonString);
        if (data && Array.isArray(data.tabs) && data.tabs.length > 0) {
          if (restoreWorkspaceData(data)) {
            saveWorkspaceToStorage();
            showToast(`Loaded ${state.tabs.length} canvas tab${state.tabs.length > 1 ? 's' : ''}`);
            return true;
          }
        }
        if (data && Array.isArray(data.elements)) {
          pushHistory();
          state.elements = sanitizeElementsArray(data.elements);
          if (data.appState && typeof data.appState === 'object') {
            if (data.appState.viewBackgroundColor) setCanvasBackground(data.appState.viewBackgroundColor);
            if (typeof data.appState.flowMode === 'string' && ALLOWED_FLOW_MODES.has(data.appState.flowMode)) {
              state.flowMode = data.appState.flowMode;
            }
            if (data.appState.flowSpeed !== undefined) {
              const spd = Number(data.appState.flowSpeed);
              if (Number.isFinite(spd) && spd > 0) {
                state.flowSpeed = Math.max(0.2, Math.min(5.0, spd));
              }
            }
          }
          state.selectedIds.clear();
          ShapeCache.clear();
          fitToScreen();
          syncUIWithSelection();
          saveWorkspaceToStorage();
          showToast('Loaded Excaliflow scene');
          return true;
        }
      } catch (err) {
        showToast('Invalid JSON file');
      }
      return false;
    }

    /* -------------------------------------------------------------------------
     * 15. UI Chrome Synchronization & Viewport Controls
     * ------------------------------------------------------------------------- */
    function closeAllDropdowns() {
      if (typeof document === 'undefined') return;
      document.querySelectorAll('.dropdown-menu.open').forEach(m => m.classList.remove('open'));
    }

    function setCanvasBackground(color) {
      state.canvasBg = color === '#000000' ? '#000000' : '#ffffff';
      if (typeof document === 'undefined') return;
      document.body.classList.toggle('dark-canvas', state.canvasBg === '#000000');
      document.getElementById('bgWhiteBtn')?.classList.toggle('active', state.canvasBg === '#ffffff');
      document.getElementById('bgBlackBtn')?.classList.toggle('active', state.canvasBg === '#000000');
      scheduleWorkspaceSave();
    }

    function syncZoomReadout() {
      if (typeof document !== 'undefined') {
        const zBtn = document.getElementById('zoomResetBtn');
        if (zBtn) zBtn.textContent = `${Math.round(state.zoom * 100)}%`;
      }
      updateQuickHudPosition();
      scheduleWorkspaceSave();
    }

    function setZoom(nextZoom, centerScreenX, centerScreenY) {
      const clamped = Math.max(0.25, Math.min(3.0, nextZoom));
      const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
      const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
      const sx = centerScreenX ?? vw / 2;
      const sy = centerScreenY ?? vh / 2;

      const worldBefore = screenToWorld(sx, sy);
      state.zoom = clamped;
      state.scrollX = sx / state.zoom - worldBefore.x;
      state.scrollY = sy / state.zoom - worldBefore.y;
      syncZoomReadout();
    }

    function fitToScreen() {
      const bounds = getDiagramExportBounds(64);
      const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
      const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
      const sidebarOffset = (typeof document !== 'undefined' &&
        !document.getElementById('leftSidebar')?.classList.contains('collapsed')) ? 115 : 0;

      const availW = Math.max(320, vw - sidebarOffset - 80);
      const availH = Math.max(240, vh - 140);
      const nextZoom = Math.max(0.25, Math.min(1.5, Math.min(availW / bounds.width, availH / bounds.height)));

      state.zoom = nextZoom;
      state.scrollX = (vw + sidebarOffset) / (2 * state.zoom) - (bounds.x + bounds.width / 2);
      state.scrollY = vh / (2 * state.zoom) - (bounds.y + bounds.height / 2);
      syncZoomReadout();
    }

    function toggleSidebar() {
      if (typeof document === 'undefined') return;
      const sb = document.getElementById('leftSidebar');
      if (sb) sb.classList.toggle('collapsed');
    }

    function updateHeaderButtons() {
      if (typeof document === 'undefined') return;
      const u = document.getElementById('btnUndo');
      const r = document.getElementById('btnRedo');
      if (u) u.disabled = state.history.undoStack.length === 0;
      if (r) r.disabled = state.history.redoStack.length === 0;

      const dot = document.getElementById('flowStatusDot');
      const mBtn = document.getElementById('masterFlowBtn');
      const badge = document.getElementById('flowBadgeText');
      if (dot) dot.classList.toggle('paused', !state.flowEnabled);
      if (mBtn) {
        mBtn.textContent = state.flowEnabled ? 'Flow: ON' : 'Flow: OFF';
        mBtn.classList.toggle('active', state.flowEnabled);
      }
      if (badge) {
        badge.textContent = `${state.flowMode.toUpperCase()} · ${state.flowSpeed}X`;
      }
      scheduleWorkspaceSave();
    }

    function updateQuickHudPosition() {
      if (typeof document === 'undefined') return;
      const hud = document.getElementById('quickHud');
      if (!hud) return;

      if (state.selectedIds.size === 0 || state.editingId) {
        hud.classList.remove('visible');
        return;
      }

      const selected = state.elements.filter(el => state.selectedIds.has(el.id));
      if (selected.length === 0) {
        hud.classList.remove('visible');
        return;
      }

      let minX = Infinity, minY = Infinity, maxX = -Infinity;
      for (const el of selected) {
        if (el.type === 'arrow') {
          const geom = getArrowGeometry(el);
          for (const p of geom.samples) {
            minX = Math.min(minX, p.x);
            minY = Math.min(minY, p.y);
            maxX = Math.max(maxX, p.x);
          }
        } else {
          minX = Math.min(minX, el.x);
          minY = Math.min(minY, el.y);
          maxX = Math.max(maxX, el.x + (el.width || 0));
        }
      }

      const topCenterScreen = worldToScreen((minX + maxX) / 2, minY);
      const clampedX = Math.max(220, Math.min(window.innerWidth - 220, topCenterScreen.x));
      const clampedY = Math.max(108, topCenterScreen.y - 18);

      hud.style.left = `${clampedX}px`;
      hud.style.top = `${clampedY}px`;
      hud.classList.add('visible');

      const first = selected[0];
      const isArrowOnly = selected.every(e => e.type === 'arrow');
      const nodeCtrls = document.getElementById('hudNodeControls');
      const arrowCtrls = document.getElementById('hudArrowControls');
      if (nodeCtrls) nodeCtrls.style.display = isArrowOnly ? 'none' : 'inline-flex';
      if (arrowCtrls) arrowCtrls.style.display = isArrowOnly ? 'inline-flex' : 'none';

      if (isArrowOnly) {
        const flowBtn = document.getElementById('hudArrowFlowBtn');
        if (flowBtn) {
          const on = first.flowEnabled !== false;
          flowBtn.textContent = on ? 'Flow ON' : 'Flow OFF';
          flowBtn.classList.toggle('active', on);
        }
      }
    }

    const STYLE_CONTROL_BINDINGS = [
      { selector: '#sidebarSwatches .color-swatch', attr: 'data-color', prop: 'strokeColor' },
      { selector: '#fillStyleRow .seg-btn', attr: 'data-fill-style', prop: 'fillStyle' },
      { selector: '#fontFamilyRow .seg-btn', attr: 'data-font-family', prop: 'fontFamily' },
      { selector: '#fontSizeRow .seg-btn', attr: 'data-font-size', prop: 'fontSize', numeric: true },
      { selector: '#roughnessRow .seg-btn', attr: 'data-roughness', prop: 'roughness', numeric: true },
      { selector: '#strokeWidthRow .seg-btn', attr: 'data-stroke-width', prop: 'strokeWidth', numeric: true },
      { selector: '#strokeStyleRow .seg-btn', attr: 'data-stroke-style', prop: 'strokeStyle' },
      { selector: '#curveTypeRow .seg-btn', attr: 'data-curve-type', prop: 'curveType' },
      { selector: '#hudFontGroup .ui-btn', attr: 'data-hud-font', prop: 'fontFamily' },
      { selector: '#hudArrowControls [data-hud-curve]', attr: 'data-hud-curve', prop: 'curveType' }
    ];

    function syncUIWithSelection() {
      if (typeof document === 'undefined') return;
      const selected = state.elements.filter(el => state.selectedIds.has(el.id));
      const ref = selected[0] || state.defaults;

      const setActiveAttr = (selector, attr, val) => {
        document.querySelectorAll(selector).forEach(btn => {
          btn.classList.toggle('active', String(btn.getAttribute(attr)) === String(val));
        });
      };

      for (const { selector, attr, prop } of STYLE_CONTROL_BINDINGS) {
        const val = prop === 'fontFamily' ? normalizeFontFamily(ref.fontFamily) : ref[prop];
        setActiveAttr(selector, attr, val);
      }
      setActiveAttr('#hudColorDots .hud-dot', 'data-color', ref.strokeColor);

      renderCanvasTabs();
      updateHeaderButtons();
      updateQuickHudPosition();
      scheduleWorkspaceSave();
    }

    function applyStyleProperty(prop, value) {
      if (prop === 'fontFamily') value = normalizeFontFamily(value);
      state.defaults[prop] = value;
      if (prop === 'curveType' && (value === 'straight' || value === 'elbow')) {
        state.defaults.curveOffset = 0;
      }

      const targets = prop === 'roughness'
        ? state.elements
        : (state.selectedIds.size > 0
            ? state.elements.filter(el => state.selectedIds.has(el.id))
            : (prop === 'fontFamily' ? state.elements : []));

      if (targets.length > 0) {
        pushHistory();
        for (const el of targets) {
          el[prop] = value;
          if (prop === 'curveType') {
            if (value === 'straight' || value === 'elbow') {
              el.curveOffset = 0;
            } else if (value === 'curved' && Math.abs(Number(el.curveOffset) || 0) < 2) {
              el.curveOffset = -36;
            }
          }
          if (prop === 'fontFamily' || prop === 'fontSize') {
            autoFitElementToText(el, el.text);
          }
          ShapeCache.invalidate(el);
        }
      }
      syncUIWithSelection();
    }

    /* -------------------------------------------------------------------------
     * 16. DOM Wiring & 60fps Animation Loop
     * ------------------------------------------------------------------------- */
    function initStudioDOM() {
      if (typeof window === 'undefined' || typeof document === 'undefined') return;
      const staticCanvas = document.getElementById('staticCanvas');
      const interactiveCanvas = document.getElementById('interactiveCanvas');
      if (!staticCanvas || !interactiveCanvas) return;

      const hudDots = document.getElementById('hudColorDots');
      if (hudDots && hudDots.children.length === 0) {
        for (const c of SEMANTIC_COLORS) {
          const dot = document.createElement('button');
          dot.className = 'hud-dot';
          dot.style.background = c.hex;
          dot.setAttribute?.('data-color', c.hex);
          dot.title = c.name;
          dot.addEventListener('click', () => applyStyleProperty('strokeColor', c.hex));
          hudDots.appendChild(dot);
        }
      }

      const resizeCanvases = () => {
        const dpr = window.devicePixelRatio || 1;
        const w = window.innerWidth;
        const h = window.innerHeight;
        for (const c of [staticCanvas, interactiveCanvas]) {
          c.width = Math.floor(w * dpr);
          c.height = Math.floor(h * dpr);
          c.style.width = `${w}px`;
          c.style.height = `${h}px`;
        }
      };
      resizeCanvases();
      window.addEventListener('resize', resizeCanvases);

      interactiveCanvas.addEventListener('pointerdown', e => {
        interactiveCanvas.setPointerCapture?.(e.pointerId);
        const pt = screenToWorld(e.clientX, e.clientY);
        pointerDownWorld(pt.x, pt.y, {
          shiftKey: e.shiftKey,
          altKey: e.altKey,
          screenX: e.clientX,
          screenY: e.clientY
        });
      });

      interactiveCanvas.addEventListener('pointermove', e => {
        const pt = screenToWorld(e.clientX, e.clientY);
        pointerMoveWorld(pt.x, pt.y, {
          shiftKey: e.shiftKey,
          altKey: e.altKey,
          screenX: e.clientX,
          screenY: e.clientY
        });
      });

      interactiveCanvas.addEventListener('pointerup', e => {
        const pt = screenToWorld(e.clientX, e.clientY);
        pointerUpWorld(pt.x, pt.y);
      });

      interactiveCanvas.addEventListener('dblclick', e => {
        const pt = screenToWorld(e.clientX, e.clientY);
        const hit = hitTestElement(pt.x, pt.y);
        if (hit) {
          if (hit.type === 'arrow') {
            pushHistory();
            hit.curveOffset = 0;
            syncUIWithSelection();
            return;
          }
          startInlineEditing(hit);
        } else {
          pushHistory();
          const box = createElement('rectangle', {
            x: pt.x - 72,
            y: pt.y - 34,
            width: 144,
            height: 68,
            text: 'New Node'
          });
          state.elements.push(box);
          state.selectedIds.clear();
          state.selectedIds.add(box.id);
          syncUIWithSelection();
          startInlineEditing(box);
        }
      });

      interactiveCanvas.addEventListener('wheel', e => {
        e.preventDefault();
        if (e.ctrlKey || e.metaKey) {
          const factor = e.deltaY < 0 ? 1.08 : 0.92;
          setZoom(state.zoom * factor, e.clientX, e.clientY);
        } else {
          state.scrollX -= e.deltaX / state.zoom;
          state.scrollY -= e.deltaY / state.zoom;
          updateQuickHudPosition();
        }
      }, { passive: false });

      const ta = document.getElementById('inlineTextEditor');
      if (ta) {
        ta.addEventListener('input', () => {
          const el = state.elements.find(e => e.id === state.editingId);
          if (el) {
            autoFitElementToText(el, ta.value);
            const scr = worldToScreen(el.x + (el.width || 0) / 2, el.y + (el.height || 0) / 2);
            const w = Math.max(120, (el.width || 120) * state.zoom);
            const h = Math.max(36, (el.height || 44) * state.zoom);
            const wrap = document.getElementById('inlineEditorWrap');
            if (wrap) {
              wrap.style.left = `${scr.x - w / 2}px`;
              wrap.style.top = `${scr.y - h / 2}px`;
            }
            ta.style.width = `${w}px`;
            ta.style.height = `${h}px`;
          }
        });
        ta.addEventListener('blur', () => commitInlineEditor());
      }

      window.addEventListener('keydown', e => {
        if (e.code === 'Space' && !state.editingId) {
          state.isSpacePanning = true;
          updateInteractiveCursor();
        }
        handleKeyDown(e);
      });
      window.addEventListener('keyup', e => {
        if (e.code === 'Space') {
          state.isSpacePanning = false;
          updateInteractiveCursor();
        }
      });

      // Drag-and-drop .excaliflow / .excalidraw / .json scene files directly onto the window
      window.addEventListener('dragover', e => e.preventDefault?.());
      window.addEventListener('drop', e => {
        e.preventDefault?.();
        const file = e.dataTransfer?.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = ev => importExcalidrawJson(String(ev.target?.result || ''));
        reader.readAsText(file);
      });

      // Dropdown toggles
      document.getElementById('canvasSwitcherBtn')?.addEventListener('click', e => {
        e.stopPropagation();
        const menu = document.getElementById('canvasesDropdown');
        const wasOpen = menu?.classList.contains('open');
        closeAllDropdowns();
        if (!wasOpen) {
          renderCanvasTabs(true);
          menu?.classList.add('open');
        }
      });
      document.getElementById('templatesMenuBtn')?.addEventListener('click', e => {
        e.stopPropagation();
        const menu = document.getElementById('templatesDropdown');
        const wasOpen = menu?.classList.contains('open');
        closeAllDropdowns();
        if (!wasOpen) menu?.classList.add('open');
      });
      document.getElementById('exportMenuBtn')?.addEventListener('click', e => {
        e.stopPropagation();
        const menu = document.getElementById('exportDropdown');
        const wasOpen = menu?.classList.contains('open');
        closeAllDropdowns();
        if (!wasOpen) menu?.classList.add('open');
      });
      window.addEventListener('click', () => closeAllDropdowns());

      document.getElementById('sidebarToggleBtn')?.addEventListener('click', toggleSidebar);
      document.getElementById('prevCanvasBtn')?.addEventListener('click', () => stepCanvasTab(-1));
      document.getElementById('nextCanvasBtn')?.addEventListener('click', () => stepCanvasTab(1));
      document.getElementById('addCanvasTabBtn')?.addEventListener('click', () => createCanvasTab());
      document.getElementById('forkCanvasTabBtn')?.addEventListener('click', () => duplicateCanvasTab());
      document.getElementById('bottomAddTabBtn')?.addEventListener('click', () => createCanvasTab());
      document.getElementById('bottomForkTabBtn')?.addEventListener('click', () => duplicateCanvasTab());
      window.addEventListener('beforeunload', () => saveWorkspaceToStorage());
      document.getElementById('btnUndo')?.addEventListener('click', undo);
      document.getElementById('btnRedo')?.addEventListener('click', redo);
      document.getElementById('bgWhiteBtn')?.addEventListener('click', () => setCanvasBackground('#ffffff'));
      document.getElementById('bgBlackBtn')?.addEventListener('click', () => setCanvasBackground('#000000'));

      document.getElementById('masterFlowBtn')?.addEventListener('click', () => {
        state.flowEnabled = !state.flowEnabled;
        updateHeaderButtons();
      });

      document.getElementById('btnSavePng')?.addEventListener('click', save2xPng);
      document.getElementById('btnCopyPng')?.addEventListener('click', copy2xPng);
      document.getElementById('btnRecordVideo')?.addEventListener('click', recordWebmVideo);
      document.getElementById('btnSaveJson')?.addEventListener('click', exportExcalidrawJson);
      document.getElementById('btnLoadJson')?.addEventListener('click', () => {
        document.getElementById('jsonFileInput')?.click();
      });
      document.getElementById('jsonFileInput')?.addEventListener('change', e => {
        const file = e.target.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = ev => importExcalidrawJson(String(ev.target?.result || ''));
        reader.readAsText(file);
        e.target.value = '';
      });
      document.getElementById('btnClearScene')?.addEventListener('click', () => {
        closeAllDropdowns();
        pushHistory();
        state.elements = [];
        state.selectedIds.clear();
        ShapeCache.clear();
        syncUIWithSelection();
      });

      document.querySelectorAll('[data-quick-add]').forEach(btn => {
        btn.addEventListener('click', () => quickAddShape(btn.getAttribute('data-quick-add')));
      });

      document.querySelectorAll('#flowModeGrid [data-flow-mode]').forEach(btn => {
        btn.addEventListener('click', () => {
          state.flowMode = btn.getAttribute('data-flow-mode');
          document.querySelectorAll('#flowModeGrid [data-flow-mode]').forEach(b => {
            b.classList.toggle('active', b === btn);
          });
          updateHeaderButtons();
        });
      });

      document.querySelectorAll('#flowSpeedRow [data-flow-speed]').forEach(btn => {
        btn.addEventListener('click', () => {
          state.flowSpeed = Number(btn.getAttribute('data-flow-speed')) || 1;
          document.querySelectorAll('#flowSpeedRow [data-flow-speed]').forEach(b => {
            b.classList.toggle('active', b === btn);
          });
          updateHeaderButtons();
        });
      });

      for (const { selector, attr, prop, numeric } of STYLE_CONTROL_BINDINGS) {
        document.querySelectorAll(selector).forEach(btn => {
          btn.addEventListener('click', () => {
            const raw = btn.getAttribute(attr);
            applyStyleProperty(prop, numeric ? Number(raw) : raw);
          });
        });
      }

      document.querySelectorAll('[data-template]').forEach(btn => {
        btn.addEventListener('click', () => {
          closeAllDropdowns();
          loadTemplate(btn.getAttribute('data-template'));
        });
      });

      document.querySelectorAll('#hudNodeControls [data-hud-morph]').forEach(btn => {
        btn.addEventListener('click', () => {
          const newType = btn.getAttribute('data-hud-morph');
          pushHistory();
          for (const id of state.selectedIds) {
            const el = state.elements.find(e => e.id === id);
            if (el && isNodeElement(el)) {
              el.type = newType;
              autoFitElementToText(el, el.text);
              ShapeCache.invalidate(el);
            }
          }
          syncUIWithSelection();
        });
      });
      document.getElementById('hudPulseBtn')?.addEventListener('click', () => triggerNodePulse());
      document.getElementById('hudNextBtn')?.addEventListener('click', () => {
        const firstId = Array.from(state.selectedIds)[0];
        const el = state.elements.find(e => e.id === firstId);
        if (el && isNodeElement(el)) chainNodeFrom(el, 'right', null, true);
      });
      document.getElementById('hudArrowFlowBtn')?.addEventListener('click', () => {
        pushHistory();
        for (const id of state.selectedIds) {
          const el = state.elements.find(e => e.id === id);
          if (el && el.type === 'arrow') el.flowEnabled = el.flowEnabled === false;
        }
        syncUIWithSelection();
      });
      document.getElementById('hudFlipArrowBtn')?.addEventListener('click', () => {
        pushHistory();
        for (const id of state.selectedIds) {
          const el = state.elements.find(e => e.id === id);
          if (el && el.type === 'arrow') {
            const tmpBind = el.startBinding;
            el.startBinding = el.endBinding;
            el.endBinding = tmpBind;
            const tx = el.x, ty = el.y;
            el.x = el.x2; el.y = el.y2;
            el.x2 = tx; el.y2 = ty;
            el.curveOffset = -(Number(el.curveOffset) || 0);
          }
        }
        syncUIWithSelection();
      });
      document.getElementById('hudDuplicateBtn')?.addEventListener('click', duplicateSelection);
      document.getElementById('hudDeleteBtn')?.addEventListener('click', deleteSelection);

      document.getElementById('toolLockBtn')?.addEventListener('click', () => toggleToolLock());
      document.querySelectorAll('#bottomToolDock [data-tool]').forEach(btn => {
        btn.addEventListener('click', () => setTool(btn.getAttribute('data-tool')));
      });

      document.getElementById('zoomOutBtn')?.addEventListener('click', () => setZoom(state.zoom * 0.85));
      document.getElementById('zoomInBtn')?.addEventListener('click', () => setZoom(state.zoom * 1.15));
      document.getElementById('zoomResetBtn')?.addEventListener('click', () => setZoom(1.0));
      document.getElementById('zoomFitBtn')?.addEventListener('click', fitToScreen);

      // Warm up official Excalidraw web fonts (Excalifont, Virgil, Cascadia, Assistant)
      if (document.fonts && document.fonts.load) {
        Promise.allSettled([
          document.fonts.load('16px Excalifont'),
          document.fonts.load('16px Virgil'),
          document.fonts.load('16px Cascadia'),
          document.fonts.load('500 16px Assistant')
        ]);
      }

      if (!loadWorkspaceFromStorage()) {
        loadTemplate('AI Agent Swarm');
        state.history.undoStack = [];
        ensureInitialTab('AI Agent Swarm');
        saveWorkspaceToStorage();
      }
      updateHeaderButtons();

      let lastFrameTime = performance.now() / 1000;
      const tick = (nowMs) => {
        const timeSec = nowMs / 1000;
        const dt = Math.min(0.05, Math.max(0.001, timeSec - lastFrameTime));
        lastFrameTime = timeSec;

        for (let i = state.activePulses.length - 1; i >= 0; i--) {
          const p = state.activePulses[i];
          p.progress += dt * (p.speed || 1.35);
          if (p.progress > 1.05) {
            state.activePulses.splice(i, 1);
          }
        }

        const dpr = window.devicePixelRatio || 1;
        const sCtx = staticCanvas.getContext('2d');
        const iCtx = interactiveCanvas.getContext('2d');

        sCtx.save();
        sCtx.setTransform(1, 0, 0, 1, 0, 0);
        sCtx.fillStyle = state.canvasBg;
        sCtx.fillRect(0, 0, staticCanvas.width, staticCanvas.height);
        sCtx.scale(dpr * state.zoom, dpr * state.zoom);
        sCtx.translate(state.scrollX, state.scrollY);
        const arrowGeoms = renderScenePasses(sCtx, timeSec, { canvasBg: state.canvasBg });
        sCtx.restore();

        iCtx.save();
        iCtx.setTransform(1, 0, 0, 1, 0, 0);
        iCtx.clearRect(0, 0, interactiveCanvas.width, interactiveCanvas.height);
        iCtx.scale(dpr * state.zoom, dpr * state.zoom);
        iCtx.translate(state.scrollX, state.scrollY);
        drawInteractiveOverlay(iCtx, arrowGeoms);
        iCtx.restore();

        requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }

    if (typeof window !== 'undefined') {
      Object.assign(window, {
        state,
        WORKSPACE_STORAGE_KEY,
        mulberry32,
        clipSegmentToShape,
        clampPointToShapeInterior,
        roughEdge,
        roughRoundRect,
        roughEllipse,
        ShapeCache,
        drawStaticElement,
        drawElementText,
        computeGraphDepths,
        triggerNodePulse,
        getArrowGeometry,
        computeBindingForShape,
        getBindingBoundaryPoint,
        findMagneticShape,
        hitTestArrowHandle,
        hitTestQuickPorts,
        hitTestElement,
        autoFitElementToText,
        findSplitTargetArrow,
        trySplitArrowWithNode,
        getDiagramExportBounds,
        renderScenePasses,
        pointerDownWorld,
        pointerMoveWorld,
        pointerUpWorld,
        handleKeyDown,
        setTool,
        toggleToolLock,
        loadTemplate,
        quickAddShape,
        createElement,
        cloneElementsWithBindings,
        undo,
        redo,
        importExcalidrawJson,
        applyStyleProperty,
        createCanvasTab,
        duplicateCanvasTab,
        switchCanvasTab,
        stepCanvasTab,
        renameCanvasTab,
        closeCanvasTab,
        saveWorkspaceToStorage,
        loadWorkspaceFromStorage,
        serializeWorkspace,
        restoreWorkspaceData
      });
      window.addEventListener('DOMContentLoaded', initStudioDOM);
    }
  </script>
</body>
</html>