[
  {
    "path": "ECCM.html",
    "content": "<!doctype html>\r\n<html lang=\"en\">\r\n<head>\r\n<link type=\"image/png\" sizes=\"32x32\" rel=\"icon\" href=\"https://img.icons8.com/stickers/32/ethernet-on.png\">\r\n<meta charset=\"utf-8\" />\r\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\r\n<title>Ethernet Cable Connection Manager</title>\r\n<style>\r\n:root{--bg:#0f1115;--panel:#171a21;--ink:#e8eaf1;--paper: #0E1117;--muted:#a6adbb;--line:#262a33;--prtPortH: 75px;--portGapFull:9px;--portGapHalf:8px;--portW12:60px;--portW6:60px;--reserved-bg:#555;--elm-page-bg-dark:#0f172a;--elm-page-bg-bright:#ffffff}\r\nhtml,body{height:100%}\r\nbody{margin:0;background:var(--bg);color:var(--ink);font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif}\r\n*,*::before,*::after{box-sizing:border-box}\r\nheader{padding:14px 18px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:12px;flex-wrap:wrap;background:linear-gradient(180deg,#12151b,#10131a)}\r\nheader h1{font-size:18px;margin:0;font-weight:650}\r\n.badge{color:var(--muted);font-size:12px;border:1px solid var(--line);padding:2px 8px;border-radius:999px}\r\n.wrap{position:relative;display:grid;grid-template-columns:340px 1fr;gap:0;height:calc(100% - 62px)}\r\n@media (max-width:1024px){.wrap{grid-template-columns:1fr;height:auto}}\r\naside,main{padding:16px}\r\naside{border-right:1px solid var(--line);background:var(--panel)}\r\nmain{overflow:auto;position:relative}\r\n.card{background:#141821;border:1px solid var(--line);border-radius:10px;padding:12px;margin-bottom:12px}\r\n.card h3{margin:0 0 8px 0;font-size:14px;font-weight:650}\r\nlabel{display:block;font-size:12px;color:var(--muted);margin:8px 0 4px}\r\n.muted{color:var(--muted)}.small{font-size:12px}\r\n.mini{padding:4px 8px;font-size:12px;border-radius:6px}\r\n.setting-row{display:flex;align-items:center;justify-content:space-between;gap:.75rem;margin:.5rem 0}\r\n.setting-row select{padding:.35rem .5rem;border-radius:.5rem}\r\ninput[type=text],input[type=number],select{width:100%;max-width:100%;background:#0f131b;color:var(--ink);border:1px solid var(--line);border-radius:8px;padding:8px 10px;outline:none}\r\nbutton,.btn{background:#11151d;color:var(--ink);border:1px solid var(--line);padding:8px 10px;border-radius:8px;cursor:pointer;font-weight:600}\r\nbutton:hover{border-color:#2a2f3b}\r\n.btn-danger{border-color:#3b2222}\r\n.dev-rows{display:flex;flex-direction:column;gap:12px}\r\n.dev-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}\r\n.device-wrap{display:block;width:100%}\r\n.device-wrap.full{grid-column:1/-1}\r\n.device{background:#131722;border:1px solid var(--line);border-radius:12px;padding:12px;position:relative;width:100%}\r\n.device-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}\r\n.device-title{font-size:15px;font-weight:650;display:flex;align-items:center;gap:8px}\r\n.swatch{width:12px;height:12px;border-radius:3px;border:1px solid #0006;display:inline-block}\r\n.device-actions{display:flex;gap:6px;flex-wrap:wrap}\r\n.meta{font-size:12px;color:var(--muted);margin-top:2px}\r\n.meta .inline-controls{margin-left:8px;display:inline-flex;gap:6px}\r\n.ports-rows{display:flex;flex-direction:column;gap:8px;margin-top:10px}\r\n.port-row{display:grid;gap:var(--portGapHalf)}\r\n.port{height: var(--prtPortH) !important;position:relative;border:1px solid var(--line);background:#0f141d;border-radius:10px;padding:4px 6px 6px;cursor:pointer;text-align:center;user-select:none;transition:background .12s}\r\n.port .num{font-size:12px;margin-top:2px;min-height:1.4em}\r\n.port .alias{font-size:12px;margin-top:2px;min-height:1.4em; white-space: nowrap;  overflow: hidden; text-align: center;  max-width: 100%;  }\r\n.port .peer{margin-top:2px;font-size:12px;font-weight:700;min-height:1.4em;white-space: nowrap;  overflow: hidden; text-align: center;  max-width: 100%;}\r\n.port.selected{}\r\n.port:not(.connected):not(.reserved) .num,.port:not(.connected):not(.reserved) .alias,.port:not(.connected):not(.reserved) .peer{color:#fff}\r\n.port.reserved .num,.port.reserved .alias,.port.reserved .peer{color:#fff!important}\r\n.port .num{  display:inline-flex;  align-items:center;  justify-content:center;  gap:4px;  line-height:1;}\r\n.port .num .num-label{ line-height:1; }\r\n.port .ind{  width:5px; height:5px;  display:inline-block;  border-radius:1px;  background: currentColor;  opacity:.9;  line-height:0;  flex:0 0 auto;  vertical-align:middle;}\r\n/* Slow link indicator: red cross in a small square */\r\n.port .ind.ind--slow{\r\n  width:10px;\r\n  height:10px;\r\n  border-radius:2px;\r\n  background:#ffffff;      /* dark theme: white */\r\n  color:#e11;              /* red cross */\r\n  display:inline-flex;\r\n  align-items:center;\r\n  justify-content:center;\r\n  font-size:8px;\r\n  font-weight:700;\r\n}\r\n\r\n/* Bright theme: red on black */\r\nhtml.theme-bright .port .ind.ind--slow{\r\n  background:#000000;\r\n  color:#e11;\r\n}\r\n.slow-warn{\r\n  font-size:10px;\r\n  line-height:1;\r\n  display:inline-block;\r\n  vertical-align:middle;\r\n}\r\n.port .ind.vlan-diamond{ transform: rotate(45deg); }\r\n.port .ind.ind--off{  opacity:0;  pointer-events:none;  }\r\nhtml.theme-bright .port .ind{ opacity:.8; }\r\n.grid-slim{width:100%;border-collapse:collapse;border:1px solid var(--line);border-radius:8px;overflow:hidden;table-layout:fixed}\r\n.grid-slim th,.grid-slim td{font-size:13px;text-align:left;padding:8px 10px;border-bottom:1px solid var(--line);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\r\n.grid-slim th{background:#121722;color:var(--muted);font-weight:600}\r\n.conn-row.highlight td{background:#1e293b }\r\n.conn-row td.deviceA .devName,.conn-row td.deviceB .devName{color:#fff;font-weight:400}\r\n.conn-row.highlight td.deviceA .devName,.conn-row.highlight td.deviceB .devName{color:var(--devColor);font-weight:700}\r\n.conn-row.reserved-row td{background:#121622}\r\n.conn-row.reserved-row:hover td{background:#151b2a}\r\n.color-picker-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\r\n.swatch-lg{width:24px;height:24px;border-radius:6px;border:1px solid #0006;display:inline-block}\r\n.color-btn{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;background:#0f141d;border:1px solid var(--line);border-radius:8px;cursor:pointer;font-weight:600;color:var(--ink)}\r\n.color-btn:hover{border-color:#2a2f3b}\r\n.palette-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center;z-index:999}\r\n.palette{background:#141821;border:1px solid var(--line);border-radius:12px;padding:12px;min-width:280px;max-width:90vw}\r\n.palette h4{margin:0 0 10px 0;font-size:14px}\r\n.palette-grid{display:grid;grid-template-columns:repeat(4,36px);gap:8px;justify-content:center}\r\n.chip{width:36px;height:36px;border-radius:8px;border:1px solid rgba(0,0,0,.35);cursor:pointer}\r\n.palette .actions{display:flex;justify-content:flex-end;margin-top:12px}\r\n.modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center;z-index:60}\r\n.modal{background:#141821;border:1px solid var(--line);border-radius:12px;padding:14px;min-width:300px;max-width:90vw}\r\n.modal h4{margin:0 0 10px 0;font-size:14px}\r\n.modal .row{display:flex;gap:8px;align-items:center;margin:6px 0}\r\n.modal label{margin:0;color:var(--ink);font-size:13px}\r\n.modal select{background:#0f131b;color:var(--ink);border:1px solid var(--line);border-radius:8px;padding:6px 10px}\r\n.modal .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:12px}\r\nhtml.theme-bright body,html.theme-bright .card,html.theme-bright aside,html.theme-bright main,html.theme-bright #settingsPanel{background:#fff!important;color:#111!important;border-color:#ccc!important;--muted: #222; --paper: #fff}\r\nhtml.theme-bright header{background:#fff!important;border-bottom:1px solid #e5e7eb!important;color:#111!important}\r\nhtml.theme-bright header h1{color:#111!important}\r\nhtml.theme-bright header .badge{background:#fff!important;color:#444!important;border-color:#e0e6ef!important}\r\nhtml.theme-bright header button,html.theme-bright header .btn,html.theme-bright header select{background:#fff!important;color:#111!important;border:1px solid #d8dee8!important}\r\nhtml.theme-bright header button:hover,html.theme-bright header .btn:hover{border-color:#9aa4b2!important}\r\nhtml.theme-bright .device{background:#fff!important;border-color:#ccc!important}\r\nhtml.theme-bright .port:not(.connected):not(.reserved){background:#fff!important;color:#000!important}\r\nhtml.theme-bright .port:not(.connected):not(.reserved) .num,html.theme-bright .port:not(.connected):not(.reserved) .alias,html.theme-bright .port:not(.connected):not(.reserved) .peer{color:#000!important}\r\nhtml.theme-bright .port.selected{}\r\nhtml.theme-bright .port.reserved{background:#555!important;color:#fff!important}\r\nhtml.theme-bright button:not(.chip),html.theme-bright .btn,html.theme-bright input[type=\"text\"],html.theme-bright input[type=\"number\"],html.theme-bright select{background:#fff!important;color:#111!important;border:1px solid #ccc!important}\r\nhtml.theme-bright button:not(.chip):hover,html.theme-bright .btn:hover{border-color:#888!important}\r\nhtml.theme-bright .grid-slim th{background:#f6f7f9!important;color:#111!important;border-color:#ccc!important}\r\nhtml.theme-bright .grid-slim td{background:#fff!important;color:#111!important;border-color:#ddd!important}\r\nhtml.theme-bright .conn-row.highlight td{background:#e8f0fe!important;color:#000!important}\r\nhtml.theme-bright .conn-row.reserved-row td{background:#f1f1f1!important;color:#000!important}\r\nhtml.theme-bright .conn-row.reserved-row:hover td{background:#e0e0e0!important}\r\nhtml.theme-bright .conn-row td.deviceA .devName,html.theme-bright .conn-row td.deviceB .devName{color:#000!important;font-weight:400}\r\nhtml.theme-bright .conn-row.highlight td.deviceA .devName,html.theme-bright .conn-row.highlight td.deviceB .devName{color:var(--devColor)!important;font-weight:700}\r\nhtml.theme-bright .palette{background:#fff!important;border-color:#ccc!important;color:#000!important}\r\nhtml.theme-bright .palette h4{color:#000!important}\r\nhtml.theme-bright .palette .chip{border:1px solid rgba(0,0,0,.4)}\r\nhtml.theme-bright .modal{background:#fff!important;border:1px solid #ccc!important;color:#111!important}\r\nhtml.theme-bright .modal h4,html.theme-bright .modal label{color:#111!important}\r\nhtml.theme-bright .modal select{background:#fff!important;color:#111!important;border:1px solid #ccc!important}\r\n.theme-toggle{display:inline-flex;border-radius:10px;overflow:hidden}\r\n.theme-toggle button{padding:6px 12px;border:1px solid var(--line);background:#11151d;color:var(--ink);cursor:pointer;font-weight:600;line-height:1;border-right:none}\r\n.theme-toggle button:first-child{border-top-left-radius:10px;border-bottom-left-radius:10px}\r\n.theme-toggle button:last-child{border-right:1px solid var(--line);border-top-right-radius:10px;border-bottom-right-radius:10px}\r\n.theme-toggle button.active{box-shadow:inset 0 0 0 2px #e5e7eb}\r\nhtml.theme-bright .theme-toggle button{background:#fff;color:#111;border-color:#ccc}\r\nhtml.theme-bright .theme-toggle button:last-child{border-right-color:#ccc}\r\nhtml.theme-bright .theme-toggle button.active{box-shadow:inset 0 0 0 2px #000}\r\nmain::-webkit-scrollbar{width:10px}\r\nmain::-webkit-scrollbar-track{background:var(--panel)}\r\nmain::-webkit-scrollbar-thumb{background-color:#555;border-radius:6px;border:2px solid var(--panel)}\r\nmain::-webkit-scrollbar-thumb:hover{background-color:#777}\r\nmain{scrollbar-width:thin;scrollbar-color:#555 var(--panel)}\r\nhtml.theme-bright main::-webkit-scrollbar-track{background:#fff!important}\r\nhtml.theme-bright main::-webkit-scrollbar-thumb{background-color:#bbb!important;border:2px solid #fff!important}\r\nhtml.theme-bright main::-webkit-scrollbar-thumb:hover{background-color:#999!important}\r\nhtml.theme-bright main{scrollbar-color:#bbb #fff!important}\r\n:root{  --hover-bg: #141821;  --hover-border: #2b3140;  --hover-ink: #e8eaf1;}\r\nhtml.theme-bright{  --hover-bg: #fffffe;  --hover-border: #cfd6e4;  --hover-ink: #111;}\r\n.hovercard{  position: fixed;  z-index: 9999;  display: none;  min-width: 220px;  max-width: 320px;  padding: 8px 10px;  font-size: 12px;  line-height: 1.3;  color: var(--hover-ink);  background: var(--hover-bg);  border: 1px solid var(--hover-border);  border-radius: 10px;  box-shadow: 0 6px 20px rgba(0,0,0,.25);  pointer-events: none;   white-space: nowrap;}\r\n.hovercard .hc-title{ font-weight: 700; margin-bottom: 4px; }\r\n.hovercard .hc-row{ display:flex; gap:8px; }\r\n.hovercard .hc-k{ color: var(--muted); min-width: 72px; }\r\n.port .spd{  display:inline-block;  margin-left:6px;  padding:1px 6px;  font-size:10px;  line-height:1.3;  border:1px solid var(--line);  border-radius:999px;  color: var(--muted);  vertical-align:middle;}\r\n.speed-menu{  position: fixed;  z-index: 9999;  background:#141821;  color:#e8eaf1;  border:1px solid var(--line);  border-radius:8px;  padding:6px;  box-shadow: 0 8px 24px rgba(0,0,0,.35);}\r\n.speed-menu select{  background:#0f131b;  color:#e8eaf1;  border:1px solid var(--line);  border-radius:6px;  padding:6px 8px;  font-size:12px;}\r\nhtml.theme-bright .speed-menu{  background:#fff;  color:#111;  border-color:#ccc;}\r\nhtml.theme-bright .speed-menu select{  background:#fff;  color:#111;  border-color:#ccc;}\r\n.slideover{  position: fixed;  inset: 0;  z-index: var(--z-overlay, 5000);  display: none;  font: inherit;  color: var(--ink);}\r\n.slideover.is-open{ display:block; }\r\n.slideover__backdrop{  position: absolute;  inset: 0;  background: var(--overlay, rgba(0,0,0,.35)); /* follows page; override if you have a var */  opacity: 0;  transition: opacity .2s ease;}\r\n.slideover.is-open .slideover__backdrop{ opacity: 1; }\r\n.slideover__panel{  position: absolute;  top: 0; right: 0; bottom: 0;  width: clamp(320px, 36vw, 480px);  background: var(--paper);  color: var(--ink);  border-left: 1px solid var(--line);  box-shadow: -12px 0 32px var(--elev, rgba(0,0,0,.28));  display: flex; flex-direction: column;  transform: translateX(100%);  transition: transform .25s ease;}\r\n.slideover.is-open .slideover__panel{ transform: translateX(0); }\r\n.slideover__header,\r\n.slideover__footer{  background: var(--paper);  color: var(--ink);  padding: 12px 16px;}\r\n.slideover__header{  display:flex; align-items:center; justify-content:space-between;  border-bottom: 1px solid var(--line);}\r\n.slideover__footer{  border-top: 1px solid var(--line);}\r\n.slideover__header h2{  margin: 0;  font-size: 18px;  font-weight: 600;  color: var(--ink);}\r\n.slideover__body{  padding: 12px 16px;  overflow: auto;  flex: 1 1 auto;  background: var(--paper);  color: var(--ink);}\r\n.slideover__close{  font-size: 28px; line-height: 1;  border: 0; background: transparent; color: var(--ink);  cursor: pointer;}\r\n@media (prefers-color-scheme: dark){  .slideover__backdrop{    background: var(--overlay-dark, rgba(0,0,0,.6));  }}\r\n@media (prefers-reduced-motion: reduce){  .slideover__backdrop,  .slideover__panel{ transition: none; }}\r\n@media print{  \r\n\t.slideover{ display:none !important; }\r\n\tinput[type=range][orient=vertical] {  appearance: slider-vertical;  width: 8px;}\r\n\t#customColorPicker input[type=range] {  margin: 0 2px;}\r\n\t#colorPreviewBox {  box-shadow: 0 0 6px rgba(0,0,0,0.4);}\r\n\t#hexOutput:focus {  outline: none;  border-color: #66ccff;}\r\n\t#hueBar {  border: 1px solid var(--line);}\r\n\t#hueMarker {  transition: top 0.1s ease;}\r\n\t#colorPreviewBox {  transition: background 0.15s ease;}\r\n\t#hexOutput {  width: 80px;  font-size: 12px;  margin-top: 4px;}\r\n}\r\n.port .peer {\r\n  position: relative;\r\n  overflow: hidden;\r\n  white-space: nowrap;\r\n  text-align: center;\r\n  max-width: 100%;\r\n}\r\n\r\n.port .peer > span {\r\n  display: inline-block;\r\n  white-space: nowrap;\r\n  position: relative;\r\n  will-change: transform;\r\n}\r\n\r\n/* Enable animation only if .scroll is present */\r\n.port .peer.scroll > span {\r\n  display: inline-block;\r\n  white-space: nowrap;\r\n  position: relative;\r\n  will-change: transform;\r\n  animation: eccm-peer-bounce 7s ease-in-out infinite;\r\n  animation-delay: 2s; \r\n}\r\n\r\n/* Keyframes:\r\n   0%–100% cycle = 7 seconds:\r\n   - 0–40%: scroll to the right\r\n   - 40–55%: PAUSE on right (1 second)\r\n   - 55–95%: scroll back left\r\n   - 95–100%: PAUSE left (0.35s)\r\n*/\r\n@keyframes eccm-peer-bounce {\r\n  0%   { transform: translateX(0); }\r\n  35%  { transform: translateX(calc(-1 * var(--peer-diff))); }\r\n  50%  { transform: translateX(calc(-1 * var(--peer-diff))); }\r\n  85%  { transform: translateX(0); }\r\n  100% { transform: translateX(0); }\r\n}\r\n\r\n</style>\r\n</head>\r\n<body>\r\n<header>\r\n  <h1>Ethernet Cable Connection Manager</h1>\r\n  <span class=\"badge\">1.0.6</span>\r\n  <div style=\"margin-left:auto;display:flex;gap:8px\">\r\n\t<button id=\"btnSettings\" class=\"btn\">Settings</button>\r\n    <button id=\"printSheet\">Print layout</button>\r\n  </div>\r\n</header>\r\n\r\n<div class=\"wrap\">\r\n  <aside>\r\n    <!-- Profiles -->\r\n    <div class=\"card\">\r\n      <h3>Profiles</h3>\r\n      <label for=\"profileSelect\">Active profile</label>\r\n      <select id=\"profileSelect\"></select>\r\n\r\n      <div style=\"display:flex;gap:8px;flex-wrap:wrap;margin-top:8px\">\r\n        <button id=\"newProfileBtn\">New</button>\r\n        <button id=\"renameProfileBtn\">Rename</button>\r\n        <button id=\"duplicateProfileBtn\">Duplicate</button>\r\n        <button id=\"deleteProfileBtn\" class=\"btn-danger\">Delete</button>\r\n        <button id=\"exportProfileBtn\" class=\"btn\">Export</button>\r\n        <button id=\"importProfileBtn\" class=\"btn\">Import</button>\r\n        <input id=\"importProfileFile\" type=\"file\" accept=\".json,application/json\" style=\"display:none\">\r\n      </div>\r\n\r\n      <div class=\"small muted\" style=\"margin-top:6px\">\r\n      </div>\r\n    </div>\r\n\r\n    <div class=\"card\">\r\n      <h3>Add device</h3>\r\n      <label for=\"devName\">Name</label>\r\n      <input id=\"devName\" type=\"text\" placeholder=\"e.g. Core Switch A\" />\r\n      <div class=\"row\">\r\n        <div>\r\n          <label for=\"devPorts\">Ports</label>\r\n          <input id=\"devPorts\" type=\"number\" inputmode=\"numeric\" min=\"1\" max=\"9999\" value=\"24\" />\r\n        </div>\r\n      </div>\r\n      <label>Colour</label>\r\n      <div class=\"color-picker-row\">\r\n        <button type=\"button\" class=\"color-btn\" id=\"openPalette\">Select colour</button>\r\n        <span id=\"devColorPreview\" class=\"swatch swatch-lg\" title=\"Selected colour\"></span>\r\n      </div>\r\n      <div style=\"margin-top:10px;display:flex;gap:8px\">\r\n        <button id=\"addBtn\">Add device</button>\r\n        <button id=\"clearAll\" class=\"btn-danger\" title=\"Delete everything\">Clear all devices</button>\r\n      </div>\r\n      <div class=\"small muted\" style=\"margin-top:6px\">\r\n        Click two free ports to connect<br>\r\n\t\t<strong>Unlink</strong> in Connections<br>\r\n\t\t<strong>Alt-click</strong> a port to set an alias<br>\r\n\t\t<strong>CTRL-click</strong> to mark as Reserved.\r\n      </div>\r\n    </div>\r\n\r\n    <!-- Backup/restore all profiles -->\r\n    <div class=\"card\">\r\n      <h3>Backup / Restore (all profiles)</h3>\r\n      <div style=\"display:flex;gap:8px;flex-wrap:wrap\">\r\n        <button id=\"backupAllBtn\" class=\"btn\">Backup all</button>\r\n        <button id=\"restoreAllBtn\" class=\"btn\">Restore all</button>\r\n        <input id=\"restoreAllFile\" type=\"file\" accept=\".json,application/json\" style=\"display:none\">\r\n      </div>\r\n      <div class=\"small muted\" style=\"margin-top:6px\">Saves or restores every profile on this device.</div>\r\n    </div>\r\n\r\n    <div class=\"card\">\r\n      <h3>Find connection</h3>\r\n      <input id=\"searchBox\" type=\"text\" placeholder=\"Filter by device, port, alias, or reserved…\" />\r\n      <div class=\"small muted\" style=\"margin-top:6px\">Filters the connections table.</div>\r\n    </div>\r\n  </aside>\r\n\r\n  <main>\r\n    <div class=\"card\">\r\n      <h3>Devices</h3>\r\n      <div id=\"devRows\" class=\"dev-rows\"></div>\r\n    </div>\r\n\r\n    <div class=\"card\">\r\n      <h3>Connections</h3>\r\n      <table class=\"grid-slim\" id=\"connTable\">\r\n        <thead><tr><th>#</th><th>Device A</th><th>Port</th><th>Alias</th><th>⇄</th><th>Device B</th><th>Port</th><th>Alias</th><th></th></tr></thead>\r\n        <tbody id=\"connBody\"></tbody>\r\n      </table>\r\n      <div class=\"small muted\">Click a row (or a connected port) to highlight both ends.</div>\r\n    </div>\r\n  </main>\r\n  \r\n\r\n\r\n  </div>\r\n</aside>\r\n</div>\r\n\r\n<!-- Settings Slide-Over (Modal) -->\r\n<div id=\"settingsModal\" class=\"slideover\" aria-hidden=\"true\">\r\n  <div class=\"slideover__backdrop\" data-close></div>\r\n  <aside class=\"slideover__panel\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"settingsTitle\" tabindex=\"-1\">\r\n    <header class=\"slideover__header\">\r\n      <h3>Settings</h3>\r\n    </header>\r\n\r\n    <div class=\"slideover__body\" id=\"settingsPanelBody\">\r\n\t\r\n\t<div class=\"card\">\r\n\t<div class=\"setting-row\" id=\"themeRow\">\r\n\t\t<label>Theme</label>\r\n\t\t<div class=\"theme-toggle\" role=\"group\" aria-label=\"Theme\">\r\n\t\t\t<button type=\"button\" id=\"themeDark\"  data-theme=\"dark\"   aria-pressed=\"false\">🌙 Dark</button>\r\n\t\t\t<button type=\"button\" id=\"themeLight\" data-theme=\"bright\" aria-pressed=\"false\">☀️ Light</button>\r\n\t\t</div>\r\n\t</div>\r\n\t</div>\r\n\t\r\n        <div class=\"card\">\r\n\t\r\n\t<div class=\"setting-row\">\r\n\t\t<label for=\"enablePortRename\">Enable Port Renaming</label>\r\n\t\t<input id=\"enablePortRename\" type=\"checkbox\" />\r\n\t</div>\r\n\t<div class=\"setting-row\">\r\n\t  <label for=\"maxPorts\" style=\"flex:1;\">Maximum ports per device</label>\r\n\t  <input id=\"maxPorts\" type=\"number\" min=\"0\" max=\"9999\" style=\"flex:1; max-width:120px;\" />\r\n\t</div>\r\n\t\r\n\t<div class=\"setting-row\">\r\n\t  <label for=\"portTermMode\">Port label</label>\r\n\t  <select id=\"portTermMode\" style=\"max-width:160px\">\r\n\t\t<option value=\"port\">Port</option>\r\n\t\t<option value=\"interface\">Interface</option>\r\n\t\t<option value=\"custom\">Custom</option>\r\n\t  </select>\r\n\t</div>\r\n\r\n\t<div class=\"setting-row\" id=\"portTermCustomRow\" style=\"display:none\">\r\n\t  <label for=\"portTermCustom\" style=\"flex:1;\">Custom label</label>\r\n\t  <input id=\"portTermCustom\" type=\"text\" placeholder=\"e.g. Jack\" style=\"flex:1; max-width:160px;\" />\r\n\t</div>\t\r\n\t\r\n\t<div style=\"margin-top:10px;display:flex;gap:8px\">\r\n\t  <button id=\"saveSettingsBtn\" class=\"btn\">Save</button>\r\n\t</div>\r\n\r\n  </div>\r\n    </div>\r\n\r\n    <footer class=\"slideover__footer\">\r\n      <button class=\"btn\" data-close>Close</button>\r\n    </footer>\r\n  </aside>\r\n</div>\r\n\r\n\r\n<!-- Palette -->\r\n<div class=\"palette-backdrop\" id=\"paletteModal\">\r\n  <div class=\"palette\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"paletteTitle\">\r\n  <h4 id=\"paletteTitle\">Select colour</h4>\r\n\t  <div style=\"display:flex;gap:20px;justify-content:center;align-items:flex-start;flex-wrap:wrap\">\r\n\t\t<div class=\"palette-grid\" id=\"paletteGrid\" style=\"grid-template-columns:repeat(4,36px)\"></div>\r\n\t  </div>\r\n\t  <div class=\"actions\"><button type=\"button\" id=\"paletteClose\">Close</button></div>\r\n\t</div>\r\n\r\n</div>\r\n\r\n<!-- Layout modal -->\r\n<div class=\"modal-backdrop\" id=\"layoutModal\">\r\n  <div class=\"modal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"layoutTitle\">\r\n    <h4 id=\"layoutTitle\">Device layout options</h4>\r\n    <div class=\"row\"><label style=\"min-width:110px\">Device</label><span id=\"layoutDeviceName\" class=\"small muted\"></span></div>\r\n    <div class=\"row\">\r\n      <label style=\"min-width:110px\">Row width</label>\r\n      <select id=\"layoutFullRow\">\r\n        <option value=\"auto\">Auto (follow rules)</option>\r\n        <option value=\"full\">Force full row</option>\r\n      </select>\r\n    </div>\r\n    <div class=\"row\" id=\"optMidWrap\">\r\n      <label style=\"min-width:110px\">13–24 ports</label>\r\n      <select id=\"layoutMidWrap\">\r\n        <option value=\"balanced\">Balanced (½ + ½)</option>\r\n        <option value=\"twelve\">12 + remainder</option>\r\n      </select>\r\n    </div>\r\n    <div class=\"row\" id=\"optSmallWrap\">\r\n      <label style=\"min-width:110px\">≤12 ports</label>\r\n      <select id=\"layoutSmallWrap\">\r\n        <option value=\"single\">Single row</option>\r\n        <option value=\"split\">Split into 2 rows</option>\r\n      </select>\r\n    </div>\r\n    <div class=\"row\" id=\"optDualLink\">\r\n      <label style=\"min-width:110px\">Dual link</label>\r\n      <select id=\"layoutDualLink\">\r\n        <option value=\"off\">Normal</option>\r\n        <option value=\"on\">Dual link</option>\r\n      </select>\r\n    </div>\r\n\t<div class=\"row\" id=\"optNumbering\">\r\n\t  <label style=\"min-width:110px\">Port numbering</label>\r\n\t\t<select id=\"layoutNumbering\">\r\n\t\t  <option value=\"row\">Left → Right (rows)</option>\r\n\t\t  <option value=\"column\">Top ↓ Bottom (columns)</option>\r\n\t\t  <option value=\"column-bt\">Bottom ↑ Top (columns)</option>\r\n\t\t</select>\r\n\t</div>\r\n    <div class=\"actions\">\r\n      <button type=\"button\" id=\"layoutCancel\">Cancel</button>\r\n      <button type=\"button\" id=\"layoutSave\">Save</button>\r\n    </div>\r\n  </div>\r\n</div>\r\n\r\n<!-- Edit Device Modal -->\r\n<div class=\"modal-backdrop\" id=\"editDeviceModal\">\r\n  <div class=\"modal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"editDeviceTitle\">\r\n    <h4 id=\"editDeviceTitle\">Edit Device</h4>\r\n\r\n    <div class=\"row\">\r\n      <label for=\"editDevName\" style=\"min-width:100px\">Name</label>\r\n      <input id=\"editDevName\" type=\"text\" placeholder=\"Device name\" />\r\n    </div>\r\n\r\n    <div class=\"row\">\r\n      <label for=\"editDevPorts\" style=\"min-width:100px\">Ports</label>\r\n      <input id=\"editDevPorts\" type=\"number\" min=\"1\" max=\"9999\" />\r\n    </div>\r\n\r\n    <div class=\"row\">\r\n      <label style=\"min-width:100px\">Colour</label>\r\n      <div class=\"color-picker-row\">\r\n        <button type=\"button\" class=\"color-btn\" id=\"editOpenPalette\">Select colour</button>\r\n        <span id=\"editDevColorPreview\" class=\"swatch swatch-lg\" title=\"Selected colour\"></span>\r\n      </div>\r\n    </div>\r\n\r\n    <div class=\"actions\">\r\n      <button type=\"button\" id=\"editDevCancel\">Cancel</button>\r\n      <button type=\"button\" id=\"editDevSave\" class=\"btn\">Save</button>\r\n    </div>\r\n  </div>\r\n</div>\r\n\r\n\r\n<script>\r\n/* ===================== HIGHLIGHT TUNING ===================== */\r\nconst HI_OUTLINE = 0; // px: outer white ring \r\nconst HI_RING    = 5; // px: inner white ring thickness\r\nconst HI_BLUR    = 0; // px: inner white glow blur\r\n\r\n/* ===================== PROFILES STORAGE ===================== */\r\nvar STORE_KEY = 'ethcm_profiles_v1';\r\nvar OLD_SINGLE_KEY = 'ethcm_v12';\r\nvar defaultState = {\r\n  devices: [],\r\n  links: [],\r\n  portAliases: {},\r\n  reservedPorts: {},\r\n  portSpeeds: {},\r\n  portVlans: {},\r\n  portLinkedToNames: {}\r\n};\r\nfunction deepClone(o){ return JSON.parse(JSON.stringify(o)); }\r\nfunction uid(){ return 'id_' + Math.random().toString(36).slice(2,10); }\r\n\r\nvar store = (function(){\r\n  try{\r\n    var raw = localStorage.getItem(STORE_KEY);\r\n    if(raw){\r\n      var parsed = JSON.parse(raw);\r\n      if(parsed && parsed.current && parsed.profiles) return parsed;\r\n    }\r\n    var oldRaw = localStorage.getItem(OLD_SINGLE_KEY);\r\n    if(oldRaw){\r\n      var one = JSON.parse(oldRaw);\r\n      normalizeState(one);\r\n      return { current:'Migrated', profiles:{ 'Migrated': one } };\r\n    }\r\n  }catch(e){}\r\n  return { current:'Default', profiles:{ 'Default': deepClone(defaultState) } };\r\n})();\r\nfunction normalizeState(st){\r\n  st.devices = Array.isArray(st.devices) ? st.devices : [];\r\n  st.links   = Array.isArray(st.links)   ? st.links   : [];\r\n\r\n  st.portAliases = st.portAliases || {};\r\n  st.reservedPorts = st.reservedPorts || {};\r\n  st.portSpeeds = st.portSpeeds || {};\r\n  st.portVlans  = st.portVlans  || {};\r\n\r\n  // Safe forward-compat field (won't break anything if unused)\r\n  st.portLinkedToNames = st.portLinkedToNames || {};\r\n\r\n  st.devices.forEach(function(d){\r\n    // Device core fields\r\n    if (!d.id) d.id = uid();\r\n    if (d.name == null) d.name = 'Unnamed';\r\n    if (d.color == null) d.color = '#888';\r\n\r\n    // Port count\r\n    if (d.ports == null) d.ports = 1;\r\n\r\n    // Customer port names (per-port rename)\r\n    if (!d.portNames || typeof d.portNames !== 'object') d.portNames = {};\r\n\r\n    // Device max speed\r\n    if (d.maxSpeed === undefined) d.maxSpeed = null;\r\n\r\n    // Layout defaults\r\n    if (d.forceFullRow === undefined) d.forceFullRow = false;\r\n    if (d.midWrapMode === undefined) d.midWrapMode = 'balanced';\r\n    if (d.smallWrap === undefined) d.smallWrap = false;\r\n    if (d.dualLink === undefined) d.dualLink = false;\r\n    if (d.numbering === undefined) d.numbering = 'row';\r\n  });\r\n}\r\nfunction saveStore(){ try{ localStorage.setItem(STORE_KEY, JSON.stringify(store)); }catch(e){} }\r\n\r\n/* Active profile reference */\r\nvar state = store.profiles[store.current];\r\n\r\n/* ===================== DOM HELPERS ===================== */\r\nfunction $(s){ return document.querySelector(s); }\r\nfunction $all(s){ return Array.prototype.slice.call(document.querySelectorAll(s)); }\r\nfunction el(tag, attrs){\r\n  var node = document.createElement(tag); attrs = attrs||{};\r\n  Object.keys(attrs).forEach(function(k){\r\n    var v = attrs[k];\r\n    if(k === 'dataset'){ Object.keys(v).forEach(function(dk){ if(v[dk]!==undefined) node.dataset[dk] = v[dk]; }); }\r\n    else if(k === 'class'){ node.className = v; }\r\n    else if(k.indexOf('on') === 0 && typeof v === 'function'){ node.addEventListener(k.slice(2), v); }\r\n    else { node.setAttribute(k, v); }\r\n  });\r\n  for(var i=2;i<arguments.length;i++){ var c = arguments[i]; if(c==null) continue; node.appendChild(c.nodeType ? c : document.createTextNode(c)); }\r\n  return node;\r\n}\r\nfunction deviceById(id){ for(var i=0;i<state.devices.length;i++){ if(state.devices[i].id===id) return state.devices[i]; } return null; }\r\nfunction indexById(id){ return state.devices.findIndex(function(d){return d.id===id;}); }\r\n\r\nfunction parsePortKey(k){\r\n  // keyFor() format in ECCM is: deviceId:port:sub  (sub may be empty)\r\n  var parts = String(k).split(':');\r\n  return {\r\n    deviceId: parts[0],\r\n    port: Number(parts[1]),\r\n    sub: (parts.length > 2 && parts[2] !== '' ? Number(parts[2]) : null)\r\n  };\r\n}\r\n\r\nfunction clearManualPortName(deviceId, port, sub){\r\n  var d = deviceById(deviceId);\r\n  if (!d || !d.portNames) return false;\r\n\r\n  var k = keyFor(deviceId, port, sub);\r\n\r\n  if (k in d.portNames) {\r\n    delete d.portNames[k];\r\n\r\n    // If portNames becomes empty, remove it entirely (keeps storage clean)\r\n    if (Object.keys(d.portNames).length === 0) delete d.portNames;\r\n\r\n    saveStore();\r\n    return true;\r\n  }\r\n\r\n  return false;\r\n}\r\n\r\nfunction portLabelWithTerm(term, port, sub){\r\n  // term must already be \"Port\" / \"Interface\" / \"Jack\" etc\r\n  return term + ' ' + port + (sub != null ? '/' + (sub + 1) : '');\r\n}\r\n\r\nfunction getLinkForEndpoint(deviceId, port, sub){\r\n  sub = (sub == null ? null : sub);\r\n\r\n  for (var i = 0; i < state.links.length; i++) {\r\n    var L = state.links[i];\r\n\r\n    var aSub = (L.a.sub == null ? null : L.a.sub);\r\n    var bSub = (L.b.sub == null ? null : L.b.sub);\r\n\r\n    if (L.a.deviceId === deviceId && L.a.port === port && aSub === sub) return L;\r\n    if (L.b.deviceId === deviceId && L.b.port === port && bSub === sub) return L;\r\n  }\r\n  return null;\r\n}\r\n\r\nfunction purgePortNamesThatMatchTerm(term){\r\n  if (!term) return false;\r\n  var changed = false;\r\n\r\n  state.devices.forEach(function(d){\r\n    if (!d.portNames) return;\r\n\r\n    Object.keys(d.portNames).forEach(function(k){\r\n      var v = (d.portNames[k] || '').trim();\r\n      if (!v) return;\r\n\r\n      var info = parsePortKey(k);\r\n      // only purge if the saved value is exactly the default label for THAT key\r\n      var def = portLabelWithTerm(term, info.port, info.sub);\r\n\r\n      if (v === def) {\r\n        delete d.portNames[k];\r\n        changed = true;\r\n      }\r\n    });\r\n\r\n    // optional clean-up if object becomes empty\r\n    if (d.portNames && Object.keys(d.portNames).length === 0) delete d.portNames;\r\n  });\r\n\r\n  return changed;\r\n}\r\n\r\nfunction getPortTerm(){\r\n  // Defaults\r\n  if (!store.settings) store.settings = {};\r\n  var mode = store.settings.portTermMode || 'port';\r\n  var custom = (store.settings.portTermCustom || '').trim();\r\n\r\n  if (mode === 'interface') return 'Interface';\r\n  if (mode === 'custom') return custom || 'Port'; // fallback if empty\r\n  return 'Port';\r\n}\r\n\r\n// \"Port 5\" / \"Interface 5\" / \"Jack 5\"\r\nfunction portLabelDefault(port, sub){\r\n  var term = getPortTerm();\r\n  return term + ' ' + port + (sub != null ? '/' + (sub + 1) : '');\r\n}\r\n\r\n// Used in searches: \"port5\", \"interface5\", \"jack5\"\r\nfunction portSearchTokens(port){\r\n  var term = getPortTerm().toLowerCase();\r\n  return [\r\n    term + port,\r\n    term + ' ' + port,\r\n    String(port)\r\n  ];\r\n}\r\n\r\n/* ===================== LINK/RESERVED HELPERS (dual-aware) ===================== */\r\nfunction keyFor(deviceId, port, sub){ return deviceId + ':' + port + ':' + (sub==null ? '' : sub); }\r\nfunction aliasFor(deviceId, port, sub){ return state.portAliases[keyFor(deviceId,port,sub)] || ''; }\r\nfunction reservedLabelFor(deviceId, port, sub){\r\n  return (state.reservedPorts && state.reservedPorts[keyFor(deviceId,port,sub)]) || null;\r\n}\r\nfunction isReservedPort(deviceId, port, sub){\r\n  return !!reservedLabelFor(deviceId, port, sub);\r\n}\r\nfunction linkForPort(deviceId, port, sub){\r\n  for(var i=0;i<state.links.length;i++){\r\n    var L = state.links[i];\r\n    if((L.a.deviceId===deviceId && L.a.port===port && (L.a.sub||null)===(sub||null)) ||\r\n       (L.b.deviceId===deviceId && L.b.port===port && (L.b.sub||null)===(sub||null))) return L;\r\n  }\r\n  return null;\r\n}\r\nfunction getPeer(deviceId, port, sub){\r\n  var L = linkForPort(deviceId, port, sub); if(!L) return null;\r\n  if (L.a.deviceId===deviceId && L.a.port===port && (L.a.sub||null)===(sub||null)) return L.b;\r\n  return L.a;\r\n}\r\nfunction speedToMbps(s){\r\n  if (!s) return Infinity;\r\n  const n = Number(String(s).replace(/[^0-9.]/g,'')) || 0;\r\n  return String(s).includes('Gbit') ? n * 1000 : n;\r\n}\r\n\r\nfunction connectPorts(a, b) {\r\n  if (linkForPort(a.deviceId,a.port,a.sub) || linkForPort(b.deviceId,b.port,b.sub)) return false;\r\n  if (isReservedPort(a.deviceId,a.port,a.sub) || isReservedPort(b.deviceId,b.port,b.sub)) return false;\r\n\r\n  // Create link\r\n  var id = uid();\r\n  state.links.push({ id:id, a:a, b:b });\r\n\r\n  // --- AUTO-NEGOTIATE SPEED ---\r\n  var devA = deviceById(a.deviceId);\r\n  var devB = deviceById(b.deviceId);\r\n\r\n  var maxA = devA && devA.maxSpeed ? devA.maxSpeed : null;\r\n  var maxB = devB && devB.maxSpeed ? devB.maxSpeed : null;\r\n\r\n  var spA = speedToMbps(maxA);\r\n  var spB = speedToMbps(maxB);\r\n\r\n  var lowest = Math.min(spA, spB);\r\n\r\n  if (lowest !== Infinity) {\r\n    var label = lowest >= 1000 ? (lowest/1000 + ' Gbit') : (lowest + ' Mbit');\r\n    setSpeedFor(a.deviceId, a.port, a.sub, label);\r\n    setSpeedFor(b.deviceId, b.port, b.sub, label);\r\n  }\r\n\r\n  saveStore();\r\n  render();\r\n  highlightLink(id);\r\n  return true;\r\n}\r\n\r\nfunction recalcLinkSpeedsForDevice(deviceId) {\r\n  const dev = deviceById(deviceId);\r\n  if (!dev) return;\r\n\r\n  state.links.forEach(function(L) {\r\n    let a = L.a;\r\n    let b = L.b;\r\n\r\n    // Only recalc links involving this device\r\n    if (a.deviceId !== deviceId && b.deviceId !== deviceId) return;\r\n\r\n    const devA = deviceById(a.deviceId);\r\n    const devB = deviceById(b.deviceId);\r\n    if (!devA || !devB) return;\r\n\r\n    const spA = speedToMbps(devA.maxSpeed);\r\n    const spB = speedToMbps(devB.maxSpeed);\r\n\r\n    const lowest = Math.min(spA, spB);\r\n\r\n    if (lowest !== Infinity) {\r\n      const label = lowest >= 1000\r\n        ? (lowest / 1000 + ' Gbit')\r\n        : (lowest + ' Mbit');\r\n\r\n      setSpeedFor(a.deviceId, a.port, a.sub, label);\r\n      setSpeedFor(b.deviceId, b.port, b.sub, label);\r\n    }\r\n  });\r\n}\r\n\r\nfunction speedFor(deviceId, port, sub){\r\n  return (state.portSpeeds || {})[keyFor(deviceId,port,sub)] || '';\r\n}\r\nfunction setSpeedFor(deviceId, port, sub, val){\r\n  var k = keyFor(deviceId,port,sub);\r\n  state.portSpeeds = state.portSpeeds || {};\r\n  if (!val) delete state.portSpeeds[k]; else state.portSpeeds[k] = String(val);\r\n  saveStore();\r\n}\r\n\r\nfunction vlanFor(deviceId, port, sub){\r\n  var v = (state.portVlans || {})[keyFor(deviceId,port,sub)];\r\n  return (v==null || v==='') ? '' : Number(v);\r\n}\r\nfunction setVlanFor(deviceId, port, sub, val){\r\n  var k = keyFor(deviceId,port,sub);\r\n  state.portVlans = state.portVlans || {};\r\n  if (val==null || val==='') { delete state.portVlans[k]; }\r\n  else {\r\n    var n = Math.max(1, Math.min(4094, Number(val)||0)); // clamp 1–4094\r\n    state.portVlans[k] = n;\r\n  }\r\n  saveStore();\r\n}\r\nfunction linkedToOverrideFor(deviceId, port, sub){\r\n  return (state.portLinkedTo || {})[keyFor(deviceId, port, sub)] || '';\r\n}\r\nfunction setLinkedToOverrideFor(deviceId, port, sub, val){\r\n  var k = keyFor(deviceId, port, sub);\r\n  state.portLinkedTo = state.portLinkedTo || {};\r\n  if (!val) delete state.portLinkedTo[k];\r\n  else state.portLinkedTo[k] = String(val);\r\n  saveStore();\r\n}\r\n\r\nfunction fmtSpeed(val){\r\n  // normalize display\r\n  switch(String(val||'')){\r\n    case '100 Mbit': return '100 Mbit';\r\n    case '1 Gbit': return '1 Gbit';\r\n    case '2.5 Gbit': return '2.5 Gbit';\r\n    case '5 Gbit': return '5 Gbit';\r\n    case '10 Gbit': return '10 Gbit';\r\n    case '25 Gbit': return '25 Gbit';\r\n    case '40 Gbit': return '40 Gbit';\r\n    case '100 Gbit': return '100 Gbit';\r\n    default: return '';\r\n  }\r\n}\r\n\r\n\r\n/* ===================== COLOUR / SELECTION ===================== */\r\nfunction hexToRgb(hex){ var h = String(hex||'').replace('#','').trim(); if (h.length===3) h = h.split('').map(function(c){return c+c}).join(''); var n = parseInt(h,16); if (isNaN(n)||h.length!==6) return {r:15,g:20,b:29}; return { r:(n>>16)&255, g:(n>>8)&255, b:n&255 }; }\r\nfunction bestTextColorFor(bgHex){ var c = hexToRgb(bgHex); var L = 0.2126*(c.r/255) + 0.7152*(c.g/255) + 0.0722*(c.b/255); return (L > 0.6) ? '#000' : '#fff'; }\r\nfunction paintPortBase(node, bgHex){\r\n  var bg = bgHex || '#0f141d';\r\n  node.style.background = bg;\r\n  node.style.borderRadius = '10px';\r\n  var txt = bestTextColorFor(bg);\r\n  node.style.color = txt;\r\n  var alias = node.querySelector('.alias'); if (alias) alias.style.color = txt;\r\n  var num   = node.querySelector('.num');   if (num)   num.style.color   = txt;\r\n  var peer  = node.querySelector('.peer');  if (peer)  peer.style.color  = txt;\r\n}\r\n\r\n/* CLEAR selection visuals */\r\nfunction clearSelectionOutlines(){\r\n  $all('.port.selected').forEach(function(n){\r\n    n.classList.remove('selected');\r\n    n.style.boxShadow = 'none';\r\n  });\r\n}\r\n\r\n/* APPLY selection visuals: same on singles and dual halves */\r\nfunction outlineForSelection(node){\r\n  node.classList.add('selected');\r\n\r\n  var isBright = document.documentElement.classList.contains('theme-bright');\r\n  var edgeClr = isBright ? '#000' : '#fff';\r\n  var glowClr = isBright ? 'rgba(0,0,0,.38)' : 'rgba(255,255,255,.38)';\r\n\r\n  var o = HI_OUTLINE, r = HI_RING, b = HI_BLUR;\r\n  node.style.boxShadow =\r\n    '0 0 0 ' + o + 'px ' + edgeClr + ',' +\r\n    'inset 0 0 0 ' + r + 'px ' + edgeClr + ',' +\r\n    'inset 0 0 ' + b + 'px ' + glowClr;\r\n}\r\n\r\n/* ---------- Hovercard (only shows while item is highlighted) ---------- */\r\nvar __hoverEl = null;\r\n\r\nfunction hcEnsure(){\r\n  if (!__hoverEl){\r\n    __hoverEl = document.createElement('div');\r\n    __hoverEl.className = 'hovercard';\r\n    document.body.appendChild(__hoverEl);\r\n  }\r\n  return __hoverEl;\r\n}\r\nfunction hcHide(){ if(__hoverEl) __hoverEl.style.display = 'none'; }\r\n\r\nfunction hcShowForTarget(target, html, evt){\r\n  var el = hcEnsure();\r\n  el.innerHTML = html;\r\n  el.style.display = 'block';\r\n  var x = 0, y = 0;\r\n  if (evt && typeof evt.clientX === 'number'){\r\n    x = evt.clientX + 14;\r\n    y = evt.clientY + 12;\r\n  } else {\r\n    var r = target.getBoundingClientRect();\r\n    x = r.right + 12;\r\n    y = r.top + 8;\r\n  }\r\n  // Keep in viewport\r\n  var vw = window.innerWidth, vh = window.innerHeight;\r\n  var ew = el.offsetWidth || 240, eh = el.offsetHeight || 100;\r\n  if (x + ew + 8 > vw) x = vw - ew - 8;\r\n  if (y + eh + 8 > vh) y = vh - eh - 8;\r\n  el.style.left = x + 'px';\r\n  el.style.top  = y + 'px';\r\n}\r\n\r\n/* Hide the hovercard whenever selection is cleared */\r\nconst __orig_clearSel = clearSelectionOutlines;\r\nclearSelectionOutlines = function(){\r\n  hcHide();\r\n  return __orig_clearSel.apply(this, arguments);\r\n};\r\n/* Also hide when we un-highlight a link */\r\nconst __orig_highlightLink = highlightLink;\r\nhighlightLink = function(id, opts){\r\n  if (!id) hcHide();\r\n  return __orig_highlightLink.apply(this, arguments);\r\n};\r\n\r\n\r\n/* ===================== UNIFORM PORT WIDTHS (two gaps) ===================== */\r\nfunction updateUniformPortWidth(){\r\n  var host = document.getElementById('devRows'); if(!host) return;\r\n  var GAP_COL = 12;\r\n  var PAD_BRD = 26;\r\n  var gapFull = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--portGapFull')) || 9;\r\n  var gapHalf = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--portGapHalf')) || 8;\r\n  var Wrows = host.getBoundingClientRect().width || 800;\r\n  var WfullInner = Wrows - PAD_BRD;\r\n  var WhalfInner = ((Wrows - GAP_COL)/2) - PAD_BRD;\r\n  var portW12 = (WfullInner - (11*gapFull)) / 12;\r\n  var portW6  = (WhalfInner - (5*gapHalf)) / 6;\r\n  portW12 = Math.max(40, portW12);\r\n  portW6  = Math.max(40, portW6);\r\n  document.documentElement.style.setProperty('--portW12', portW12 + 'px');\r\n  document.documentElement.style.setProperty('--portW6',  portW6  + 'px');\r\n}\r\nvar __pw_timer=null;\r\nwindow.addEventListener('resize', function(){ clearTimeout(__pw_timer); __pw_timer=setTimeout(updateUniformPortWidth, 60); });\r\n\r\n/* ===================== LAYOUT RULES ===================== */\r\nfunction isFullWidthDevice(d){\r\n  if (d.forceFullRow) return true;\r\n  if ((d.ports||1) >= 13) return true;\r\n  if ((d.ports||1) >= 7 && !d.smallWrap) return true;\r\n  return false;\r\n}\r\nfunction splitPortsIntoRows(n, dev){\r\n  if (n === 12 && dev.smallWrap) return [6, 6];\r\n\r\n  if (n >= 12){\r\n    if (n >= 13 && n <= 24 && dev.midWrapMode === 'balanced'){\r\n      var a = Math.ceil(n/2);\r\n      return [Math.min(12, a), Math.min(12, n - a)];\r\n    }\r\n    var rows = [], rem = n;\r\n    while (rem > 0){ rows.push(Math.min(12, rem)); rem -= 12; }\r\n    return rows;\r\n  }\r\n  if (n >= 7){\r\n    if (dev.smallWrap){ var a = Math.ceil(n/2); return [a, n - a]; }\r\n    return [n];\r\n  }\r\n  return [n];\r\n}\r\n\r\n\r\n/* ===================== CONNECT SELECTION ===================== */\r\nvar pendingPort = null;\r\nvar highlightedLinkId = null;\r\n\r\n/* ===================== RENDER DEVICES ===================== */\r\nfunction applyPeerScrolling() {\r\n  requestAnimationFrame(() => {\r\n    const peers = document.querySelectorAll('.peer');\r\n\r\n    peers.forEach(peer => {\r\n      const span = peer.querySelector('span');\r\n      if (!span) return;\r\n\r\n      const sw = span.getBoundingClientRect().width;\r\n      const cw = peer.clientWidth;\r\n\r\n      if (sw > cw) {\r\n        // calculate how far to bounce\r\n        const diff = sw - cw;\r\n        span.style.setProperty('--peer-width', `${cw}px`);\r\n        span.style.setProperty('--peer-diff', `${diff}px`);\r\n\r\n        peer.classList.add('scroll');\r\n      } else {\r\n        peer.classList.remove('scroll');\r\n      }\r\n    });\r\n  });\r\n}\r\n\r\n\r\nfunction renderDevices(){\r\n  var host = $('#devRows'); host.innerHTML='';\r\n  if(!state.devices.length){ host.appendChild(el('div',{class:'muted'},'No devices yet — add one on the left.')); updateUniformPortWidth(); return; }\r\n\r\n  var i=0;\r\n  while(i < state.devices.length){\r\n    var rowEl = el('div',{class:'dev-row'});\r\n    var d = state.devices[i];\r\n    if (isFullWidthDevice(d)){\r\n      rowEl.appendChild(renderDeviceWrap(d, true)); i += 1;\r\n    } else {\r\n      rowEl.appendChild(renderDeviceWrap(d, false));\r\n      if (i+1 < state.devices.length && !isFullWidthDevice(state.devices[i+1])){\r\n        rowEl.appendChild(renderDeviceWrap(state.devices[i+1], false)); i += 2;\r\n      } else {\r\n        rowEl.appendChild(el('div',{class:'device-wrap'}, el('div',{class:'device', style:'visibility:hidden'}, ' '))); i += 1;\r\n      }\r\n    }\r\n    host.appendChild(rowEl);\r\n  }\r\n  updateUniformPortWidth();\r\n}\r\n\r\nfunction renderDeviceWrap(d, fullWidth){\r\n  var wrap = el('div',{class:'device-wrap ' + (fullWidth ? 'full' : ''), dataset:{id:d.id}});\r\n  wrap.draggable = true;\r\n\r\n  wrap.addEventListener('dragstart', function(e){\r\n    wrap.classList.add('dragging');\r\n    e.dataTransfer.setData('text/plain', d.id);\r\n    e.dataTransfer.effectAllowed='move';\r\n  });\r\n  wrap.addEventListener('dragend', function(){ wrap.classList.remove('dragging'); });\r\n  wrap.addEventListener('dragover', function(e){ e.preventDefault(); e.dataTransfer.dropEffect='move'; });\r\n  wrap.addEventListener('drop', function(e){\r\n    e.preventDefault();\r\n    var draggedId = e.dataTransfer.getData('text/plain'); if (!draggedId || draggedId === d.id) return;\r\n    var from = indexById(draggedId), to = indexById(d.id); if (from<0 || to<0) return;\r\n    var item = state.devices.splice(from,1)[0]; if (from < to) to -= 1; state.devices.splice(to,0,item);\r\n    saveStore(); render();\r\n  });\r\n\r\n  var head = el('div',{class:'device-head'},\r\n    el('div',{class:'device-title'},\r\n      el('span',{class:'swatch', style:'background:'+(d.color||'#888')}),\r\n      document.createTextNode(d.name||'Unnamed')\r\n    ),\r\n    el('div',{class:'device-actions'},\r\n      el('button',{title:'Layout options', onclick:function(ev){ ev.stopPropagation(); openLayoutModal(d.id); }}, 'Layout'),\r\n\t\tel('button', {\r\n\t\t  title: 'Edit device',\r\n\t\t  onclick: function (ev) {\r\n\t\t\tev.stopPropagation();\r\n\t\t\topenEditDeviceModal(d.id);\r\n\t\t  }\r\n\t\t}, 'Edit'),\r\n      el('button',{class:'btn-danger',title:'Delete', onclick:function(ev){\r\n        ev.stopPropagation();\r\n        if(!confirm('Delete \"'+(d.name||'Unnamed')+'\" and its links?')) return;\r\n        state.links = state.links.filter(function(L){\r\n          return String(L.a.deviceId)!==String(d.id) && String(L.b.deviceId)!==String(d.id);\r\n        });\r\n        state.devices = state.devices.filter(function(x){ return String(x.id)!==String(d.id); });\r\n        Object.keys(state.portAliases).forEach(function(k){\r\n          if(k.split(':')[0]===String(d.id)) delete state.portAliases[k];\r\n        });\r\n        saveStore(); render();\r\n      }}, 'Delete')\r\n    )\r\n  );\r\n\r\n  var meta = el('div',{class:'meta'},\r\n    document.createTextNode((d.ports||1)+' ports'),\r\n    (function(){\r\n      var c = el('span',{class:'inline-controls'},\r\n        el('button',{class:'mini', title:'Remove one port', onclick:function(e){ e.stopPropagation(); if ((d.ports||1) <= 1) return; var newCount = (d.ports||1)-1; var affected = linksOnPortsBeingRemoved(d, newCount); if (affected.length > 0 && !confirm('Warning: The port(s) that will be removed have linked connections (' + affected.length + '). Removing the port will also remove these connections. Are you sure you want to continue?')) return; changePorts(d, newCount); saveStore(); render(); }}, '– ' + getPortTerm()),\r\n\t\tel('button',{class:'mini', title:'Add one port', onclick:function(e){ e.stopPropagation(); changePorts(d, (d.ports||1)+1); saveStore(); render(); }}, '+ ' + getPortTerm())      \r\n      );\r\n      return c;\r\n    })()\r\n  );\r\n\r\n  var portsContainer = el('div',{class:'ports-rows'});\r\nvar rows = splitPortsIntoRows(d.ports||1, d);\r\nvar total = d.ports || 1;\r\nvar seqByRow = rows.map(function(cnt){ return new Array(cnt); });\r\n\r\nfunction buildRowMajor(){\r\n  var n = 1;\r\n  rows.forEach(function(count, r){\r\n    for (var c=0; c<count; c++) seqByRow[r][c] = n++;\r\n  });\r\n}\r\n\r\nfunction buildColumnMajor(){\r\n  var maxCols = Math.max.apply(null, rows);\r\n  var n = 1;\r\n  for (var c=0; c<maxCols && n<=total; c++){\r\n    for (var r=0; r<rows.length && n<=total; r++){\r\n      if (c < rows[r]) { seqByRow[r][c] = n++; }\r\n    }\r\n  }\r\n  for (var r=0; r<rows.length; r++){\r\n    for (var c=0; c<rows[r]; c++){\r\n      if (seqByRow[r][c] == null) seqByRow[r][c] = n++;\r\n    }\r\n  }\r\n}\r\n\r\nfunction buildColumnMajorBottomTop(){\r\n  var maxCols = Math.max.apply(null, rows);\r\n  var n = 1;\r\n\r\n  // Fill by columns, but bottom row first\r\n  for (var c=0; c<maxCols && n<=total; c++){\r\n    for (var r=rows.length-1; r>=0 && n<=total; r--){\r\n      if (c < rows[r]) { seqByRow[r][c] = n++; }\r\n    }\r\n  }\r\n\r\n  // Safety fill (should rarely be needed)\r\n  for (var r=0; r<rows.length; r++){\r\n    for (var c=0; c<rows[r]; c++){\r\n      if (seqByRow[r][c] == null) seqByRow[r][c] = n++;\r\n    }\r\n  }\r\n}\r\n\r\n\r\n// Choose numbering mode\r\nif (d.numbering === 'column') buildColumnMajor();\r\nelse if (d.numbering === 'column-bt') buildColumnMajorBottomTop();\r\nelse buildRowMajor();\r\n\r\n  function createSubPort(d, p, sub){\r\n  var linked   = !!linkForPort(d.id, p, sub);\r\n  var peer     = linked ? getPeer(d.id,p,sub) : null;\r\n  var peerDev  = peer ? deviceById(peer.deviceId) : null;\r\n  var peerPort = peer ? peer.port : null;\r\n  var alias    = aliasFor(d.id,p,sub);\r\n  var reserved = reservedLabelFor(d.id,p,sub);\r\n\r\n  var rawSpeed = (typeof speedFor === 'function') ? speedFor(d.id, p, sub) : '';\r\n  var spdVal   = fmtSpeed(rawSpeed) || '';\r\n  var vlanVal  = (typeof vlanFor === 'function') ? vlanFor(d.id, p, sub) : '';\r\n\r\n  var hasSpeed = (rawSpeed !== '' && rawSpeed != null);\r\n  var hasVlan  = (vlanVal  !== '' && vlanVal  != null);\r\n\r\n// Auto-negotiate for older links that have no stored speed yet\r\nif (linked && !hasSpeed) {\r\n  var dev    = deviceById(d.id);\r\n  var peerDv = peerDev; // already computed above\r\n\r\n  if (dev && dev.maxSpeed && peerDv && peerDv.maxSpeed) {\r\n    var spA   = speedToMbps(dev.maxSpeed);\r\n    var spB   = speedToMbps(peerDv.maxSpeed);\r\n    var low   = Math.min(spA, spB);\r\n\r\n    if (low !== Infinity) {\r\n      var label = low >= 1000 ? (low/1000 + ' Gbit') : (low + ' Mbit');\r\n\r\n      // Persist on both ends so future renders see it\r\n      setSpeedFor(d.id, p, sub, label);\r\n      setSpeedFor(peer.deviceId, peer.port, peer.sub, label);\r\n\r\n      rawSpeed = label;\r\n      spdVal   = fmtSpeed(label);\r\n      hasSpeed = true;\r\n    }\r\n  }\r\n}\r\n\r\n\r\nvar leftInd  = el('span',{class:'ind spd-dot'}, '');\r\nvar rightInd = el('span',{class:'ind vlan-diamond'}, '');\r\n\r\nif (hasSpeed){\r\n  leftInd.title = spdVal;\r\n} else {\r\n  leftInd.classList.add('ind--off');\r\n}\r\n\r\nif (hasVlan){\r\n  rightInd.title = String(vlanVal);\r\n} else {\r\n  rightInd.classList.add('ind--off');\r\n}\r\n\r\nvar portLabel =\r\n  (d.portNames && d.portNames[keyFor(d.id, p, sub)]) ||\r\n  portLabelDefault(p, sub);\r\n\r\nvar numEl = el('div',{class:'num'},\r\n  leftInd,\r\n  el('span',{class:'num-label'}, portLabel),\r\n  rightInd\r\n);\r\n\r\nfunction bindMiniHover(indEl, label, value){\r\n  if(!indEl || indEl.classList.contains('ind--off')) return;\r\n  indEl.addEventListener('mouseenter', function(e){\r\n    hcShowForTarget(indEl,\r\n      '<div class=\"hc-title\">'+label+'</div><div>'+value+'</div>', e);\r\n  });\r\n  indEl.addEventListener('mousemove', function(e){\r\n    hcShowForTarget(indEl,\r\n      '<div class=\"hc-title\">'+label+'</div><div>'+value+'</div>', e);\r\n  });\r\n  indEl.addEventListener('mouseleave', hcHide);\r\n}\r\nbindMiniHover(leftInd,  'Link speed', spdVal);\r\nbindMiniHover(rightInd, 'VLAN',  String(vlanVal));\r\n// Slow-link indicator: port speed < device max → add \"!\" before speed square\r\n(function () {\r\n  var dev = deviceById(d.id);\r\n  if (!dev || !dev.maxSpeed) return;\r\n  if (!rawSpeed) return; // no explicit port speed set → nothing to compare\r\n\r\n  function toMbps(s) {\r\n    var txt = String(s || '').toLowerCase();\r\n    if (!txt) return 0;\r\n    var num = parseFloat(txt.replace(/[^0-9.]/g, '')) || 0;\r\n    if (!num) return 0;\r\n    // Treat values like \"1 gbit\", \"1 gbps\" etc. as Gbit\r\n    if (txt.indexOf('gbit') !== -1 || txt.indexOf('gbps') !== -1) return num * 1000;\r\n    return num; // assume Mbit\r\n  }\r\n\r\n  var devMaxMbps = toMbps(dev.maxSpeed);\r\n  var portMbps   = toMbps(rawSpeed);\r\n\r\n  if (devMaxMbps && portMbps && portMbps < devMaxMbps) {\r\n    leftInd.insertAdjacentHTML(\r\n      'beforebegin',\r\n      '<span class=\"slow-warn\" style=\"font-weight:900;margin-right:2px;\">!</span>'\r\n    );\r\n  }\r\n})();\r\n\r\n// Build peer text: Device Name + Port Name or Reserved\r\nvar defaultPeerText =\r\n  reserved\r\n    ? (reserved || 'Reserved')\r\n    : (\r\n        peer && peerDev\r\n          ? (peerDev.name + ' - ' +\r\n             (\r\n               (peerDev.portNames && peerDev.portNames[keyFor(peer.deviceId, peerPort, peer.sub)]) ||\r\n               portLabelDefault(peerPort, peer.sub)\r\n             )\r\n            )\r\n          : ''\r\n      );\r\n\r\n// If user has overridden \"Linked to\", show it here too\r\nvar peerOverride = (typeof linkedToOverrideFor === 'function') ? linkedToOverrideFor(d.id, p, sub) : '';\r\nvar peerText = (peerOverride !== '' ? peerOverride : defaultPeerText);\r\n\r\n\r\n// Create peer element with a <span> for scrolling later\r\nvar peerEl = el(\r\n  'div',\r\n  { class: 'peer' },\r\n  el('span', {}, peerText)\r\n);\r\n\r\n\r\n\r\n  var node = el('div',{\r\n      class:'port'+(linked?' connected':'')+(reserved?' reserved':''), \r\n      dataset:{deviceId:d.id, port:p, sub:(sub==null?undefined:sub)}\r\n    },\r\n    numEl, \r\n    el('div',{class:'alias'}, alias||''),\r\n\tpeerEl \r\n  );\r\n\r\n  if (reserved){\r\n    paintPortBase(node, 'var(--reserved-bg)');\r\n  } else if (linked && peerDev){\r\n    paintPortBase(node, peerDev.color || '#22354a');\r\n  } else {\r\n    paintPortBase(node, '#0f141d');\r\n  }\r\n\r\n  node.addEventListener('click', function(ev){\r\n    if (ev.altKey){\r\n      var curr = aliasFor(d.id,p,sub);\r\n      var next = prompt('Optional port label (blank to clear):', curr||'');\r\n      if(next===null) return;\r\n      var k = keyFor(d.id,p,sub);\r\n      if(!next.trim()) delete state.portAliases[k]; else state.portAliases[k] = next.trim();\r\n      saveStore(); render(); return;\r\n    }\r\n\r\n    if (ev.ctrlKey){\r\n      var k = keyFor(d.id,p,sub);\r\n      if (state.reservedPorts && state.reservedPorts[k]){\r\n\t\tvar term = getPortTerm();\r\n        if(confirm('Clear reserved status for ' + term + ' ' +p+(sub!=null?('/'+(sub+1)):'')+'?')){\r\n          delete state.reservedPorts[k];\r\n        }\r\n      } else {\r\n        if (!state.reservedPorts) state.reservedPorts = {};\r\n        var lbl = prompt('Reserved port label (e.g. WAN):', '');\r\n        if (lbl===null) return;\r\n        state.reservedPorts[k] = (lbl && lbl.trim()) ? lbl.trim() : 'Reserved';\r\n      }\r\n      pendingPort = null;\r\n      saveStore(); render();\r\n      return;\r\n    }\r\n\r\n    if (reserved){\r\n      clearSelectionOutlines();\r\n      outlineForSelection(node);\r\n      highlightedLinkId = null; applyRowHighlight();\r\n      pendingPort = null;\r\n      return;\r\n    }\r\n\r\n    if (linkForPort(d.id, p, sub)) {\r\n      clearSelectionOutlines();\r\n      var L1 = linkForPort(d.id, p, sub);\r\n      highlightLink(L1.id, { from:{deviceId:d.id, port:p, sub:sub} });\r\n      pendingPort = null; return;\r\n    }\r\n\r\n    if (!pendingPort){\r\n      pendingPort = {deviceId:d.id, port:p, sub:sub};\r\n      clearSelectionOutlines(); outlineForSelection(node);\r\n      highlightedLinkId = null; applyRowHighlight();\r\n      return;\r\n    }\r\n    if (linkForPort(d.id, p, sub) || linkForPort(pendingPort.deviceId, pendingPort.port, pendingPort.sub) ||\r\n        isReservedPort(d.id,p,sub) || isReservedPort(pendingPort.deviceId,pendingPort.port,pendingPort.sub)){\r\n      alert('That port (or the previously selected one) is unavailable. Unlink/clear Reserved first.');\r\n      pendingPort = null; clearSelectionOutlines(); highlightLink(null); return;\r\n    }\r\n\r\n    var devA = deviceById(pendingPort.deviceId);\r\n    var devB = deviceById(d.id);\r\n    var msg = 'Create link:\\n' + (devA?devA.name:'A') + getPortTerm() + pendingPort.port + (pendingPort.sub!=null?'/'+(pendingPort.sub+1):'')\r\n              + ' ⇄ ' + (devB?devB.name:'B') + ' Port ' + p + (sub!=null?'/'+(sub+1):'');\r\n    if (!confirm(msg)){ pendingPort = null; clearSelectionOutlines(); return; }\r\n    var ok = connectPorts(pendingPort, {deviceId:d.id, port:p, sub:sub});\r\n    pendingPort = null;\r\n    if (!ok){ alert('Could not connect.'); clearSelectionOutlines(); highlightLink(null); }\r\n  });\r\n\r\n  function buildHoverHTML() {\r\n    var liveAlias = aliasFor(d.id, p, sub) || '—';\r\n    var liveSpeed = (typeof speedFor === 'function' ? fmtSpeed(speedFor(d.id, p, sub)) : '') || '—';\r\n\r\n    var vlanRaw  = (typeof vlanFor==='function' ? vlanFor(d.id, p, sub) : '');\r\n    var vlanText = (vlanRaw === '' ? '—' : vlanRaw);\r\n\r\n    var liveReserved = typeof isReservedPort === 'function' && isReservedPort(d.id, p, sub);\r\n    var liveLink = linkForPort(d.id, p, sub);\r\n    var status = liveReserved ? 'Reserved' : (liveLink ? 'Linked' : 'Free');\r\n\r\n    var peerTxt = '—';\r\n    if (liveReserved) {\r\n      peerTxt = (typeof reservedLabelFor === 'function' && reservedLabelFor(d.id, p, sub)) || 'Reserved';\r\n    } else if (liveLink) {\r\n      var livePeer = getPeer(d.id, p, sub);\r\n      var livePeerDev = livePeer ? deviceById(livePeer.deviceId) : null;\r\n      if (livePeer && livePeerDev) {\r\n        peerTxt = livePeerDev.name + ' • Port ' + livePeer.port +\r\n                  (livePeer.sub != null ? '/' + (livePeer.sub + 1) : '');\r\n      }\r\n    }\r\n\r\n    return (\r\n      '<div class=\"hc-title\">' + (d.name || 'Device') + '</div>' +\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">' + getPortTerm() + '</div><div>' +\r\n        p + (sub != null ? '/' + (sub + 1) : '') + '</div></div>' +\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">Alias</div><div>' + liveAlias + '</div></div>' +\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">Peer</div><div>' + peerTxt + '</div></div>'+\t\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">Status</div><div>' + status + '</div></div>' +\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">Link speed</div><div>' + liveSpeed + '</div></div>' +\r\n      '<div class=\"hc-row\"><div class=\"hc-k\">VLAN</div><div>' + vlanText  + '</div></div>'\r\n    );\r\n  }\r\n\r\n\tnode.addEventListener('mouseenter', function (e) {\r\n\t  if (__menuOpen || !node.classList.contains('selected')) return;\r\n\t  hcShowForTarget(node, buildHoverHTML(), e);\r\n\t});\r\n\tnode.addEventListener('mousemove', function (e) {\r\n\t  if (__menuOpen || !node.classList.contains('selected')) return;\r\n\t  hcShowForTarget(node, buildHoverHTML(), e);\r\n\t});\r\n\r\n  node.addEventListener('mouseleave', function () { hcHide(); });\r\n\r\n  node.addEventListener('contextmenu', function(ev){\r\n    openSpeedMenu(ev, d.id, p, sub);\r\n  });\r\n\r\n  return node;\r\n}\r\n\r\n\r\n  function renderPortCell(d, p){\r\n    if (!d.dualLink) return createSubPort(d, p, null);\r\n    var wrapCell = document.createElement('div');\r\n    wrapCell.className = 'dual-cell';\r\n    wrapCell.style.display = 'flex';\r\n    wrapCell.style.flexDirection = 'column';\r\n    wrapCell.style.border = '1px solid var(--line)';\r\n    wrapCell.style.borderRadius = '10px';\r\n    wrapCell.style.overflow = 'hidden';\r\n    wrapCell.style.background = 'transparent';\r\n    var top = createSubPort(d, p, 0);\r\n    top.style.border = '0';\r\n    top.style.borderRadius = '10px 10px 0 0';\r\n    var bottom = createSubPort(d, p, 1);\r\n    bottom.style.border = '0';\r\n    bottom.style.borderTop = '1px solid var(--line)';\r\n    bottom.style.borderRadius = '0 0 10px 10px';\r\n    wrapCell.appendChild(top); wrapCell.appendChild(bottom);\r\n    return wrapCell;\r\n  }\r\n\r\n\trows.forEach(function(count, rIndex){\r\n\t  var row = el('div',{class:'port-row'});\r\n\t  row.style.gridTemplateColumns = fullWidth ? 'repeat(12, var(--portW12))' : 'repeat(6, var(--portW6))';\r\n\t  row.style.gap = fullWidth ? 'var(--portGapFull)' : 'var(--portGapHalf)';\r\n\t  for (var c=0; c<count; c++){\r\n\t\tvar p = seqByRow[rIndex][c];\r\n\t\trow.appendChild(renderPortCell(d, p));\r\n\t  }\r\n\t  portsContainer.appendChild(row);\r\n\t});\r\n\r\n  var card = el('div',{class:'device', id:'dev-'+d.id}, head, meta, portsContainer);\r\n  wrap.appendChild(card);\r\n  return wrap;\r\n}\r\n\r\n/* ===================== CHANGE PORT COUNT ===================== */\r\n/** Returns links on device d that would be removed when reducing to newCount ports (port numbers > newCount). */\r\nfunction linksOnPortsBeingRemoved(d, newCount){\r\n  if (newCount >= (d.ports || 1)) return [];\r\n  return state.links.filter(function(L){\r\n    var aRemoved = L.a.deviceId === d.id && L.a.port > newCount;\r\n    var bRemoved = L.b.deviceId === d.id && L.b.port > newCount;\r\n    return aRemoved || bRemoved;\r\n  });\r\n}\r\n\r\nfunction changePorts(d, newCount){\r\n  newCount = Math.max(1, Math.min(9999, Number(newCount)||1));\r\n  if (newCount === d.ports) return;\r\n  if (newCount < d.ports){\r\n    state.links = state.links.filter(function(L){\r\n      var aOk = !(L.a.deviceId===d.id && L.a.port>newCount);\r\n      var bOk = !(L.b.deviceId===d.id && L.b.port>newCount);\r\n      return aOk && bOk;\r\n    });\r\n    Object.keys(state.portAliases).forEach(function(k){\r\n      var parts = k.split(':'); if(parts[0]===d.id && Number(parts[1])>newCount) delete state.portAliases[k];\r\n    });\r\n    Object.keys(state.reservedPorts).forEach(function(k){\r\n      var parts = k.split(':'); if(parts[0]===d.id && Number(parts[1])>newCount) delete state.reservedPorts[k];\r\n    });\r\n  }\r\n  d.ports = newCount;\r\n}\r\n\r\n/* ===================== CONNECTIONS TABLE ===================== */\r\nfunction renderConnections() {\r\n  var tb = $('#connBody');\r\n  tb.innerHTML = '';\r\n\r\n  var q = ($('#searchBox').value || '').toLowerCase().trim();\r\n  var rows = [];\r\n\r\n  state.links.forEach(function (L, i) {\r\n    var da = deviceById(L.a.deviceId),\r\n        db = deviceById(L.b.deviceId);\r\n\r\n    var aName  = (da && da.name) || 'Unknown';\r\n    var bName  = (db && db.name) || 'Unknown';\r\n    var aAlias = aliasFor(L.a.deviceId, L.a.port, L.a.sub);\r\n    var bAlias = aliasFor(L.b.deviceId, L.b.port, L.b.sub);\r\n\r\n    // Use per-port custom name if present, otherwise fall back to the GLOBAL term (\"Port/Interface/Custom\")\r\n    var aPortLabel =\r\n      (da && da.portNames && da.portNames[keyFor(L.a.deviceId, L.a.port, L.a.sub)]) ||\r\n      portLabelDefault(L.a.port, L.a.sub);\r\n\r\n    var bPortLabel =\r\n      (db && db.portNames && db.portNames[keyFor(L.b.deviceId, L.b.port, L.b.sub)]) ||\r\n      portLabelDefault(L.b.port, L.b.sub);\r\n\r\n    var parts = [\r\n      aName,\r\n      ...portSearchTokens(L.a.port),\r\n      aPortLabel,\r\n      bName,\r\n      ...portSearchTokens(L.b.port),\r\n      bPortLabel,\r\n      aAlias,\r\n      bAlias\r\n    ];\r\n\r\n    var text = parts.join(' ').toLowerCase();\r\n    if (q && text.indexOf(q) === -1) return;\r\n\r\n    var aColor = da ? (da.color || '#ccc') : '#ccc';\r\n    var bColor = db ? (db.color || '#ccc') : '#ccc';\r\n\r\n    var tr = el(\r\n      'tr',\r\n      { class: 'conn-row', dataset: { linkId: L.id } },\r\n      el('td', {}, String(i + 1)),\r\n      el(\r\n        'td',\r\n        { class: 'deviceA' },\r\n        el('span', { class: 'devName', style: '--devColor:' + aColor, title: aName }, aName)\r\n      ),\r\n      el('td', {}, aPortLabel),\r\n      el('td', {}, aAlias),\r\n      el('td', {}, '⇄'),\r\n      el(\r\n        'td',\r\n        { class: 'deviceB' },\r\n        el('span', { class: 'devName', style: '--devColor:' + bColor, title: bName }, bName)\r\n      ),\r\n      el('td', {}, bPortLabel),\r\n      el('td', {}, bAlias),\r\n      el(\r\n        'td',\r\n        {},\r\n        el('button', { class: 'btn-danger', onclick: function () { unlink(L.id); } }, 'Unlink')\r\n      )\r\n    );\r\n\r\n    tr.addEventListener('click', function (e) {\r\n      if (e.target.tagName.toLowerCase() === 'button') return;\r\n      if (highlightedLinkId === L.id) {\r\n        highlightLink(null);\r\n        clearSelectionOutlines();\r\n        return;\r\n      }\r\n      highlightLink(L.id);\r\n\r\n      function sel(ep) {\r\n        var s = '.port[data-device-id=\"' + ep.deviceId + '\"][data-port=\"' + ep.port + '\"]';\r\n        if (ep.sub != null) s += '[data-sub=\"' + ep.sub + '\"]';\r\n        return s;\r\n      }\r\n\r\n      clearSelectionOutlines();\r\n      var portA = document.querySelector(sel(L.a));\r\n      var portB = document.querySelector(sel(L.b));\r\n      if (portA) outlineForSelection(portA);\r\n      if (portB) outlineForSelection(portB);\r\n    });\r\n\r\n    tr.addEventListener('mouseenter', function (e) {\r\n      if (!tr.classList.contains('highlight')) return;\r\n\r\n      var html =\r\n        '<div class=\"hc-title\">Connection</div>' +\r\n        '<div class=\"hc-row\"><div class=\"hc-k\">A</div><div>' +\r\n          aName + ' • ' + aPortLabel + (aAlias ? ' • ' + aAlias : '') +\r\n        '</div></div>' +\r\n        '<div class=\"hc-row\"><div class=\"hc-k\">B</div><div>' +\r\n          bName + ' • ' + bPortLabel + (bAlias ? ' • ' + bAlias : '') +\r\n        '</div></div>';\r\n\r\n      hcShowForTarget(tr, html, e);\r\n    });\r\n\r\n    tr.addEventListener('mousemove', function (e) {\r\n      if (!tr.hasAttribute('data-link-id')) return;\r\n      if (!tr.classList.contains('highlight')) return;\r\n      hcShowForTarget(tr, __hoverEl && __hoverEl.innerHTML || '', e);\r\n    });\r\n\r\n    tr.addEventListener('mouseleave', hcHide);\r\n\r\n    rows.push(tr);\r\n  });\r\n\r\n  // Reserved rows\r\n  if (state.reservedPorts) {\r\n    Object.keys(state.reservedPorts).forEach(function (k) {\r\n      var parts = k.split(':');\r\n      var devId = parts[0];\r\n      var port  = Number(parts[1]);\r\n      var sub   = (parts[2] === '' ? null : Number(parts[2]));\r\n      var d     = deviceById(devId);\r\n      if (!d) return;\r\n\r\n      var rLabel = state.reservedPorts[k];\r\n      var alias  = aliasFor(devId, port, sub);\r\n\r\n      var reservedPortLabel =\r\n        (d && d.portNames && d.portNames[keyFor(devId, port, sub)]) ||\r\n        portLabelDefault(port, sub);\r\n\r\n      var textParts = [\r\n        (d && d.name) || 'Unknown',\r\n        ...portSearchTokens(port),\r\n        reservedPortLabel,\r\n        alias || '',\r\n        rLabel || '',\r\n        (sub != null ? (sub === 0 ? 'top' : 'bottom') : '')\r\n      ];\r\n\r\n      var text = textParts.join(' ').toLowerCase();\r\n      if (q && text.indexOf(q) === -1) return;\r\n\r\n      var tr = el(\r\n        'tr',\r\n        {\r\n          class: 'conn-row reserved-row',\r\n          dataset: {\r\n            deviceId: devId,\r\n            port: String(port),\r\n            sub: (sub == null ? '' : String(sub))\r\n          }\r\n        },\r\n        el('td', {}, '—'),\r\n        el(\r\n          'td',\r\n          { class: 'deviceA' },\r\n          el(\r\n            'span',\r\n            { class: 'devName', style: '--devColor:' + (d.color || '#ccc'), title: d.name },\r\n            d.name\r\n          )\r\n        ),\r\n        el('td', {}, reservedPortLabel),\r\n        el('td', {}, alias || ''),\r\n        el('td', {}, '⟂'),\r\n        el(\r\n          'td',\r\n          { class: 'deviceB' },\r\n          el(\r\n            'span',\r\n            { class: 'devName', style: '--devColor:#666', title: 'Reserved' },\r\n            'Reserved'\r\n          )\r\n        ),\r\n        el('td', {}, '—'),\r\n        el('td', {}, rLabel || ''),\r\n        el(\r\n          'td',\r\n          {},\r\n          el('button', {\r\n              class: 'btn-danger',\r\n              onclick: function () {\r\n                delete state.reservedPorts[k];\r\n                saveStore();\r\n                render();\r\n              }\r\n            },\r\n            'Clear'\r\n          )\r\n        )\r\n      );\r\n\r\n      tr.addEventListener('click', function (e) {\r\n        if (e.target.tagName.toLowerCase() === 'button') return;\r\n        highlightedLinkId = null;\r\n        applyRowHighlight();\r\n        clearSelectionOutlines();\r\n\r\n        var sel =\r\n          '.port[data-device-id=\"' + devId + '\"][data-port=\"' + port + '\"]' +\r\n          (sub != null ? '[data-sub=\"' + sub + '\"]' : '');\r\n\r\n        var n = document.querySelector(sel);\r\n        if (n) outlineForSelection(n);\r\n      });\r\n\r\n      rows.push(tr);\r\n    });\r\n  }\r\n\r\n  if (!rows.length) {\r\n    tb.appendChild(\r\n      el(\r\n        'tr',\r\n        {},\r\n        el('td', { colspan: '9', class: 'muted' }, 'No connections found.')\r\n      )\r\n    );\r\n  } else {\r\n    rows.forEach(function (r) { tb.appendChild(r); });\r\n  }\r\n\r\n  applyRowHighlight();\r\n}\r\n\r\nfunction applyRowHighlight(){ $all('.conn-row').forEach(function(r){ if(highlightedLinkId && r.dataset.linkId===highlightedLinkId) r.classList.add('highlight'); else r.classList.remove('highlight'); }); }\r\nfunction highlightLink(linkId, opts){\r\n  highlightedLinkId = linkId; applyRowHighlight(); clearSelectionOutlines();\r\n  if (!linkId) return;\r\n  var L = state.links.find(function(x){ return x.id===linkId; }); if (!L) return;\r\n  function sel(ep){ var s='.port[data-device-id=\"'+ep.deviceId+'\"][data-port=\"'+ep.port+'\"]'; if(ep.sub!=null) s+='[data-sub=\"'+ep.sub+'\"]'; return s; }\r\n  var portA = document.querySelector(sel(L.a));\r\n  var portB = document.querySelector(sel(L.b));\r\n  if (portA) outlineForSelection(portA);\r\n  if (portB) outlineForSelection(portB);\r\n  if (opts && opts.from){\r\n    var origin = document.querySelector(sel(opts.from));\r\n    if (origin){ outlineForSelection(origin); }\r\n  }\r\n}\r\nfunction unlink(linkId){\r\n  state.links = state.links.filter(function(L){ return L.id!==linkId; });\r\n  if(highlightedLinkId===linkId) highlightedLinkId=null;\r\n  saveStore(); render();\r\n}\r\n\r\n/* ------- Speed picker (context menu) ------- */\r\nvar __speedMenu = null;\r\nvar __menuOpen = false;\r\n\r\nfunction closeSpeedMenu(){\r\n  if(__speedMenu){\r\n    __speedMenu.remove();\r\n    __speedMenu = null;\r\n  }\r\n  __menuOpen = false;\r\n  hcHide();\r\n  clearSelectionOutlines();\r\n}\r\n\r\nfunction openSpeedMenu(e, deviceId, port, sub){\r\n  closeSpeedMenu();\r\n  e.preventDefault();\r\n\r\n  __menuOpen = true;\r\n  hcHide();\r\n\r\n  clearSelectionOutlines();\r\n  const portEl = document.querySelector(\r\n    `.port[data-device-id=\"${deviceId}\"][data-port=\"${port}\"]${sub != null ? `[data-sub=\"${sub}\"]` : ''}`\r\n  );\r\n  if (portEl) outlineForSelection(portEl);\r\n\r\n  function defaultLabel(p, s){\r\n    if (typeof portLabelDefault === 'function') return portLabelDefault(p, s);\r\n    return 'Port ' + p + (s != null ? '/' + (s + 1) : '');\r\n  }\r\n\r\n  // Current link (if any) for this endpoint\r\n  var link = (typeof getLinkForEndpoint === 'function')\r\n    ? getLinkForEndpoint(deviceId, port, sub)\r\n    : null;\r\n\r\n  // Peer info (if linked)\r\n  var peer = null;\r\n  if (link) {\r\n    var aSub = (link.a.sub == null ? null : link.a.sub);\r\n    var bSub = (link.b.sub == null ? null : link.b.sub);\r\n    var subN = (sub == null ? null : sub);\r\n\r\n    if (link.a.deviceId === deviceId && link.a.port === port && aSub === subN) peer = link.b;\r\n    else peer = link.a;\r\n  }\r\n\r\n  var curSpeed = speedFor(deviceId, port, sub) || '';\r\n  var curVlan  = vlanFor(deviceId, port, sub);\r\n  var curVlanStr = (curVlan === '' || curVlan == null) ? '' : String(curVlan);\r\n\r\n  var peerDev = null;\r\n  var peerPortLabel = '';\r\n  if (peer) {\r\n    peerDev = deviceById(peer.deviceId);\r\n    peerPortLabel =\r\n      (peerDev && peerDev.portNames && peerDev.portNames[keyFor(peer.deviceId, peer.port, peer.sub)]) ||\r\n      defaultLabel(peer.port, peer.sub);\r\n  }\r\n\r\n  var div = document.createElement('div');\r\n  div.className = 'speed-menu';\r\n\r\n  div.innerHTML =\r\n    '<div style=\"font-size:12px;margin-bottom:6px;font-weight:600\">Port settings</div>' +\r\n\r\n    (store.settings.enablePortRename ? (\r\n      '<div style=\"display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px\">' +\r\n        '<label for=\"__nameInput\" style=\"margin:0;white-space:nowrap;min-width:70px\">Port name</label>' +\r\n        '<input id=\"__nameInput\" type=\"text\" placeholder=\"e.g. Channel 1\" ' +\r\n               'style=\"flex:1;padding:4px 6px;font-size:12px;border-radius:6px;' +\r\n                      'border:1px solid var(--line);background:var(--bg);color:var(--ink)\">' +\r\n        '<button id=\"__nameReset\" type=\"button\" title=\"Reset to default\" ' +\r\n               'style=\"padding:4px 6px;font-size:11px;border-radius:6px;border:1px solid var(--line);' +\r\n                      'background:var(--bg);color:var(--ink);cursor:pointer;\">↺</button>' +\r\n      '</div>'\r\n    ) : '') +\r\n\r\n    '<div style=\"display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px\">' +\r\n      '<label for=\"__aliasInput\" style=\"margin:0;white-space:nowrap;min-width:70px\">Alias</label>' +\r\n      '<input id=\"__aliasInput\" type=\"text\" placeholder=\"Alias (optional)\" ' +\r\n             'style=\"flex:1;padding:4px 6px;font-size:12px;border-radius:6px;' +\r\n                    'border:1px solid var(--line);background:var(--bg);color:var(--ink)\">' +\r\n    '</div>' +\r\n\r\n    '<div style=\"display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px\">' +\r\n      '<label for=\"__speedSelect\" style=\"margin:0;white-space:nowrap;min-width:70px\">Link speed</label>' +\r\n      '<select id=\"__speedSelect\" style=\"flex:1\">' +\r\n        '<option value=\"\">(none)</option>' +\r\n        '<option>100 Mbit</option><option>1 Gbit</option><option>2.5 Gbit</option>' +\r\n        '<option>5 Gbit</option><option>10 Gbit</option><option>25 Gbit</option>' +\r\n        '<option>40 Gbit</option><option>100 Gbit</option>' +\r\n      '</select>' +\r\n    '</div>' +\r\n\r\n    '<div style=\"display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:8px\">' +\r\n      '<label for=\"__vlanInput\" style=\"margin:0;white-space:nowrap;min-width:70px\">VLAN</label>' +\r\n      '<input id=\"__vlanInput\" type=\"number\" min=\"1\" max=\"4094\" step=\"1\" placeholder=\"1–4094\" ' +\r\n             'style=\"flex:1;padding:4px 6px;font-size:12px;border-radius:6px;border:1px solid var(--line);' +\r\n                    'background:var(--bg);color:var(--ink)\">' +\r\n    '</div>' +\r\n\r\n    (peerDev ? (\r\n      '<div style=\"display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:8px\">' +\r\n        '<label for=\"__linkedTo\" style=\"margin:0;white-space:nowrap;min-width:70px\">Linked To</label>' +\r\n        '<input id=\"__linkedTo\" type=\"text\" readonly ' +\r\n          'value=\"' + peerDev.name + ' – ' + peerPortLabel + '\" ' +\r\n          'style=\"padding:4px 6px;font-size:12px;border-radius:6px;border:1px solid var(--line);background:var(--bg);color:var(--ink);' +\r\n                 'display:inline-block;white-space:nowrap;overflow:hidden;\" />' +\r\n      '</div>'\r\n    ) : '') +\r\n\r\n'<div style=\"display:flex;gap:6px;justify-content:space-between\">' +\r\n\r\n  (peerDev\r\n    ? '<button id=\"__unlinkBtn\" class=\"btn\" type=\"button\" ' +\r\n        'style=\"background:#b91c1c;border-color:#b91c1c;color:#fff;font-weight:700\">Unlink</button>'\r\n    : '<div></div>'\r\n  ) +\r\n\r\n  '<div style=\"display:flex;gap:6px\">' +\r\n    '<button id=\"__speedCancel\" class=\"btn\" type=\"button\">Cancel</button>' +\r\n    '<button id=\"__speedSave\"   class=\"btn\" type=\"button\" style=\"font-weight:700\">Save</button>' +\r\n  '</div>' +\r\n\r\n'</div>';\r\n\r\n  document.body.appendChild(div);\r\n  __speedMenu = div;\r\n\r\n  // Auto-fit \"Linked to\" width (your existing behaviour)\r\n  (function() {\r\n    const inp = div.querySelector('#__linkedTo');\r\n    if (!inp) return;\r\n\r\n    const measurer = document.createElement('span');\r\n    measurer.style.cssText =\r\n      'position:absolute;visibility:hidden;white-space:nowrap;' +\r\n      'padding:4px 6px;font-size:12px;font-family:inherit;';\r\n    measurer.textContent = inp.value;\r\n\r\n    document.body.appendChild(measurer);\r\n\r\n    const baseWidth = measurer.offsetWidth;\r\n    const extra     = 16;\r\n    const minWidth  = 160;\r\n\r\n    inp.style.width = Math.max(minWidth, baseWidth + extra) + 'px';\r\n\r\n    document.body.removeChild(measurer);\r\n  })();\r\n\r\n  div.addEventListener('mousedown', function(ev){ ev.stopPropagation(); }, { capture:true });\r\n\r\n  // Port name input + reset behaviour\r\n  var nin = div.querySelector('#__nameInput');\r\n  if (store.settings.enablePortRename && nin) {\r\n    const dev = deviceById(deviceId);\r\n    const k = keyFor(deviceId, port, sub);\r\n    const currentName =\r\n      (dev && dev.portNames && dev.portNames[k]) ||\r\n      defaultLabel(port, sub);\r\n\r\n    nin.value = currentName;\r\n  }\r\n\r\n  const resetBtn = div.querySelector('#__nameReset');\r\n  if (resetBtn && nin) {\r\n    resetBtn.addEventListener('click', function(){\r\n      // TRUE reset: delete stored override\r\n      var d = deviceById(deviceId);\r\n      if (d && d.portNames) {\r\n        delete d.portNames[keyFor(deviceId, port, sub)];\r\n        if (Object.keys(d.portNames).length === 0) delete d.portNames;\r\n        saveStore();\r\n      }\r\n      nin.value = defaultLabel(port, sub);\r\n      render();\r\n    });\r\n  }\r\n\r\n  var ain = div.querySelector('#__aliasInput');\r\n  var sel = div.querySelector('#__speedSelect');\r\n  var vin = div.querySelector('#__vlanInput');\r\n\r\n  ain.value = aliasFor(deviceId, port, sub) || '';\r\n  sel.value = curSpeed || '';\r\n  vin.value = curVlanStr;\r\n\r\n  // Hook up Unlink\r\n  var unlinkBtn = div.querySelector('#__unlinkBtn');\r\n  if (unlinkBtn && link && peerDev) {\r\n    unlinkBtn.addEventListener('click', function(){\r\n      var thisDev = deviceById(deviceId);\r\n      var thisName = thisDev ? thisDev.name : 'Unknown';\r\n      var thisPortLabel =\r\n        (thisDev && thisDev.portNames && thisDev.portNames[keyFor(deviceId, port, sub)]) ||\r\n        defaultLabel(port, sub);\r\n\r\n      var peerName = peerDev ? peerDev.name : 'Unknown';\r\n\r\n      var msg =\r\n        'Unlink connection?\\n\\n' +\r\n        thisName + ' — ' + thisPortLabel + '\\n' +\r\n        '↔\\n' +\r\n        peerName + ' — ' + peerPortLabel;\r\n\r\n      if (!confirm(msg)) return;\r\n\r\n      unlink(link.id);\r\n      closeSpeedMenu();\r\n      render();\r\n    });\r\n  }\r\n\r\n  var x = e.clientX, y = e.clientY;\r\n  var vw = window.innerWidth, vh = window.innerHeight;\r\n  var rw = 260, rh = 150;\r\n  if (x + rw + 8 > vw) x = vw - rw - 8;\r\n  if (y + rh + 8 > vh) y = vh - rh - 8;\r\n  div.style.left = x + 'px';\r\n  div.style.top  = y + 'px';\r\n\r\n  function doSave(){\r\n    // Port rename (store ONLY real overrides)\r\n    if (store.settings.enablePortRename && nin) {\r\n      var dev = deviceById(deviceId);\r\n      if (dev) {\r\n        var k = keyFor(deviceId, port, sub);\r\n        var val = (nin.value || '').trim();\r\n        var def = defaultLabel(port, sub);\r\n\r\n        if (!val || val === def) {\r\n          if (dev.portNames) {\r\n            delete dev.portNames[k];\r\n            if (Object.keys(dev.portNames).length === 0) delete dev.portNames;\r\n          }\r\n        } else {\r\n          dev.portNames = dev.portNames || {};\r\n          dev.portNames[k] = val;\r\n        }\r\n      }\r\n    }\r\n\r\n    // Alias\r\n    var aliasRaw = ain.value.trim();\r\n    var aliasKey = keyFor(deviceId, port, sub);\r\n    if (!aliasRaw) delete state.portAliases[aliasKey];\r\n    else state.portAliases[aliasKey] = aliasRaw;\r\n\r\n    // Speed + VLAN\r\n    var speedVal = sel.value || '';\r\n    var vlanRaw  = (vin.value || '').trim();\r\n    var vlanVal  = vlanRaw === '' ? '' : Math.max(1, Math.min(4094, Number(vlanRaw) || 0));\r\n\r\n    setSpeedFor(deviceId, port, sub, speedVal);\r\n    setVlanFor(deviceId, port, sub, vlanVal);\r\n\r\n    saveStore();\r\n    render();\r\n    closeSpeedMenu();\r\n  }\r\n\r\n  div.querySelector('#__speedSave').addEventListener('click', doSave);\r\n  div.querySelector('#__speedCancel').addEventListener('click', closeSpeedMenu);\r\n\r\n  vin.addEventListener('keydown', function(ev){\r\n    if (ev.key === 'Enter') doSave();\r\n    if (ev.key === 'Escape') closeSpeedMenu();\r\n  });\r\n\r\n  setTimeout(function(){\r\n    function onDoc(e2){\r\n      if (__speedMenu && !__speedMenu.contains(e2.target)) closeSpeedMenu();\r\n    }\r\n    function onEsc(e2){ if (e2.key === 'Escape') closeSpeedMenu(); }\r\n    document.addEventListener('mousedown', onDoc, { once:true, capture:true });\r\n    document.addEventListener('keydown', onEsc, { once:true });\r\n    window.addEventListener('wheel', closeSpeedMenu, { once:true, passive:true });\r\n  }, 0);\r\n}\r\n\r\n/* ===================== PRINT ===================== */\r\nfunction openPrintSheet(includeTable){\r\n  var devicesHTML = document.getElementById('devRows').innerHTML;\r\n  var tableEl = document.getElementById('connTable');\r\n  var tableHTML = (includeTable && tableEl) ? tableEl.outerHTML : '';\r\n  var when = new Date().toLocaleString();\r\n\r\n  var css = ''\r\n+ '@page{size:A4 portrait;margin:12mm}\\n'\r\n+ '@page:first{size:A4 landscape;margin:12mm}\\n'\r\n+ '*{box-sizing:border-box}\\n'\r\n+ '@media print{*{-webkit-print-color-adjust:exact;print-color-adjust:exact}}\\n'\r\n+ '.device,.port,.dual-cell,.swatch,header{ -webkit-print-color-adjust:exact; print-color-adjust:exact }\\n'\r\n+ '.page{break-inside:avoid;page-break-inside:avoid}\\n'\r\n+ '.page + .page{break-before:page;page-break-before:always}\\n'\r\n+ ':root{--ink:#111;--line:#ddd;--prtPortH:75px;--prtGap:0px}\\n'\r\n+ '.port{height:var(--prtPortH)!important;box-sizing:border-box;overflow:hidden;display:block}\\n'\r\n+ '.dual-cell{display:flex;flex-direction:column;gap:var(--prtGap);height:calc(var(--prtPortH)*2 + var(--prtGap))!important;box-sizing:border-box;overflow:hidden}\\n'\r\n+ '.dual-cell .port{height:var(--prtPortH)!important;border:0!important;border-radius:0!important}\\n'\r\n+ '.dual-cell .port:first-child{border-bottom:1px solid #333!important}\\n'\r\n\r\n  + '*{box-sizing:border-box}\\n'\r\n  + 'body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;color:var(--ink);background:#fff;margin:0}\\n'\r\n  + '.page{max-width:calc(297mm - 16mm);margin:10mm auto}\\n'\r\n  + 'header{display:flex;align-items:baseline;justify-content:space-between;margin-bottom:12px}\\n'\r\n  + 'h1{font-size:18px;margin:0}\\n'\r\n  + '.meta{font-size:12px;color:#555}\\n'\r\n  + '.dev-rows{display:flex;flex-direction:column;gap:12px}\\n'\r\n  + '.dev-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}\\n'\r\n  + '.device-wrap{width:100%}\\n'\r\n  + '.device-wrap.full{grid-column:1 / -1}\\n'\r\n  + '.device{background:#fff;border:1px solid var(--line);border-radius:10px;padding:10px;overflow:hidden}\\n'\r\n  + '.device-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}\\n'\r\n  + '.device-title{font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}\\n'\r\n  + '.device-actions,.inline-controls{display:none!important}\\n'\r\n  + '.swatch{width:12px;height:12px;border-radius:3px;border:1px solid #0003;display:inline-block}\\n'\r\n  + '.ports-rows{display:flex;flex-direction:column;gap:8px;margin-top:10px;overflow:hidden}\\n'\r\n  + '.port-row{display:grid;justify-content:start;align-content:start}\\n'\r\n  + '.device-wrap.full .port-row{grid-template-columns:repeat(12,minmax(40px,1fr));gap:10px !important;}\\n'\r\n  + '.device-wrap:not(.full) .port-row{grid-template-columns:repeat(6,minmax(40px,1fr));gap:7px !important;}\\n'\r\n  /* --------------------------------------------------------------------------- */\r\n  + '.port{border:1px solid #333;border-radius:8px;padding:6px 3px 4px;text-align:center;grid-column:auto!important;width:auto!important}\\n'\r\n  + '.port .num{font-size:12px;font-weight:600}\\n'\r\n  + '.port .alias{font-size:11px;margin-top:2px;min-height:1.1em}\\n'\r\n  + '.port .peer{font-size:12px;font-weight:700;margin-top:4px;min-height:1.2em}\\n'\r\n  + '.port:not(.connected):not(.reserved){background:#fff !important;border-color:#444 !important}\\n'\r\n  + '.port:not(.connected):not(.reserved) .num,'\r\n  + '.port:not(.connected):not(.reserved) .alias,'\r\n  + '.port:not(.connected):not(.reserved) .peer{color:#000 !important}\\n'\r\n  + '.port.connected{color:#000}\\n'\r\n  + '.port.reserved{background:#555 !important;color:#fff !important;border-color:#333 !important}\\n'\r\n  + '.dual-cell{border-color:#333 !important}\\n'\r\n  + '.port.reserved .num,.port.reserved .alias,.port.reserved .peer{color:#fff !important}\\n'\r\n  + 'table{width:100%;border-collapse:collapse;margin-top:16px}\\n'\r\n  + 'th,td{border:1px solid var(--line);padding:6px 8px;font-size:12px;text-align:left}\\n'\r\n  + 'th{background:#f6f7f9;font-weight:700}\\n'\r\n  + 'th:last-child, td:last-child{display:none}\\n'\r\n  + '@media print{.controls{display:none};}\\n';\r\n\r\n\r\n  var html = ''\r\n  + '<!doctype html><html><head><meta charset=\"utf-8\">'\r\n  + '<title>Ethernet Cable Connection Manager – Print</title><style>' + css + '</style></head><body>'\r\n  + '<div class=\"page\">'\r\n  + '<header><h1>Profile: ' + store.current + '</h1><div class=\"meta\">' + 'Ethernet Cable Connection Manager: <a href=\"https://https://github.com/bijomaru78/eccm\" target=\"_blank\">https://github.com/bijomaru78/eccm</a> - Printed on '+when+'</div></header>' \r\n  + '<section id=\"printDevices\" class=\"dev-rows\">' + devicesHTML + '</section>'\r\n  + (tableHTML ? '<div class=\"page\"><h2 style=\"font-size:16px;margin:18px 0 8px\">Connections</h2>' + tableHTML + '</div>' : '')\r\n  + '<div class=\"controls\" style=\"margin-top:12px\"><button onclick=\"window.print()\">Print</button></div>'\r\n  + '</div>'\r\n  + '<script>(function(){'\r\n  + '  var GAP_FULL=9, GAP_HALF=7, MIN_TRACK=40;'\r\n  + '  function sizeRows(){'\r\n  + '    var rows=document.querySelectorAll(\".port-row,[data-port-row]\");'\r\n  + '    for(var i=0;i<rows.length;i++){'\r\n  + '      var row=rows[i];'\r\n  + '      var wrap=row.closest(\".device-wrap\");'\r\n  + '      row.style.display = \"grid\";'\r\n  + '      row.style.justifyContent = \"start\";'\r\n  + '      row.style.alignContent = \"start\";'\r\n  + '      row.style.gridAutoFlow = \"row\";'\r\n  + '      var isFull = wrap && wrap.classList.contains(\"full\");'\r\n  + '      var cols   = isFull ? 12 : 6;'\r\n  + '      var gap    = isFull ? GAP_FULL : GAP_HALF;'\r\n  + '      var inner = row.getBoundingClientRect().width;'\r\n  + '      if(inner && inner > 0){'\r\n  + '        var track = Math.floor((inner - gap * (cols - 1)) / cols);'\r\n  + '        if (!(track > 0)) track = 60;'\r\n  + '        if (track < MIN_TRACK) track = MIN_TRACK;'\r\n  + '\t\t track += -3;'\r\n  + '        row.style.gridTemplateColumns = \"repeat(\" + cols + \", \" + track + \"px)\";'\r\n  + '      }'\r\n  + '      row.style.gap = gap + \"px\";'\r\n  + '    }'\r\n  + '  }'\r\n  + '  requestAnimationFrame(function(){ requestAnimationFrame(sizeRows); });'\r\n  + '  Array.prototype.forEach.call(document.querySelectorAll(\".port\"),function(p){'\r\n  + '    if(!p.classList.contains(\"connected\") && !p.classList.contains(\"reserved\")){'\r\n  + '      p.style.background=\"\"; p.style.color=\"\";'\r\n  + '      p.querySelectorAll(\".num,.alias,.peer\").forEach(function(el){ el.style.color=\"\"; });'\r\n  + '    }'\r\n  + '  });'\r\n  + '  Array.prototype.forEach.call(document.querySelectorAll(\"[draggable]\"),function(el){el.removeAttribute(\"draggable\");});'\r\n  + '})();<\\/script>'\r\n  + '</body></html>';\r\n\r\n  var win = window.open('', '_blank');\r\n  win.document.open();\r\n  win.document.write(html);\r\n  win.document.close();\r\n  \r\n  win.onload = function() {\r\n  win.focus();\r\n  setTimeout(function() {\r\n    win.print();\r\n    win.close();\r\n  }, 30); \r\n};\r\n}\r\n\r\n\r\n\r\n/* ===================== ORCHESTRATION ===================== */\r\nfunction render(){ renderDevices(); applyPeerScrolling(); renderConnections(); }\r\n\r\n/* ===================== PALETTE ===================== */\r\n(function(){\r\n  const palette = [\r\n  '#FFCDD2','#C8E6C9','#BBDEFB','#F5F5F5',\r\n  '#F44336','#4CAF50','#2196F3','#E0E0E0',\r\n  '#FF0000','#00FF00','#0000FF','#BDBDBD',\r\n  '#FF6F00','#FFFF00','#BF00FF','#9E9E9E',\r\n  '#FF9800','#FFEB3B','#9C27B0','#757575',\r\n  '#FFB74D','#FFF176','#BA68C8','#616161'\r\n]\r\n\r\n   const modal   = document.getElementById('paletteModal');\r\n  const grid    = document.getElementById('paletteGrid');\r\n  const openBtn = document.getElementById('openPalette');\r\n  const closeBtn= document.getElementById('paletteClose');\r\n  const previewSidebar = document.getElementById('devColorPreview');\r\n  let chosenColor = '#E74C3C';\r\n\r\n  function open(){ modal.style.display='flex'; }\r\n  function close(){ modal.style.display='none'; }\r\n  function updatePreview(){ previewSidebar.style.background = chosenColor; }\r\n\r\n  /* ---------- RGB / HSV conversion helpers ---------- */\r\n  function rgbToHex(r,g,b){\r\n    return '#' + [r,g,b].map(x=>x.toString(16).padStart(2,'0')).join('').toUpperCase();\r\n  }\r\n  function hexToRgb(hex){\r\n    const n = parseInt(hex.replace('#',''),16);\r\n    return {r:(n>>16)&255, g:(n>>8)&255, b:n&255};\r\n  }\r\n  function rgbToHsv(r, g, b) {\r\n    r/=255; g/=255; b/=255;\r\n    const max = Math.max(r,g,b), min = Math.min(r,g,b);\r\n    const d = max-min;\r\n    let h,s,v = max;\r\n    s = max===0 ? 0 : d/max;\r\n    if(max===min) h=0;\r\n    else {\r\n      switch(max){\r\n        case r: h=(g-b)/d + (g<b?6:0); break;\r\n        case g: h=(b-r)/d + 2; break;\r\n        case b: h=(r-g)/d + 4; break;\r\n      }\r\n      h /= 6;\r\n    }\r\n    return {h:h*360, s:s*100, v:v*100};\r\n  }\r\n  function hsvToRgb(h, s, v){\r\n    h/=360; s/=100; v/=100;\r\n    const i = Math.floor(h*6);\r\n    const f = h*6 - i;\r\n    const p = v*(1-s);\r\n    const q = v*(1-f*s);\r\n    const t = v*(1-(1-f)*s);\r\n    let r,g,b;\r\n    switch(i%6){\r\n      case 0: r=v; g=t; b=p; break;\r\n      case 1: r=q; g=v; b=p; break;\r\n      case 2: r=p; g=v; b=t; break;\r\n      case 3: r=p; g=q; b=v; break;\r\n      case 4: r=t; g=p; b=v; break;\r\n      case 5: r=v; g=p; b=q; break;\r\n    }\r\n    return {r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255)};\r\n  }\r\n\r\n  /* ---------- Build palette grid ---------- */\r\n  grid.innerHTML = '';\r\n  palette.forEach(hex=>{\r\n    const chip = document.createElement('button');\r\n    chip.className='chip';\r\n    chip.style.background=hex;\r\n    chip.title=hex;\r\n    chip.addEventListener('click',()=>{\r\n      chosenColor=hex;\r\n      updateFromHex(hex);\r\n      updatePreview();\r\n    });\r\n    grid.appendChild(chip);\r\n  });\r\n\r\n  /* ---------- Add custom sliders ---------- */\r\nconst customHTML = `\r\n  <div id=\"customColorPicker\"\r\n       style=\"display:grid;\r\n              grid-template-columns:repeat(5,1fr);\r\n              grid-template-rows:auto auto auto;\r\n              gap:12px;\r\n              align-items:center;\r\n              justify-items:center;\r\n              margin-left:12px;\r\n              margin-top:6px;\">\r\n\r\n    <!-- Headers -->\r\n    <div style=\"font-size:12px;color:var(--muted)\">Hue</div>\r\n    <div style=\"font-size:12px;color:var(--muted)\">Sat</div>\r\n    <div style=\"font-size:12px;color:var(--muted)\">R</div>\r\n    <div style=\"font-size:12px;color:var(--muted)\">G</div>\r\n    <div style=\"font-size:12px;color:var(--muted)\">B</div>\r\n\r\n    <!-- Sliders -->\r\n<div id=\"hueWrap\"\r\n     style=\"position:relative;height:120px;width:16px;display:flex;align-items:center;justify-content:center;\">\r\n  <!-- static hue gradient -->\r\n  <div id=\"hueBar\"\r\n       style=\"position:absolute;inset:0;\r\n              background:linear-gradient(to top, red, yellow, lime, cyan, blue, magenta, red);\r\n              border-radius:6px;filter:brightness(0.9);\">\r\n  </div>\r\n  <!-- moving indicator -->\r\n  <div id=\"hueMarker\"\r\n       style=\"position:absolute;left:0;right:0;height:2px;background:white;\r\n              border-radius:1px;box-shadow:0 0 4px rgba(0,0,0,0.8);pointer-events:none;\">\r\n  </div>\r\n  <!-- functional slider -->\r\n  <input type=\"range\" id=\"hueSlider\" min=\"0\" max=\"360\"\r\n         style=\"position:relative;z-index:5;height:120px;width:16px;\r\n                appearance:slider-vertical;writing-mode:bt-lr;\r\n                opacity:0;\">\r\n</div>\r\n\r\n    <input type=\"range\" id=\"satSlider\" min=\"0\" max=\"100\"\r\n           style=\"height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;\">\r\n    <input type=\"range\" id=\"rSlider\" min=\"0\" max=\"255\"\r\n           style=\"height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;\">\r\n    <input type=\"range\" id=\"gSlider\" min=\"0\" max=\"255\"\r\n           style=\"height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;\">\r\n    <input type=\"range\" id=\"bSlider\" min=\"0\" max=\"255\"\r\n           style=\"height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;\">\r\n\r\n<!-- Preview -->\r\n<div id=\"colorPreviewBox\"\r\n     style=\"grid-column:1 / span 5;\r\n            width:36px;height:36px;\r\n            border-radius:8px;\r\n            border:1px solid #333;\r\n            box-shadow:0 0 8px rgba(0,0,0,0.25);\r\n            margin-top:10px;\"></div>\r\n\r\n<!-- Hex field (editable) -->\r\n<input type=\"text\" id=\"hexOutput\"\r\n       placeholder=\"#RRGGBB\"\r\n       style=\"grid-column:1 / span 5;\r\n              width:110px;\r\n              text-align:center;\r\n              font-size:13px;\r\n              background:#0f141d;\r\n              border:1px solid var(--line);\r\n              border-radius:6px;\r\n              color:var(--ink);\r\n              padding:5px;\r\n              margin-top:6px;\">\r\n\r\n  </div>`;\r\n\r\n\r\n  grid.insertAdjacentHTML('afterend', customHTML);\r\n\r\n  /* ---------- DOM refs ---------- */\r\n  const hSlider=document.getElementById('hueSlider');\r\n  const sSlider=document.getElementById('satSlider');\r\n  const rSlider=document.getElementById('rSlider');\r\n  const gSlider=document.getElementById('gSlider');\r\n  const bSlider=document.getElementById('bSlider');\r\n  const colorBox=document.getElementById('colorPreviewBox');\r\n  const hexOut=document.getElementById('hexOutput');\r\n\r\n  /* ---------- Core update logic ---------- */\r\n  function updatePreviewBox(hex){\r\n    colorBox.style.background=hex;\r\n    hexOut.value=hex.toUpperCase();\r\n    chosenColor=hex;\r\n    updatePreview();\r\n  }\r\n  \r\n  function updateHueMarker() {\r\n  const hue = +hSlider.value || 0;\r\n  const marker = document.getElementById('hueMarker');\r\n  if (!marker) return;\r\n  const bar = document.getElementById('hueWrap');\r\n  const height = bar ? bar.clientHeight : 120;\r\n  const pos = height - (hue / 360) * height; // invert so 0°=bottom, 360°=top\r\n  marker.style.top = `${pos - 1}px`;\r\n}\r\n\r\n\r\n  function updateFromRGB(){\r\n    const r=+rSlider.value, g=+gSlider.value, b=+bSlider.value;\r\n    const hex=rgbToHex(r,g,b);\r\n    const {h,s}=rgbToHsv(r,g,b);\r\n    hSlider.value=Math.round(h);\r\n    sSlider.value=Math.round(s);\r\n    updatePreviewBox(hex);\r\n\tupdateHueMarker();\r\n  }\r\n\r\n  function updateFromHSV(){\r\n    const h=+hSlider.value, s=+sSlider.value;\r\n    const {r,g,b}=hsvToRgb(h,s,100);\r\n    rSlider.value=r; gSlider.value=g; bSlider.value=b;\r\n    const hex=rgbToHex(r,g,b);\r\n    updatePreviewBox(hex);\r\n\tupdateHueMarker();\r\n  }\r\n\r\n  function updateFromHex(hex){\r\n    const {r,g,b}=hexToRgb(hex);\r\n    rSlider.value=r; gSlider.value=g; bSlider.value=b;\r\n    const {h,s}=rgbToHsv(r,g,b);\r\n    hSlider.value=Math.round(h);\r\n    sSlider.value=Math.round(s);\r\n    updatePreviewBox(hex);\r\n\tupdateHueMarker();\r\n  }\r\n\r\n  /* ---------- Events ---------- */\r\n  [rSlider,gSlider,bSlider].forEach(sl=>sl.addEventListener('input',updateFromRGB));\r\n  [hSlider,sSlider].forEach(sl=>sl.addEventListener('input',updateFromHSV));\r\n\thexOut.addEventListener('input', e => {\r\n\t  const v = e.target.value.trim();\r\n\t  // allow partial input like \"#ff\" without breaking live update\r\n\t  if (/^#?[0-9A-Fa-f]{0,6}$/.test(v)) {\r\n\t\te.target.style.borderColor = 'var(--line)';\r\n\t  } else {\r\n\t\te.target.style.borderColor = '#d33'; // red outline if invalid\r\n\t\treturn;\r\n\t  }\r\n\t  if (/^#?[0-9A-Fa-f]{6}$/.test(v)) {\r\n\t\tconst hex = v.startsWith('#') ? v.toUpperCase() : '#' + v.toUpperCase();\r\n\t\tupdateFromHex(hex);\r\n\t  }\r\n\t});\r\n\r\n\r\n  /* ---------- Modal + Add device ---------- */\r\n  openBtn.addEventListener('click',open);\r\n  closeBtn.addEventListener('click',close);\r\n\r\n  document.getElementById('addBtn').addEventListener('click',function(){\r\n    const name=document.getElementById('devName').value.trim();\r\n    const ports=Math.max(1,Math.min(9999,Number(document.getElementById('devPorts').value)||1));\r\n    if(!name){alert('Please enter a device name.');return;}\r\n    state.devices.push({\r\n      id:uid(),name,ports,color:chosenColor,\r\n      forceFullRow:false,midWrapMode:'balanced',smallWrap:false,dualLink:false,\r\n      numbering:'row'\r\n    });\r\n    document.getElementById('devName').value='';\r\n    saveStore();render();\r\n  });\r\n\r\n  updateFromHex(chosenColor);\r\n  updateHueMarker();\r\n})();\r\n\r\n\r\n/* ===================== LAYOUT MODAL ===================== */\r\nfunction openLayoutModal(deviceId){\r\n  var d = deviceById(deviceId); if (!d) return;\r\n  var backdrop = $('#layoutModal');\r\n  var nameEl = $('#layoutDeviceName');\r\n  var selFull = $('#layoutFullRow');\r\n  var selMid = $('#layoutMidWrap');\r\n  var selSmall = $('#layoutSmallWrap');\r\n  var selDual = $('#layoutDualLink');\r\n  var rowMid = $('#optMidWrap');\r\n  var rowSmall = $('#optSmallWrap');\r\n  var selNumbering = $('#layoutNumbering');\r\n\r\n\r\n  nameEl.textContent = d.name + ' ('+d.ports+' ports)';\r\n  selFull.value = d.forceFullRow ? 'full' : 'auto';\r\n  selMid.value = (d.midWrapMode === 'twelve') ? 'twelve' : 'balanced';\r\n  selSmall.value = d.smallWrap ? 'split' : 'single';\r\n  selDual.value = d.dualLink ? 'on' : 'off';\r\n  selNumbering.value = (d.numbering === 'column' || d.numbering === 'column-bt') ? d.numbering : 'row';\r\n\r\n  rowMid.style.display   = (d.ports>=13 && d.ports<=24) ? 'flex' : 'none';\r\n  rowSmall.style.display = (d.ports>=7  && d.ports<=12) ? 'flex' : 'none';\r\n\r\n  $('#layoutCancel').onclick = function(){ backdrop.style.display='none'; };\r\n  $('#layoutSave').onclick = function(){\r\n    d.forceFullRow = (selFull.value === 'full');\r\n    if (d.ports>=13 && d.ports<=24) d.midWrapMode = (selMid.value === 'twelve') ? 'twelve' : 'balanced';\r\n    if (d.ports>=7  && d.ports<=12) d.smallWrap   = (selSmall.value === 'split');\r\n    d.dualLink = (selDual.value === 'on');\r\n\td.numbering = (selNumbering.value === 'column' || selNumbering.value === 'column-bt') ? selNumbering.value : 'row';\r\n    saveStore(); backdrop.style.display='none'; render();\r\n  };\r\n  /* --- allow Escape key & outside click to close Layout modal --- */\r\n(function wireLayoutModalClose() {\r\n  const modal = document.getElementById('layoutModal');\r\n  if (!modal) return;\r\n\r\n  // Close on Escape\r\n  document.addEventListener('keydown', function (e) {\r\n    if (modal.style.display === 'flex' && e.key === 'Escape') {\r\n      modal.style.display = 'none';\r\n    }\r\n  });\r\n\r\n  // Close when clicking backdrop (outside the inner .modal)\r\n  modal.addEventListener('click', function (e) {\r\n    if (e.target === modal) {\r\n      modal.style.display = 'none';\r\n    }\r\n  });\r\n})();\r\n\r\n  backdrop.style.display = 'flex';\r\n}\r\n\r\n/* ===================== EDIT DEVICE MODAL ===================== */\r\nlet currentEditDevice = null;\r\nlet editChosenColor = '#888';\r\n\r\nfunction openEditDeviceModal(deviceId) {\r\n  const d = deviceById(deviceId);\r\n  if (!d) return;\r\n\r\n  currentEditDevice = d;\r\n  const modal = document.getElementById('editDeviceModal');\r\n  const nameInput = document.getElementById('editDevName');\r\n  const portsInput = document.getElementById('editDevPorts');\r\n  const preview = document.getElementById('editDevColorPreview');\r\n\r\n  nameInput.value = d.name || '';\r\n  portsInput.value = d.ports || 1;\r\n  editChosenColor = d.color || '#888';\r\n  preview.style.background = editChosenColor;\r\n\tconst speedOptions = [\r\n\t  '', '100 Mbit', '1 Gbit', '2.5 Gbit', '5 Gbit',\r\n\t  '10 Gbit', '25 Gbit', '40 Gbit', '100 Gbit'\r\n\t];\r\n\r\n\tlet maxSpeedRow = document.getElementById('editDevMaxSpeedRow');\r\n\tif (!maxSpeedRow) {\r\n\t  maxSpeedRow = document.createElement('div');\r\n\t  maxSpeedRow.className = 'row';\r\n\t  maxSpeedRow.id = 'editDevMaxSpeedRow';\r\n\t  maxSpeedRow.innerHTML =\r\n\t\t'<label style=\"min-width:100px\">Max speed</label>' +\r\n\t\t'<select id=\"editDevMaxSpeed\"></select>';\r\n\t  modal.querySelector('.modal').insertBefore(\r\n\t\tmaxSpeedRow,\r\n\t\tmodal.querySelector('.actions')\r\n\t  );\r\n\t}\r\n\r\n\tconst speedSel = document.getElementById('editDevMaxSpeed');\r\n\tspeedSel.innerHTML = speedOptions\r\n\t  .map(s => `<option value=\"${s}\">${s || '(none)'}</option>`)\r\n\t  .join('');\r\n\tspeedSel.value = d.maxSpeed || '';\r\n\r\n  modal.style.display = 'flex';\r\n}\r\n\r\nfunction closeEditDeviceModal() {\r\n  document.getElementById('editDeviceModal').style.display = 'none';\r\n  currentEditDevice = null;\r\n}\r\n\r\n/* --- use main palette modal for Edit Device colour selection --- */\r\n(function setupEditColorPicker() {\r\n  const paletteModal = document.getElementById('paletteModal');\r\n  const openBtn = document.getElementById('editOpenPalette');\r\n  const preview = document.getElementById('editDevColorPreview');\r\n  const paletteGrid = document.getElementById('paletteGrid');\r\n  const closeBtn = document.getElementById('paletteClose');\r\n  let tempTarget = null;\r\n\r\n  // open shared palette modal but record the target (edit or add)\r\n  openBtn.addEventListener('click', function () {\r\n    tempTarget = 'edit';\r\n    paletteModal.style.display = 'flex';\r\n  });\r\n\r\n  // intercept clicks in palette grid to update the correct target\r\n  paletteGrid.querySelectorAll('.chip').forEach(chip => {\r\n    chip.addEventListener('click', function () {\r\n      const hex = chip.title || chip.style.background;\r\n      if (tempTarget === 'edit') {\r\n        editChosenColor = hex;\r\n        preview.style.background = hex;\r\n      } else {\r\n        // fallback for add device\r\n        chosenColor = hex;\r\n        document.getElementById('devColorPreview').style.background = hex;\r\n      }\r\n      paletteModal.style.display = 'none';\r\n    });\r\n  });\r\n\r\n  // close palette normally\r\n  closeBtn.addEventListener('click', function () {\r\n    paletteModal.style.display = 'none';\r\n    tempTarget = null;\r\n  });\r\n})();\r\n\r\n\r\n/* --- modal buttons --- */\r\ndocument.getElementById('editDevCancel').addEventListener('click', closeEditDeviceModal);\r\ndocument.getElementById('editDevSave').addEventListener('click', function() {\r\n  if (!currentEditDevice) return;\r\n  const name = document.getElementById('editDevName').value.trim();\r\n  const ports = Math.max(1, Math.min(9999, Number(document.getElementById('editDevPorts').value) || 1));\r\n  currentEditDevice.name = name || currentEditDevice.name;\r\n  if (ports < (currentEditDevice.ports || 1)) {\r\n    var affected = linksOnPortsBeingRemoved(currentEditDevice, ports);\r\n    if (affected.length > 0 && !confirm('Warning: The port(s) that will be removed have linked connections (' + affected.length + '). Removing the port will also remove these connections. Are you sure you want to continue?')) {\r\n      // user cancelled – do not change port count\r\n    } else {\r\n      changePorts(currentEditDevice, ports);\r\n    }\r\n  } else {\r\n    changePorts(currentEditDevice, ports);\r\n  }\r\n  currentEditDevice.color = editChosenColor;\r\n  const speedSel = document.getElementById('editDevMaxSpeed');\r\n  currentEditDevice.maxSpeed = speedSel ? speedSel.value || null : null;\r\n  recalcLinkSpeedsForDevice(currentEditDevice.id);\r\n  saveStore(); render();\r\n  closeEditDeviceModal();\r\n});\r\n/* --- allow Escape key & outside click to close --- */\r\n(function wireEditModalClose() {\r\n  const modal = document.getElementById('editDeviceModal');\r\n  if (!modal) return;\r\n\r\n  // Close on Escape\r\n  document.addEventListener('keydown', function (e) {\r\n    if (modal.style.display === 'flex' && e.key === 'Escape') {\r\n      closeEditDeviceModal();\r\n    }\r\n  });\r\n\r\n  // Close when clicking outside the modal box\r\n  modal.addEventListener('click', function (e) {\r\n    if (e.target === modal) {\r\n      closeEditDeviceModal();\r\n    }\r\n  });\r\n})();\r\n\r\n/* ===================== PROFILES UI ===================== */\r\nfunction refreshProfileSelect(){\r\n  var sel = document.getElementById('profileSelect');\r\n  sel.innerHTML = '';\r\n  Object.keys(store.profiles).forEach(function(name){\r\n    var opt = document.createElement('option');\r\n    opt.value = name; opt.textContent = name;\r\n    if (name === store.current) opt.selected = true;\r\n    sel.appendChild(opt);\r\n  });\r\n  sel.value = store.current;\r\n}\r\nfunction switchProfile(name){\r\n  if (!store.profiles[name]) return;\r\n  store.current = name;\r\n  state = store.profiles[name];\r\n  normalizeState(state);\r\n  saveStore();\r\n  refreshProfileSelect();\r\n  render();\r\n}\r\ndocument.getElementById('profileSelect').addEventListener('change', function(){ switchProfile(this.value); });\r\n\r\ndocument.getElementById('newProfileBtn').addEventListener('click', function(){\r\n  var name = prompt('New profile name:', 'Customer '+(Object.keys(store.profiles).length+1));\r\n  if(!name) return; name = name.trim(); if(!name) return;\r\n  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }\r\n  store.profiles[name] = deepClone(defaultState); saveStore();\r\n  refreshProfileSelect(); switchProfile(name);\r\n});\r\n\r\ndocument.getElementById('renameProfileBtn').addEventListener('click', function(){\r\n  var current = store.current;\r\n  var name = prompt('Rename profile \"'+current+'\" to:', current);\r\n  if(!name || !name.trim()) return; name = name.trim();\r\n  if(name === current) return;\r\n  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }\r\n  store.profiles[name] = state; delete store.profiles[current];\r\n  store.current = name; saveStore(); refreshProfileSelect(); render();\r\n});\r\n\r\ndocument.getElementById('duplicateProfileBtn').addEventListener('click', function(){\r\n  var base = store.current;\r\n  var name = prompt('Duplicate profile as:', base+' (copy)');\r\n  if(!name || !name.trim()) return; name = name.trim();\r\n  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }\r\n  store.profiles[name] = deepClone(state); saveStore();\r\n  refreshProfileSelect(); switchProfile(name);\r\n});\r\n\r\ndocument.getElementById('deleteProfileBtn').addEventListener('click', function(){\r\n  var names = Object.keys(store.profiles);\r\n  if(names.length<=1){ alert('You must keep at least one profile.'); return; }\r\n  var current = store.current;\r\n  if(!confirm('Delete profile \"'+current+'\"? This cannot be undone.')) return;\r\n  delete store.profiles[current];\r\n  var next = Object.keys(store.profiles)[0];\r\n  store.current = next; state = store.profiles[next];\r\n  saveStore(); refreshProfileSelect(); render();\r\n});\r\n\r\n/* ===================== EXPORT / IMPORT PROFILE (full-fidelity) ===================== */\r\n\r\n/* Export profile (exports EVERYTHING in state, with versioning) */\r\ndocument.getElementById('exportProfileBtn').addEventListener('click', function(){\r\n  // Full-fidelity export (supports all new fields + future ones)\r\n  var data = {\r\n    schema: 'eccm-profile',\r\n    schemaVersion: 2,\r\n    appVersion: '1.0.5',\r\n    profileName: store.current,\r\n    state: deepClone(state),\r\n    exportedAt: new Date().toISOString()\r\n  };\r\n\r\n  var blob = new Blob([JSON.stringify(data, null, 2)], { type:'application/json' });\r\n  var url = URL.createObjectURL(blob);\r\n  var a = document.createElement('a');\r\n  a.href = url;\r\n  a.download = 'ethernet-profile-' + store.current.replace(/[^a-z0-9-_]+/gi,'_') + '.json';\r\n  document.body.appendChild(a);\r\n  a.click();\r\n  a.remove();\r\n  URL.revokeObjectURL(url);\r\n});\r\n\r\n\r\n/* Import profile (accepts both new schema + legacy exports) */\r\ndocument.getElementById('importProfileBtn').addEventListener('click', function(){\r\n  document.getElementById('importProfileFile').click();\r\n});\r\n\r\ndocument.getElementById('importProfileFile').addEventListener('change', function(e){\r\n  var file = e.target.files && e.target.files[0];\r\n  if(!file) return;\r\n\r\n  var reader = new FileReader();\r\n\r\n  reader.onload = function(){\r\n    try{\r\n      var parsed = JSON.parse(reader.result);\r\n\r\n      // ---------- 1) Determine incoming state (new schema or legacy) ----------\r\n      var incomingState = null;\r\n\r\n      // New schema: { schema, schemaVersion, profileName, state:{...} }\r\n      if (parsed && parsed.state && typeof parsed.state === 'object') {\r\n        incomingState = parsed.state;\r\n      } else {\r\n        // Legacy schema: { devices, links, portAliases, reservedPorts, ... }\r\n        incomingState = {\r\n          devices: parsed.devices,\r\n          links: parsed.links,\r\n          portAliases: parsed.portAliases,\r\n          reservedPorts: parsed.reservedPorts,\r\n          portSpeeds: parsed.portSpeeds,\r\n          portVlans: parsed.portVlans,\r\n          portLinkedToNames: parsed.portLinkedToNames\r\n        };\r\n      }\r\n\r\n      // Basic validation\r\n      if(!incomingState || !Array.isArray(incomingState.devices) || !Array.isArray(incomingState.links)){\r\n        throw new Error('Invalid schema (missing devices/links).');\r\n      }\r\n\r\n      // ---------- 2) Normalise + clamp ----------\r\n      normalizeState(incomingState);\r\n\r\n      // Respect current app setting (if available) for max ports\r\n      var maxPorts = (typeof getMaxPortsSetting === 'function') ? getMaxPortsSetting() : 512;\r\n\r\n      incomingState.devices = incomingState.devices.map(function(d){\r\n        // Keep all fields we know + preserve any extras by copying d wholesale\r\n        var out = Object.assign({}, d);\r\n\r\n        out.id = d.id || uid();\r\n        out.name = String(d.name || 'Unnamed');\r\n        out.color = d.color || '#888';\r\n\r\n        out.ports = Math.max(1, Math.min(maxPorts, Number(d.ports) || 1));\r\n\r\n        // Layout fields\r\n        out.forceFullRow = !!d.forceFullRow;\r\n        out.midWrapMode  = (d.midWrapMode === 'twelve') ? 'twelve' : 'balanced';\r\n        out.smallWrap    = !!d.smallWrap;\r\n        out.dualLink     = !!d.dualLink;\r\n        out.numbering    = (d.numbering === 'column') ? 'column' : 'row';\r\n\r\n        // Per-device fields\r\n        out.maxSpeed = (d.maxSpeed == null || d.maxSpeed === '') ? null : String(d.maxSpeed);\r\n        out.portNames = (d.portNames && typeof d.portNames === 'object') ? d.portNames : {};\r\n\r\n        return out;\r\n      });\r\n\r\n      // Rebuild id set for link filtering\r\n      var idSet = Object.create(null);\r\n      incomingState.devices.forEach(function(d){ idSet[String(d.id)] = true; });\r\n\r\n      incomingState.links = (incomingState.links || []).map(function(L){\r\n        return {\r\n          id: L.id || uid(),\r\n          a: {\r\n            deviceId: String(L.a && L.a.deviceId),\r\n            port: Number(L.a && L.a.port),\r\n            sub: (L.a && L.a.sub == null) ? null : Number(L.a.sub)\r\n          },\r\n          b: {\r\n            deviceId: String(L.b && L.b.deviceId),\r\n            port: Number(L.b && L.b.port),\r\n            sub: (L.b && L.b.sub == null) ? null : Number(L.b.sub)\r\n          }\r\n        };\r\n      }).filter(function(L){\r\n        // Must reference known devices + valid port numbers\r\n        return (\r\n          idSet[L.a.deviceId] && idSet[L.b.deviceId] &&\r\n          L.a.port >= 1 && L.b.port >= 1\r\n        );\r\n      });\r\n\r\n      // Ensure maps exist (import could be missing them)\r\n      incomingState.portAliases = incomingState.portAliases || {};\r\n      incomingState.reservedPorts = incomingState.reservedPorts || {};\r\n      incomingState.portSpeeds = incomingState.portSpeeds || {};\r\n      incomingState.portVlans  = incomingState.portVlans  || {};\r\n      incomingState.portLinkedToNames = incomingState.portLinkedToNames || {};\r\n\r\n      // ---------- 3) Save under user-chosen profile name ----------\r\n      var suggested =\r\n        (parsed.profileName || '').toString().trim() ||\r\n        ('Imported ' + new Date().toLocaleString());\r\n\r\n      var name = prompt('Name for imported profile:', suggested);\r\n      if(!name || !name.trim()) return;\r\n      name = name.trim();\r\n\r\n      if(store.profiles[name]){\r\n        alert('A profile with that name already exists.');\r\n        return;\r\n      }\r\n\r\n      store.profiles[name] = incomingState;\r\n\r\n      saveStore();\r\n      refreshProfileSelect();\r\n      switchProfile(name);\r\n\r\n    }catch(err){\r\n      alert('Import failed: ' + err.message);\r\n    }finally{\r\n      e.target.value = '';\r\n    }\r\n  };\r\n\r\n  reader.readAsText(file);\r\n});\r\n\r\n/* ===================== BACKUP / RESTORE (all profiles) ===================== */\r\ndocument.getElementById('backupAllBtn').addEventListener('click', function(){\r\n  // Full-store backup (all profiles + settings + current profile)\r\n  var payload = {\r\n    schema: 'eccm-backup',\r\n    schemaVersion: 2,\r\n    appVersion: '1.0.5',\r\n    exportedAt: new Date().toISOString(),\r\n    store: deepClone(store)\r\n  };\r\n\r\n  var blob = new Blob([JSON.stringify(payload, null, 2)], {type:'application/json'});\r\n  var url = URL.createObjectURL(blob);\r\n  var a = document.createElement('a');\r\n  a.href = url;\r\n  a.download = 'ethernet-all-profiles-backup.json';\r\n  document.body.appendChild(a);\r\n  a.click();\r\n  a.remove();\r\n  URL.revokeObjectURL(url);\r\n});\r\n\r\ndocument.getElementById('restoreAllBtn').addEventListener('click', function(){\r\n  document.getElementById('restoreAllFile').click();\r\n});\r\n\r\ndocument.getElementById('restoreAllFile').addEventListener('change', function(e){\r\n  var file = e.target.files && e.target.files[0];\r\n  if(!file) return;\r\n\r\n  var reader = new FileReader();\r\n\r\n  reader.onload = function(){\r\n    try{\r\n      var parsed = JSON.parse(reader.result);\r\n\r\n      // Accept NEW backups: { schema:'eccm-backup', store:{...} }\r\n      // Accept LEGACY backups: raw store object { current, profiles, ... }\r\n      var incomingStore = null;\r\n\r\n      if (parsed && parsed.schema === 'eccm-backup' && parsed.store && typeof parsed.store === 'object') {\r\n        incomingStore = parsed.store;\r\n      } else if (parsed && parsed.current && parsed.profiles) {\r\n        // legacy format: store dump\r\n        incomingStore = parsed;\r\n      } else if (parsed && parsed.schema === 'eccm-profile') {\r\n        throw new Error('This file is a single-profile export. Use \"Import Profile\", not \"Restore All\".');\r\n      } else {\r\n        throw new Error('Invalid backup file (unrecognised schema).');\r\n      }\r\n\r\n      if(!incomingStore.profiles || typeof incomingStore.profiles !== 'object'){\r\n        throw new Error('Invalid backup file (missing profiles).');\r\n      }\r\n\r\n      // Ensure settings exist + defaults\r\n      if (!incomingStore.settings) incomingStore.settings = { maxPorts: 512, enablePortRename: false };\r\n      if (incomingStore.settings.maxPorts == null) incomingStore.settings.maxPorts = 512;\r\n      if (incomingStore.settings.enablePortRename === undefined) incomingStore.settings.enablePortRename = false;\r\n\r\n      // Normalise every profile (this is where all the new fields are preserved)\r\n      Object.keys(incomingStore.profiles).forEach(function(name){\r\n        normalizeState(incomingStore.profiles[name]);\r\n      });\r\n\r\n      // Ensure \"current\" points to an existing profile\r\n      if (!incomingStore.current || !incomingStore.profiles[incomingStore.current]) {\r\n        var names = Object.keys(incomingStore.profiles);\r\n        incomingStore.current = names.length ? names[0] : 'Default';\r\n      }\r\n\r\n      // If somehow profiles are empty, create at least one\r\n      if (Object.keys(incomingStore.profiles).length === 0) {\r\n        incomingStore.profiles = { 'Default': deepClone(defaultState) };\r\n        incomingStore.current = 'Default';\r\n        normalizeState(incomingStore.profiles['Default']);\r\n      }\r\n\r\n      // Commit\r\n      store = incomingStore;\r\n      state = store.profiles[store.current] || deepClone(defaultState);\r\n\r\n      saveStore();\r\n      refreshProfileSelect();\r\n      applySettings();\r\n      render();\r\n\r\n    }catch(err){\r\n      alert('Restore failed: ' + err.message);\r\n    }finally{\r\n      e.target.value = '';\r\n    }\r\n  };\r\n\r\n  reader.readAsText(file);\r\n});\r\n\r\n/* ===================== SEARCH + PRINT ===================== */\r\ndocument.getElementById('searchBox').addEventListener('input', renderConnections);\r\ndocument.getElementById('printSheet').addEventListener('click', function(){ openPrintSheet(true); });\r\n\r\n/* ===================== CLEAR ALL (current profile only) ===================== */\r\ndocument.getElementById('clearAll').addEventListener('click', function(){\r\n  if(!confirm('Delete ALL devices and connections in profile \"'+store.current+'\"?')) return;\r\n  store.profiles[store.current] = deepClone(defaultState);\r\n  state = store.profiles[store.current];\r\n  saveStore(); render();\r\n});\r\n\r\n/* ===================== GLOBAL BLANK-SPACE CLICK: CLEAR SELECTION ===================== */\r\ndocument.addEventListener('click', function(e){\r\n  if (\r\n    e.target.closest('.port') ||\r\n    e.target.closest('.conn-row') ||\r\n    e.target.closest('.palette-backdrop') ||\r\n    e.target.closest('.modal-backdrop') ||\r\n    e.target.closest('.device-actions') ||\r\n    e.target.closest('button, input, select, label')\r\n  ){ return; }\r\n  pendingPort = null; highlightLink(null); clearSelectionOutlines();\r\n}, true);\r\n\r\n/* ===================== SETTINGS ===================== */\r\nif (!store.settings)\r\n  store.settings = { \r\n    maxPorts: 512, \r\n    enablePortRename: false,\r\n    portTermMode: 'port',\r\n    portTermCustom: ''\r\n  };\r\n\r\nif (store.settings.enablePortRename === undefined)\r\n  store.settings.enablePortRename = false;\r\n\r\nfunction getMaxPortsSetting() {\r\n  return Math.max(1, Number(store.settings?.maxPorts) || 512);\r\n}\r\n\r\nfunction saveSettings() {\r\n  saveStore();\r\n  applySettings();\r\n}\r\n\r\nfunction applySettings() {\r\n  // Ensure settings object exists (safe fallback)\r\n  if (!store.settings) store.settings = {};\r\n\r\n  // Defaults for new setting (don’t overwrite existing)\r\n  if (!('portTermMode' in store.settings)) store.settings.portTermMode = 'port';\r\n  if (!('portTermCustom' in store.settings)) store.settings.portTermCustom = '';\r\n\r\n  const maxPorts = getMaxPortsSetting();\r\n\r\n  // Device \"Ports\" input (Add Device modal)\r\n  const devPorts = document.getElementById('devPorts');\r\n  if (devPorts) {\r\n    devPorts.max = String(maxPorts);\r\n    if (Number(devPorts.value) > maxPorts) devPorts.value = String(maxPorts);\r\n  }\r\n\r\n  // Settings: maxPorts\r\n  const maxPortsInput = document.getElementById('maxPorts');\r\n  if (maxPortsInput) {\r\n    maxPortsInput.value = String(maxPorts);\r\n  }\r\n\r\n  // Settings: enablePortRename\r\n  const enablePortRenameEl = document.getElementById('enablePortRename');\r\n  if (enablePortRenameEl) {\r\n    enablePortRenameEl.checked = !!store.settings.enablePortRename;\r\n  }\r\n\r\n  // =========================\r\n  // Settings: Port label term\r\n  // =========================\r\n  const portTermModeEl = document.getElementById('portTermMode');\r\n  const portTermCustomEl = document.getElementById('portTermCustom');\r\n  const portTermCustomRow = document.getElementById('portTermCustomRow');\r\n\r\n  if (portTermModeEl) {\r\n    // Set current value\r\n    portTermModeEl.value = store.settings.portTermMode || 'port';\r\n\r\n    // Bind change listener ONCE\r\n    if (!portTermModeEl.dataset.bound) {\r\n      portTermModeEl.dataset.bound = '1';\r\n      portTermModeEl.addEventListener('change', () => {\r\n        const isCustom = portTermModeEl.value === 'custom';\r\n        if (portTermCustomRow) portTermCustomRow.style.display = isCustom ? 'flex' : 'none';\r\n      });\r\n    }\r\n  }\r\n\r\n  if (portTermCustomEl) {\r\n    portTermCustomEl.value = store.settings.portTermCustom || '';\r\n  }\r\n\r\n  if (portTermCustomRow) {\r\n    const mode = (portTermModeEl && portTermModeEl.value) || store.settings.portTermMode || 'port';\r\n    portTermCustomRow.style.display = (mode === 'custom') ? 'flex' : 'none';\r\n  }\r\n}\r\n\r\napplySettings();\r\n\r\nconst maxPortsInput = document.getElementById('maxPorts');\r\nconst saveSettingsBtn = document.getElementById('saveSettingsBtn');\r\nconst enablePortRenameEl = document.getElementById('enablePortRename');\r\n\r\nif (saveSettingsBtn && maxPortsInput && enablePortRenameEl) {\r\n  saveSettingsBtn.addEventListener('click', () => {\r\n    const val = Math.max(1, Number(maxPortsInput.value) || 9999);\r\n    store.settings.maxPorts = val;\r\n    store.settings.enablePortRename = !!enablePortRenameEl.checked;\r\n\tconst portTermModeEl = document.getElementById('portTermMode');\r\n\tconst portTermCustomEl = document.getElementById('portTermCustom');\r\n\r\n\tstore.settings.portTermMode = portTermModeEl ? portTermModeEl.value : 'port';\r\n\tstore.settings.portTermCustom = portTermCustomEl ? portTermCustomEl.value.trim() : '';\r\n    saveSettings();\r\n\trender();\r\n\t\r\n\tconst modal = document.getElementById('settingsModal');\r\n    if (modal) {\r\n      modal.classList.remove('is-open');\r\n      modal.setAttribute('aria-hidden', 'true');\r\n    }\r\n  });\r\n}\r\n\r\nif (enablePortRenameEl) {\r\n  enablePortRenameEl.checked = !!store.settings.enablePortRename;\r\n}\r\n\r\n(function clampBeforeAdd() {\r\n  const addBtn = document.getElementById('addBtn');\r\n  const devPorts = document.getElementById('devPorts');\r\n  if (!addBtn || !devPorts) return;\r\n\r\n  devPorts.addEventListener('input', () => {\r\n    const maxPorts = getMaxPortsSetting();\r\n    let v = Math.max(1, Number(devPorts.value) || 1);\r\n    if (v > maxPorts) v = maxPorts;\r\n    devPorts.value = String(v);\r\n  });\r\n\r\n  addBtn.addEventListener(\r\n    'click',\r\n    () => {\r\n      const maxPorts = getMaxPortsSetting();\r\n      let v = Math.max(1, Number(devPorts.value) || 1);\r\n      if (v > maxPorts) devPorts.value = String(maxPorts);\r\n    },\r\n    true\r\n  );\r\n})();\r\n\r\nconst __orig_changePorts = changePorts;\r\nchangePorts = function (d, newCount) {\r\n  const maxPorts = getMaxPortsSetting();\r\n  const clamped = Math.max(1, Math.min(maxPorts, Number(newCount) || 1));\r\n  return __orig_changePorts(d, clamped);\r\n};\r\n\r\n/* ===================== INIT ===================== */\r\nfunction initProfilesUI(){ refreshProfileSelect(); }\r\ninitProfilesUI();\r\nrender();\r\nupdateUniformPortWidth();\r\n\r\n\r\n\r\n\r\n(function(){\r\n  const STORE_KEY = 'elmStore';\r\n\r\n  function safeLoad(){\r\n    try { return JSON.parse(localStorage.getItem(STORE_KEY) || '{}'); }\r\n    catch { return {}; }\r\n  }\r\n  function safeSave(obj){\r\n    try { localStorage.setItem(STORE_KEY, JSON.stringify(obj)); } catch {}\r\n  }\r\n\r\n  function getStore(){\r\n    const s = (window.store && typeof window.store === 'object') ? window.store : safeLoad();\r\n    if (!s.settings) s.settings = {};\r\n    if (!s.settings.theme) s.settings.theme = 'dark';\r\n    return s;\r\n  }\r\n\r\n  function applyTheme(theme){\r\n    document.documentElement.classList.toggle('theme-bright', theme === 'bright');\r\n  }\r\n\r\n  function persistTheme(theme){\r\n    if (window.store && typeof window.store === 'object') {\r\n      window.store.settings = window.store.settings || {};\r\n      window.store.settings.theme = theme;\r\n      if (typeof window.saveStore === 'function') {\r\n        try { window.saveStore(); } catch {}\r\n      } else {\r\n        safeSave(window.store);\r\n      }\r\n    } else {\r\n      const s = getStore();\r\n      s.settings.theme = theme;\r\n      safeSave(s);\r\n    }\r\n  }\r\n\r\n  function init(){\r\n    const store = getStore();\r\n    applyTheme(store.settings.theme);\r\n\r\n    var sel = document.getElementById('themeSelect');\r\n    if (sel){\r\n      sel.value = (store.settings.theme === 'bright') ? 'bright' : 'dark';\r\n      sel.addEventListener('change', function(){\r\n        const theme = sel.value;\r\n        applyTheme(theme);\r\n        persistTheme(theme);\r\n        if (typeof window.render === 'function') {\r\n          try { window.render(); } catch {}\r\n        }\r\n      });\r\n    }\r\n  }\r\n\r\n  if (document.readyState === 'loading') {\r\n    document.addEventListener('DOMContentLoaded', init);\r\n  } else {\r\n    init();\r\n  }\r\n})();\r\n</script>\r\n<script>\r\n(function(){\r\n  const LS_KEY = 'elmTheme';\r\n  const getTheme = () => (localStorage.getItem(LS_KEY) === 'bright' ? 'bright' : 'dark');\r\n  const applyTheme = (t) => document.documentElement.classList.toggle('theme-bright', t === 'bright');\r\n  const setTheme = (t) => { localStorage.setItem(LS_KEY, t); applyTheme(t); updateButtons(t); if (typeof window.render==='function') { try{ render(); }catch{} } };\r\n\r\n  function updateButtons(t){\r\n    const darkBtn  = document.getElementById('themeDark');\r\n    const lightBtn = document.getElementById('themeLight');\r\n    if(!darkBtn || !lightBtn) return;\r\n    const isBright = t === 'bright';\r\n    darkBtn.classList.toggle('active', !isBright);\r\n    lightBtn.classList.toggle('active', isBright);\r\n    darkBtn.setAttribute('aria-pressed', String(!isBright));\r\n    lightBtn.setAttribute('aria-pressed', String(isBright));\r\n  }\r\n\r\n  function wire(){\r\n    const darkBtn  = document.getElementById('themeDark');\r\n    const lightBtn = document.getElementById('themeLight');\r\n    if(!darkBtn || !lightBtn) return;\r\n\r\n    darkBtn.addEventListener('click',  () => setTheme('dark'));\r\n    lightBtn.addEventListener('click', () => setTheme('bright'));\r\n\r\n    const current = getTheme();\r\n    applyTheme(current);\r\n    updateButtons(current);\r\n  }\r\n\r\n  if (document.readyState === 'loading') {\r\n    document.addEventListener('DOMContentLoaded', wire, { once:true });\r\n  } else {\r\n    wire();\r\n  }\r\n})();\r\n</script>\r\n<script>\r\n(() => {\r\n  const btn = document.getElementById('btnSettings');\r\n  const modal = document.getElementById('settingsModal');\r\n  const panel = modal?.querySelector('.slideover__panel');\r\n  const closers = modal?.querySelectorAll('[data-close]');\r\n  let lastFocused = null;\r\n\r\n  function openSettings() {\r\n    if (!modal) return;\r\n    lastFocused = document.activeElement;\r\n    modal.classList.add('is-open');\r\n    modal.setAttribute('aria-hidden', 'false');\r\n    applySettings();\r\n    setTimeout(() => panel?.focus(), 0);\r\n    document.addEventListener('keydown', onKey);\r\n    document.addEventListener('focus', trapFocus, true);\r\n  }\r\n\r\n  function closeSettings() {\r\n    if (!modal) return;\r\n    modal.classList.remove('is-open');\r\n    modal.setAttribute('aria-hidden', 'true');\r\n    document.removeEventListener('keydown', onKey);\r\n    document.removeEventListener('focus', trapFocus, true);\r\n    if (lastFocused && typeof lastFocused.focus === 'function') {\r\n      lastFocused.focus();\r\n    }\r\n  }\r\n\r\n  function onKey(e) {\r\n    if (e.key === 'Escape') closeSettings();\r\n  }\r\n\r\n  function trapFocus(e) {\r\n    if (!modal.classList.contains('is-open')) return;\r\n    if (!panel.contains(e.target)) {\r\n      e.stopPropagation();\r\n      panel.focus();\r\n    }\r\n  }\r\n\r\n  btn?.addEventListener('click', openSettings);\r\n  closers?.forEach(el => el.addEventListener('click', closeSettings));\r\n})();\r\n\r\n/* ===================== UNIVERSAL ESCAPE HANDLER ===================== */\r\n(function modalEscapeManager() {\r\n  const modals = {\r\n    palette: document.getElementById('paletteModal'),\r\n    edit: document.getElementById('editDeviceModal'),\r\n    layout: document.getElementById('layoutModal')\r\n  };\r\n\r\n  function isOpen(el) {\r\n    return el && el.style.display === 'flex';\r\n  }\r\n\r\n  function closeTopmost() {\r\n    if (isOpen(modals.palette)) {\r\n      modals.palette.style.display = 'none';\r\n      return true;\r\n    }\r\n    if (isOpen(modals.edit)) {\r\n      modals.edit.style.display = 'none';\r\n      currentEditDevice = null;\r\n      return true;\r\n    }\r\n    if (isOpen(modals.layout)) {\r\n      modals.layout.style.display = 'none';\r\n      return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  document.addEventListener('keydown', function (e) {\r\n    if (e.key === 'Escape') {\r\n      const closed = closeTopmost();\r\n      if (closed) {\r\n        e.stopPropagation();\r\n        e.preventDefault();\r\n      }\r\n    }\r\n  });\r\n})();\r\n\r\n</script>\r\n</body>\r\n</html>\r\n"
  },
  {
    "path": "FUNDING.yml",
    "content": "buy_me_a_coffee: bijomaru78\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "MANUAL.md",
    "content": "# User Manual\n\nThis tool helps you visually map, label, and manage Ethernet connections. It runs entirely in your browser, works offline, and saves everything automatically in your profile.  \n\n---\n\n## 📂 Profiles\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/ef2269ef-8c23-462b-8ee2-91ea4771d4b5\" />\n  \nProfiles let you keep different layouts (e.g. home, client A, client B).\n\n- **Create a new profile** → *Profiles* card → **New**  \n- **Switch profiles** → Use the dropdown at the top of the *Profiles* card  \n- **Rename** → Select a profile, then click **Rename**  \n- **Duplicate** → Clone the current profile with **Duplicate**  \n- **Delete** → Removes the current profile (at least one profile must exist)  \n- **Export** → Save a single profile as a JSON file  \n- **Import** → Load a profile from a JSON file\n\n---\n\n## 🖥️ Adding Devices\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/258a22fe-af58-40fc-b814-96d53bfff7c3\" />\n\nEach device is shown as a card with its own ports. Using clear names and distinct colours makes layouts easier to read, especially when you have multiple switches or patch panels. You can also edit or delete devices later if your setup changes — everything autosaves. Devices can be linked together through their ports, giving you a live view of how your network fits together.  \n\n- In the *Add device* card, enter a **name** (e.g. *Core Switch A*)  \n- Choose the **number of ports** (1–512)  \n- Click **Select colour** to assign a colour (helps distinguish devices)  \n- Click **Add device**  \n- Devices can be reordered by dragging them  \n\n---\n\n## ⚙️ Configuring Devices\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/af86ca1e-664e-4270-94d4-cccc04ef0ddb\" />\n\nConfiguring the layout makes your map easier to follow, whether you prefer full-width rows, split views, or dual-link ports. These options don’t affect the connections themselves — only how the device is displayed for clarity.  \n\nClick **Layout** on a device to adjust how its ports display:\n- **Row width**: full-width (12 ports per row) or half-width (6 ports per row)  \n- **13–24 ports**: choose *balanced* (split evenly) or *12 + remainder*  \n- **≤12 ports**: choose single row or split into 2 rows  \n- **Dual link**: each port can be split into 2 sub-ports  \n\n---\n\n## 🔗 Linking Ports\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/f9948f18-f1ac-48b1-a742-d2c3c002c8fe\" />\n\nWhen linking, you’ll be shown a confirmation prompt with both device names and port numbers, so you can double-check before saving the connection.  \n\n- Click one free port, then another free port → confirm to create a connection  \n- Both ends will be coloured with their peer’s device colour  \n- Linked ports show an arrow ⇄  \n\n---\n\n## 🏷️ Labelling & Reserving Ports\n- **ALT + Click** a port → add or edit a label (alias)  \n  - Example: *WAN*, *Printer*, *AP-1*  \n- **CTRL + Click** a port → mark it as *reserved* (grey background)  \n  - Use for ports connected to devices **outside** this layout (e.g. ISP modem, patch panel, office uplink) - so they appear as connected without having to be linked to another port\n  - Combine with ALT-label to describe what’s at the other end  \n    - Example: CTRL-reserve port with a label for location, e.g. *Office*  → ALT-label to specify what's connected, e.g. *PC-4*  \n\n---\n\n## 💾 Backup & Restore (all profiles)\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/da133980-4be6-4c4d-b9b6-413cede3510d\" />\n\nBackups are useful if you want to move your layouts to another computer or just keep a copy in case your browser storage is cleared. Restoring will overwrite your current profiles, so it’s best to take a fresh backup first if you want to merge changes later. \n\n- **Backup all** → saves every profile (devices + links) into one JSON file  \n- **Restore all** → load a backup and replace everything\n\n---\n\n## 🔍 Finding Connections\n\n<img align=\"right\" width=\"250\" alt=\"image\" src=\"https://github.com/user-attachments/assets/f0cf1111-f080-49f0-b396-331f0c8940b7\" />\n\nThis makes it easy to track down a specific cable in larger layouts without scanning visually. You can search by device name, port number, or any custom alias you’ve added.  \n\n- Use the search box (*Find connection* card) to filter by device, port, or alias  \n- The *Connections* table shows all links, with both devices, ports, and labels  \n- Click a row → highlights both ends of the link  \n\n---\n\n## ❌ Managing Connections\n\n<img align=\"right\" width=\"150\" alt=\"image\" src=\"https://github.com/user-attachments/assets/8bc8bb52-7854-4274-ae89-5829c1501a01\" />\n\nFrom the *Connections* table:\n- **Unlink** → break a connection between two ports  \n- **Clear** → clear a Reserved port (can also be cleared by **CTRL + clicking** the reserved port again)\n\n---\n\n## 🖨️ Printing\n- Use **Print layout** (top-right) to generate a printable sheet of devices + connections  \n\n---\n\n## 📝 Tips\n- Profiles autosave automatically — no need to press “Save”  \n- Use colours to quickly group devices by type or rack position  \n- Labels + reserved ports are powerful for documenting external links  \n\n---\n"
  },
  {
    "path": "README.md",
    "content": "# Ethernet Cable Connection Manager\n\nA lightweight, browser-based tool for mapping Ethernet connections.  \nCreate switches, patch panels, wall ports, routers, etc. Assign ports, connect them, and visualise how your network is wired.  \n\n_Featured on:_<br>\n🎞️ _<a href=\"https://www.youtube.com/watch?v=j_T4FLumWC8\" target=\"_blank\">ECCM - Ethernet Cable Connection Manager - Clarity on Cabling by Awesome Open Source</a>_<br> \n🎞️ _<a href=\"https://www.youtube.com/watch?v=b_ggjSxFNYM&t=81s\" target=\"_blank\">Best Docker Apps of September 2025 by ServersatHome</a>_<br>\n🎞️ _<a href=\"https://www.youtube.com/watch?v=BWz9uFSNA8A&t=1245s\" target=\"_blank\">Docker full of tools by MP Studio</a>_<br>\n_Thank you for sharing!_\n\n📖 **User Manual** see [MANUAL.md](MANUAL.md)\n\n📍 **Roadmap / To-Do:** see [ROADMAP.md](ROADMAP.md)\n\n- 🖥️ Works offline (pure HTML + JavaScript, no server required)  \n- 📂 Save/export/import layouts as JSON  \n- 🖨️ Print sheets with device colours and linked ports  \n- 👥 Manage multiple profiles (e.g., different customer networks)  \n- 🎨 Colour-code devices and customise port aliases  \n- 🔌 Dual-link ports supported (patch panels, wall sockets)\n\n**_Editor (Dark and Light mode):_**\n\n<img src=\"https://github.com/bijomaru78/eccm/blob/main/eccm_ui_dark_light_animation.gif?raw=true\">\n\n**_Print sheet (devices and ports):_**\n\n<img width=\"900\" alt=\"image\" src=\"https://github.com/user-attachments/assets/fdb68294-eeec-43c5-b5c9-0b978d6fdc28\" />\n\n**_Print sheet (connections table):_**\n\n<img width=\"617\" height=\"558\" alt=\"image\" src=\"https://github.com/user-attachments/assets/4967c6f2-caf6-4eb2-add0-2a1d5170ad0d\" />\n\n\n## 🚀 Try it online\nYou can open the app instantly here (hosted via GitHub Pages):  \n👉 [Ethernet Cable Connection Manager DEMO](https://bijomaru78.github.io/eccm/ECCM.html)\n\nOr download the zip from the releases page and run it locally.\n\n## 📥 Download\nGrab the latest release here:  \n👉 [Releases](https://github.com/bijomaru78/eccm/releases)\n\n## 💡 Support\nThis project is free and open source (GPL-3.0).  \nIf it saves you time or helps in your work, consider supporting development:  \n\n<a href=\"https://www.buymeacoffee.com/bijomaru78\" target=\"_blank\"><img src=\"https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png\" alt=\"Buy Me A Coffee\" style=\"height: 60px !important;width: 217px !important;\" ></a>\n\n## 📜 License\nThis project is licensed under the **GNU GPL-3.0**.  \nYou are free to use, modify, and redistribute it, but if you distribute changes, you must also provide the source code under the same license.\n"
  },
  {
    "path": "ROADMAP.md",
    "content": "# Ethernet Cable Connection Manager — Roadmap\n\nThis roadmap tracks near-term fixes, planned features, and ideas.  \nIf something here matters to you, please open/👍 an issue so I can prioritise.\n\n---\n\n## ✅ Completed\n- Profiles: create/rename/duplicate/delete/switch\n- Export/Import single profile + Backup/Restore all profiles\n- Device layout options (full/half rows, 12+remainder / balanced, dual-link)\n- Link confirmation prompt\n- Find connections + highlight in UI\n- A4 layout; colours (linked keep device colour, unlinked white/black text, reserved grey)\n- Improve on-screen cheat-sheet (`?` key): ALT = label, CTRL = reserve, click-to-link\n- Consistent inner-glow selection for single/dual ports (no layout shift)\n- Colour contrast checks for print (linked text always readable)\n- Remove 512 port limit\n- Local settings page\n- Dark/light mode switch\n\n---\n\n## 🧰 In progress / Next up (P0 = highest)\n- **P0**\n  - [ ] Port settings - additional values such as port speed and VLAN configurable via a right-click menu\n  - [ ] Hover card - select port + hover, reveal a pop-up window including all the information about the port, including the additional settings (see above)\n- **P1**\n  - [ ] “Quick Start” 5-step section at top of manual\n- **P1**\n  - [ ] Swatch colours + easier way to edit colour for existing devices\n---\n\n## 🎯 Short-term candidates\n\n---\n\n## 💡 Later / Ideas\n\n  - [ ] Visible link (line) between selected/linked ports\n\n\n- [MANUAL.md](MANUAL.md)\n- [Issues](../../issues)\n"
  }
]