Full Code of bijomaru78/eccm for AI

main cb2b6b1ee999 cached
6 files
165.9 KB
44.1k tokens
1 requests
Download .txt
Repository: bijomaru78/eccm
Branch: main
Commit: cb2b6b1ee999
Files: 6
Total size: 165.9 KB

Directory structure:
gitextract_sla9q__l/

├── ECCM.html
├── FUNDING.yml
├── LICENSE
├── MANUAL.md
├── README.md
└── ROADMAP.md

================================================
FILE CONTENTS
================================================

================================================
FILE: ECCM.html
================================================
<!doctype html>
<html lang="en">
<head>
<link type="image/png" sizes="32x32" rel="icon" href="https://img.icons8.com/stickers/32/ethernet-on.png">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Ethernet Cable Connection Manager</title>
<style>
: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}
html,body{height:100%}
body{margin:0;background:var(--bg);color:var(--ink);font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif}
*,*::before,*::after{box-sizing:border-box}
header{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)}
header h1{font-size:18px;margin:0;font-weight:650}
.badge{color:var(--muted);font-size:12px;border:1px solid var(--line);padding:2px 8px;border-radius:999px}
.wrap{position:relative;display:grid;grid-template-columns:340px 1fr;gap:0;height:calc(100% - 62px)}
@media (max-width:1024px){.wrap{grid-template-columns:1fr;height:auto}}
aside,main{padding:16px}
aside{border-right:1px solid var(--line);background:var(--panel)}
main{overflow:auto;position:relative}
.card{background:#141821;border:1px solid var(--line);border-radius:10px;padding:12px;margin-bottom:12px}
.card h3{margin:0 0 8px 0;font-size:14px;font-weight:650}
label{display:block;font-size:12px;color:var(--muted);margin:8px 0 4px}
.muted{color:var(--muted)}.small{font-size:12px}
.mini{padding:4px 8px;font-size:12px;border-radius:6px}
.setting-row{display:flex;align-items:center;justify-content:space-between;gap:.75rem;margin:.5rem 0}
.setting-row select{padding:.35rem .5rem;border-radius:.5rem}
input[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}
button,.btn{background:#11151d;color:var(--ink);border:1px solid var(--line);padding:8px 10px;border-radius:8px;cursor:pointer;font-weight:600}
button:hover{border-color:#2a2f3b}
.btn-danger{border-color:#3b2222}
.dev-rows{display:flex;flex-direction:column;gap:12px}
.dev-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
.device-wrap{display:block;width:100%}
.device-wrap.full{grid-column:1/-1}
.device{background:#131722;border:1px solid var(--line);border-radius:12px;padding:12px;position:relative;width:100%}
.device-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
.device-title{font-size:15px;font-weight:650;display:flex;align-items:center;gap:8px}
.swatch{width:12px;height:12px;border-radius:3px;border:1px solid #0006;display:inline-block}
.device-actions{display:flex;gap:6px;flex-wrap:wrap}
.meta{font-size:12px;color:var(--muted);margin-top:2px}
.meta .inline-controls{margin-left:8px;display:inline-flex;gap:6px}
.ports-rows{display:flex;flex-direction:column;gap:8px;margin-top:10px}
.port-row{display:grid;gap:var(--portGapHalf)}
.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}
.port .num{font-size:12px;margin-top:2px;min-height:1.4em}
.port .alias{font-size:12px;margin-top:2px;min-height:1.4em; white-space: nowrap;  overflow: hidden; text-align: center;  max-width: 100%;  }
.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%;}
.port.selected{}
.port:not(.connected):not(.reserved) .num,.port:not(.connected):not(.reserved) .alias,.port:not(.connected):not(.reserved) .peer{color:#fff}
.port.reserved .num,.port.reserved .alias,.port.reserved .peer{color:#fff!important}
.port .num{  display:inline-flex;  align-items:center;  justify-content:center;  gap:4px;  line-height:1;}
.port .num .num-label{ line-height:1; }
.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;}
/* Slow link indicator: red cross in a small square */
.port .ind.ind--slow{
  width:10px;
  height:10px;
  border-radius:2px;
  background:#ffffff;      /* dark theme: white */
  color:#e11;              /* red cross */
  display:inline-flex;
  align-items:center;
  justify-content:center;
  font-size:8px;
  font-weight:700;
}

/* Bright theme: red on black */
html.theme-bright .port .ind.ind--slow{
  background:#000000;
  color:#e11;
}
.slow-warn{
  font-size:10px;
  line-height:1;
  display:inline-block;
  vertical-align:middle;
}
.port .ind.vlan-diamond{ transform: rotate(45deg); }
.port .ind.ind--off{  opacity:0;  pointer-events:none;  }
html.theme-bright .port .ind{ opacity:.8; }
.grid-slim{width:100%;border-collapse:collapse;border:1px solid var(--line);border-radius:8px;overflow:hidden;table-layout:fixed}
.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}
.grid-slim th{background:#121722;color:var(--muted);font-weight:600}
.conn-row.highlight td{background:#1e293b }
.conn-row td.deviceA .devName,.conn-row td.deviceB .devName{color:#fff;font-weight:400}
.conn-row.highlight td.deviceA .devName,.conn-row.highlight td.deviceB .devName{color:var(--devColor);font-weight:700}
.conn-row.reserved-row td{background:#121622}
.conn-row.reserved-row:hover td{background:#151b2a}
.color-picker-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.swatch-lg{width:24px;height:24px;border-radius:6px;border:1px solid #0006;display:inline-block}
.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)}
.color-btn:hover{border-color:#2a2f3b}
.palette-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center;z-index:999}
.palette{background:#141821;border:1px solid var(--line);border-radius:12px;padding:12px;min-width:280px;max-width:90vw}
.palette h4{margin:0 0 10px 0;font-size:14px}
.palette-grid{display:grid;grid-template-columns:repeat(4,36px);gap:8px;justify-content:center}
.chip{width:36px;height:36px;border-radius:8px;border:1px solid rgba(0,0,0,.35);cursor:pointer}
.palette .actions{display:flex;justify-content:flex-end;margin-top:12px}
.modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center;z-index:60}
.modal{background:#141821;border:1px solid var(--line);border-radius:12px;padding:14px;min-width:300px;max-width:90vw}
.modal h4{margin:0 0 10px 0;font-size:14px}
.modal .row{display:flex;gap:8px;align-items:center;margin:6px 0}
.modal label{margin:0;color:var(--ink);font-size:13px}
.modal select{background:#0f131b;color:var(--ink);border:1px solid var(--line);border-radius:8px;padding:6px 10px}
.modal .actions{display:flex;gap:8px;justify-content:flex-end;margin-top:12px}
html.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}
html.theme-bright header{background:#fff!important;border-bottom:1px solid #e5e7eb!important;color:#111!important}
html.theme-bright header h1{color:#111!important}
html.theme-bright header .badge{background:#fff!important;color:#444!important;border-color:#e0e6ef!important}
html.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}
html.theme-bright header button:hover,html.theme-bright header .btn:hover{border-color:#9aa4b2!important}
html.theme-bright .device{background:#fff!important;border-color:#ccc!important}
html.theme-bright .port:not(.connected):not(.reserved){background:#fff!important;color:#000!important}
html.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}
html.theme-bright .port.selected{}
html.theme-bright .port.reserved{background:#555!important;color:#fff!important}
html.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}
html.theme-bright button:not(.chip):hover,html.theme-bright .btn:hover{border-color:#888!important}
html.theme-bright .grid-slim th{background:#f6f7f9!important;color:#111!important;border-color:#ccc!important}
html.theme-bright .grid-slim td{background:#fff!important;color:#111!important;border-color:#ddd!important}
html.theme-bright .conn-row.highlight td{background:#e8f0fe!important;color:#000!important}
html.theme-bright .conn-row.reserved-row td{background:#f1f1f1!important;color:#000!important}
html.theme-bright .conn-row.reserved-row:hover td{background:#e0e0e0!important}
html.theme-bright .conn-row td.deviceA .devName,html.theme-bright .conn-row td.deviceB .devName{color:#000!important;font-weight:400}
html.theme-bright .conn-row.highlight td.deviceA .devName,html.theme-bright .conn-row.highlight td.deviceB .devName{color:var(--devColor)!important;font-weight:700}
html.theme-bright .palette{background:#fff!important;border-color:#ccc!important;color:#000!important}
html.theme-bright .palette h4{color:#000!important}
html.theme-bright .palette .chip{border:1px solid rgba(0,0,0,.4)}
html.theme-bright .modal{background:#fff!important;border:1px solid #ccc!important;color:#111!important}
html.theme-bright .modal h4,html.theme-bright .modal label{color:#111!important}
html.theme-bright .modal select{background:#fff!important;color:#111!important;border:1px solid #ccc!important}
.theme-toggle{display:inline-flex;border-radius:10px;overflow:hidden}
.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}
.theme-toggle button:first-child{border-top-left-radius:10px;border-bottom-left-radius:10px}
.theme-toggle button:last-child{border-right:1px solid var(--line);border-top-right-radius:10px;border-bottom-right-radius:10px}
.theme-toggle button.active{box-shadow:inset 0 0 0 2px #e5e7eb}
html.theme-bright .theme-toggle button{background:#fff;color:#111;border-color:#ccc}
html.theme-bright .theme-toggle button:last-child{border-right-color:#ccc}
html.theme-bright .theme-toggle button.active{box-shadow:inset 0 0 0 2px #000}
main::-webkit-scrollbar{width:10px}
main::-webkit-scrollbar-track{background:var(--panel)}
main::-webkit-scrollbar-thumb{background-color:#555;border-radius:6px;border:2px solid var(--panel)}
main::-webkit-scrollbar-thumb:hover{background-color:#777}
main{scrollbar-width:thin;scrollbar-color:#555 var(--panel)}
html.theme-bright main::-webkit-scrollbar-track{background:#fff!important}
html.theme-bright main::-webkit-scrollbar-thumb{background-color:#bbb!important;border:2px solid #fff!important}
html.theme-bright main::-webkit-scrollbar-thumb:hover{background-color:#999!important}
html.theme-bright main{scrollbar-color:#bbb #fff!important}
:root{  --hover-bg: #141821;  --hover-border: #2b3140;  --hover-ink: #e8eaf1;}
html.theme-bright{  --hover-bg: #fffffe;  --hover-border: #cfd6e4;  --hover-ink: #111;}
.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;}
.hovercard .hc-title{ font-weight: 700; margin-bottom: 4px; }
.hovercard .hc-row{ display:flex; gap:8px; }
.hovercard .hc-k{ color: var(--muted); min-width: 72px; }
.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;}
.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);}
.speed-menu select{  background:#0f131b;  color:#e8eaf1;  border:1px solid var(--line);  border-radius:6px;  padding:6px 8px;  font-size:12px;}
html.theme-bright .speed-menu{  background:#fff;  color:#111;  border-color:#ccc;}
html.theme-bright .speed-menu select{  background:#fff;  color:#111;  border-color:#ccc;}
.slideover{  position: fixed;  inset: 0;  z-index: var(--z-overlay, 5000);  display: none;  font: inherit;  color: var(--ink);}
.slideover.is-open{ display:block; }
.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;}
.slideover.is-open .slideover__backdrop{ opacity: 1; }
.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;}
.slideover.is-open .slideover__panel{ transform: translateX(0); }
.slideover__header,
.slideover__footer{  background: var(--paper);  color: var(--ink);  padding: 12px 16px;}
.slideover__header{  display:flex; align-items:center; justify-content:space-between;  border-bottom: 1px solid var(--line);}
.slideover__footer{  border-top: 1px solid var(--line);}
.slideover__header h2{  margin: 0;  font-size: 18px;  font-weight: 600;  color: var(--ink);}
.slideover__body{  padding: 12px 16px;  overflow: auto;  flex: 1 1 auto;  background: var(--paper);  color: var(--ink);}
.slideover__close{  font-size: 28px; line-height: 1;  border: 0; background: transparent; color: var(--ink);  cursor: pointer;}
@media (prefers-color-scheme: dark){  .slideover__backdrop{    background: var(--overlay-dark, rgba(0,0,0,.6));  }}
@media (prefers-reduced-motion: reduce){  .slideover__backdrop,  .slideover__panel{ transition: none; }}
@media print{  
	.slideover{ display:none !important; }
	input[type=range][orient=vertical] {  appearance: slider-vertical;  width: 8px;}
	#customColorPicker input[type=range] {  margin: 0 2px;}
	#colorPreviewBox {  box-shadow: 0 0 6px rgba(0,0,0,0.4);}
	#hexOutput:focus {  outline: none;  border-color: #66ccff;}
	#hueBar {  border: 1px solid var(--line);}
	#hueMarker {  transition: top 0.1s ease;}
	#colorPreviewBox {  transition: background 0.15s ease;}
	#hexOutput {  width: 80px;  font-size: 12px;  margin-top: 4px;}
}
.port .peer {
  position: relative;
  overflow: hidden;
  white-space: nowrap;
  text-align: center;
  max-width: 100%;
}

.port .peer > span {
  display: inline-block;
  white-space: nowrap;
  position: relative;
  will-change: transform;
}

/* Enable animation only if .scroll is present */
.port .peer.scroll > span {
  display: inline-block;
  white-space: nowrap;
  position: relative;
  will-change: transform;
  animation: eccm-peer-bounce 7s ease-in-out infinite;
  animation-delay: 2s; 
}

/* Keyframes:
   0%–100% cycle = 7 seconds:
   - 0–40%: scroll to the right
   - 40–55%: PAUSE on right (1 second)
   - 55–95%: scroll back left
   - 95–100%: PAUSE left (0.35s)
*/
@keyframes eccm-peer-bounce {
  0%   { transform: translateX(0); }
  35%  { transform: translateX(calc(-1 * var(--peer-diff))); }
  50%  { transform: translateX(calc(-1 * var(--peer-diff))); }
  85%  { transform: translateX(0); }
  100% { transform: translateX(0); }
}

</style>
</head>
<body>
<header>
  <h1>Ethernet Cable Connection Manager</h1>
  <span class="badge">1.0.6</span>
  <div style="margin-left:auto;display:flex;gap:8px">
	<button id="btnSettings" class="btn">Settings</button>
    <button id="printSheet">Print layout</button>
  </div>
</header>

<div class="wrap">
  <aside>
    <!-- Profiles -->
    <div class="card">
      <h3>Profiles</h3>
      <label for="profileSelect">Active profile</label>
      <select id="profileSelect"></select>

      <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px">
        <button id="newProfileBtn">New</button>
        <button id="renameProfileBtn">Rename</button>
        <button id="duplicateProfileBtn">Duplicate</button>
        <button id="deleteProfileBtn" class="btn-danger">Delete</button>
        <button id="exportProfileBtn" class="btn">Export</button>
        <button id="importProfileBtn" class="btn">Import</button>
        <input id="importProfileFile" type="file" accept=".json,application/json" style="display:none">
      </div>

      <div class="small muted" style="margin-top:6px">
      </div>
    </div>

    <div class="card">
      <h3>Add device</h3>
      <label for="devName">Name</label>
      <input id="devName" type="text" placeholder="e.g. Core Switch A" />
      <div class="row">
        <div>
          <label for="devPorts">Ports</label>
          <input id="devPorts" type="number" inputmode="numeric" min="1" max="9999" value="24" />
        </div>
      </div>
      <label>Colour</label>
      <div class="color-picker-row">
        <button type="button" class="color-btn" id="openPalette">Select colour</button>
        <span id="devColorPreview" class="swatch swatch-lg" title="Selected colour"></span>
      </div>
      <div style="margin-top:10px;display:flex;gap:8px">
        <button id="addBtn">Add device</button>
        <button id="clearAll" class="btn-danger" title="Delete everything">Clear all devices</button>
      </div>
      <div class="small muted" style="margin-top:6px">
        Click two free ports to connect<br>
		<strong>Unlink</strong> in Connections<br>
		<strong>Alt-click</strong> a port to set an alias<br>
		<strong>CTRL-click</strong> to mark as Reserved.
      </div>
    </div>

    <!-- Backup/restore all profiles -->
    <div class="card">
      <h3>Backup / Restore (all profiles)</h3>
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <button id="backupAllBtn" class="btn">Backup all</button>
        <button id="restoreAllBtn" class="btn">Restore all</button>
        <input id="restoreAllFile" type="file" accept=".json,application/json" style="display:none">
      </div>
      <div class="small muted" style="margin-top:6px">Saves or restores every profile on this device.</div>
    </div>

    <div class="card">
      <h3>Find connection</h3>
      <input id="searchBox" type="text" placeholder="Filter by device, port, alias, or reserved…" />
      <div class="small muted" style="margin-top:6px">Filters the connections table.</div>
    </div>
  </aside>

  <main>
    <div class="card">
      <h3>Devices</h3>
      <div id="devRows" class="dev-rows"></div>
    </div>

    <div class="card">
      <h3>Connections</h3>
      <table class="grid-slim" id="connTable">
        <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>
        <tbody id="connBody"></tbody>
      </table>
      <div class="small muted">Click a row (or a connected port) to highlight both ends.</div>
    </div>
  </main>
  


  </div>
</aside>
</div>

<!-- Settings Slide-Over (Modal) -->
<div id="settingsModal" class="slideover" aria-hidden="true">
  <div class="slideover__backdrop" data-close></div>
  <aside class="slideover__panel" role="dialog" aria-modal="true" aria-labelledby="settingsTitle" tabindex="-1">
    <header class="slideover__header">
      <h3>Settings</h3>
    </header>

    <div class="slideover__body" id="settingsPanelBody">
	
	<div class="card">
	<div class="setting-row" id="themeRow">
		<label>Theme</label>
		<div class="theme-toggle" role="group" aria-label="Theme">
			<button type="button" id="themeDark"  data-theme="dark"   aria-pressed="false">🌙 Dark</button>
			<button type="button" id="themeLight" data-theme="bright" aria-pressed="false">☀️ Light</button>
		</div>
	</div>
	</div>
	
        <div class="card">
	
	<div class="setting-row">
		<label for="enablePortRename">Enable Port Renaming</label>
		<input id="enablePortRename" type="checkbox" />
	</div>
	<div class="setting-row">
	  <label for="maxPorts" style="flex:1;">Maximum ports per device</label>
	  <input id="maxPorts" type="number" min="0" max="9999" style="flex:1; max-width:120px;" />
	</div>
	
	<div class="setting-row">
	  <label for="portTermMode">Port label</label>
	  <select id="portTermMode" style="max-width:160px">
		<option value="port">Port</option>
		<option value="interface">Interface</option>
		<option value="custom">Custom</option>
	  </select>
	</div>

	<div class="setting-row" id="portTermCustomRow" style="display:none">
	  <label for="portTermCustom" style="flex:1;">Custom label</label>
	  <input id="portTermCustom" type="text" placeholder="e.g. Jack" style="flex:1; max-width:160px;" />
	</div>	
	
	<div style="margin-top:10px;display:flex;gap:8px">
	  <button id="saveSettingsBtn" class="btn">Save</button>
	</div>

  </div>
    </div>

    <footer class="slideover__footer">
      <button class="btn" data-close>Close</button>
    </footer>
  </aside>
</div>


<!-- Palette -->
<div class="palette-backdrop" id="paletteModal">
  <div class="palette" role="dialog" aria-modal="true" aria-labelledby="paletteTitle">
  <h4 id="paletteTitle">Select colour</h4>
	  <div style="display:flex;gap:20px;justify-content:center;align-items:flex-start;flex-wrap:wrap">
		<div class="palette-grid" id="paletteGrid" style="grid-template-columns:repeat(4,36px)"></div>
	  </div>
	  <div class="actions"><button type="button" id="paletteClose">Close</button></div>
	</div>

</div>

<!-- Layout modal -->
<div class="modal-backdrop" id="layoutModal">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="layoutTitle">
    <h4 id="layoutTitle">Device layout options</h4>
    <div class="row"><label style="min-width:110px">Device</label><span id="layoutDeviceName" class="small muted"></span></div>
    <div class="row">
      <label style="min-width:110px">Row width</label>
      <select id="layoutFullRow">
        <option value="auto">Auto (follow rules)</option>
        <option value="full">Force full row</option>
      </select>
    </div>
    <div class="row" id="optMidWrap">
      <label style="min-width:110px">13–24 ports</label>
      <select id="layoutMidWrap">
        <option value="balanced">Balanced (½ + ½)</option>
        <option value="twelve">12 + remainder</option>
      </select>
    </div>
    <div class="row" id="optSmallWrap">
      <label style="min-width:110px">≤12 ports</label>
      <select id="layoutSmallWrap">
        <option value="single">Single row</option>
        <option value="split">Split into 2 rows</option>
      </select>
    </div>
    <div class="row" id="optDualLink">
      <label style="min-width:110px">Dual link</label>
      <select id="layoutDualLink">
        <option value="off">Normal</option>
        <option value="on">Dual link</option>
      </select>
    </div>
	<div class="row" id="optNumbering">
	  <label style="min-width:110px">Port numbering</label>
		<select id="layoutNumbering">
		  <option value="row">Left → Right (rows)</option>
		  <option value="column">Top ↓ Bottom (columns)</option>
		  <option value="column-bt">Bottom ↑ Top (columns)</option>
		</select>
	</div>
    <div class="actions">
      <button type="button" id="layoutCancel">Cancel</button>
      <button type="button" id="layoutSave">Save</button>
    </div>
  </div>
</div>

<!-- Edit Device Modal -->
<div class="modal-backdrop" id="editDeviceModal">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="editDeviceTitle">
    <h4 id="editDeviceTitle">Edit Device</h4>

    <div class="row">
      <label for="editDevName" style="min-width:100px">Name</label>
      <input id="editDevName" type="text" placeholder="Device name" />
    </div>

    <div class="row">
      <label for="editDevPorts" style="min-width:100px">Ports</label>
      <input id="editDevPorts" type="number" min="1" max="9999" />
    </div>

    <div class="row">
      <label style="min-width:100px">Colour</label>
      <div class="color-picker-row">
        <button type="button" class="color-btn" id="editOpenPalette">Select colour</button>
        <span id="editDevColorPreview" class="swatch swatch-lg" title="Selected colour"></span>
      </div>
    </div>

    <div class="actions">
      <button type="button" id="editDevCancel">Cancel</button>
      <button type="button" id="editDevSave" class="btn">Save</button>
    </div>
  </div>
</div>


<script>
/* ===================== HIGHLIGHT TUNING ===================== */
const HI_OUTLINE = 0; // px: outer white ring 
const HI_RING    = 5; // px: inner white ring thickness
const HI_BLUR    = 0; // px: inner white glow blur

/* ===================== PROFILES STORAGE ===================== */
var STORE_KEY = 'ethcm_profiles_v1';
var OLD_SINGLE_KEY = 'ethcm_v12';
var defaultState = {
  devices: [],
  links: [],
  portAliases: {},
  reservedPorts: {},
  portSpeeds: {},
  portVlans: {},
  portLinkedToNames: {}
};
function deepClone(o){ return JSON.parse(JSON.stringify(o)); }
function uid(){ return 'id_' + Math.random().toString(36).slice(2,10); }

var store = (function(){
  try{
    var raw = localStorage.getItem(STORE_KEY);
    if(raw){
      var parsed = JSON.parse(raw);
      if(parsed && parsed.current && parsed.profiles) return parsed;
    }
    var oldRaw = localStorage.getItem(OLD_SINGLE_KEY);
    if(oldRaw){
      var one = JSON.parse(oldRaw);
      normalizeState(one);
      return { current:'Migrated', profiles:{ 'Migrated': one } };
    }
  }catch(e){}
  return { current:'Default', profiles:{ 'Default': deepClone(defaultState) } };
})();
function normalizeState(st){
  st.devices = Array.isArray(st.devices) ? st.devices : [];
  st.links   = Array.isArray(st.links)   ? st.links   : [];

  st.portAliases = st.portAliases || {};
  st.reservedPorts = st.reservedPorts || {};
  st.portSpeeds = st.portSpeeds || {};
  st.portVlans  = st.portVlans  || {};

  // Safe forward-compat field (won't break anything if unused)
  st.portLinkedToNames = st.portLinkedToNames || {};

  st.devices.forEach(function(d){
    // Device core fields
    if (!d.id) d.id = uid();
    if (d.name == null) d.name = 'Unnamed';
    if (d.color == null) d.color = '#888';

    // Port count
    if (d.ports == null) d.ports = 1;

    // Customer port names (per-port rename)
    if (!d.portNames || typeof d.portNames !== 'object') d.portNames = {};

    // Device max speed
    if (d.maxSpeed === undefined) d.maxSpeed = null;

    // Layout defaults
    if (d.forceFullRow === undefined) d.forceFullRow = false;
    if (d.midWrapMode === undefined) d.midWrapMode = 'balanced';
    if (d.smallWrap === undefined) d.smallWrap = false;
    if (d.dualLink === undefined) d.dualLink = false;
    if (d.numbering === undefined) d.numbering = 'row';
  });
}
function saveStore(){ try{ localStorage.setItem(STORE_KEY, JSON.stringify(store)); }catch(e){} }

/* Active profile reference */
var state = store.profiles[store.current];

/* ===================== DOM HELPERS ===================== */
function $(s){ return document.querySelector(s); }
function $all(s){ return Array.prototype.slice.call(document.querySelectorAll(s)); }
function el(tag, attrs){
  var node = document.createElement(tag); attrs = attrs||{};
  Object.keys(attrs).forEach(function(k){
    var v = attrs[k];
    if(k === 'dataset'){ Object.keys(v).forEach(function(dk){ if(v[dk]!==undefined) node.dataset[dk] = v[dk]; }); }
    else if(k === 'class'){ node.className = v; }
    else if(k.indexOf('on') === 0 && typeof v === 'function'){ node.addEventListener(k.slice(2), v); }
    else { node.setAttribute(k, v); }
  });
  for(var i=2;i<arguments.length;i++){ var c = arguments[i]; if(c==null) continue; node.appendChild(c.nodeType ? c : document.createTextNode(c)); }
  return node;
}
function deviceById(id){ for(var i=0;i<state.devices.length;i++){ if(state.devices[i].id===id) return state.devices[i]; } return null; }
function indexById(id){ return state.devices.findIndex(function(d){return d.id===id;}); }

function parsePortKey(k){
  // keyFor() format in ECCM is: deviceId:port:sub  (sub may be empty)
  var parts = String(k).split(':');
  return {
    deviceId: parts[0],
    port: Number(parts[1]),
    sub: (parts.length > 2 && parts[2] !== '' ? Number(parts[2]) : null)
  };
}

function clearManualPortName(deviceId, port, sub){
  var d = deviceById(deviceId);
  if (!d || !d.portNames) return false;

  var k = keyFor(deviceId, port, sub);

  if (k in d.portNames) {
    delete d.portNames[k];

    // If portNames becomes empty, remove it entirely (keeps storage clean)
    if (Object.keys(d.portNames).length === 0) delete d.portNames;

    saveStore();
    return true;
  }

  return false;
}

function portLabelWithTerm(term, port, sub){
  // term must already be "Port" / "Interface" / "Jack" etc
  return term + ' ' + port + (sub != null ? '/' + (sub + 1) : '');
}

function getLinkForEndpoint(deviceId, port, sub){
  sub = (sub == null ? null : sub);

  for (var i = 0; i < state.links.length; i++) {
    var L = state.links[i];

    var aSub = (L.a.sub == null ? null : L.a.sub);
    var bSub = (L.b.sub == null ? null : L.b.sub);

    if (L.a.deviceId === deviceId && L.a.port === port && aSub === sub) return L;
    if (L.b.deviceId === deviceId && L.b.port === port && bSub === sub) return L;
  }
  return null;
}

function purgePortNamesThatMatchTerm(term){
  if (!term) return false;
  var changed = false;

  state.devices.forEach(function(d){
    if (!d.portNames) return;

    Object.keys(d.portNames).forEach(function(k){
      var v = (d.portNames[k] || '').trim();
      if (!v) return;

      var info = parsePortKey(k);
      // only purge if the saved value is exactly the default label for THAT key
      var def = portLabelWithTerm(term, info.port, info.sub);

      if (v === def) {
        delete d.portNames[k];
        changed = true;
      }
    });

    // optional clean-up if object becomes empty
    if (d.portNames && Object.keys(d.portNames).length === 0) delete d.portNames;
  });

  return changed;
}

function getPortTerm(){
  // Defaults
  if (!store.settings) store.settings = {};
  var mode = store.settings.portTermMode || 'port';
  var custom = (store.settings.portTermCustom || '').trim();

  if (mode === 'interface') return 'Interface';
  if (mode === 'custom') return custom || 'Port'; // fallback if empty
  return 'Port';
}

// "Port 5" / "Interface 5" / "Jack 5"
function portLabelDefault(port, sub){
  var term = getPortTerm();
  return term + ' ' + port + (sub != null ? '/' + (sub + 1) : '');
}

// Used in searches: "port5", "interface5", "jack5"
function portSearchTokens(port){
  var term = getPortTerm().toLowerCase();
  return [
    term + port,
    term + ' ' + port,
    String(port)
  ];
}

/* ===================== LINK/RESERVED HELPERS (dual-aware) ===================== */
function keyFor(deviceId, port, sub){ return deviceId + ':' + port + ':' + (sub==null ? '' : sub); }
function aliasFor(deviceId, port, sub){ return state.portAliases[keyFor(deviceId,port,sub)] || ''; }
function reservedLabelFor(deviceId, port, sub){
  return (state.reservedPorts && state.reservedPorts[keyFor(deviceId,port,sub)]) || null;
}
function isReservedPort(deviceId, port, sub){
  return !!reservedLabelFor(deviceId, port, sub);
}
function linkForPort(deviceId, port, sub){
  for(var i=0;i<state.links.length;i++){
    var L = state.links[i];
    if((L.a.deviceId===deviceId && L.a.port===port && (L.a.sub||null)===(sub||null)) ||
       (L.b.deviceId===deviceId && L.b.port===port && (L.b.sub||null)===(sub||null))) return L;
  }
  return null;
}
function getPeer(deviceId, port, sub){
  var L = linkForPort(deviceId, port, sub); if(!L) return null;
  if (L.a.deviceId===deviceId && L.a.port===port && (L.a.sub||null)===(sub||null)) return L.b;
  return L.a;
}
function speedToMbps(s){
  if (!s) return Infinity;
  const n = Number(String(s).replace(/[^0-9.]/g,'')) || 0;
  return String(s).includes('Gbit') ? n * 1000 : n;
}

function connectPorts(a, b) {
  if (linkForPort(a.deviceId,a.port,a.sub) || linkForPort(b.deviceId,b.port,b.sub)) return false;
  if (isReservedPort(a.deviceId,a.port,a.sub) || isReservedPort(b.deviceId,b.port,b.sub)) return false;

  // Create link
  var id = uid();
  state.links.push({ id:id, a:a, b:b });

  // --- AUTO-NEGOTIATE SPEED ---
  var devA = deviceById(a.deviceId);
  var devB = deviceById(b.deviceId);

  var maxA = devA && devA.maxSpeed ? devA.maxSpeed : null;
  var maxB = devB && devB.maxSpeed ? devB.maxSpeed : null;

  var spA = speedToMbps(maxA);
  var spB = speedToMbps(maxB);

  var lowest = Math.min(spA, spB);

  if (lowest !== Infinity) {
    var label = lowest >= 1000 ? (lowest/1000 + ' Gbit') : (lowest + ' Mbit');
    setSpeedFor(a.deviceId, a.port, a.sub, label);
    setSpeedFor(b.deviceId, b.port, b.sub, label);
  }

  saveStore();
  render();
  highlightLink(id);
  return true;
}

function recalcLinkSpeedsForDevice(deviceId) {
  const dev = deviceById(deviceId);
  if (!dev) return;

  state.links.forEach(function(L) {
    let a = L.a;
    let b = L.b;

    // Only recalc links involving this device
    if (a.deviceId !== deviceId && b.deviceId !== deviceId) return;

    const devA = deviceById(a.deviceId);
    const devB = deviceById(b.deviceId);
    if (!devA || !devB) return;

    const spA = speedToMbps(devA.maxSpeed);
    const spB = speedToMbps(devB.maxSpeed);

    const lowest = Math.min(spA, spB);

    if (lowest !== Infinity) {
      const label = lowest >= 1000
        ? (lowest / 1000 + ' Gbit')
        : (lowest + ' Mbit');

      setSpeedFor(a.deviceId, a.port, a.sub, label);
      setSpeedFor(b.deviceId, b.port, b.sub, label);
    }
  });
}

function speedFor(deviceId, port, sub){
  return (state.portSpeeds || {})[keyFor(deviceId,port,sub)] || '';
}
function setSpeedFor(deviceId, port, sub, val){
  var k = keyFor(deviceId,port,sub);
  state.portSpeeds = state.portSpeeds || {};
  if (!val) delete state.portSpeeds[k]; else state.portSpeeds[k] = String(val);
  saveStore();
}

function vlanFor(deviceId, port, sub){
  var v = (state.portVlans || {})[keyFor(deviceId,port,sub)];
  return (v==null || v==='') ? '' : Number(v);
}
function setVlanFor(deviceId, port, sub, val){
  var k = keyFor(deviceId,port,sub);
  state.portVlans = state.portVlans || {};
  if (val==null || val==='') { delete state.portVlans[k]; }
  else {
    var n = Math.max(1, Math.min(4094, Number(val)||0)); // clamp 1–4094
    state.portVlans[k] = n;
  }
  saveStore();
}
function linkedToOverrideFor(deviceId, port, sub){
  return (state.portLinkedTo || {})[keyFor(deviceId, port, sub)] || '';
}
function setLinkedToOverrideFor(deviceId, port, sub, val){
  var k = keyFor(deviceId, port, sub);
  state.portLinkedTo = state.portLinkedTo || {};
  if (!val) delete state.portLinkedTo[k];
  else state.portLinkedTo[k] = String(val);
  saveStore();
}

function fmtSpeed(val){
  // normalize display
  switch(String(val||'')){
    case '100 Mbit': return '100 Mbit';
    case '1 Gbit': return '1 Gbit';
    case '2.5 Gbit': return '2.5 Gbit';
    case '5 Gbit': return '5 Gbit';
    case '10 Gbit': return '10 Gbit';
    case '25 Gbit': return '25 Gbit';
    case '40 Gbit': return '40 Gbit';
    case '100 Gbit': return '100 Gbit';
    default: return '';
  }
}


/* ===================== COLOUR / SELECTION ===================== */
function 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 }; }
function 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'; }
function paintPortBase(node, bgHex){
  var bg = bgHex || '#0f141d';
  node.style.background = bg;
  node.style.borderRadius = '10px';
  var txt = bestTextColorFor(bg);
  node.style.color = txt;
  var alias = node.querySelector('.alias'); if (alias) alias.style.color = txt;
  var num   = node.querySelector('.num');   if (num)   num.style.color   = txt;
  var peer  = node.querySelector('.peer');  if (peer)  peer.style.color  = txt;
}

/* CLEAR selection visuals */
function clearSelectionOutlines(){
  $all('.port.selected').forEach(function(n){
    n.classList.remove('selected');
    n.style.boxShadow = 'none';
  });
}

/* APPLY selection visuals: same on singles and dual halves */
function outlineForSelection(node){
  node.classList.add('selected');

  var isBright = document.documentElement.classList.contains('theme-bright');
  var edgeClr = isBright ? '#000' : '#fff';
  var glowClr = isBright ? 'rgba(0,0,0,.38)' : 'rgba(255,255,255,.38)';

  var o = HI_OUTLINE, r = HI_RING, b = HI_BLUR;
  node.style.boxShadow =
    '0 0 0 ' + o + 'px ' + edgeClr + ',' +
    'inset 0 0 0 ' + r + 'px ' + edgeClr + ',' +
    'inset 0 0 ' + b + 'px ' + glowClr;
}

/* ---------- Hovercard (only shows while item is highlighted) ---------- */
var __hoverEl = null;

function hcEnsure(){
  if (!__hoverEl){
    __hoverEl = document.createElement('div');
    __hoverEl.className = 'hovercard';
    document.body.appendChild(__hoverEl);
  }
  return __hoverEl;
}
function hcHide(){ if(__hoverEl) __hoverEl.style.display = 'none'; }

function hcShowForTarget(target, html, evt){
  var el = hcEnsure();
  el.innerHTML = html;
  el.style.display = 'block';
  var x = 0, y = 0;
  if (evt && typeof evt.clientX === 'number'){
    x = evt.clientX + 14;
    y = evt.clientY + 12;
  } else {
    var r = target.getBoundingClientRect();
    x = r.right + 12;
    y = r.top + 8;
  }
  // Keep in viewport
  var vw = window.innerWidth, vh = window.innerHeight;
  var ew = el.offsetWidth || 240, eh = el.offsetHeight || 100;
  if (x + ew + 8 > vw) x = vw - ew - 8;
  if (y + eh + 8 > vh) y = vh - eh - 8;
  el.style.left = x + 'px';
  el.style.top  = y + 'px';
}

/* Hide the hovercard whenever selection is cleared */
const __orig_clearSel = clearSelectionOutlines;
clearSelectionOutlines = function(){
  hcHide();
  return __orig_clearSel.apply(this, arguments);
};
/* Also hide when we un-highlight a link */
const __orig_highlightLink = highlightLink;
highlightLink = function(id, opts){
  if (!id) hcHide();
  return __orig_highlightLink.apply(this, arguments);
};


/* ===================== UNIFORM PORT WIDTHS (two gaps) ===================== */
function updateUniformPortWidth(){
  var host = document.getElementById('devRows'); if(!host) return;
  var GAP_COL = 12;
  var PAD_BRD = 26;
  var gapFull = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--portGapFull')) || 9;
  var gapHalf = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--portGapHalf')) || 8;
  var Wrows = host.getBoundingClientRect().width || 800;
  var WfullInner = Wrows - PAD_BRD;
  var WhalfInner = ((Wrows - GAP_COL)/2) - PAD_BRD;
  var portW12 = (WfullInner - (11*gapFull)) / 12;
  var portW6  = (WhalfInner - (5*gapHalf)) / 6;
  portW12 = Math.max(40, portW12);
  portW6  = Math.max(40, portW6);
  document.documentElement.style.setProperty('--portW12', portW12 + 'px');
  document.documentElement.style.setProperty('--portW6',  portW6  + 'px');
}
var __pw_timer=null;
window.addEventListener('resize', function(){ clearTimeout(__pw_timer); __pw_timer=setTimeout(updateUniformPortWidth, 60); });

/* ===================== LAYOUT RULES ===================== */
function isFullWidthDevice(d){
  if (d.forceFullRow) return true;
  if ((d.ports||1) >= 13) return true;
  if ((d.ports||1) >= 7 && !d.smallWrap) return true;
  return false;
}
function splitPortsIntoRows(n, dev){
  if (n === 12 && dev.smallWrap) return [6, 6];

  if (n >= 12){
    if (n >= 13 && n <= 24 && dev.midWrapMode === 'balanced'){
      var a = Math.ceil(n/2);
      return [Math.min(12, a), Math.min(12, n - a)];
    }
    var rows = [], rem = n;
    while (rem > 0){ rows.push(Math.min(12, rem)); rem -= 12; }
    return rows;
  }
  if (n >= 7){
    if (dev.smallWrap){ var a = Math.ceil(n/2); return [a, n - a]; }
    return [n];
  }
  return [n];
}


/* ===================== CONNECT SELECTION ===================== */
var pendingPort = null;
var highlightedLinkId = null;

/* ===================== RENDER DEVICES ===================== */
function applyPeerScrolling() {
  requestAnimationFrame(() => {
    const peers = document.querySelectorAll('.peer');

    peers.forEach(peer => {
      const span = peer.querySelector('span');
      if (!span) return;

      const sw = span.getBoundingClientRect().width;
      const cw = peer.clientWidth;

      if (sw > cw) {
        // calculate how far to bounce
        const diff = sw - cw;
        span.style.setProperty('--peer-width', `${cw}px`);
        span.style.setProperty('--peer-diff', `${diff}px`);

        peer.classList.add('scroll');
      } else {
        peer.classList.remove('scroll');
      }
    });
  });
}


function renderDevices(){
  var host = $('#devRows'); host.innerHTML='';
  if(!state.devices.length){ host.appendChild(el('div',{class:'muted'},'No devices yet — add one on the left.')); updateUniformPortWidth(); return; }

  var i=0;
  while(i < state.devices.length){
    var rowEl = el('div',{class:'dev-row'});
    var d = state.devices[i];
    if (isFullWidthDevice(d)){
      rowEl.appendChild(renderDeviceWrap(d, true)); i += 1;
    } else {
      rowEl.appendChild(renderDeviceWrap(d, false));
      if (i+1 < state.devices.length && !isFullWidthDevice(state.devices[i+1])){
        rowEl.appendChild(renderDeviceWrap(state.devices[i+1], false)); i += 2;
      } else {
        rowEl.appendChild(el('div',{class:'device-wrap'}, el('div',{class:'device', style:'visibility:hidden'}, ' '))); i += 1;
      }
    }
    host.appendChild(rowEl);
  }
  updateUniformPortWidth();
}

function renderDeviceWrap(d, fullWidth){
  var wrap = el('div',{class:'device-wrap ' + (fullWidth ? 'full' : ''), dataset:{id:d.id}});
  wrap.draggable = true;

  wrap.addEventListener('dragstart', function(e){
    wrap.classList.add('dragging');
    e.dataTransfer.setData('text/plain', d.id);
    e.dataTransfer.effectAllowed='move';
  });
  wrap.addEventListener('dragend', function(){ wrap.classList.remove('dragging'); });
  wrap.addEventListener('dragover', function(e){ e.preventDefault(); e.dataTransfer.dropEffect='move'; });
  wrap.addEventListener('drop', function(e){
    e.preventDefault();
    var draggedId = e.dataTransfer.getData('text/plain'); if (!draggedId || draggedId === d.id) return;
    var from = indexById(draggedId), to = indexById(d.id); if (from<0 || to<0) return;
    var item = state.devices.splice(from,1)[0]; if (from < to) to -= 1; state.devices.splice(to,0,item);
    saveStore(); render();
  });

  var head = el('div',{class:'device-head'},
    el('div',{class:'device-title'},
      el('span',{class:'swatch', style:'background:'+(d.color||'#888')}),
      document.createTextNode(d.name||'Unnamed')
    ),
    el('div',{class:'device-actions'},
      el('button',{title:'Layout options', onclick:function(ev){ ev.stopPropagation(); openLayoutModal(d.id); }}, 'Layout'),
		el('button', {
		  title: 'Edit device',
		  onclick: function (ev) {
			ev.stopPropagation();
			openEditDeviceModal(d.id);
		  }
		}, 'Edit'),
      el('button',{class:'btn-danger',title:'Delete', onclick:function(ev){
        ev.stopPropagation();
        if(!confirm('Delete "'+(d.name||'Unnamed')+'" and its links?')) return;
        state.links = state.links.filter(function(L){
          return String(L.a.deviceId)!==String(d.id) && String(L.b.deviceId)!==String(d.id);
        });
        state.devices = state.devices.filter(function(x){ return String(x.id)!==String(d.id); });
        Object.keys(state.portAliases).forEach(function(k){
          if(k.split(':')[0]===String(d.id)) delete state.portAliases[k];
        });
        saveStore(); render();
      }}, 'Delete')
    )
  );

  var meta = el('div',{class:'meta'},
    document.createTextNode((d.ports||1)+' ports'),
    (function(){
      var c = el('span',{class:'inline-controls'},
        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()),
		el('button',{class:'mini', title:'Add one port', onclick:function(e){ e.stopPropagation(); changePorts(d, (d.ports||1)+1); saveStore(); render(); }}, '+ ' + getPortTerm())      
      );
      return c;
    })()
  );

  var portsContainer = el('div',{class:'ports-rows'});
var rows = splitPortsIntoRows(d.ports||1, d);
var total = d.ports || 1;
var seqByRow = rows.map(function(cnt){ return new Array(cnt); });

function buildRowMajor(){
  var n = 1;
  rows.forEach(function(count, r){
    for (var c=0; c<count; c++) seqByRow[r][c] = n++;
  });
}

function buildColumnMajor(){
  var maxCols = Math.max.apply(null, rows);
  var n = 1;
  for (var c=0; c<maxCols && n<=total; c++){
    for (var r=0; r<rows.length && n<=total; r++){
      if (c < rows[r]) { seqByRow[r][c] = n++; }
    }
  }
  for (var r=0; r<rows.length; r++){
    for (var c=0; c<rows[r]; c++){
      if (seqByRow[r][c] == null) seqByRow[r][c] = n++;
    }
  }
}

function buildColumnMajorBottomTop(){
  var maxCols = Math.max.apply(null, rows);
  var n = 1;

  // Fill by columns, but bottom row first
  for (var c=0; c<maxCols && n<=total; c++){
    for (var r=rows.length-1; r>=0 && n<=total; r--){
      if (c < rows[r]) { seqByRow[r][c] = n++; }
    }
  }

  // Safety fill (should rarely be needed)
  for (var r=0; r<rows.length; r++){
    for (var c=0; c<rows[r]; c++){
      if (seqByRow[r][c] == null) seqByRow[r][c] = n++;
    }
  }
}


// Choose numbering mode
if (d.numbering === 'column') buildColumnMajor();
else if (d.numbering === 'column-bt') buildColumnMajorBottomTop();
else buildRowMajor();

  function createSubPort(d, p, sub){
  var linked   = !!linkForPort(d.id, p, sub);
  var peer     = linked ? getPeer(d.id,p,sub) : null;
  var peerDev  = peer ? deviceById(peer.deviceId) : null;
  var peerPort = peer ? peer.port : null;
  var alias    = aliasFor(d.id,p,sub);
  var reserved = reservedLabelFor(d.id,p,sub);

  var rawSpeed = (typeof speedFor === 'function') ? speedFor(d.id, p, sub) : '';
  var spdVal   = fmtSpeed(rawSpeed) || '';
  var vlanVal  = (typeof vlanFor === 'function') ? vlanFor(d.id, p, sub) : '';

  var hasSpeed = (rawSpeed !== '' && rawSpeed != null);
  var hasVlan  = (vlanVal  !== '' && vlanVal  != null);

// Auto-negotiate for older links that have no stored speed yet
if (linked && !hasSpeed) {
  var dev    = deviceById(d.id);
  var peerDv = peerDev; // already computed above

  if (dev && dev.maxSpeed && peerDv && peerDv.maxSpeed) {
    var spA   = speedToMbps(dev.maxSpeed);
    var spB   = speedToMbps(peerDv.maxSpeed);
    var low   = Math.min(spA, spB);

    if (low !== Infinity) {
      var label = low >= 1000 ? (low/1000 + ' Gbit') : (low + ' Mbit');

      // Persist on both ends so future renders see it
      setSpeedFor(d.id, p, sub, label);
      setSpeedFor(peer.deviceId, peer.port, peer.sub, label);

      rawSpeed = label;
      spdVal   = fmtSpeed(label);
      hasSpeed = true;
    }
  }
}


var leftInd  = el('span',{class:'ind spd-dot'}, '');
var rightInd = el('span',{class:'ind vlan-diamond'}, '');

if (hasSpeed){
  leftInd.title = spdVal;
} else {
  leftInd.classList.add('ind--off');
}

if (hasVlan){
  rightInd.title = String(vlanVal);
} else {
  rightInd.classList.add('ind--off');
}

var portLabel =
  (d.portNames && d.portNames[keyFor(d.id, p, sub)]) ||
  portLabelDefault(p, sub);

var numEl = el('div',{class:'num'},
  leftInd,
  el('span',{class:'num-label'}, portLabel),
  rightInd
);

function bindMiniHover(indEl, label, value){
  if(!indEl || indEl.classList.contains('ind--off')) return;
  indEl.addEventListener('mouseenter', function(e){
    hcShowForTarget(indEl,
      '<div class="hc-title">'+label+'</div><div>'+value+'</div>', e);
  });
  indEl.addEventListener('mousemove', function(e){
    hcShowForTarget(indEl,
      '<div class="hc-title">'+label+'</div><div>'+value+'</div>', e);
  });
  indEl.addEventListener('mouseleave', hcHide);
}
bindMiniHover(leftInd,  'Link speed', spdVal);
bindMiniHover(rightInd, 'VLAN',  String(vlanVal));
// Slow-link indicator: port speed < device max → add "!" before speed square
(function () {
  var dev = deviceById(d.id);
  if (!dev || !dev.maxSpeed) return;
  if (!rawSpeed) return; // no explicit port speed set → nothing to compare

  function toMbps(s) {
    var txt = String(s || '').toLowerCase();
    if (!txt) return 0;
    var num = parseFloat(txt.replace(/[^0-9.]/g, '')) || 0;
    if (!num) return 0;
    // Treat values like "1 gbit", "1 gbps" etc. as Gbit
    if (txt.indexOf('gbit') !== -1 || txt.indexOf('gbps') !== -1) return num * 1000;
    return num; // assume Mbit
  }

  var devMaxMbps = toMbps(dev.maxSpeed);
  var portMbps   = toMbps(rawSpeed);

  if (devMaxMbps && portMbps && portMbps < devMaxMbps) {
    leftInd.insertAdjacentHTML(
      'beforebegin',
      '<span class="slow-warn" style="font-weight:900;margin-right:2px;">!</span>'
    );
  }
})();

// Build peer text: Device Name + Port Name or Reserved
var defaultPeerText =
  reserved
    ? (reserved || 'Reserved')
    : (
        peer && peerDev
          ? (peerDev.name + ' - ' +
             (
               (peerDev.portNames && peerDev.portNames[keyFor(peer.deviceId, peerPort, peer.sub)]) ||
               portLabelDefault(peerPort, peer.sub)
             )
            )
          : ''
      );

// If user has overridden "Linked to", show it here too
var peerOverride = (typeof linkedToOverrideFor === 'function') ? linkedToOverrideFor(d.id, p, sub) : '';
var peerText = (peerOverride !== '' ? peerOverride : defaultPeerText);


// Create peer element with a <span> for scrolling later
var peerEl = el(
  'div',
  { class: 'peer' },
  el('span', {}, peerText)
);



  var node = el('div',{
      class:'port'+(linked?' connected':'')+(reserved?' reserved':''), 
      dataset:{deviceId:d.id, port:p, sub:(sub==null?undefined:sub)}
    },
    numEl, 
    el('div',{class:'alias'}, alias||''),
	peerEl 
  );

  if (reserved){
    paintPortBase(node, 'var(--reserved-bg)');
  } else if (linked && peerDev){
    paintPortBase(node, peerDev.color || '#22354a');
  } else {
    paintPortBase(node, '#0f141d');
  }

  node.addEventListener('click', function(ev){
    if (ev.altKey){
      var curr = aliasFor(d.id,p,sub);
      var next = prompt('Optional port label (blank to clear):', curr||'');
      if(next===null) return;
      var k = keyFor(d.id,p,sub);
      if(!next.trim()) delete state.portAliases[k]; else state.portAliases[k] = next.trim();
      saveStore(); render(); return;
    }

    if (ev.ctrlKey){
      var k = keyFor(d.id,p,sub);
      if (state.reservedPorts && state.reservedPorts[k]){
		var term = getPortTerm();
        if(confirm('Clear reserved status for ' + term + ' ' +p+(sub!=null?('/'+(sub+1)):'')+'?')){
          delete state.reservedPorts[k];
        }
      } else {
        if (!state.reservedPorts) state.reservedPorts = {};
        var lbl = prompt('Reserved port label (e.g. WAN):', '');
        if (lbl===null) return;
        state.reservedPorts[k] = (lbl && lbl.trim()) ? lbl.trim() : 'Reserved';
      }
      pendingPort = null;
      saveStore(); render();
      return;
    }

    if (reserved){
      clearSelectionOutlines();
      outlineForSelection(node);
      highlightedLinkId = null; applyRowHighlight();
      pendingPort = null;
      return;
    }

    if (linkForPort(d.id, p, sub)) {
      clearSelectionOutlines();
      var L1 = linkForPort(d.id, p, sub);
      highlightLink(L1.id, { from:{deviceId:d.id, port:p, sub:sub} });
      pendingPort = null; return;
    }

    if (!pendingPort){
      pendingPort = {deviceId:d.id, port:p, sub:sub};
      clearSelectionOutlines(); outlineForSelection(node);
      highlightedLinkId = null; applyRowHighlight();
      return;
    }
    if (linkForPort(d.id, p, sub) || linkForPort(pendingPort.deviceId, pendingPort.port, pendingPort.sub) ||
        isReservedPort(d.id,p,sub) || isReservedPort(pendingPort.deviceId,pendingPort.port,pendingPort.sub)){
      alert('That port (or the previously selected one) is unavailable. Unlink/clear Reserved first.');
      pendingPort = null; clearSelectionOutlines(); highlightLink(null); return;
    }

    var devA = deviceById(pendingPort.deviceId);
    var devB = deviceById(d.id);
    var msg = 'Create link:\n' + (devA?devA.name:'A') + getPortTerm() + pendingPort.port + (pendingPort.sub!=null?'/'+(pendingPort.sub+1):'')
              + ' ⇄ ' + (devB?devB.name:'B') + ' Port ' + p + (sub!=null?'/'+(sub+1):'');
    if (!confirm(msg)){ pendingPort = null; clearSelectionOutlines(); return; }
    var ok = connectPorts(pendingPort, {deviceId:d.id, port:p, sub:sub});
    pendingPort = null;
    if (!ok){ alert('Could not connect.'); clearSelectionOutlines(); highlightLink(null); }
  });

  function buildHoverHTML() {
    var liveAlias = aliasFor(d.id, p, sub) || '—';
    var liveSpeed = (typeof speedFor === 'function' ? fmtSpeed(speedFor(d.id, p, sub)) : '') || '—';

    var vlanRaw  = (typeof vlanFor==='function' ? vlanFor(d.id, p, sub) : '');
    var vlanText = (vlanRaw === '' ? '—' : vlanRaw);

    var liveReserved = typeof isReservedPort === 'function' && isReservedPort(d.id, p, sub);
    var liveLink = linkForPort(d.id, p, sub);
    var status = liveReserved ? 'Reserved' : (liveLink ? 'Linked' : 'Free');

    var peerTxt = '—';
    if (liveReserved) {
      peerTxt = (typeof reservedLabelFor === 'function' && reservedLabelFor(d.id, p, sub)) || 'Reserved';
    } else if (liveLink) {
      var livePeer = getPeer(d.id, p, sub);
      var livePeerDev = livePeer ? deviceById(livePeer.deviceId) : null;
      if (livePeer && livePeerDev) {
        peerTxt = livePeerDev.name + ' • Port ' + livePeer.port +
                  (livePeer.sub != null ? '/' + (livePeer.sub + 1) : '');
      }
    }

    return (
      '<div class="hc-title">' + (d.name || 'Device') + '</div>' +
      '<div class="hc-row"><div class="hc-k">' + getPortTerm() + '</div><div>' +
        p + (sub != null ? '/' + (sub + 1) : '') + '</div></div>' +
      '<div class="hc-row"><div class="hc-k">Alias</div><div>' + liveAlias + '</div></div>' +
      '<div class="hc-row"><div class="hc-k">Peer</div><div>' + peerTxt + '</div></div>'+	
      '<div class="hc-row"><div class="hc-k">Status</div><div>' + status + '</div></div>' +
      '<div class="hc-row"><div class="hc-k">Link speed</div><div>' + liveSpeed + '</div></div>' +
      '<div class="hc-row"><div class="hc-k">VLAN</div><div>' + vlanText  + '</div></div>'
    );
  }

	node.addEventListener('mouseenter', function (e) {
	  if (__menuOpen || !node.classList.contains('selected')) return;
	  hcShowForTarget(node, buildHoverHTML(), e);
	});
	node.addEventListener('mousemove', function (e) {
	  if (__menuOpen || !node.classList.contains('selected')) return;
	  hcShowForTarget(node, buildHoverHTML(), e);
	});

  node.addEventListener('mouseleave', function () { hcHide(); });

  node.addEventListener('contextmenu', function(ev){
    openSpeedMenu(ev, d.id, p, sub);
  });

  return node;
}


  function renderPortCell(d, p){
    if (!d.dualLink) return createSubPort(d, p, null);
    var wrapCell = document.createElement('div');
    wrapCell.className = 'dual-cell';
    wrapCell.style.display = 'flex';
    wrapCell.style.flexDirection = 'column';
    wrapCell.style.border = '1px solid var(--line)';
    wrapCell.style.borderRadius = '10px';
    wrapCell.style.overflow = 'hidden';
    wrapCell.style.background = 'transparent';
    var top = createSubPort(d, p, 0);
    top.style.border = '0';
    top.style.borderRadius = '10px 10px 0 0';
    var bottom = createSubPort(d, p, 1);
    bottom.style.border = '0';
    bottom.style.borderTop = '1px solid var(--line)';
    bottom.style.borderRadius = '0 0 10px 10px';
    wrapCell.appendChild(top); wrapCell.appendChild(bottom);
    return wrapCell;
  }

	rows.forEach(function(count, rIndex){
	  var row = el('div',{class:'port-row'});
	  row.style.gridTemplateColumns = fullWidth ? 'repeat(12, var(--portW12))' : 'repeat(6, var(--portW6))';
	  row.style.gap = fullWidth ? 'var(--portGapFull)' : 'var(--portGapHalf)';
	  for (var c=0; c<count; c++){
		var p = seqByRow[rIndex][c];
		row.appendChild(renderPortCell(d, p));
	  }
	  portsContainer.appendChild(row);
	});

  var card = el('div',{class:'device', id:'dev-'+d.id}, head, meta, portsContainer);
  wrap.appendChild(card);
  return wrap;
}

/* ===================== CHANGE PORT COUNT ===================== */
/** Returns links on device d that would be removed when reducing to newCount ports (port numbers > newCount). */
function linksOnPortsBeingRemoved(d, newCount){
  if (newCount >= (d.ports || 1)) return [];
  return state.links.filter(function(L){
    var aRemoved = L.a.deviceId === d.id && L.a.port > newCount;
    var bRemoved = L.b.deviceId === d.id && L.b.port > newCount;
    return aRemoved || bRemoved;
  });
}

function changePorts(d, newCount){
  newCount = Math.max(1, Math.min(9999, Number(newCount)||1));
  if (newCount === d.ports) return;
  if (newCount < d.ports){
    state.links = state.links.filter(function(L){
      var aOk = !(L.a.deviceId===d.id && L.a.port>newCount);
      var bOk = !(L.b.deviceId===d.id && L.b.port>newCount);
      return aOk && bOk;
    });
    Object.keys(state.portAliases).forEach(function(k){
      var parts = k.split(':'); if(parts[0]===d.id && Number(parts[1])>newCount) delete state.portAliases[k];
    });
    Object.keys(state.reservedPorts).forEach(function(k){
      var parts = k.split(':'); if(parts[0]===d.id && Number(parts[1])>newCount) delete state.reservedPorts[k];
    });
  }
  d.ports = newCount;
}

/* ===================== CONNECTIONS TABLE ===================== */
function renderConnections() {
  var tb = $('#connBody');
  tb.innerHTML = '';

  var q = ($('#searchBox').value || '').toLowerCase().trim();
  var rows = [];

  state.links.forEach(function (L, i) {
    var da = deviceById(L.a.deviceId),
        db = deviceById(L.b.deviceId);

    var aName  = (da && da.name) || 'Unknown';
    var bName  = (db && db.name) || 'Unknown';
    var aAlias = aliasFor(L.a.deviceId, L.a.port, L.a.sub);
    var bAlias = aliasFor(L.b.deviceId, L.b.port, L.b.sub);

    // Use per-port custom name if present, otherwise fall back to the GLOBAL term ("Port/Interface/Custom")
    var aPortLabel =
      (da && da.portNames && da.portNames[keyFor(L.a.deviceId, L.a.port, L.a.sub)]) ||
      portLabelDefault(L.a.port, L.a.sub);

    var bPortLabel =
      (db && db.portNames && db.portNames[keyFor(L.b.deviceId, L.b.port, L.b.sub)]) ||
      portLabelDefault(L.b.port, L.b.sub);

    var parts = [
      aName,
      ...portSearchTokens(L.a.port),
      aPortLabel,
      bName,
      ...portSearchTokens(L.b.port),
      bPortLabel,
      aAlias,
      bAlias
    ];

    var text = parts.join(' ').toLowerCase();
    if (q && text.indexOf(q) === -1) return;

    var aColor = da ? (da.color || '#ccc') : '#ccc';
    var bColor = db ? (db.color || '#ccc') : '#ccc';

    var tr = el(
      'tr',
      { class: 'conn-row', dataset: { linkId: L.id } },
      el('td', {}, String(i + 1)),
      el(
        'td',
        { class: 'deviceA' },
        el('span', { class: 'devName', style: '--devColor:' + aColor, title: aName }, aName)
      ),
      el('td', {}, aPortLabel),
      el('td', {}, aAlias),
      el('td', {}, '⇄'),
      el(
        'td',
        { class: 'deviceB' },
        el('span', { class: 'devName', style: '--devColor:' + bColor, title: bName }, bName)
      ),
      el('td', {}, bPortLabel),
      el('td', {}, bAlias),
      el(
        'td',
        {},
        el('button', { class: 'btn-danger', onclick: function () { unlink(L.id); } }, 'Unlink')
      )
    );

    tr.addEventListener('click', function (e) {
      if (e.target.tagName.toLowerCase() === 'button') return;
      if (highlightedLinkId === L.id) {
        highlightLink(null);
        clearSelectionOutlines();
        return;
      }
      highlightLink(L.id);

      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;
      }

      clearSelectionOutlines();
      var portA = document.querySelector(sel(L.a));
      var portB = document.querySelector(sel(L.b));
      if (portA) outlineForSelection(portA);
      if (portB) outlineForSelection(portB);
    });

    tr.addEventListener('mouseenter', function (e) {
      if (!tr.classList.contains('highlight')) return;

      var html =
        '<div class="hc-title">Connection</div>' +
        '<div class="hc-row"><div class="hc-k">A</div><div>' +
          aName + ' • ' + aPortLabel + (aAlias ? ' • ' + aAlias : '') +
        '</div></div>' +
        '<div class="hc-row"><div class="hc-k">B</div><div>' +
          bName + ' • ' + bPortLabel + (bAlias ? ' • ' + bAlias : '') +
        '</div></div>';

      hcShowForTarget(tr, html, e);
    });

    tr.addEventListener('mousemove', function (e) {
      if (!tr.hasAttribute('data-link-id')) return;
      if (!tr.classList.contains('highlight')) return;
      hcShowForTarget(tr, __hoverEl && __hoverEl.innerHTML || '', e);
    });

    tr.addEventListener('mouseleave', hcHide);

    rows.push(tr);
  });

  // Reserved rows
  if (state.reservedPorts) {
    Object.keys(state.reservedPorts).forEach(function (k) {
      var parts = k.split(':');
      var devId = parts[0];
      var port  = Number(parts[1]);
      var sub   = (parts[2] === '' ? null : Number(parts[2]));
      var d     = deviceById(devId);
      if (!d) return;

      var rLabel = state.reservedPorts[k];
      var alias  = aliasFor(devId, port, sub);

      var reservedPortLabel =
        (d && d.portNames && d.portNames[keyFor(devId, port, sub)]) ||
        portLabelDefault(port, sub);

      var textParts = [
        (d && d.name) || 'Unknown',
        ...portSearchTokens(port),
        reservedPortLabel,
        alias || '',
        rLabel || '',
        (sub != null ? (sub === 0 ? 'top' : 'bottom') : '')
      ];

      var text = textParts.join(' ').toLowerCase();
      if (q && text.indexOf(q) === -1) return;

      var tr = el(
        'tr',
        {
          class: 'conn-row reserved-row',
          dataset: {
            deviceId: devId,
            port: String(port),
            sub: (sub == null ? '' : String(sub))
          }
        },
        el('td', {}, '—'),
        el(
          'td',
          { class: 'deviceA' },
          el(
            'span',
            { class: 'devName', style: '--devColor:' + (d.color || '#ccc'), title: d.name },
            d.name
          )
        ),
        el('td', {}, reservedPortLabel),
        el('td', {}, alias || ''),
        el('td', {}, '⟂'),
        el(
          'td',
          { class: 'deviceB' },
          el(
            'span',
            { class: 'devName', style: '--devColor:#666', title: 'Reserved' },
            'Reserved'
          )
        ),
        el('td', {}, '—'),
        el('td', {}, rLabel || ''),
        el(
          'td',
          {},
          el('button', {
              class: 'btn-danger',
              onclick: function () {
                delete state.reservedPorts[k];
                saveStore();
                render();
              }
            },
            'Clear'
          )
        )
      );

      tr.addEventListener('click', function (e) {
        if (e.target.tagName.toLowerCase() === 'button') return;
        highlightedLinkId = null;
        applyRowHighlight();
        clearSelectionOutlines();

        var sel =
          '.port[data-device-id="' + devId + '"][data-port="' + port + '"]' +
          (sub != null ? '[data-sub="' + sub + '"]' : '');

        var n = document.querySelector(sel);
        if (n) outlineForSelection(n);
      });

      rows.push(tr);
    });
  }

  if (!rows.length) {
    tb.appendChild(
      el(
        'tr',
        {},
        el('td', { colspan: '9', class: 'muted' }, 'No connections found.')
      )
    );
  } else {
    rows.forEach(function (r) { tb.appendChild(r); });
  }

  applyRowHighlight();
}

function applyRowHighlight(){ $all('.conn-row').forEach(function(r){ if(highlightedLinkId && r.dataset.linkId===highlightedLinkId) r.classList.add('highlight'); else r.classList.remove('highlight'); }); }
function highlightLink(linkId, opts){
  highlightedLinkId = linkId; applyRowHighlight(); clearSelectionOutlines();
  if (!linkId) return;
  var L = state.links.find(function(x){ return x.id===linkId; }); if (!L) return;
  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; }
  var portA = document.querySelector(sel(L.a));
  var portB = document.querySelector(sel(L.b));
  if (portA) outlineForSelection(portA);
  if (portB) outlineForSelection(portB);
  if (opts && opts.from){
    var origin = document.querySelector(sel(opts.from));
    if (origin){ outlineForSelection(origin); }
  }
}
function unlink(linkId){
  state.links = state.links.filter(function(L){ return L.id!==linkId; });
  if(highlightedLinkId===linkId) highlightedLinkId=null;
  saveStore(); render();
}

/* ------- Speed picker (context menu) ------- */
var __speedMenu = null;
var __menuOpen = false;

function closeSpeedMenu(){
  if(__speedMenu){
    __speedMenu.remove();
    __speedMenu = null;
  }
  __menuOpen = false;
  hcHide();
  clearSelectionOutlines();
}

function openSpeedMenu(e, deviceId, port, sub){
  closeSpeedMenu();
  e.preventDefault();

  __menuOpen = true;
  hcHide();

  clearSelectionOutlines();
  const portEl = document.querySelector(
    `.port[data-device-id="${deviceId}"][data-port="${port}"]${sub != null ? `[data-sub="${sub}"]` : ''}`
  );
  if (portEl) outlineForSelection(portEl);

  function defaultLabel(p, s){
    if (typeof portLabelDefault === 'function') return portLabelDefault(p, s);
    return 'Port ' + p + (s != null ? '/' + (s + 1) : '');
  }

  // Current link (if any) for this endpoint
  var link = (typeof getLinkForEndpoint === 'function')
    ? getLinkForEndpoint(deviceId, port, sub)
    : null;

  // Peer info (if linked)
  var peer = null;
  if (link) {
    var aSub = (link.a.sub == null ? null : link.a.sub);
    var bSub = (link.b.sub == null ? null : link.b.sub);
    var subN = (sub == null ? null : sub);

    if (link.a.deviceId === deviceId && link.a.port === port && aSub === subN) peer = link.b;
    else peer = link.a;
  }

  var curSpeed = speedFor(deviceId, port, sub) || '';
  var curVlan  = vlanFor(deviceId, port, sub);
  var curVlanStr = (curVlan === '' || curVlan == null) ? '' : String(curVlan);

  var peerDev = null;
  var peerPortLabel = '';
  if (peer) {
    peerDev = deviceById(peer.deviceId);
    peerPortLabel =
      (peerDev && peerDev.portNames && peerDev.portNames[keyFor(peer.deviceId, peer.port, peer.sub)]) ||
      defaultLabel(peer.port, peer.sub);
  }

  var div = document.createElement('div');
  div.className = 'speed-menu';

  div.innerHTML =
    '<div style="font-size:12px;margin-bottom:6px;font-weight:600">Port settings</div>' +

    (store.settings.enablePortRename ? (
      '<div style="display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px">' +
        '<label for="__nameInput" style="margin:0;white-space:nowrap;min-width:70px">Port name</label>' +
        '<input id="__nameInput" type="text" placeholder="e.g. Channel 1" ' +
               'style="flex:1;padding:4px 6px;font-size:12px;border-radius:6px;' +
                      'border:1px solid var(--line);background:var(--bg);color:var(--ink)">' +
        '<button id="__nameReset" type="button" title="Reset to default" ' +
               'style="padding:4px 6px;font-size:11px;border-radius:6px;border:1px solid var(--line);' +
                      'background:var(--bg);color:var(--ink);cursor:pointer;">↺</button>' +
      '</div>'
    ) : '') +

    '<div style="display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px">' +
      '<label for="__aliasInput" style="margin:0;white-space:nowrap;min-width:70px">Alias</label>' +
      '<input id="__aliasInput" type="text" placeholder="Alias (optional)" ' +
             'style="flex:1;padding:4px 6px;font-size:12px;border-radius:6px;' +
                    'border:1px solid var(--line);background:var(--bg);color:var(--ink)">' +
    '</div>' +

    '<div style="display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:6px">' +
      '<label for="__speedSelect" style="margin:0;white-space:nowrap;min-width:70px">Link speed</label>' +
      '<select id="__speedSelect" style="flex:1">' +
        '<option value="">(none)</option>' +
        '<option>100 Mbit</option><option>1 Gbit</option><option>2.5 Gbit</option>' +
        '<option>5 Gbit</option><option>10 Gbit</option><option>25 Gbit</option>' +
        '<option>40 Gbit</option><option>100 Gbit</option>' +
      '</select>' +
    '</div>' +

    '<div style="display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:8px">' +
      '<label for="__vlanInput" style="margin:0;white-space:nowrap;min-width:70px">VLAN</label>' +
      '<input id="__vlanInput" type="number" min="1" max="4094" step="1" placeholder="1–4094" ' +
             'style="flex:1;padding:4px 6px;font-size:12px;border-radius:6px;border:1px solid var(--line);' +
                    'background:var(--bg);color:var(--ink)">' +
    '</div>' +

    (peerDev ? (
      '<div style="display:flex;align-items:center;gap:6px;font-size:12px;margin-bottom:8px">' +
        '<label for="__linkedTo" style="margin:0;white-space:nowrap;min-width:70px">Linked To</label>' +
        '<input id="__linkedTo" type="text" readonly ' +
          'value="' + peerDev.name + ' – ' + peerPortLabel + '" ' +
          'style="padding:4px 6px;font-size:12px;border-radius:6px;border:1px solid var(--line);background:var(--bg);color:var(--ink);' +
                 'display:inline-block;white-space:nowrap;overflow:hidden;" />' +
      '</div>'
    ) : '') +

'<div style="display:flex;gap:6px;justify-content:space-between">' +

  (peerDev
    ? '<button id="__unlinkBtn" class="btn" type="button" ' +
        'style="background:#b91c1c;border-color:#b91c1c;color:#fff;font-weight:700">Unlink</button>'
    : '<div></div>'
  ) +

  '<div style="display:flex;gap:6px">' +
    '<button id="__speedCancel" class="btn" type="button">Cancel</button>' +
    '<button id="__speedSave"   class="btn" type="button" style="font-weight:700">Save</button>' +
  '</div>' +

'</div>';

  document.body.appendChild(div);
  __speedMenu = div;

  // Auto-fit "Linked to" width (your existing behaviour)
  (function() {
    const inp = div.querySelector('#__linkedTo');
    if (!inp) return;

    const measurer = document.createElement('span');
    measurer.style.cssText =
      'position:absolute;visibility:hidden;white-space:nowrap;' +
      'padding:4px 6px;font-size:12px;font-family:inherit;';
    measurer.textContent = inp.value;

    document.body.appendChild(measurer);

    const baseWidth = measurer.offsetWidth;
    const extra     = 16;
    const minWidth  = 160;

    inp.style.width = Math.max(minWidth, baseWidth + extra) + 'px';

    document.body.removeChild(measurer);
  })();

  div.addEventListener('mousedown', function(ev){ ev.stopPropagation(); }, { capture:true });

  // Port name input + reset behaviour
  var nin = div.querySelector('#__nameInput');
  if (store.settings.enablePortRename && nin) {
    const dev = deviceById(deviceId);
    const k = keyFor(deviceId, port, sub);
    const currentName =
      (dev && dev.portNames && dev.portNames[k]) ||
      defaultLabel(port, sub);

    nin.value = currentName;
  }

  const resetBtn = div.querySelector('#__nameReset');
  if (resetBtn && nin) {
    resetBtn.addEventListener('click', function(){
      // TRUE reset: delete stored override
      var d = deviceById(deviceId);
      if (d && d.portNames) {
        delete d.portNames[keyFor(deviceId, port, sub)];
        if (Object.keys(d.portNames).length === 0) delete d.portNames;
        saveStore();
      }
      nin.value = defaultLabel(port, sub);
      render();
    });
  }

  var ain = div.querySelector('#__aliasInput');
  var sel = div.querySelector('#__speedSelect');
  var vin = div.querySelector('#__vlanInput');

  ain.value = aliasFor(deviceId, port, sub) || '';
  sel.value = curSpeed || '';
  vin.value = curVlanStr;

  // Hook up Unlink
  var unlinkBtn = div.querySelector('#__unlinkBtn');
  if (unlinkBtn && link && peerDev) {
    unlinkBtn.addEventListener('click', function(){
      var thisDev = deviceById(deviceId);
      var thisName = thisDev ? thisDev.name : 'Unknown';
      var thisPortLabel =
        (thisDev && thisDev.portNames && thisDev.portNames[keyFor(deviceId, port, sub)]) ||
        defaultLabel(port, sub);

      var peerName = peerDev ? peerDev.name : 'Unknown';

      var msg =
        'Unlink connection?\n\n' +
        thisName + ' — ' + thisPortLabel + '\n' +
        '↔\n' +
        peerName + ' — ' + peerPortLabel;

      if (!confirm(msg)) return;

      unlink(link.id);
      closeSpeedMenu();
      render();
    });
  }

  var x = e.clientX, y = e.clientY;
  var vw = window.innerWidth, vh = window.innerHeight;
  var rw = 260, rh = 150;
  if (x + rw + 8 > vw) x = vw - rw - 8;
  if (y + rh + 8 > vh) y = vh - rh - 8;
  div.style.left = x + 'px';
  div.style.top  = y + 'px';

  function doSave(){
    // Port rename (store ONLY real overrides)
    if (store.settings.enablePortRename && nin) {
      var dev = deviceById(deviceId);
      if (dev) {
        var k = keyFor(deviceId, port, sub);
        var val = (nin.value || '').trim();
        var def = defaultLabel(port, sub);

        if (!val || val === def) {
          if (dev.portNames) {
            delete dev.portNames[k];
            if (Object.keys(dev.portNames).length === 0) delete dev.portNames;
          }
        } else {
          dev.portNames = dev.portNames || {};
          dev.portNames[k] = val;
        }
      }
    }

    // Alias
    var aliasRaw = ain.value.trim();
    var aliasKey = keyFor(deviceId, port, sub);
    if (!aliasRaw) delete state.portAliases[aliasKey];
    else state.portAliases[aliasKey] = aliasRaw;

    // Speed + VLAN
    var speedVal = sel.value || '';
    var vlanRaw  = (vin.value || '').trim();
    var vlanVal  = vlanRaw === '' ? '' : Math.max(1, Math.min(4094, Number(vlanRaw) || 0));

    setSpeedFor(deviceId, port, sub, speedVal);
    setVlanFor(deviceId, port, sub, vlanVal);

    saveStore();
    render();
    closeSpeedMenu();
  }

  div.querySelector('#__speedSave').addEventListener('click', doSave);
  div.querySelector('#__speedCancel').addEventListener('click', closeSpeedMenu);

  vin.addEventListener('keydown', function(ev){
    if (ev.key === 'Enter') doSave();
    if (ev.key === 'Escape') closeSpeedMenu();
  });

  setTimeout(function(){
    function onDoc(e2){
      if (__speedMenu && !__speedMenu.contains(e2.target)) closeSpeedMenu();
    }
    function onEsc(e2){ if (e2.key === 'Escape') closeSpeedMenu(); }
    document.addEventListener('mousedown', onDoc, { once:true, capture:true });
    document.addEventListener('keydown', onEsc, { once:true });
    window.addEventListener('wheel', closeSpeedMenu, { once:true, passive:true });
  }, 0);
}

/* ===================== PRINT ===================== */
function openPrintSheet(includeTable){
  var devicesHTML = document.getElementById('devRows').innerHTML;
  var tableEl = document.getElementById('connTable');
  var tableHTML = (includeTable && tableEl) ? tableEl.outerHTML : '';
  var when = new Date().toLocaleString();

  var css = ''
+ '@page{size:A4 portrait;margin:12mm}\n'
+ '@page:first{size:A4 landscape;margin:12mm}\n'
+ '*{box-sizing:border-box}\n'
+ '@media print{*{-webkit-print-color-adjust:exact;print-color-adjust:exact}}\n'
+ '.device,.port,.dual-cell,.swatch,header{ -webkit-print-color-adjust:exact; print-color-adjust:exact }\n'
+ '.page{break-inside:avoid;page-break-inside:avoid}\n'
+ '.page + .page{break-before:page;page-break-before:always}\n'
+ ':root{--ink:#111;--line:#ddd;--prtPortH:75px;--prtGap:0px}\n'
+ '.port{height:var(--prtPortH)!important;box-sizing:border-box;overflow:hidden;display:block}\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'
+ '.dual-cell .port{height:var(--prtPortH)!important;border:0!important;border-radius:0!important}\n'
+ '.dual-cell .port:first-child{border-bottom:1px solid #333!important}\n'

  + '*{box-sizing:border-box}\n'
  + 'body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;color:var(--ink);background:#fff;margin:0}\n'
  + '.page{max-width:calc(297mm - 16mm);margin:10mm auto}\n'
  + 'header{display:flex;align-items:baseline;justify-content:space-between;margin-bottom:12px}\n'
  + 'h1{font-size:18px;margin:0}\n'
  + '.meta{font-size:12px;color:#555}\n'
  + '.dev-rows{display:flex;flex-direction:column;gap:12px}\n'
  + '.dev-row{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}\n'
  + '.device-wrap{width:100%}\n'
  + '.device-wrap.full{grid-column:1 / -1}\n'
  + '.device{background:#fff;border:1px solid var(--line);border-radius:10px;padding:10px;overflow:hidden}\n'
  + '.device-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}\n'
  + '.device-title{font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}\n'
  + '.device-actions,.inline-controls{display:none!important}\n'
  + '.swatch{width:12px;height:12px;border-radius:3px;border:1px solid #0003;display:inline-block}\n'
  + '.ports-rows{display:flex;flex-direction:column;gap:8px;margin-top:10px;overflow:hidden}\n'
  + '.port-row{display:grid;justify-content:start;align-content:start}\n'
  + '.device-wrap.full .port-row{grid-template-columns:repeat(12,minmax(40px,1fr));gap:10px !important;}\n'
  + '.device-wrap:not(.full) .port-row{grid-template-columns:repeat(6,minmax(40px,1fr));gap:7px !important;}\n'
  /* --------------------------------------------------------------------------- */
  + '.port{border:1px solid #333;border-radius:8px;padding:6px 3px 4px;text-align:center;grid-column:auto!important;width:auto!important}\n'
  + '.port .num{font-size:12px;font-weight:600}\n'
  + '.port .alias{font-size:11px;margin-top:2px;min-height:1.1em}\n'
  + '.port .peer{font-size:12px;font-weight:700;margin-top:4px;min-height:1.2em}\n'
  + '.port:not(.connected):not(.reserved){background:#fff !important;border-color:#444 !important}\n'
  + '.port:not(.connected):not(.reserved) .num,'
  + '.port:not(.connected):not(.reserved) .alias,'
  + '.port:not(.connected):not(.reserved) .peer{color:#000 !important}\n'
  + '.port.connected{color:#000}\n'
  + '.port.reserved{background:#555 !important;color:#fff !important;border-color:#333 !important}\n'
  + '.dual-cell{border-color:#333 !important}\n'
  + '.port.reserved .num,.port.reserved .alias,.port.reserved .peer{color:#fff !important}\n'
  + 'table{width:100%;border-collapse:collapse;margin-top:16px}\n'
  + 'th,td{border:1px solid var(--line);padding:6px 8px;font-size:12px;text-align:left}\n'
  + 'th{background:#f6f7f9;font-weight:700}\n'
  + 'th:last-child, td:last-child{display:none}\n'
  + '@media print{.controls{display:none};}\n';


  var html = ''
  + '<!doctype html><html><head><meta charset="utf-8">'
  + '<title>Ethernet Cable Connection Manager – Print</title><style>' + css + '</style></head><body>'
  + '<div class="page">'
  + '<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>' 
  + '<section id="printDevices" class="dev-rows">' + devicesHTML + '</section>'
  + (tableHTML ? '<div class="page"><h2 style="font-size:16px;margin:18px 0 8px">Connections</h2>' + tableHTML + '</div>' : '')
  + '<div class="controls" style="margin-top:12px"><button onclick="window.print()">Print</button></div>'
  + '</div>'
  + '<script>(function(){'
  + '  var GAP_FULL=9, GAP_HALF=7, MIN_TRACK=40;'
  + '  function sizeRows(){'
  + '    var rows=document.querySelectorAll(".port-row,[data-port-row]");'
  + '    for(var i=0;i<rows.length;i++){'
  + '      var row=rows[i];'
  + '      var wrap=row.closest(".device-wrap");'
  + '      row.style.display = "grid";'
  + '      row.style.justifyContent = "start";'
  + '      row.style.alignContent = "start";'
  + '      row.style.gridAutoFlow = "row";'
  + '      var isFull = wrap && wrap.classList.contains("full");'
  + '      var cols   = isFull ? 12 : 6;'
  + '      var gap    = isFull ? GAP_FULL : GAP_HALF;'
  + '      var inner = row.getBoundingClientRect().width;'
  + '      if(inner && inner > 0){'
  + '        var track = Math.floor((inner - gap * (cols - 1)) / cols);'
  + '        if (!(track > 0)) track = 60;'
  + '        if (track < MIN_TRACK) track = MIN_TRACK;'
  + '		 track += -3;'
  + '        row.style.gridTemplateColumns = "repeat(" + cols + ", " + track + "px)";'
  + '      }'
  + '      row.style.gap = gap + "px";'
  + '    }'
  + '  }'
  + '  requestAnimationFrame(function(){ requestAnimationFrame(sizeRows); });'
  + '  Array.prototype.forEach.call(document.querySelectorAll(".port"),function(p){'
  + '    if(!p.classList.contains("connected") && !p.classList.contains("reserved")){'
  + '      p.style.background=""; p.style.color="";'
  + '      p.querySelectorAll(".num,.alias,.peer").forEach(function(el){ el.style.color=""; });'
  + '    }'
  + '  });'
  + '  Array.prototype.forEach.call(document.querySelectorAll("[draggable]"),function(el){el.removeAttribute("draggable");});'
  + '})();<\/script>'
  + '</body></html>';

  var win = window.open('', '_blank');
  win.document.open();
  win.document.write(html);
  win.document.close();
  
  win.onload = function() {
  win.focus();
  setTimeout(function() {
    win.print();
    win.close();
  }, 30); 
};
}



/* ===================== ORCHESTRATION ===================== */
function render(){ renderDevices(); applyPeerScrolling(); renderConnections(); }

/* ===================== PALETTE ===================== */
(function(){
  const palette = [
  '#FFCDD2','#C8E6C9','#BBDEFB','#F5F5F5',
  '#F44336','#4CAF50','#2196F3','#E0E0E0',
  '#FF0000','#00FF00','#0000FF','#BDBDBD',
  '#FF6F00','#FFFF00','#BF00FF','#9E9E9E',
  '#FF9800','#FFEB3B','#9C27B0','#757575',
  '#FFB74D','#FFF176','#BA68C8','#616161'
]

   const modal   = document.getElementById('paletteModal');
  const grid    = document.getElementById('paletteGrid');
  const openBtn = document.getElementById('openPalette');
  const closeBtn= document.getElementById('paletteClose');
  const previewSidebar = document.getElementById('devColorPreview');
  let chosenColor = '#E74C3C';

  function open(){ modal.style.display='flex'; }
  function close(){ modal.style.display='none'; }
  function updatePreview(){ previewSidebar.style.background = chosenColor; }

  /* ---------- RGB / HSV conversion helpers ---------- */
  function rgbToHex(r,g,b){
    return '#' + [r,g,b].map(x=>x.toString(16).padStart(2,'0')).join('').toUpperCase();
  }
  function hexToRgb(hex){
    const n = parseInt(hex.replace('#',''),16);
    return {r:(n>>16)&255, g:(n>>8)&255, b:n&255};
  }
  function rgbToHsv(r, g, b) {
    r/=255; g/=255; b/=255;
    const max = Math.max(r,g,b), min = Math.min(r,g,b);
    const d = max-min;
    let h,s,v = max;
    s = max===0 ? 0 : d/max;
    if(max===min) h=0;
    else {
      switch(max){
        case r: h=(g-b)/d + (g<b?6:0); break;
        case g: h=(b-r)/d + 2; break;
        case b: h=(r-g)/d + 4; break;
      }
      h /= 6;
    }
    return {h:h*360, s:s*100, v:v*100};
  }
  function hsvToRgb(h, s, v){
    h/=360; s/=100; v/=100;
    const i = Math.floor(h*6);
    const f = h*6 - i;
    const p = v*(1-s);
    const q = v*(1-f*s);
    const t = v*(1-(1-f)*s);
    let r,g,b;
    switch(i%6){
      case 0: r=v; g=t; b=p; break;
      case 1: r=q; g=v; b=p; break;
      case 2: r=p; g=v; b=t; break;
      case 3: r=p; g=q; b=v; break;
      case 4: r=t; g=p; b=v; break;
      case 5: r=v; g=p; b=q; break;
    }
    return {r:Math.round(r*255), g:Math.round(g*255), b:Math.round(b*255)};
  }

  /* ---------- Build palette grid ---------- */
  grid.innerHTML = '';
  palette.forEach(hex=>{
    const chip = document.createElement('button');
    chip.className='chip';
    chip.style.background=hex;
    chip.title=hex;
    chip.addEventListener('click',()=>{
      chosenColor=hex;
      updateFromHex(hex);
      updatePreview();
    });
    grid.appendChild(chip);
  });

  /* ---------- Add custom sliders ---------- */
const customHTML = `
  <div id="customColorPicker"
       style="display:grid;
              grid-template-columns:repeat(5,1fr);
              grid-template-rows:auto auto auto;
              gap:12px;
              align-items:center;
              justify-items:center;
              margin-left:12px;
              margin-top:6px;">

    <!-- Headers -->
    <div style="font-size:12px;color:var(--muted)">Hue</div>
    <div style="font-size:12px;color:var(--muted)">Sat</div>
    <div style="font-size:12px;color:var(--muted)">R</div>
    <div style="font-size:12px;color:var(--muted)">G</div>
    <div style="font-size:12px;color:var(--muted)">B</div>

    <!-- Sliders -->
<div id="hueWrap"
     style="position:relative;height:120px;width:16px;display:flex;align-items:center;justify-content:center;">
  <!-- static hue gradient -->
  <div id="hueBar"
       style="position:absolute;inset:0;
              background:linear-gradient(to top, red, yellow, lime, cyan, blue, magenta, red);
              border-radius:6px;filter:brightness(0.9);">
  </div>
  <!-- moving indicator -->
  <div id="hueMarker"
       style="position:absolute;left:0;right:0;height:2px;background:white;
              border-radius:1px;box-shadow:0 0 4px rgba(0,0,0,0.8);pointer-events:none;">
  </div>
  <!-- functional slider -->
  <input type="range" id="hueSlider" min="0" max="360"
         style="position:relative;z-index:5;height:120px;width:16px;
                appearance:slider-vertical;writing-mode:bt-lr;
                opacity:0;">
</div>

    <input type="range" id="satSlider" min="0" max="100"
           style="height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;">
    <input type="range" id="rSlider" min="0" max="255"
           style="height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;">
    <input type="range" id="gSlider" min="0" max="255"
           style="height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;">
    <input type="range" id="bSlider" min="0" max="255"
           style="height:120px;width:10px;appearance:slider-vertical;writing-mode:bt-lr;">

<!-- Preview -->
<div id="colorPreviewBox"
     style="grid-column:1 / span 5;
            width:36px;height:36px;
            border-radius:8px;
            border:1px solid #333;
            box-shadow:0 0 8px rgba(0,0,0,0.25);
            margin-top:10px;"></div>

<!-- Hex field (editable) -->
<input type="text" id="hexOutput"
       placeholder="#RRGGBB"
       style="grid-column:1 / span 5;
              width:110px;
              text-align:center;
              font-size:13px;
              background:#0f141d;
              border:1px solid var(--line);
              border-radius:6px;
              color:var(--ink);
              padding:5px;
              margin-top:6px;">

  </div>`;


  grid.insertAdjacentHTML('afterend', customHTML);

  /* ---------- DOM refs ---------- */
  const hSlider=document.getElementById('hueSlider');
  const sSlider=document.getElementById('satSlider');
  const rSlider=document.getElementById('rSlider');
  const gSlider=document.getElementById('gSlider');
  const bSlider=document.getElementById('bSlider');
  const colorBox=document.getElementById('colorPreviewBox');
  const hexOut=document.getElementById('hexOutput');

  /* ---------- Core update logic ---------- */
  function updatePreviewBox(hex){
    colorBox.style.background=hex;
    hexOut.value=hex.toUpperCase();
    chosenColor=hex;
    updatePreview();
  }
  
  function updateHueMarker() {
  const hue = +hSlider.value || 0;
  const marker = document.getElementById('hueMarker');
  if (!marker) return;
  const bar = document.getElementById('hueWrap');
  const height = bar ? bar.clientHeight : 120;
  const pos = height - (hue / 360) * height; // invert so 0°=bottom, 360°=top
  marker.style.top = `${pos - 1}px`;
}


  function updateFromRGB(){
    const r=+rSlider.value, g=+gSlider.value, b=+bSlider.value;
    const hex=rgbToHex(r,g,b);
    const {h,s}=rgbToHsv(r,g,b);
    hSlider.value=Math.round(h);
    sSlider.value=Math.round(s);
    updatePreviewBox(hex);
	updateHueMarker();
  }

  function updateFromHSV(){
    const h=+hSlider.value, s=+sSlider.value;
    const {r,g,b}=hsvToRgb(h,s,100);
    rSlider.value=r; gSlider.value=g; bSlider.value=b;
    const hex=rgbToHex(r,g,b);
    updatePreviewBox(hex);
	updateHueMarker();
  }

  function updateFromHex(hex){
    const {r,g,b}=hexToRgb(hex);
    rSlider.value=r; gSlider.value=g; bSlider.value=b;
    const {h,s}=rgbToHsv(r,g,b);
    hSlider.value=Math.round(h);
    sSlider.value=Math.round(s);
    updatePreviewBox(hex);
	updateHueMarker();
  }

  /* ---------- Events ---------- */
  [rSlider,gSlider,bSlider].forEach(sl=>sl.addEventListener('input',updateFromRGB));
  [hSlider,sSlider].forEach(sl=>sl.addEventListener('input',updateFromHSV));
	hexOut.addEventListener('input', e => {
	  const v = e.target.value.trim();
	  // allow partial input like "#ff" without breaking live update
	  if (/^#?[0-9A-Fa-f]{0,6}$/.test(v)) {
		e.target.style.borderColor = 'var(--line)';
	  } else {
		e.target.style.borderColor = '#d33'; // red outline if invalid
		return;
	  }
	  if (/^#?[0-9A-Fa-f]{6}$/.test(v)) {
		const hex = v.startsWith('#') ? v.toUpperCase() : '#' + v.toUpperCase();
		updateFromHex(hex);
	  }
	});


  /* ---------- Modal + Add device ---------- */
  openBtn.addEventListener('click',open);
  closeBtn.addEventListener('click',close);

  document.getElementById('addBtn').addEventListener('click',function(){
    const name=document.getElementById('devName').value.trim();
    const ports=Math.max(1,Math.min(9999,Number(document.getElementById('devPorts').value)||1));
    if(!name){alert('Please enter a device name.');return;}
    state.devices.push({
      id:uid(),name,ports,color:chosenColor,
      forceFullRow:false,midWrapMode:'balanced',smallWrap:false,dualLink:false,
      numbering:'row'
    });
    document.getElementById('devName').value='';
    saveStore();render();
  });

  updateFromHex(chosenColor);
  updateHueMarker();
})();


/* ===================== LAYOUT MODAL ===================== */
function openLayoutModal(deviceId){
  var d = deviceById(deviceId); if (!d) return;
  var backdrop = $('#layoutModal');
  var nameEl = $('#layoutDeviceName');
  var selFull = $('#layoutFullRow');
  var selMid = $('#layoutMidWrap');
  var selSmall = $('#layoutSmallWrap');
  var selDual = $('#layoutDualLink');
  var rowMid = $('#optMidWrap');
  var rowSmall = $('#optSmallWrap');
  var selNumbering = $('#layoutNumbering');


  nameEl.textContent = d.name + ' ('+d.ports+' ports)';
  selFull.value = d.forceFullRow ? 'full' : 'auto';
  selMid.value = (d.midWrapMode === 'twelve') ? 'twelve' : 'balanced';
  selSmall.value = d.smallWrap ? 'split' : 'single';
  selDual.value = d.dualLink ? 'on' : 'off';
  selNumbering.value = (d.numbering === 'column' || d.numbering === 'column-bt') ? d.numbering : 'row';

  rowMid.style.display   = (d.ports>=13 && d.ports<=24) ? 'flex' : 'none';
  rowSmall.style.display = (d.ports>=7  && d.ports<=12) ? 'flex' : 'none';

  $('#layoutCancel').onclick = function(){ backdrop.style.display='none'; };
  $('#layoutSave').onclick = function(){
    d.forceFullRow = (selFull.value === 'full');
    if (d.ports>=13 && d.ports<=24) d.midWrapMode = (selMid.value === 'twelve') ? 'twelve' : 'balanced';
    if (d.ports>=7  && d.ports<=12) d.smallWrap   = (selSmall.value === 'split');
    d.dualLink = (selDual.value === 'on');
	d.numbering = (selNumbering.value === 'column' || selNumbering.value === 'column-bt') ? selNumbering.value : 'row';
    saveStore(); backdrop.style.display='none'; render();
  };
  /* --- allow Escape key & outside click to close Layout modal --- */
(function wireLayoutModalClose() {
  const modal = document.getElementById('layoutModal');
  if (!modal) return;

  // Close on Escape
  document.addEventListener('keydown', function (e) {
    if (modal.style.display === 'flex' && e.key === 'Escape') {
      modal.style.display = 'none';
    }
  });

  // Close when clicking backdrop (outside the inner .modal)
  modal.addEventListener('click', function (e) {
    if (e.target === modal) {
      modal.style.display = 'none';
    }
  });
})();

  backdrop.style.display = 'flex';
}

/* ===================== EDIT DEVICE MODAL ===================== */
let currentEditDevice = null;
let editChosenColor = '#888';

function openEditDeviceModal(deviceId) {
  const d = deviceById(deviceId);
  if (!d) return;

  currentEditDevice = d;
  const modal = document.getElementById('editDeviceModal');
  const nameInput = document.getElementById('editDevName');
  const portsInput = document.getElementById('editDevPorts');
  const preview = document.getElementById('editDevColorPreview');

  nameInput.value = d.name || '';
  portsInput.value = d.ports || 1;
  editChosenColor = d.color || '#888';
  preview.style.background = editChosenColor;
	const speedOptions = [
	  '', '100 Mbit', '1 Gbit', '2.5 Gbit', '5 Gbit',
	  '10 Gbit', '25 Gbit', '40 Gbit', '100 Gbit'
	];

	let maxSpeedRow = document.getElementById('editDevMaxSpeedRow');
	if (!maxSpeedRow) {
	  maxSpeedRow = document.createElement('div');
	  maxSpeedRow.className = 'row';
	  maxSpeedRow.id = 'editDevMaxSpeedRow';
	  maxSpeedRow.innerHTML =
		'<label style="min-width:100px">Max speed</label>' +
		'<select id="editDevMaxSpeed"></select>';
	  modal.querySelector('.modal').insertBefore(
		maxSpeedRow,
		modal.querySelector('.actions')
	  );
	}

	const speedSel = document.getElementById('editDevMaxSpeed');
	speedSel.innerHTML = speedOptions
	  .map(s => `<option value="${s}">${s || '(none)'}</option>`)
	  .join('');
	speedSel.value = d.maxSpeed || '';

  modal.style.display = 'flex';
}

function closeEditDeviceModal() {
  document.getElementById('editDeviceModal').style.display = 'none';
  currentEditDevice = null;
}

/* --- use main palette modal for Edit Device colour selection --- */
(function setupEditColorPicker() {
  const paletteModal = document.getElementById('paletteModal');
  const openBtn = document.getElementById('editOpenPalette');
  const preview = document.getElementById('editDevColorPreview');
  const paletteGrid = document.getElementById('paletteGrid');
  const closeBtn = document.getElementById('paletteClose');
  let tempTarget = null;

  // open shared palette modal but record the target (edit or add)
  openBtn.addEventListener('click', function () {
    tempTarget = 'edit';
    paletteModal.style.display = 'flex';
  });

  // intercept clicks in palette grid to update the correct target
  paletteGrid.querySelectorAll('.chip').forEach(chip => {
    chip.addEventListener('click', function () {
      const hex = chip.title || chip.style.background;
      if (tempTarget === 'edit') {
        editChosenColor = hex;
        preview.style.background = hex;
      } else {
        // fallback for add device
        chosenColor = hex;
        document.getElementById('devColorPreview').style.background = hex;
      }
      paletteModal.style.display = 'none';
    });
  });

  // close palette normally
  closeBtn.addEventListener('click', function () {
    paletteModal.style.display = 'none';
    tempTarget = null;
  });
})();


/* --- modal buttons --- */
document.getElementById('editDevCancel').addEventListener('click', closeEditDeviceModal);
document.getElementById('editDevSave').addEventListener('click', function() {
  if (!currentEditDevice) return;
  const name = document.getElementById('editDevName').value.trim();
  const ports = Math.max(1, Math.min(9999, Number(document.getElementById('editDevPorts').value) || 1));
  currentEditDevice.name = name || currentEditDevice.name;
  if (ports < (currentEditDevice.ports || 1)) {
    var affected = linksOnPortsBeingRemoved(currentEditDevice, ports);
    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?')) {
      // user cancelled – do not change port count
    } else {
      changePorts(currentEditDevice, ports);
    }
  } else {
    changePorts(currentEditDevice, ports);
  }
  currentEditDevice.color = editChosenColor;
  const speedSel = document.getElementById('editDevMaxSpeed');
  currentEditDevice.maxSpeed = speedSel ? speedSel.value || null : null;
  recalcLinkSpeedsForDevice(currentEditDevice.id);
  saveStore(); render();
  closeEditDeviceModal();
});
/* --- allow Escape key & outside click to close --- */
(function wireEditModalClose() {
  const modal = document.getElementById('editDeviceModal');
  if (!modal) return;

  // Close on Escape
  document.addEventListener('keydown', function (e) {
    if (modal.style.display === 'flex' && e.key === 'Escape') {
      closeEditDeviceModal();
    }
  });

  // Close when clicking outside the modal box
  modal.addEventListener('click', function (e) {
    if (e.target === modal) {
      closeEditDeviceModal();
    }
  });
})();

/* ===================== PROFILES UI ===================== */
function refreshProfileSelect(){
  var sel = document.getElementById('profileSelect');
  sel.innerHTML = '';
  Object.keys(store.profiles).forEach(function(name){
    var opt = document.createElement('option');
    opt.value = name; opt.textContent = name;
    if (name === store.current) opt.selected = true;
    sel.appendChild(opt);
  });
  sel.value = store.current;
}
function switchProfile(name){
  if (!store.profiles[name]) return;
  store.current = name;
  state = store.profiles[name];
  normalizeState(state);
  saveStore();
  refreshProfileSelect();
  render();
}
document.getElementById('profileSelect').addEventListener('change', function(){ switchProfile(this.value); });

document.getElementById('newProfileBtn').addEventListener('click', function(){
  var name = prompt('New profile name:', 'Customer '+(Object.keys(store.profiles).length+1));
  if(!name) return; name = name.trim(); if(!name) return;
  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }
  store.profiles[name] = deepClone(defaultState); saveStore();
  refreshProfileSelect(); switchProfile(name);
});

document.getElementById('renameProfileBtn').addEventListener('click', function(){
  var current = store.current;
  var name = prompt('Rename profile "'+current+'" to:', current);
  if(!name || !name.trim()) return; name = name.trim();
  if(name === current) return;
  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }
  store.profiles[name] = state; delete store.profiles[current];
  store.current = name; saveStore(); refreshProfileSelect(); render();
});

document.getElementById('duplicateProfileBtn').addEventListener('click', function(){
  var base = store.current;
  var name = prompt('Duplicate profile as:', base+' (copy)');
  if(!name || !name.trim()) return; name = name.trim();
  if(store.profiles[name]){ alert('A profile with that name already exists.'); return; }
  store.profiles[name] = deepClone(state); saveStore();
  refreshProfileSelect(); switchProfile(name);
});

document.getElementById('deleteProfileBtn').addEventListener('click', function(){
  var names = Object.keys(store.profiles);
  if(names.length<=1){ alert('You must keep at least one profile.'); return; }
  var current = store.current;
  if(!confirm('Delete profile "'+current+'"? This cannot be undone.')) return;
  delete store.profiles[current];
  var next = Object.keys(store.profiles)[0];
  store.current = next; state = store.profiles[next];
  saveStore(); refreshProfileSelect(); render();
});

/* ===================== EXPORT / IMPORT PROFILE (full-fidelity) ===================== */

/* Export profile (exports EVERYTHING in state, with versioning) */
document.getElementById('exportProfileBtn').addEventListener('click', function(){
  // Full-fidelity export (supports all new fields + future ones)
  var data = {
    schema: 'eccm-profile',
    schemaVersion: 2,
    appVersion: '1.0.5',
    profileName: store.current,
    state: deepClone(state),
    exportedAt: new Date().toISOString()
  };

  var blob = new Blob([JSON.stringify(data, null, 2)], { type:'application/json' });
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = url;
  a.download = 'ethernet-profile-' + store.current.replace(/[^a-z0-9-_]+/gi,'_') + '.json';
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
});


/* Import profile (accepts both new schema + legacy exports) */
document.getElementById('importProfileBtn').addEventListener('click', function(){
  document.getElementById('importProfileFile').click();
});

document.getElementById('importProfileFile').addEventListener('change', function(e){
  var file = e.target.files && e.target.files[0];
  if(!file) return;

  var reader = new FileReader();

  reader.onload = function(){
    try{
      var parsed = JSON.parse(reader.result);

      // ---------- 1) Determine incoming state (new schema or legacy) ----------
      var incomingState = null;

      // New schema: { schema, schemaVersion, profileName, state:{...} }
      if (parsed && parsed.state && typeof parsed.state === 'object') {
        incomingState = parsed.state;
      } else {
        // Legacy schema: { devices, links, portAliases, reservedPorts, ... }
        incomingState = {
          devices: parsed.devices,
          links: parsed.links,
          portAliases: parsed.portAliases,
          reservedPorts: parsed.reservedPorts,
          portSpeeds: parsed.portSpeeds,
          portVlans: parsed.portVlans,
          portLinkedToNames: parsed.portLinkedToNames
        };
      }

      // Basic validation
      if(!incomingState || !Array.isArray(incomingState.devices) || !Array.isArray(incomingState.links)){
        throw new Error('Invalid schema (missing devices/links).');
      }

      // ---------- 2) Normalise + clamp ----------
      normalizeState(incomingState);

      // Respect current app setting (if available) for max ports
      var maxPorts = (typeof getMaxPortsSetting === 'function') ? getMaxPortsSetting() : 512;

      incomingState.devices = incomingState.devices.map(function(d){
        // Keep all fields we know + preserve any extras by copying d wholesale
        var out = Object.assign({}, d);

        out.id = d.id || uid();
        out.name = String(d.name || 'Unnamed');
        out.color = d.color || '#888';

        out.ports = Math.max(1, Math.min(maxPorts, Number(d.ports) || 1));

        // Layout fields
        out.forceFullRow = !!d.forceFullRow;
        out.midWrapMode  = (d.midWrapMode === 'twelve') ? 'twelve' : 'balanced';
        out.smallWrap    = !!d.smallWrap;
        out.dualLink     = !!d.dualLink;
        out.numbering    = (d.numbering === 'column') ? 'column' : 'row';

        // Per-device fields
        out.maxSpeed = (d.maxSpeed == null || d.maxSpeed === '') ? null : String(d.maxSpeed);
        out.portNames = (d.portNames && typeof d.portNames === 'object') ? d.portNames : {};

        return out;
      });

      // Rebuild id set for link filtering
      var idSet = Object.create(null);
      incomingState.devices.forEach(function(d){ idSet[String(d.id)] = true; });

      incomingState.links = (incomingState.links || []).map(function(L){
        return {
          id: L.id || uid(),
          a: {
            deviceId: String(L.a && L.a.deviceId),
            port: Number(L.a && L.a.port),
            sub: (L.a && L.a.sub == null) ? null : Number(L.a.sub)
          },
          b: {
            deviceId: String(L.b && L.b.deviceId),
            port: Number(L.b && L.b.port),
            sub: (L.b && L.b.sub == null) ? null : Number(L.b.sub)
          }
        };
      }).filter(function(L){
        // Must reference known devices + valid port numbers
        return (
          idSet[L.a.deviceId] && idSet[L.b.deviceId] &&
          L.a.port >= 1 && L.b.port >= 1
        );
      });

      // Ensure maps exist (import could be missing them)
      incomingState.portAliases = incomingState.portAliases || {};
      incomingState.reservedPorts = incomingState.reservedPorts || {};
      incomingState.portSpeeds = incomingState.portSpeeds || {};
      incomingState.portVlans  = incomingState.portVlans  || {};
      incomingState.portLinkedToNames = incomingState.portLinkedToNames || {};

      // ---------- 3) Save under user-chosen profile name ----------
      var suggested =
        (parsed.profileName || '').toString().trim() ||
        ('Imported ' + new Date().toLocaleString());

      var name = prompt('Name for imported profile:', suggested);
      if(!name || !name.trim()) return;
      name = name.trim();

      if(store.profiles[name]){
        alert('A profile with that name already exists.');
        return;
      }

      store.profiles[name] = incomingState;

      saveStore();
      refreshProfileSelect();
      switchProfile(name);

    }catch(err){
      alert('Import failed: ' + err.message);
    }finally{
      e.target.value = '';
    }
  };

  reader.readAsText(file);
});

/* ===================== BACKUP / RESTORE (all profiles) ===================== */
document.getElementById('backupAllBtn').addEventListener('click', function(){
  // Full-store backup (all profiles + settings + current profile)
  var payload = {
    schema: 'eccm-backup',
    schemaVersion: 2,
    appVersion: '1.0.5',
    exportedAt: new Date().toISOString(),
    store: deepClone(store)
  };

  var blob = new Blob([JSON.stringify(payload, null, 2)], {type:'application/json'});
  var url = URL.createObjectURL(blob);
  var a = document.createElement('a');
  a.href = url;
  a.download = 'ethernet-all-profiles-backup.json';
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
});

document.getElementById('restoreAllBtn').addEventListener('click', function(){
  document.getElementById('restoreAllFile').click();
});

document.getElementById('restoreAllFile').addEventListener('change', function(e){
  var file = e.target.files && e.target.files[0];
  if(!file) return;

  var reader = new FileReader();

  reader.onload = function(){
    try{
      var parsed = JSON.parse(reader.result);

      // Accept NEW backups: { schema:'eccm-backup', store:{...} }
      // Accept LEGACY backups: raw store object { current, profiles, ... }
      var incomingStore = null;

      if (parsed && parsed.schema === 'eccm-backup' && parsed.store && typeof parsed.store === 'object') {
        incomingStore = parsed.store;
      } else if (parsed && parsed.current && parsed.profiles) {
        // legacy format: store dump
        incomingStore = parsed;
      } else if (parsed && parsed.schema === 'eccm-profile') {
        throw new Error('This file is a single-profile export. Use "Import Profile", not "Restore All".');
      } else {
        throw new Error('Invalid backup file (unrecognised schema).');
      }

      if(!incomingStore.profiles || typeof incomingStore.profiles !== 'object'){
        throw new Error('Invalid backup file (missing profiles).');
      }

      // Ensure settings exist + defaults
      if (!incomingStore.settings) incomingStore.settings = { maxPorts: 512, enablePortRename: false };
      if (incomingStore.settings.maxPorts == null) incomingStore.settings.maxPorts = 512;
      if (incomingStore.settings.enablePortRename === undefined) incomingStore.settings.enablePortRename = false;

      // Normalise every profile (this is where all the new fields are preserved)
      Object.keys(incomingStore.profiles).forEach(function(name){
        normalizeState(incomingStore.profiles[name]);
      });

      // Ensure "current" points to an existing profile
      if (!incomingStore.current || !incomingStore.profiles[incomingStore.current]) {
        var names = Object.keys(incomingStore.profiles);
        incomingStore.current = names.length ? names[0] : 'Default';
      }

      // If somehow profiles are empty, create at least one
      if (Object.keys(incomingStore.profiles).length === 0) {
        incomingStore.profiles = { 'Default': deepClone(defaultState) };
        incomingStore.current = 'Default';
        normalizeState(incomingStore.profiles['Default']);
      }

      // Commit
      store = incomingStore;
      state = store.profiles[store.current] || deepClone(defaultState);

      saveStore();
      refreshProfileSelect();
      applySettings();
      render();

    }catch(err){
      alert('Restore failed: ' + err.message);
    }finally{
      e.target.value = '';
    }
  };

  reader.readAsText(file);
});

/* ===================== SEARCH + PRINT ===================== */
document.getElementById('searchBox').addEventListener('input', renderConnections);
document.getElementById('printSheet').addEventListener('click', function(){ openPrintSheet(true); });

/* ===================== CLEAR ALL (current profile only) ===================== */
document.getElementById('clearAll').addEventListener('click', function(){
  if(!confirm('Delete ALL devices and connections in profile "'+store.current+'"?')) return;
  store.profiles[store.current] = deepClone(defaultState);
  state = store.profiles[store.current];
  saveStore(); render();
});

/* ===================== GLOBAL BLANK-SPACE CLICK: CLEAR SELECTION ===================== */
document.addEventListener('click', function(e){
  if (
    e.target.closest('.port') ||
    e.target.closest('.conn-row') ||
    e.target.closest('.palette-backdrop') ||
    e.target.closest('.modal-backdrop') ||
    e.target.closest('.device-actions') ||
    e.target.closest('button, input, select, label')
  ){ return; }
  pendingPort = null; highlightLink(null); clearSelectionOutlines();
}, true);

/* ===================== SETTINGS ===================== */
if (!store.settings)
  store.settings = { 
    maxPorts: 512, 
    enablePortRename: false,
    portTermMode: 'port',
    portTermCustom: ''
  };

if (store.settings.enablePortRename === undefined)
  store.settings.enablePortRename = false;

function getMaxPortsSetting() {
  return Math.max(1, Number(store.settings?.maxPorts) || 512);
}

function saveSettings() {
  saveStore();
  applySettings();
}

function applySettings() {
  // Ensure settings object exists (safe fallback)
  if (!store.settings) store.settings = {};

  // Defaults for new setting (don’t overwrite existing)
  if (!('portTermMode' in store.settings)) store.settings.portTermMode = 'port';
  if (!('portTermCustom' in store.settings)) store.settings.portTermCustom = '';

  const maxPorts = getMaxPortsSetting();

  // Device "Ports" input (Add Device modal)
  const devPorts = document.getElementById('devPorts');
  if (devPorts) {
    devPorts.max = String(maxPorts);
    if (Number(devPorts.value) > maxPorts) devPorts.value = String(maxPorts);
  }

  // Settings: maxPorts
  const maxPortsInput = document.getElementById('maxPorts');
  if (maxPortsInput) {
    maxPortsInput.value = String(maxPorts);
  }

  // Settings: enablePortRename
  const enablePortRenameEl = document.getElementById('enablePortRename');
  if (enablePortRenameEl) {
    enablePortRenameEl.checked = !!store.settings.enablePortRename;
  }

  // =========================
  // Settings: Port label term
  // =========================
  const portTermModeEl = document.getElementById('portTermMode');
  const portTermCustomEl = document.getElementById('portTermCustom');
  const portTermCustomRow = document.getElementById('portTermCustomRow');

  if (portTermModeEl) {
    // Set current value
    portTermModeEl.value = store.settings.portTermMode || 'port';

    // Bind change listener ONCE
    if (!portTermModeEl.dataset.bound) {
      portTermModeEl.dataset.bound = '1';
      portTermModeEl.addEventListener('change', () => {
        const isCustom = portTermModeEl.value === 'custom';
        if (portTermCustomRow) portTermCustomRow.style.display = isCustom ? 'flex' : 'none';
      });
    }
  }

  if (portTermCustomEl) {
    portTermCustomEl.value = store.settings.portTermCustom || '';
  }

  if (portTermCustomRow) {
    const mode = (portTermModeEl && portTermModeEl.value) || store.settings.portTermMode || 'port';
    portTermCustomRow.style.display = (mode === 'custom') ? 'flex' : 'none';
  }
}

applySettings();

const maxPortsInput = document.getElementById('maxPorts');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
const enablePortRenameEl = document.getElementById('enablePortRename');

if (saveSettingsBtn && maxPortsInput && enablePortRenameEl) {
  saveSettingsBtn.addEventListener('click', () => {
    const val = Math.max(1, Number(maxPortsInput.value) || 9999);
    store.settings.maxPorts = val;
    store.settings.enablePortRename = !!enablePortRenameEl.checked;
	const portTermModeEl = document.getElementById('portTermMode');
	const portTermCustomEl = document.getElementById('portTermCustom');

	store.settings.portTermMode = portTermModeEl ? portTermModeEl.value : 'port';
	store.settings.portTermCustom = portTermCustomEl ? portTermCustomEl.value.trim() : '';
    saveSettings();
	render();
	
	const modal = document.getElementById('settingsModal');
    if (modal) {
      modal.classList.remove('is-open');
      modal.setAttribute('aria-hidden', 'true');
    }
  });
}

if (enablePortRenameEl) {
  enablePortRenameEl.checked = !!store.settings.enablePortRename;
}

(function clampBeforeAdd() {
  const addBtn = document.getElementById('addBtn');
  const devPorts = document.getElementById('devPorts');
  if (!addBtn || !devPorts) return;

  devPorts.addEventListener('input', () => {
    const maxPorts = getMaxPortsSetting();
    let v = Math.max(1, Number(devPorts.value) || 1);
    if (v > maxPorts) v = maxPorts;
    devPorts.value = String(v);
  });

  addBtn.addEventListener(
    'click',
    () => {
      const maxPorts = getMaxPortsSetting();
      let v = Math.max(1, Number(devPorts.value) || 1);
      if (v > maxPorts) devPorts.value = String(maxPorts);
    },
    true
  );
})();

const __orig_changePorts = changePorts;
changePorts = function (d, newCount) {
  const maxPorts = getMaxPortsSetting();
  const clamped = Math.max(1, Math.min(maxPorts, Number(newCount) || 1));
  return __orig_changePorts(d, clamped);
};

/* ===================== INIT ===================== */
function initProfilesUI(){ refreshProfileSelect(); }
initProfilesUI();
render();
updateUniformPortWidth();




(function(){
  const STORE_KEY = 'elmStore';

  function safeLoad(){
    try { return JSON.parse(localStorage.getItem(STORE_KEY) || '{}'); }
    catch { return {}; }
  }
  function safeSave(obj){
    try { localStorage.setItem(STORE_KEY, JSON.stringify(obj)); } catch {}
  }

  function getStore(){
    const s = (window.store && typeof window.store === 'object') ? window.store : safeLoad();
    if (!s.settings) s.settings = {};
    if (!s.settings.theme) s.settings.theme = 'dark';
    return s;
  }

  function applyTheme(theme){
    document.documentElement.classList.toggle('theme-bright', theme === 'bright');
  }

  function persistTheme(theme){
    if (window.store && typeof window.store === 'object') {
      window.store.settings = window.store.settings || {};
      window.store.settings.theme = theme;
      if (typeof window.saveStore === 'function') {
        try { window.saveStore(); } catch {}
      } else {
        safeSave(window.store);
      }
    } else {
      const s = getStore();
      s.settings.theme = theme;
      safeSave(s);
    }
  }

  function init(){
    const store = getStore();
    applyTheme(store.settings.theme);

    var sel = document.getElementById('themeSelect');
    if (sel){
      sel.value = (store.settings.theme === 'bright') ? 'bright' : 'dark';
      sel.addEventListener('change', function(){
        const theme = sel.value;
        applyTheme(theme);
        persistTheme(theme);
        if (typeof window.render === 'function') {
          try { window.render(); } catch {}
        }
      });
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
</script>
<script>
(function(){
  const LS_KEY = 'elmTheme';
  const getTheme = () => (localStorage.getItem(LS_KEY) === 'bright' ? 'bright' : 'dark');
  const applyTheme = (t) => document.documentElement.classList.toggle('theme-bright', t === 'bright');
  const setTheme = (t) => { localStorage.setItem(LS_KEY, t); applyTheme(t); updateButtons(t); if (typeof window.render==='function') { try{ render(); }catch{} } };

  function updateButtons(t){
    const darkBtn  = document.getElementById('themeDark');
    const lightBtn = document.getElementById('themeLight');
    if(!darkBtn || !lightBtn) return;
    const isBright = t === 'bright';
    darkBtn.classList.toggle('active', !isBright);
    lightBtn.classList.toggle('active', isBright);
    darkBtn.setAttribute('aria-pressed', String(!isBright));
    lightBtn.setAttribute('aria-pressed', String(isBright));
  }

  function wire(){
    const darkBtn  = document.getElementById('themeDark');
    const lightBtn = document.getElementById('themeLight');
    if(!darkBtn || !lightBtn) return;

    darkBtn.addEventListener('click',  () => setTheme('dark'));
    lightBtn.addEventListener('click', () => setTheme('bright'));

    const current = getTheme();
    applyTheme(current);
    updateButtons(current);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', wire, { once:true });
  } else {
    wire();
  }
})();
</script>
<script>
(() => {
  const btn = document.getElementById('btnSettings');
  const modal = document.getElementById('settingsModal');
  const panel = modal?.querySelector('.slideover__panel');
  const closers = modal?.querySelectorAll('[data-close]');
  let lastFocused = null;

  function openSettings() {
    if (!modal) return;
    lastFocused = document.activeElement;
    modal.classList.add('is-open');
    modal.setAttribute('aria-hidden', 'false');
    applySettings();
    setTimeout(() => panel?.focus(), 0);
    document.addEventListener('keydown', onKey);
    document.addEventListener('focus', trapFocus, true);
  }

  function closeSettings() {
    if (!modal) return;
    modal.classList.remove('is-open');
    modal.setAttribute('aria-hidden', 'true');
    document.removeEventListener('keydown', onKey);
    document.removeEventListener('focus', trapFocus, true);
    if (lastFocused && typeof lastFocused.focus === 'function') {
      lastFocused.focus();
    }
  }

  function onKey(e) {
    if (e.key === 'Escape') closeSettings();
  }

  function trapFocus(e) {
    if (!modal.classList.contains('is-open')) return;
    if (!panel.contains(e.target)) {
      e.stopPropagation();
      panel.focus();
    }
  }

  btn?.addEventListener('click', openSettings);
  closers?.forEach(el => el.addEventListener('click', closeSettings));
})();

/* ===================== UNIVERSAL ESCAPE HANDLER ===================== */
(function modalEscapeManager() {
  const modals = {
    palette: document.getElementById('paletteModal'),
    edit: document.getElementById('editDeviceModal'),
    layout: document.getElementById('layoutModal')
  };

  function isOpen(el) {
    return el && el.style.display === 'flex';
  }

  function closeTopmost() {
    if (isOpen(modals.palette)) {
      modals.palette.style.display = 'none';
      return true;
    }
    if (isOpen(modals.edit)) {
      modals.edit.style.display = 'none';
      currentEditDevice = null;
      return true;
    }
    if (isOpen(modals.layout)) {
      modals.layout.style.display = 'none';
      return true;
    }
    return false;
  }

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') {
      const closed = closeTopmost();
      if (closed) {
        e.stopPropagation();
        e.preventDefault();
      }
    }
  });
})();

</script>
</body>
</html>


================================================
FILE: FUNDING.yml
================================================
buy_me_a_coffee: bijomaru78



================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: MANUAL.md
================================================
# User Manual

This 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.  

---

## 📂 Profiles

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/ef2269ef-8c23-462b-8ee2-91ea4771d4b5" />
  
Profiles let you keep different layouts (e.g. home, client A, client B).

- **Create a new profile** → *Profiles* card → **New**  
- **Switch profiles** → Use the dropdown at the top of the *Profiles* card  
- **Rename** → Select a profile, then click **Rename**  
- **Duplicate** → Clone the current profile with **Duplicate**  
- **Delete** → Removes the current profile (at least one profile must exist)  
- **Export** → Save a single profile as a JSON file  
- **Import** → Load a profile from a JSON file

---

## 🖥️ Adding Devices

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/258a22fe-af58-40fc-b814-96d53bfff7c3" />

Each 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.  

- In the *Add device* card, enter a **name** (e.g. *Core Switch A*)  
- Choose the **number of ports** (1–512)  
- Click **Select colour** to assign a colour (helps distinguish devices)  
- Click **Add device**  
- Devices can be reordered by dragging them  

---

## ⚙️ Configuring Devices

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/af86ca1e-664e-4270-94d4-cccc04ef0ddb" />

Configuring 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.  

Click **Layout** on a device to adjust how its ports display:
- **Row width**: full-width (12 ports per row) or half-width (6 ports per row)  
- **13–24 ports**: choose *balanced* (split evenly) or *12 + remainder*  
- **≤12 ports**: choose single row or split into 2 rows  
- **Dual link**: each port can be split into 2 sub-ports  

---

## 🔗 Linking Ports

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/f9948f18-f1ac-48b1-a742-d2c3c002c8fe" />

When linking, you’ll be shown a confirmation prompt with both device names and port numbers, so you can double-check before saving the connection.  

- Click one free port, then another free port → confirm to create a connection  
- Both ends will be coloured with their peer’s device colour  
- Linked ports show an arrow ⇄  

---

## 🏷️ Labelling & Reserving Ports
- **ALT + Click** a port → add or edit a label (alias)  
  - Example: *WAN*, *Printer*, *AP-1*  
- **CTRL + Click** a port → mark it as *reserved* (grey background)  
  - 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
  - Combine with ALT-label to describe what’s at the other end  
    - Example: CTRL-reserve port with a label for location, e.g. *Office*  → ALT-label to specify what's connected, e.g. *PC-4*  

---

## 💾 Backup & Restore (all profiles)

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/da133980-4be6-4c4d-b9b6-413cede3510d" />

Backups 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. 

- **Backup all** → saves every profile (devices + links) into one JSON file  
- **Restore all** → load a backup and replace everything

---

## 🔍 Finding Connections

<img align="right" width="250" alt="image" src="https://github.com/user-attachments/assets/f0cf1111-f080-49f0-b396-331f0c8940b7" />

This 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.  

- Use the search box (*Find connection* card) to filter by device, port, or alias  
- The *Connections* table shows all links, with both devices, ports, and labels  
- Click a row → highlights both ends of the link  

---

## ❌ Managing Connections

<img align="right" width="150" alt="image" src="https://github.com/user-attachments/assets/8bc8bb52-7854-4274-ae89-5829c1501a01" />

From the *Connections* table:
- **Unlink** → break a connection between two ports  
- **Clear** → clear a Reserved port (can also be cleared by **CTRL + clicking** the reserved port again)

---

## 🖨️ Printing
- Use **Print layout** (top-right) to generate a printable sheet of devices + connections  

---

## 📝 Tips
- Profiles autosave automatically — no need to press “Save”  
- Use colours to quickly group devices by type or rack position  
- Labels + reserved ports are powerful for documenting external links  

---


================================================
FILE: README.md
================================================
# Ethernet Cable Connection Manager

A lightweight, browser-based tool for mapping Ethernet connections.  
Create switches, patch panels, wall ports, routers, etc. Assign ports, connect them, and visualise how your network is wired.  

_Featured on:_<br>
🎞️ _<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> 
🎞️ _<a href="https://www.youtube.com/watch?v=b_ggjSxFNYM&t=81s" target="_blank">Best Docker Apps of September 2025 by ServersatHome</a>_<br>
🎞️ _<a href="https://www.youtube.com/watch?v=BWz9uFSNA8A&t=1245s" target="_blank">Docker full of tools by MP Studio</a>_<br>
_Thank you for sharing!_

📖 **User Manual** see [MANUAL.md](MANUAL.md)

📍 **Roadmap / To-Do:** see [ROADMAP.md](ROADMAP.md)

- 🖥️ Works offline (pure HTML + JavaScript, no server required)  
- 📂 Save/export/import layouts as JSON  
- 🖨️ Print sheets with device colours and linked ports  
- 👥 Manage multiple profiles (e.g., different customer networks)  
- 🎨 Colour-code devices and customise port aliases  
- 🔌 Dual-link ports supported (patch panels, wall sockets)

**_Editor (Dark and Light mode):_**

<img src="https://github.com/bijomaru78/eccm/blob/main/eccm_ui_dark_light_animation.gif?raw=true">

**_Print sheet (devices and ports):_**

<img width="900" alt="image" src="https://github.com/user-attachments/assets/fdb68294-eeec-43c5-b5c9-0b978d6fdc28" />

**_Print sheet (connections table):_**

<img width="617" height="558" alt="image" src="https://github.com/user-attachments/assets/4967c6f2-caf6-4eb2-add0-2a1d5170ad0d" />


## 🚀 Try it online
You can open the app instantly here (hosted via GitHub Pages):  
👉 [Ethernet Cable Connection Manager DEMO](https://bijomaru78.github.io/eccm/ECCM.html)

Or download the zip from the releases page and run it locally.

## 📥 Download
Grab the latest release here:  
👉 [Releases](https://github.com/bijomaru78/eccm/releases)

## 💡 Support
This project is free and open source (GPL-3.0).  
If it saves you time or helps in your work, consider supporting development:  

<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>

## 📜 License
This project is licensed under the **GNU GPL-3.0**.  
You are free to use, modify, and redistribute it, but if you distribute changes, you must also provide the source code under the same license.


================================================
FILE: ROADMAP.md
================================================
# Ethernet Cable Connection Manager — Roadmap

This roadmap tracks near-term fixes, planned features, and ideas.  
If something here matters to you, please open/👍 an issue so I can prioritise.

---

## ✅ Completed
- Profiles: create/rename/duplicate/delete/switch
- Export/Import single profile + Backup/Restore all profiles
- Device layout options (full/half rows, 12+remainder / balanced, dual-link)
- Link confirmation prompt
- Find connections + highlight in UI
- A4 layout; colours (linked keep device colour, unlinked white/black text, reserved grey)
- Improve on-screen cheat-sheet (`?` key): ALT = label, CTRL = reserve, click-to-link
- Consistent inner-glow selection for single/dual ports (no layout shift)
- Colour contrast checks for print (linked text always readable)
- Remove 512 port limit
- Local settings page
- Dark/light mode switch

---

## 🧰 In progress / Next up (P0 = highest)
- **P0**
  - [ ] Port settings - additional values such as port speed and VLAN configurable via a right-click menu
  - [ ] Hover card - select port + hover, reveal a pop-up window including all the information about the port, including the additional settings (see above)
- **P1**
  - [ ] “Quick Start” 5-step section at top of manual
- **P1**
  - [ ] Swatch colours + easier way to edit colour for existing devices
---

## 🎯 Short-term candidates

---

## 💡 Later / Ideas

  - [ ] Visible link (line) between selected/linked ports


- [MANUAL.md](MANUAL.md)
- [Issues](../../issues)
Download .txt
gitextract_sla9q__l/

├── ECCM.html
├── FUNDING.yml
├── LICENSE
├── MANUAL.md
├── README.md
└── ROADMAP.md
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (179K chars).
[
  {
    "path": "ECCM.html",
    "chars": 125382,
    "preview": "<!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/"
  },
  {
    "path": "FUNDING.yml",
    "chars": 29,
    "preview": "buy_me_a_coffee: bijomaru78\n\n"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "MANUAL.md",
    "chars": 5279,
    "preview": "# User Manual\n\nThis tool helps you visually map, label, and manage Ethernet connections. It runs entirely in your browse"
  },
  {
    "path": "README.md",
    "chars": 2545,
    "preview": "# Ethernet Cable Connection Manager\n\nA lightweight, browser-based tool for mapping Ethernet connections.  \nCreate switch"
  },
  {
    "path": "ROADMAP.md",
    "chars": 1485,
    "preview": "# Ethernet Cable Connection Manager — Roadmap\n\nThis roadmap tracks near-term fixes, planned features, and ideas.  \nIf so"
  }
]

About this extraction

This page contains the full source code of the bijomaru78/eccm GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (165.9 KB), approximately 44.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!