ZZhenyu2Liangoptimize evococo
9c4447f5创建于 9月14日历史提交
<!DOCTYPE html>
<html lang="en" data-theme="dark">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EvoCoCo | Autonomous Tournament Engine</title>

    <!-- Theme bootstrap: apply saved theme before first paint to avoid flash -->
    <script>
        (function () {
            var theme = 'dark';
            try {
                var saved = localStorage.getItem('evococo-theme');
                if (saved === 'light' || saved === 'dark') theme = saved;
            } catch (e) { /* private mode etc. — fall back to default */ }
            document.documentElement.setAttribute('data-theme', theme);
        })();
    </script>

    <style>
        /* ==========================================================================
           1. DESIGN TOKENS (CSS custom properties — single source of truth)
           ========================================================================== */
        :root {
            color-scheme: light;
            --bg: #f8fafc;
            --bg-panel: #ffffff;
            --bg-subtle: #f1f5f9;
            --bg-inset: #eef2f7;
            --bg-overlay: rgba(15, 23, 42, 0.03);
            --header-bg: rgba(255, 255, 255, 0.92);
            --border: #e2e8f0;
            --border-strong: #cbd5e1;
            --text: #1e293b;
            --text-muted: #64748b;
            --text-faint: #94a3b8;
            --primary: #4f46e5;
            --primary-strong: #4338ca;
            --primary-contrast: #ffffff;
            --primary-soft: rgba(99, 102, 241, 0.10);
            --primary-border: rgba(99, 102, 241, 0.30);
            --success: #059669;
            --success-soft: rgba(16, 185, 129, 0.14);
            --danger: #e11d48;
            --danger-soft: rgba(244, 63, 94, 0.14);
            --warning: #d97706;
            --warning-soft: rgba(245, 158, 11, 0.16);
            --pattern: #94a3b8;
            --caret: #4f46e5;
            --shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.06);
            --shadow-md: 0 8px 24px rgba(15, 23, 42, 0.08);
            --shadow-lg: 0 20px 40px rgba(15, 23, 42, 0.14);
            /* Syntax palette (light) */
            --tok-plain: #1a1a1a;
            --tok-keyword: #0000ff;
            --tok-string: #a31515;
            --tok-number: #098658;
            --tok-comment: #008000;
            --tok-function: #795e26;
            --tok-attr: #001080;
            --tok-decorator: #001080;
            --sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            --mono: ui-monospace, "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, "Courier New", monospace;
        }

        [data-theme="dark"] {
            color-scheme: dark;
            --bg: #020617;
            --bg-panel: #0f172a;
            --bg-subtle: rgba(255, 255, 255, 0.03);
            --bg-inset: rgba(0, 0, 0, 0.35);
            --bg-overlay: rgba(255, 255, 255, 0.01);
            --header-bg: rgba(15, 23, 42, 0.75);
            --border: rgba(255, 255, 255, 0.06);
            --border-strong: rgba(255, 255, 255, 0.14);
            --text: #e2e8f0;
            --text-muted: #94a3b8;
            --text-faint: #64748b;
            --primary: #818cf8;
            --primary-strong: #a5b4fc;
            --primary-soft: rgba(99, 102, 241, 0.16);
            --primary-border: rgba(99, 102, 241, 0.40);
            --success: #34d399;
            --success-soft: rgba(16, 185, 129, 0.18);
            --danger: #fb7185;
            --danger-soft: rgba(244, 63, 94, 0.18);
            --warning: #fbbf24;
            --warning-soft: rgba(245, 158, 11, 0.20);
            --pattern: #6366f1;
            --caret: #818cf8;
            --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.5);
            --shadow-md: 0 8px 24px rgba(0, 0, 0, 0.5);
            --shadow-lg: 0 20px 40px rgba(0, 0, 0, 0.6);
            /* Syntax palette (dark, atom-one-dark inspired) */
            --tok-plain: #abb2bf;
            --tok-keyword: #c678dd;
            --tok-string: #98c379;
            --tok-number: #d19a66;
            --tok-comment: #5c6370;
            --tok-function: #61afef;
            --tok-attr: #e06c75;
            --tok-decorator: #e06c75;
        }

        /* ==========================================================================
           2. BASE / RESET
           ========================================================================== */
        * {
            box-sizing: border-box;
        }

        html,
        body {
            margin: 0;
            height: 100%;
        }

        body {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            font-family: var(--sans);
            font-size: 14px;
            color: var(--text);
            background: var(--bg);
            position: relative;
            transition: background-color 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        button {
            font-family: inherit;
        }

        .hidden {
            display: none !important;
        }

        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0 0 0 0);
            white-space: nowrap;
            border: 0;
        }

        /* Minimalist scrollbars */
        ::-webkit-scrollbar {
            width: 5px;
            height: 5px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--text-faint);
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--primary);
        }

        /* Dynamic tech-grid background */
        .bg-pattern {
            position: absolute;
            inset: 0;
            color: var(--pattern);
            background-image: radial-gradient(circle at center, transparent 0%, currentColor 100%),
                linear-gradient(currentColor 1px, transparent 1px),
                linear-gradient(90deg, currentColor 1px, transparent 1px);
            background-size: 100% 100%, 30px 30px, 30px 30px;
            opacity: 0.04;
            pointer-events: none;
            z-index: 0;
        }

        /* ==========================================================================
           3. ICONS (inline SVG sprite — no icon fonts)
           ========================================================================== */
        .icon {
            width: 18px;
            height: 18px;
            fill: none;
            stroke: currentColor;
            stroke-width: 2;
            stroke-linecap: round;
            stroke-linejoin: round;
            flex-shrink: 0;
        }

        .icon-lg {
            width: 22px;
            height: 22px;
        }

        .icon-xl {
            width: 60px;
            height: 60px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .icon-spin {
            animation: spin 1.2s linear infinite;
        }

        /* ==========================================================================
           4. ANIMATIONS
           ========================================================================== */
        @keyframes fadeInSlide {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-step {
            animation: fadeInSlide 0.4s ease-out forwards;
        }

        @keyframes pulse {
            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.45;
            }
        }

        @keyframes shimmer {
            0% {
                transform: translateX(-100%);
            }

            100% {
                transform: translateX(100%);
            }
        }

        /* ==========================================================================
           5. HEADER
           ========================================================================== */
        header {
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            padding: 0 24px;
            border-bottom: 1px solid var(--border);
            background: var(--header-bg);
            backdrop-filter: blur(12px);
            box-shadow: var(--shadow-sm);
            z-index: 30;
            flex-shrink: 0;
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 14px;
            min-width: 0;
        }

        .logo {
            position: relative;
            width: 44px;
            height: 44px;
            flex-shrink: 0;
        }

        .logo-glow {
            position: absolute;
            inset: 0;
            background: var(--primary);
            filter: blur(14px);
            opacity: 0.45;
            border-radius: 12px;
        }

        .logo-tile {
            position: relative;
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: linear-gradient(135deg, #6366f1, #4338ca);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: var(--shadow-md);
            transition: transform 0.2s;
        }

        .logo:hover .logo-tile {
            transform: scale(1.06);
        }

        .brand h1 {
            margin: 0;
            font-size: 22px;
            font-weight: 900;
            letter-spacing: -0.02em;
            color: var(--text);
            text-transform: uppercase;
            line-height: 1;
            display: flex;
            align-items: center;
            white-space: nowrap;
        }

        .version {
            font-size: 10px;
            font-family: var(--mono);
            font-weight: 700;
            color: var(--primary);
            background: var(--primary-soft);
            border: 1px solid var(--primary-border);
            padding: 2px 8px;
            border-radius: 6px;
            margin-left: 8px;
        }

        .tagline {
            margin: 4px 0 0;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.4em;
            font-weight: 800;
            color: var(--text-faint);
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 14px;
            flex-shrink: 0;
        }

        .connection-badge {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 10px 18px;
            border-radius: 12px;
            border: 1px solid var(--border);
            background: var(--bg-subtle);
            box-shadow: var(--shadow-sm);
            transition: all 0.3s;
        }

        .connection-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--danger);
            box-shadow: 0 0 12px var(--danger);
            transition: background 0.3s, box-shadow 0.3s;
        }

        .connection-dot.on {
            background: var(--success);
            box-shadow: 0 0 12px var(--success);
            animation: pulse 2s infinite;
        }

        .connection-text {
            font-size: 11px;
            font-weight: 800;
            font-family: var(--mono);
            text-transform: uppercase;
            letter-spacing: 0.15em;
            color: var(--text-muted);
            white-space: nowrap;
            transition: color 0.3s;
        }

        .connection-text.on {
            color: var(--success);
        }

        .access-panel {
            position: relative;
            z-index: 20;
            flex-shrink: 0;
            padding: 12px 24px;
            border-bottom: 1px solid var(--border);
            background: var(--bg-panel);
        }

        .access-panel p {
            margin: 0 0 8px;
            color: var(--text-muted);
        }

        .access-form {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }

        .access-form input {
            width: min(340px, 100%);
            padding: 10px 12px;
            border: 1px solid var(--border-strong);
            border-radius: 10px;
            background: var(--bg-inset);
            color: var(--text);
            font: inherit;
        }

        .access-form button {
            padding: 10px 16px;
        }

        /* ==========================================================================
           6. BUTTONS
           ========================================================================== */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            font-weight: 800;
            border: none;
            cursor: pointer;
            border-radius: 14px;
            transition: all 0.15s ease;
            text-transform: uppercase;
            letter-spacing: 0.12em;
        }

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

        .btn:disabled {
            opacity: 0.75;
            cursor: not-allowed;
        }

        .btn-primary {
            background: linear-gradient(180deg, var(--primary), var(--primary-strong));
            color: var(--primary-contrast);
            box-shadow: var(--shadow-md);
            border-bottom: 4px solid rgba(0, 0, 0, 0.25);
        }

        .btn-primary:hover:not(:disabled) {
            filter: brightness(1.08);
        }

        .btn-danger {
            background: var(--danger);
            color: #ffffff;
            border-bottom: 4px solid rgba(0, 0, 0, 0.25);
            box-shadow: var(--shadow-md);
        }

        .btn-danger:hover:not(:disabled) {
            filter: brightness(1.08);
        }

        .btn-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            border: 1px solid var(--border);
            background: var(--bg-panel);
            color: var(--text-muted);
            box-shadow: var(--shadow-sm);
        }

        .btn-icon:hover {
            background: var(--bg-subtle);
            color: var(--text);
        }

        .btn-icon-sm {
            width: 34px;
            height: 34px;
            border-radius: 10px;
        }

        .shimmer-btn {
            position: relative;
            overflow: hidden;
        }

        .shimmer-btn::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.12), transparent);
            animation: shimmer 2s infinite;
            pointer-events: none;
        }

        .run-btn {
            flex: 3;
            height: 64px;
            font-size: 15px;
            letter-spacing: 0.25em;
        }

        .stop-btn {
            flex: 1;
            height: 64px;
            display: none;
            font-size: 13px;
        }

        .stop-btn.visible {
            display: inline-flex;
            animation: fadeInSlide 0.3s ease-out;
        }

        /* ==========================================================================
           7. MAIN LAYOUT (3 resizable panels)
           ========================================================================== */
        main {
            flex: 1;
            display: flex;
            overflow: hidden;
            z-index: 10;
        }

        .panel {
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        #panel-left {
            width: 35%;
            min-width: 300px;
            background: var(--bg-panel);
            border-right: 1px solid var(--border);
        }

        #panel-middle {
            width: 30%;
            min-width: 280px;
            background: var(--bg-inset);
            border-right: 1px solid var(--border);
            position: relative;
        }

        #panel-right {
            flex: 1;
            min-width: 0;
            background: var(--bg-panel);
            position: relative;
        }

        .resizer-x {
            width: 6px;
            flex: 0 0 6px;
            cursor: col-resize;
            position: relative;
            z-index: 50;
            background: transparent;
        }

        .resizer-x::after {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 1px;
            background: var(--border);
            transition: background 0.2s, width 0.2s, box-shadow 0.2s;
        }

        .resizer-x:hover::after,
        .resizer-x.resizing::after {
            background: var(--primary);
            width: 2px;
            box-shadow: 0 0 8px var(--primary);
        }

        .resizer-y {
            height: 6px;
            flex: 0 0 6px;
            cursor: row-resize;
            position: relative;
            z-index: 50;
            background: transparent;
        }

        .resizer-y::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            height: 1px;
            background: var(--border);
            transition: background 0.2s, height 0.2s, box-shadow 0.2s;
        }

        .resizer-y:hover::after,
        .resizer-y.resizing::after {
            background: var(--primary);
            height: 2px;
            box-shadow: 0 0 8px var(--primary);
        }

        /* Panel headers */
        .panel-head {
            padding: 16px 24px;
            border-bottom: 1px solid var(--border);
            background: var(--bg-subtle);
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-shrink: 0;
        }

        .panel-title {
            margin: 0;
            font-size: 13px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.22em;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .panel-title .icon {
            color: var(--primary);
        }

        .file-tag {
            font-size: 10px;
            font-family: var(--mono);
            font-weight: 700;
            color: var(--primary);
            opacity: 0.8;
            font-style: italic;
            letter-spacing: 0.05em;
        }

        /* ==========================================================================
           8. CODE EDITOR (textarea + highlight overlay + line numbers)
           ========================================================================== */
        .editor-container {
            flex: 1;
            display: flex;
            overflow: hidden;
            font-family: var(--mono);
            position: relative;
        }

        .line-numbers {
            width: 50px;
            padding: 24px 0;
            text-align: right;
            color: var(--text-faint);
            font-size: 12px;
            font-weight: 500;
            user-select: none;
            border-right: 1px solid var(--primary-border);
            background: linear-gradient(to right, var(--bg-overlay), transparent);
            line-height: 1.625;
            overflow: hidden;
        }

        .editor-wrapper {
            position: relative;
            flex: 1;
            overflow: hidden;
        }

        #source-input,
        #highlight-overlay {
            width: 100%;
            height: 100%;
            padding: 24px;
            font-family: var(--mono);
            font-size: 13.5px;
            line-height: 1.625;
            white-space: pre-wrap;
            word-wrap: break-word;
            border: none;
            position: absolute;
            top: 0;
            left: 0;
            tab-size: 4;
            margin: 0;
        }

        #source-input {
            background: transparent;
            color: transparent;
            caret-color: var(--caret);
            z-index: 2;
            resize: none;
            outline: none;
            overflow-y: auto;
            overflow-x: hidden;
        }

        #highlight-overlay {
            z-index: 1;
            pointer-events: none;
            background: transparent;
            overflow: hidden;
            color: var(--tok-plain);
        }

        #highlight-overlay code {
            background: transparent !important;
            padding: 0 !important;
            font-family: inherit;
        }

        /* Editor footer / controls */
        .editor-footer {
            padding: 20px 24px;
            border-top: 1px solid var(--border);
            background: var(--bg-panel);
            display: flex;
            flex-direction: column;
            gap: 14px;
            flex-shrink: 0;
        }

        .editor-actions {
            display: flex;
            gap: 16px;
            width: 100%;
        }

        /* ==========================================================================
           9. EXECUTION TRACE (flow of steps)
           ========================================================================== */
        #panel-middle-top {
            display: flex;
            flex-direction: column;
            height: 65%;
            min-height: 100px;
        }

        #flow-container {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
            position: relative;
            scroll-behavior: smooth;
        }

        .flow-grid {
            position: absolute;
            inset: 0;
            pointer-events: none;
            opacity: 0.04;
            background-image: linear-gradient(var(--pattern) 1px, transparent 1px),
                linear-gradient(90deg, var(--pattern) 1px, transparent 1px);
            background-size: 40px 40px;
        }

        #empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: var(--text-faint);
            transition: opacity 0.5s;
        }

        #empty-state.faded {
            opacity: 0;
        }

        #empty-state .icon {
            opacity: 0.2;
            transform: rotate(-12deg);
            margin-bottom: 24px;
        }

        #empty-state p {
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.5em;
            opacity: 0.3;
        }

        /* Step cards */
        .step-item {
            position: relative;
            padding-left: 64px;
            padding-bottom: 56px;
        }

        .step-line {
            position: absolute;
            left: 25px;
            top: 48px;
            bottom: 0;
            width: 2.5px;
            background: var(--primary-border);
            box-shadow: 0 0 8px var(--primary-soft);
            transition: background 0.3s;
        }

        .step-item:last-child .step-line {
            background: transparent;
        }

        .step-badge {
            position: absolute;
            left: 0;
            top: 0;
            z-index: 10;
        }

        .status-bg {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: var(--bg-panel);
            border: 2px solid var(--border-strong);
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: var(--shadow-sm);
            transition: border-color 0.2s, box-shadow 0.2s, transform 0.2s;
        }

        .status-bg .icon {
            color: var(--primary);
        }

        .status-bg.ok {
            border-color: var(--success);
            box-shadow: 0 0 20px var(--success-soft);
        }

        .status-bg.fail {
            border-color: var(--danger);
            box-shadow: 0 0 20px var(--danger-soft);
        }

        .status-icon.ok {
            color: var(--success) !important;
        }

        .status-icon.fail {
            color: var(--danger) !important;
        }

        .cyber-card {
            background: var(--bg-panel);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 22px;
            position: relative;
            overflow: hidden;
            box-shadow: var(--shadow-md);
            transition: transform 0.25s, box-shadow 0.25s, border-color 0.25s;
            margin-left: 8px;
        }

        .cyber-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--shadow-lg);
            border-color: var(--primary-border);
        }

        .card-deco {
            position: absolute;
            top: 0;
            right: 0;
            padding: 12px;
            opacity: 0.05;
            transform: rotate(12deg);
            transition: transform 0.3s;
            color: var(--primary);
        }

        .cyber-card:hover .card-deco {
            transform: rotate(0deg);
        }

        .card-head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            margin-bottom: 12px;
        }

        .step-title {
            margin: 0;
            font-size: 15px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.12em;
            color: var(--text);
            word-break: break-word;
        }

        .step-desc {
            margin: 0;
            font-size: 13px;
            color: var(--text-muted);
            line-height: 1.5;
            font-weight: 700;
            font-style: italic;
            word-break: break-word;
        }

        .step-tag {
            font-size: 10px;
            padding: 6px 14px;
            border-radius: 8px;
            font-weight: 800;
            letter-spacing: 0.15em;
            text-transform: uppercase;
            border: 1px solid;
            white-space: nowrap;
        }

        .tag-active {
            background: var(--primary-soft);
            color: var(--primary);
            border-color: var(--primary-border);
        }

        .tag-ok {
            background: var(--success-soft);
            color: var(--success);
            border-color: var(--success);
        }

        .tag-fail {
            background: var(--danger-soft);
            color: var(--danger);
            border-color: var(--danger);
        }

        /* ==========================================================================
           10. RUNTIME OUTPUT (terminal)
           ========================================================================== */
        #panel-middle-bottom {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: var(--bg-panel);
            overflow: hidden;
            border-top: 1px solid var(--border);
        }

        .term-head {
            padding: 12px 20px;
            background: var(--bg-subtle);
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }

        .term-label {
            margin: 0;
            font-size: 11px;
            font-weight: 800;
            font-family: var(--mono);
            letter-spacing: 0.15em;
            text-transform: uppercase;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-light {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: var(--primary);
            box-shadow: 0 0 8px var(--primary);
            animation: pulse 2s infinite;
        }

        #terminal-content {
            flex: 1;
            overflow-y: auto;
            padding: 18px 20px;
            font-family: var(--mono);
            font-size: 11.5px;
            line-height: 1.6;
            color: var(--text-muted);
        }

        .term-placeholder {
            font-style: italic;
            opacity: 0.3;
            font-weight: 800;
            letter-spacing: -0.02em;
        }

        .log-line {
            display: flex;
            gap: 16px;
            padding: 7px 0;
            border-bottom: 1px solid transparent;
            word-break: break-word;
        }

        .log-line:hover {
            background: var(--bg-overlay);
        }

        .log-time {
            opacity: 0.4;
            user-select: none;
            font-weight: 800;
            font-size: 10px;
            letter-spacing: -0.02em;
            flex-shrink: 0;
        }

        .log-muted {
            color: var(--text-muted);
        }

        .log-ok {
            color: var(--success);
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.02em;
        }

        .log-err {
            color: var(--danger);
            font-weight: 800;
        }

        .log-warn {
            color: var(--warning);
            font-weight: 700;
        }

        .log-accent {
            color: var(--primary);
            font-weight: 700;
        }

        .log-danger {
            color: var(--danger);
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.1em;
        }

        /* ==========================================================================
           11. OUTPUT VIEWS (tabs + code / blueprint / ir)
           ========================================================================== */
        .tablist {
            display: flex;
            border-bottom: 1px solid var(--border);
            background: var(--bg-panel);
            flex-shrink: 0;
        }

        .tab-btn {
            flex: 1;
            padding: 18px 24px;
            font-size: 13px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.2em;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            color: var(--text-faint);
            background: transparent;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            transition: color 0.2s, border-color 0.2s, background 0.2s;
        }

        .tab-btn:hover {
            color: var(--text-muted);
        }

        .tab-btn.tab-active {
            color: var(--primary);
            border-bottom-color: var(--primary);
            background: linear-gradient(to top, var(--primary-soft), transparent);
        }

        .views {
            flex: 1;
            position: relative;
            overflow: hidden;
            background: var(--bg-subtle);
        }

        .view {
            position: absolute;
            inset: 0;
            overflow: auto;
        }

        #view-code pre {
            padding: 28px;
            font-family: var(--mono);
            font-size: 14px;
            line-height: 1.65;
            margin: 0;
        }

        #code-content {
            display: block;
            color: var(--tok-plain);
        }

        .markdown-container {
            padding: 24px;
        }

        .markdown-body {
            max-width: 780px;
            color: var(--text-muted);
            font-size: 14px;
            line-height: 1.7;
        }

        .markdown-body h1,
        .markdown-body h2,
        .markdown-body h3,
        .markdown-body h4,
        .markdown-body h5,
        .markdown-body h6 {
            color: var(--primary);
            font-weight: 800;
            letter-spacing: -0.02em;
            margin: 1.1em 0 0.45em;
        }

        .markdown-body h1 {
            font-size: 22px;
        }

        .markdown-body h2 {
            font-size: 18px;
        }

        .markdown-body h3 {
            font-size: 15px;
        }

        .markdown-body p {
            margin: 0.6em 0;
        }

        .markdown-body pre {
            background: var(--bg-panel);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 16px;
            overflow-x: auto;
            font-family: var(--mono);
            font-size: 12.5px;
            line-height: 1.6;
        }

        .markdown-body code {
            font-family: var(--mono);
        }

        .markdown-inline-code {
            color: var(--primary);
            background: var(--primary-soft);
            padding: 1px 6px;
            border-radius: 6px;
            font-size: 0.9em;
        }

        .markdown-body a {
            color: var(--primary);
            text-decoration: underline;
        }

        .markdown-body ul,
        .markdown-body ol {
            padding-left: 24px;
            margin: 0.6em 0;
        }

        .markdown-body li {
            margin: 0.25em 0;
        }

        .markdown-body blockquote {
            margin: 0.8em 0;
            padding: 4px 16px;
            border-left: 3px solid var(--primary-border);
            color: var(--text-muted);
            font-style: italic;
        }

        .markdown-body hr {
            border: none;
            border-top: 1px solid var(--border);
            margin: 1.2em 0;
        }

        /* Copy floating action button */
        .copy-fab {
            position: absolute;
            bottom: 48px;
            right: 48px;
            z-index: 40;
            width: 64px;
            height: 64px;
            border-radius: 16px;
            background: var(--bg-panel);
            color: var(--text-muted);
            border: 1px solid var(--border);
            box-shadow: var(--shadow-lg);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .copy-fab:hover {
            border-color: var(--primary);
            box-shadow: 0 0 24px var(--primary-soft);
            color: var(--text);
        }

        .copy-fab:active {
            transform: scale(0.9);
        }

        .copy-fab.ok {
            color: var(--success);
            border-color: var(--success);
        }

        .copy-fab.fail {
            color: var(--danger);
            border-color: var(--danger);
        }

        /* Syntax token colors */
        .tok-keyword {
            color: var(--tok-keyword);
            font-weight: 700;
        }

        .tok-comment {
            color: var(--tok-comment);
            font-style: italic;
        }

        .tok-string {
            color: var(--tok-string);
            font-weight: 500;
        }

        .tok-number {
            color: var(--tok-number);
        }

        .tok-function {
            color: var(--tok-function);
            font-weight: 600;
        }

        .tok-attr {
            color: var(--tok-attr);
        }

        .tok-decorator {
            color: var(--tok-decorator);
            font-weight: 600;
        }

        /* ==========================================================================
           12. RESPONSIVE
           ========================================================================== */
        @media (max-width: 960px) {
            main {
                flex-direction: column;
                overflow-y: auto;
            }

            .resizer-x,
            .resizer-y {
                display: none;
            }

            #panel-left,
            #panel-middle,
            #panel-right {
                width: 100% !important;
                min-width: 0 !important;
                border-right: none;
            }

            #panel-left {
                min-height: 420px;
            }

            #panel-middle {
                min-height: 520px;
                border-top: 1px solid var(--border);
            }

            #panel-right {
                min-height: 460px;
                border-top: 1px solid var(--border);
            }

            #panel-middle-top {
                height: 55% !important;
            }

            .copy-fab {
                bottom: 24px;
                right: 24px;
            }

            header {
                padding: 0 16px;
            }
        }

        @media (max-width: 560px) {
            .tagline {
                display: none;
            }

            .connection-badge {
                padding: 8px 12px;
            }

            .connection-text {
                display: none;
            }

            .brand h1 {
                font-size: 17px;
            }
        }
    </style>
</head>

<body>
    <!-- Inline SVG icon sprite (dependency-free replacement for icon fonts) -->
    <svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">
        <symbol id="icon-branch" viewBox="0 0 24 24"><line x1="6" y1="3" x2="6" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></symbol>
        <symbol id="icon-moon" viewBox="0 0 24 24"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" /></symbol>
        <symbol id="icon-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="5" /><line x1="12" y1="1" x2="12" y2="3" /><line x1="12" y1="21" x2="12" y2="23" /><line x1="4.22" y1="4.22" x2="5.64" y2="5.64" /><line x1="18.36" y1="18.36" x2="19.78" y2="19.78" /><line x1="1" y1="12" x2="3" y2="12" /><line x1="21" y1="12" x2="23" y2="12" /><line x1="4.22" y1="19.78" x2="5.64" y2="18.36" /><line x1="18.36" y1="5.64" x2="19.78" y2="4.22" /></symbol>
        <symbol id="icon-microchip" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2" /><rect x="9" y="9" width="6" height="6" /><line x1="9" y1="1" x2="9" y2="4" /><line x1="15" y1="1" x2="15" y2="4" /><line x1="9" y1="20" x2="9" y2="23" /><line x1="15" y1="20" x2="15" y2="23" /><line x1="20" y1="9" x2="23" y2="9" /><line x1="20" y1="14" x2="23" y2="14" /><line x1="1" y1="9" x2="4" y2="9" /><line x1="1" y1="14" x2="4" y2="14" /></symbol>
        <symbol id="icon-play" viewBox="0 0 24 24"><polygon points="6 3 20 12 6 21 6 3" /></symbol>
        <symbol id="icon-sync" viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10" /><polyline points="1 20 1 14 7 14" /><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" /></symbol>
        <symbol id="icon-stop" viewBox="0 0 24 24"><rect x="6" y="6" width="12" height="12" rx="2" /></symbol>
        <symbol id="icon-diagram" viewBox="0 0 24 24"><circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" /><line x1="8.59" y1="13.51" x2="15.42" y2="17.49" /><line x1="15.41" y1="6.51" x2="8.59" y2="10.49" /></symbol>
        <symbol id="icon-network" viewBox="0 0 24 24"><circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" /><line x1="8.59" y1="13.51" x2="15.42" y2="17.49" /><line x1="15.41" y1="6.51" x2="8.59" y2="10.49" /></symbol>
        <symbol id="icon-terminal" viewBox="0 0 24 24"><polyline points="4 17 10 11 4 5" /><line x1="12" y1="19" x2="20" y2="19" /></symbol>
        <symbol id="icon-trash" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><line x1="10" y1="11" x2="10" y2="17" /><line x1="14" y1="11" x2="14" y2="17" /></symbol>
        <symbol id="icon-python" viewBox="0 0 24 24"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></symbol>
        <symbol id="icon-code" viewBox="0 0 24 24"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></symbol>
        <symbol id="icon-blueprint" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" /><polygon points="16.24 7.76 14.12 14.12 7.76 16.24 9.88 9.88 16.24 7.76" /><line x1="12" y1="2" x2="12" y2="22" /></symbol>
        <symbol id="icon-atom" viewBox="0 0 24 24"><circle cx="12" cy="12" r="1" /><ellipse cx="12" cy="12" rx="10" ry="4.5" /><ellipse cx="12" cy="12" rx="10" ry="4.5" transform="rotate(60 12 12)" /><ellipse cx="12" cy="12" rx="10" ry="4.5" transform="rotate(120 12 12)" /></symbol>
        <symbol id="icon-copy" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /></symbol>
        <symbol id="icon-check" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12" /></symbol>
        <symbol id="icon-bolt" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></symbol>
        <symbol id="icon-cube" viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" /><polyline points="3.27 6.96 12 12.01 20.73 6.96" /><line x1="12" y1="22.08" x2="12" y2="12" /></symbol>
        <symbol id="icon-database" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="9" ry="3" /><path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3" /><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" /></symbol>
        <symbol id="icon-cogs" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" /></symbol>
        <symbol id="icon-robot" viewBox="0 0 24 24"><rect x="4" y="8" width="16" height="12" rx="2" /><circle cx="12" cy="4" r="2" /><path d="M12 6v2" /><circle cx="9" cy="14" r="1" /><circle cx="15" cy="14" r="1" /></symbol>
        <symbol id="icon-chart" viewBox="0 0 24 24"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" /></symbol>
        <symbol id="icon-flask" viewBox="0 0 24 24"><line x1="10" y1="2" x2="14" y2="2" /><line x1="12" y1="2" x2="12" y2="5" /><path d="M17.5 5c0 1.5-1 3.5-1.5 4.5l3 9.5a2 2 0 0 1-1.9 2.5H6.9a2 2 0 0 1-1.9-2.5l3-9.5c-.5-1-1.5-3-1.5-4.5" /><line x1="7.5" y1="13" x2="16.5" y2="13" /></symbol>
        <symbol id="icon-circle" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" /></symbol>
        <symbol id="icon-bug" viewBox="0 0 24 24"><rect x="8" y="2" width="8" height="4" rx="1" /><path d="M8 6v3a4 4 0 0 0 8 0V6" /><path d="M4 12h16" /><path d="M4 16h16" /><path d="M12 9v11" /></symbol>
        <symbol id="icon-file" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" /></symbol>
    </svg>

    <div class="bg-pattern" aria-hidden="true"></div>

    <!-- Screen-reader live region for connection/run status -->
    <div id="live-status" class="sr-only" aria-live="polite"></div>

    <!-- ============================== HEADER ============================== -->
    <header>
        <div class="brand">
            <div class="logo" aria-hidden="true">
                <div class="logo-glow"></div>
                <div class="logo-tile">
                    <svg class="icon icon-lg"><use href="#icon-branch" /></svg>
                </div>
            </div>
            <div>
                <h1>EvoCoCo <span class="version">3.0</span></h1>
                <p class="tagline">Autonomous Tournament Engine</p>
            </div>
        </div>

        <div class="header-actions">
            <button id="theme-btn" class="btn btn-icon" type="button" aria-label="Toggle color theme" title="Toggle theme">
                <svg class="icon"><use id="theme-icon" href="#icon-moon" /></svg>
            </button>
            <div id="connection-badge" class="connection-badge">
                <div id="connection-dot" class="connection-dot" aria-hidden="true"></div>
                <span id="connection-text" class="connection-text">Link-Inactive</span>
            </div>
        </div>
    </header>

    <section id="access-panel" class="access-panel hidden" aria-label="Backend connection">
        <p id="access-message" role="status">Open the link printed by the backend, or paste its access token below.</p>
        <form id="access-form" class="access-form">
            <label for="access-token">Access token</label>
            <input id="access-token" type="password" autocomplete="off" spellcheck="false"
                aria-describedby="access-message" placeholder="Token from the backend startup link" required>
            <button class="btn btn-primary" type="submit">Connect</button>
        </form>
    </section>

    <!-- ============================== MAIN ============================== -->
    <main id="main-container">

        <!-- ============ Editor Panel ============ -->
        <section id="panel-left" class="panel" aria-label="Source code editor panel">
            <div class="panel-head">
                <h2 class="panel-title">
                    <svg class="icon"><use href="#icon-microchip" /></svg>
                    Source Stream
                </h2>
                <span class="file-tag">source.raw</span>
            </div>

            <div class="editor-container">
                <div id="line-numbers" class="line-numbers" aria-hidden="true"></div>
                <div class="editor-wrapper">
                    <pre id="highlight-overlay" aria-hidden="true"></pre>
                    <textarea id="source-input" spellcheck="false" aria-label="MATLAB source code editor"
                        aria-describedby="editor-hint"></textarea>
                </div>
            </div>

            <div class="editor-footer">
                <p id="editor-hint" class="sr-only">Press Ctrl+Enter to run the pipeline.</p>
                <div class="editor-actions">
                    <button id="run-btn" class="btn btn-primary shimmer-btn run-btn" type="button" disabled>
                        <svg class="icon icon-lg"><use id="run-icon" href="#icon-play" /></svg>
                        <span class="btn-label">Run Agent</span>
                    </button>
                    <button id="stop-btn" class="btn btn-danger stop-btn" type="button">
                        <svg class="icon"><use href="#icon-stop" /></svg>
                        <span>Stop</span>
                    </button>
                </div>
            </div>
        </section>

        <div class="resizer-x" id="resizer-left" role="separator" aria-orientation="vertical"
            aria-label="Resize editor panel" tabindex="0"></div>

        <!-- ============ Trace + Logs Panel ============ -->
        <section id="panel-middle" class="panel" aria-label="Execution trace and logs panel">
            <div id="panel-middle-top">
                <div class="panel-head">
                    <h2 class="panel-title">
                        <svg class="icon"><use href="#icon-diagram" /></svg>
                        Execution Trace
                    </h2>
                </div>
                <div class="flex-1 overflow-auto" id="flow-container">
                    <div class="flow-grid" aria-hidden="true"></div>
                    <div id="empty-state">
                        <svg class="icon icon-xl"><use href="#icon-terminal" /></svg>
                        <p>Awaiting Signal</p>
                    </div>
                </div>
            </div>

            <div class="resizer-y" id="resizer-middle" role="separator" aria-orientation="horizontal"
                aria-label="Resize trace panel" tabindex="0"></div>

            <div id="panel-middle-bottom">
                <div class="term-head">
                    <p class="term-label">
                        <span class="status-light" aria-hidden="true"></span>
                        Runtime Output
                    </p>
                    <button id="clear-logs-btn" class="btn btn-icon btn-icon-sm" type="button"
                        aria-label="Clear runtime output" title="Clear output">
                        <svg class="icon"><use href="#icon-trash" /></svg>
                    </button>
                </div>
                <div id="terminal-content" role="log" aria-live="polite" aria-label="Runtime output log">
                    <div class="term-placeholder">&gt;&gt;&gt; Ready for secure deployment.</div>
                </div>
            </div>
        </section>

        <div class="resizer-x" id="resizer-right" role="separator" aria-orientation="vertical"
            aria-label="Resize trace panel" tabindex="0"></div>

        <!-- ============ Output Views Panel ============ -->
        <section id="panel-right" class="panel" aria-label="Output views panel">
            <div class="tablist" id="tablist" role="tablist" aria-label="Output views">
                <button id="tab-code" class="tab-btn" role="tab" aria-selected="true" aria-controls="view-code"
                    tabindex="0">
                    <svg class="icon"><use href="#icon-python" /></svg>
                    Python
                </button>
                <button id="tab-blueprint" class="tab-btn" role="tab" aria-selected="false" aria-controls="view-blueprint"
                    tabindex="-1">
                    <svg class="icon"><use href="#icon-blueprint" /></svg>
                    Blueprint
                </button>
                <button id="tab-ir" class="tab-btn" role="tab" aria-selected="false" aria-controls="view-ir" tabindex="-1">
                    <svg class="icon"><use href="#icon-atom" /></svg>
                    Analyst
                </button>
            </div>

            <div class="views">
                <div id="view-code" class="view" role="tabpanel" aria-labelledby="tab-code">
                    <pre><code id="code-content" class="language-python"># Process results will be materialized here...</code></pre>
                </div>
                <div id="view-blueprint" class="view hidden markdown-container" role="tabpanel"
                    aria-labelledby="tab-blueprint"></div>
                <div id="view-ir" class="view hidden markdown-container" role="tabpanel" aria-labelledby="tab-ir"></div>
            </div>

            <button id="copy-btn" class="copy-fab" type="button" aria-label="Copy current view" title="Copy current view">
                <svg class="icon icon-lg"><use id="copy-icon" href="#icon-copy" /></svg>
            </button>
        </section>
    </main>

    <!-- ============================== STEP TEMPLATE ============================== -->
    <template id="step-template">
        <div class="step-item animate-step">
            <div class="step-line" aria-hidden="true"></div>
            <div class="step-badge">
                <div class="status-bg">
                    <svg class="icon status-icon icon-spin" aria-hidden="true"><use href="#icon-sync" /></svg>
                </div>
            </div>
            <div class="cyber-card">
                <div class="card-deco" aria-hidden="true">
                    <svg class="icon icon-lg"><use href="#icon-cube" /></svg>
                </div>
                <div class="card-head">
                    <h3 class="step-title">Node Module</h3>
                    <span class="step-tag tag-active">Active</span>
                </div>
                <p class="step-desc">Calibrating module parameters...</p>
            </div>
        </div>
    </template>

    <noscript>
        <p style="padding:16px;color:var(--text, #1e293b)">EvoCoCo requires JavaScript to run. Please enable it.</p>
    </noscript>

    <script>
        'use strict';

        /* ==========================================================================
           CONSTANTS & STATE
           ========================================================================== */

        // Fallback endpoint when opened via file:// (no http(s) origin to derive from).
        const WS_FALLBACK_URL = 'ws://localhost:8000/ws';
        const MAX_LOG_LINES = 300;
        const RECONNECT_BASE_MS = 1000;   // first retry after 1s
        const RECONNECT_MAX_MS = 30000;   // cap backoff at 30s
        const TOKEN_STORAGE_KEY = 'evococo-access-token';

        const state = {
            socket: null,
            reconnectAttempts: 0,
            pendingReconnect: null,
            manualStop: false,   // true after the user pressed Stop (suppresses alarm logs)
            accessToken: '',
            authenticated: false,
            authenticationBlocked: false,
            isRunning: false
        };

        let activeTab = 'code';
        let emptyStateProto = null; // pristine copy of #empty-state used to restore it between runs

        /* ==========================================================================
           SMALL HELPERS
           ========================================================================== */

        // Escape HTML so that any backend-supplied string can be rendered safely (no XSS).
        function escapeHtml(s) {
            return String(s)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        }

        function isSocketOpen() {
            return !!(state.socket && state.socket.readyState === WebSocket.OPEN);
        }

        function isConnectionReady() {
            return isSocketOpen() && state.authenticated;
        }

        function announce(msg) {
            const el = document.getElementById('live-status');
            if (el) el.textContent = msg;
        }

        function scrollToBottom(id) {
            const el = document.getElementById(id);
            if (el) el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
        }

        /* ==========================================================================
           SYNTAX HIGHLIGHTING (tiny regex tokenizers — replace highlight.js)
           ========================================================================== */

        // Walk `code` with `tokenRe` and emit escaped HTML with per-group token spans.
        function tokenizeToHtml(code, tokenRe, groupToClass) {
            let html = '';
            let last = 0;
            let m;
            tokenRe.lastIndex = 0;
            while ((m = tokenRe.exec(code)) !== null) {
                if (m.index > last) html += escapeHtml(code.slice(last, m.index));
                let cls = null;
                for (let g = 1; g < m.length; g++) {
                    if (m[g] !== undefined) { cls = groupToClass[g]; break; }
                }
                html += '<span class="' + (cls || 'tok-plain') + '">' + escapeHtml(m[0]) + '</span>';
                last = m.index + m[0].length;
                if (m[0].length === 0) tokenRe.lastIndex++; // safety; these regexes never match empty
            }
            if (last < code.length) html += escapeHtml(code.slice(last));
            return html;
        }

        // MATLAB tokenizer (editor overlay). Order matters: comment, string, number, keyword, call.
        const MATLAB_RE = /(%.*$)|('(?:[^']|'')*')|("(?:[^"\\]|\\.)*")|(\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)|(\b(?:function|end|if|else|elseif|for|while|switch|case|otherwise|return|break|continue|classdef|methods|properties|events|try|catch|global|persistent|true|false|inf|nan)\b)|([A-Za-z_]\w*(?=\s*\())/gim;

        function highlightMatlab(code) {
            return tokenizeToHtml(code, MATLAB_RE, {
                1: 'tok-comment',
                2: 'tok-string',
                3: 'tok-string',
                4: 'tok-number',
                5: 'tok-keyword',
                6: 'tok-function'
            });
        }

        // Python tokenizer (result code + markdown fenced blocks).
        const PY_RE = /(#[^\n]*)|('''[\s\S]*?'''|"""[\s\S]*?"""|'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*")|(\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?[jJ]?\b)|(\b(?:def|class|if|elif|else|for|while|return|import|from|as|with|try|except|finally|raise|pass|break|continue|lambda|yield|global|nonlocal|and|or|not|in|is|None|True|False|self|async|await|del|assert)\b)|(@[A-Za-z_]\w*)|([A-Za-z_]\w*(?=\s*\())/g;

        function highlightPython(code) {
            return tokenizeToHtml(code, PY_RE, {
                1: 'tok-comment',
                2: 'tok-string',
                3: 'tok-number',
                4: 'tok-keyword',
                5: 'tok-decorator',
                6: 'tok-function'
            });
        }

        /* ==========================================================================
           MINIMAL MARKDOWN RENDERER (safe: escapes everything first)
           ========================================================================== */

        function inlineMarkdown(text) {
            let s = escapeHtml(text);
            // links — href whitelisted to http/https/mailto/#/relative
            s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, function (match, label, url) {
                let href = url;
                if (!/^(https?:|mailto:|#|\/)/i.test(href)) href = '#';
                return '<a href="' + href + '" target="_blank" rel="noopener noreferrer">' + label + '</a>';
            });
            s = s.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
            s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>');
            s = s.replace(/`([^`\n]+)`/g, '<code class="markdown-inline-code">$1</code>');
            return s;
        }

        function mdToHtml(md) {
            const lines = String(md || '').split(/\r?\n/);
            let html = '';
            let i = 0;
            let inCode = false;
            let codeLang = '';
            let codeLines = [];
            let listType = null;

            const flushList = function () {
                if (listType) { html += '</' + listType + '>'; listType = null; }
            };

            while (i < lines.length) {
                const line = lines[i];

                // Fenced code blocks
                if (/^\s*```/.test(line)) {
                    flushList();
                    if (inCode) {
                        const body = codeLines.join('\n');
                        html += '<pre><code class="markdown-code">' +
                            (/^\s*(python|py)\s*$/i.test(codeLang) ? highlightPython(body) : escapeHtml(body)) +
                            '</code></pre>';
                        inCode = false;
                    } else {
                        inCode = true;
                        codeLang = line.replace(/^\s*```\s*/, '').trim();
                        codeLines = [];
                    }
                    i++;
                    continue;
                }
                if (inCode) { codeLines.push(line); i++; continue; }

                // Headings
                const h = line.match(/^(#{1,6})\s+(.*)$/);
                if (h) {
                    flushList();
                    const lvl = h[1].length;
                    html += '<h' + lvl + '>' + inlineMarkdown(h[2]) + '</h' + lvl + '>';
                    i++;
                    continue;
                }

                // Blockquote
                const bq = line.match(/^\s*>\s?(.*)$/);
                if (bq) {
                    flushList();
                    html += '<blockquote>' + inlineMarkdown(bq[1]) + '</blockquote>';
                    i++;
                    continue;
                }

                // Horizontal rule
                if (/^\s*[-*_]{3,}\s*$/.test(line)) {
                    flushList();
                    html += '<hr>';
                    i++;
                    continue;
                }

                // Lists
                const ul = line.match(/^\s*[-*+]\s+(.*)$/);
                const ol = line.match(/^\s*\d+[.)]\s+(.*)$/);
                if (ul || ol) {
                    const tag = ul ? 'ul' : 'ol';
                    if (listType !== tag) { flushList(); html += '<' + tag + '>'; listType = tag; }
                    html += '<li>' + inlineMarkdown((ul || ol)[1]) + '</li>';
                    i++;
                    continue;
                }

                // Blank line closes any open list
                if (/^\s*$/.test(line)) { flushList(); i++; continue; }

                // Paragraph
                flushList();
                html += '<p>' + inlineMarkdown(line) + '</p>';
                i++;
            }

            flushList();
            if (inCode) html += '<pre><code class="markdown-code">' + escapeHtml(codeLines.join('\n')) + '</code></pre>';
            return html;
        }

        function renderMarkdown(id, md) {
            const container = document.getElementById(id);
            container.innerHTML = '<div class="markdown-body animate-step">' + mdToHtml(md) + '</div>';
        }

        /* ==========================================================================
           STEP ICON MAPPING (server sends Font-Awesome-style names -> sprite ids)
           ========================================================================== */
        const ICON_ALIASES = {
            'fa-microchip': 'microchip', 'fa-cube': 'cube', 'fa-database': 'database',
            'fa-bolt': 'bolt', 'fa-code': 'code', 'fa-terminal': 'terminal',
            'fa-cogs': 'cogs', 'fa-gears': 'cogs', 'fa-robot': 'robot',
            'fa-chart-line': 'chart', 'fa-flask': 'flask', 'fa-network-wired': 'network',
            'fa-atom': 'atom', 'fa-drafting-compass': 'blueprint', 'fa-python': 'python',
            'fa-check': 'check', 'fa-sync': 'sync', 'fa-play': 'play', 'fa-stop': 'stop',
            'fa-circle': 'circle', 'fa-bug': 'bug', 'fa-file': 'file'
        };

        function iconId(icon) {
            if (!icon) return 'microchip';
            const raw = String(icon).trim();
            if (ICON_ALIASES[raw]) return ICON_ALIASES[raw];
            const bare = raw.replace(/^fa[srb]?\s+fa-/, '').replace(/^fa-/, '');
            return ICON_ALIASES['fa-' + bare] || ICON_ALIASES[bare] || 'microchip';
        }

        /* ==========================================================================
           EDITOR: input sync, line numbers, scroll mirroring
           ========================================================================== */

        function handleInput() {
            const input = document.getElementById('source-input');
            const overlay = document.getElementById('highlight-overlay');
            let content = input.value;
            // keep a visible trailing line when the text ends with a newline
            if (content[content.length - 1] === '\n') content += ' ';
            overlay.innerHTML = highlightMatlab(content);
            updateLineNumbers();
            syncScroll();
        }

        function updateLineNumbers() {
            const input = document.getElementById('source-input');
            const count = input.value.split('\n').length;
            let nums = '';
            for (let i = 1; i <= count; i++) nums += i + '<br>';
            document.getElementById('line-numbers').innerHTML = nums;
        }

        function syncScroll() {
            const input = document.getElementById('source-input');
            const overlay = document.getElementById('highlight-overlay');
            const lineNumbers = document.getElementById('line-numbers');
            overlay.scrollTop = input.scrollTop;
            overlay.scrollLeft = input.scrollLeft;
            lineNumbers.scrollTop = input.scrollTop;
        }

        /* ==========================================================================
           WEB SOCKET LIFECYCLE (exponential backoff reconnect, manual-stop aware)
           ========================================================================== */

        function wsUrl() {
            if (location.protocol === 'https:') return 'wss://' + location.host + '/ws';
            if (location.protocol === 'http:') return 'ws://' + location.host + '/ws';
            return WS_FALLBACK_URL; // file:// or unknown origins
        }

        function rememberAccessToken(token) {
            state.accessToken = token;
            try {
                if (token) sessionStorage.setItem(TOKEN_STORAGE_KEY, token);
                else sessionStorage.removeItem(TOKEN_STORAGE_KEY);
            } catch (err) { /* Keep the token in memory if session storage is unavailable. */ }
        }

        function initAccessToken() {
            const fragment = new URLSearchParams(location.hash.slice(1));
            let token = '';
            if (fragment.has('token')) {
                token = (fragment.get('token') || '').trim();
                try {
                    history.replaceState(null, '', location.pathname + location.search);
                } catch (err) {
                    location.hash = '';
                }
            } else {
                try { token = (sessionStorage.getItem(TOKEN_STORAGE_KEY) || '').trim(); }
                catch (err) { /* The connection form remains available. */ }
            }
            rememberAccessToken(token);
        }

        function showAccessPrompt(message, focus) {
            document.getElementById('access-panel').classList.remove('hidden');
            document.getElementById('access-message').textContent = message;
            if (focus) document.getElementById('access-token').focus();
        }

        function submitAccessToken(e) {
            e.preventDefault();
            const input = document.getElementById('access-token');
            const token = input.value.trim();
            if (!token) {
                showAccessPrompt('Paste the access token from the backend startup link.', true);
                return;
            }
            rememberAccessToken(token);
            input.value = '';
            state.authenticationBlocked = false;
            state.manualStop = false;
            state.reconnectAttempts = 0;
            const previousSocket = state.socket;
            state.socket = null;
            if (previousSocket) previousSocket.close();
            showAccessPrompt('Connecting to the backend...');
            connect();
        }

        function clearPendingReconnect() {
            if (state.pendingReconnect) {
                clearTimeout(state.pendingReconnect);
                state.pendingReconnect = null;
            }
        }

        function scheduleReconnect() {
            clearPendingReconnect();
            if (state.authenticationBlocked || !state.accessToken) return;
            const delay = Math.min(RECONNECT_BASE_MS * Math.pow(2, state.reconnectAttempts), RECONNECT_MAX_MS);
            state.reconnectAttempts += 1;
            state.pendingReconnect = setTimeout(function () {
                state.pendingReconnect = null;
                connect();
            }, delay);
        }

        function connect() {
            clearPendingReconnect();
            if (state.socket && state.socket.readyState !== WebSocket.CLOSED) return;
            state.authenticated = false;
            updateConnection(false);
            setRunButtonState(false);
            if (state.authenticationBlocked || !state.accessToken) {
                showAccessPrompt('Open the link printed by the backend, or paste its access token below.');
                return;
            }

            let sock;
            try {
                sock = new WebSocket(wsUrl());
            } catch (err) {
                log('SYSTEM: Failed to open WebSocket.', 'log-err');
                scheduleReconnect();
                return;
            }

            state.socket = sock;
            setRunButtonState(false); // disabled until the backend confirms authentication

            sock.onopen = function () {
                if (state.socket !== sock) return;
                sock.send(JSON.stringify({ type: 'auth', token: state.accessToken }));
            };

            sock.onmessage = function (e) {
                if (state.socket !== sock) return;
                let data;
                try {
                    data = JSON.parse(e.data);
                } catch (err) {
                    log('SYSTEM: Malformed message received.', 'log-err');
                    return;
                }
                if (!data || typeof data !== 'object' || Array.isArray(data)) {
                    log('SYSTEM: Malformed message received.', 'log-err');
                    return;
                }
                if (data.type === 'auth_ok') {
                    if (state.authenticated || state.manualStop || !isSocketOpen()) return;
                    state.authenticated = true;
                    state.reconnectAttempts = 0;
                    state.manualStop = false;
                    document.getElementById('access-panel').classList.add('hidden');
                    updateConnection(true);
                    log('SYSTEM: Authenticated bridge established.', 'log-ok');
                    setRunButtonState(state.isRunning);
                    return;
                }
                if (!state.authenticated || state.manualStop) return;
                handleMessage(data);
            };

            sock.onerror = function () {
                if (state.socket !== sock) return;
                log('SYSTEM: Node sync error detected.', 'log-err');
            };

            sock.onclose = function (e) {
                if (state.socket !== sock) return;
                state.socket = null;
                state.authenticated = false;
                updateConnection(false);
                setRunButtonState(false);
                if (e.code === 1008) {
                    state.authenticationBlocked = true;
                    state.manualStop = false;
                    clearPendingReconnect();
                    rememberAccessToken('');
                    resetUI();
                    showAccessPrompt('Access denied. Open the latest backend startup link, or enter its token again.', true);
                    log('SYSTEM: Access denied. Enter the current backend access token to reconnect.', 'log-err');
                    return;
                }
                if (state.manualStop) {
                    // User pressed Stop: the close was intentional — reconnect quietly.
                    state.manualStop = false;
                    log('SYSTEM: Bridge closed by user. Reconnecting...', 'log-muted');
                    scheduleReconnect();
                    return;
                }
                if (state.isRunning) {
                    // Unexpected drop mid-run: abort the run state so the UI is not stuck.
                    resetUI();
                    log('CRITICAL: Link severed mid-run. Run aborted.', 'log-err');
                } else {
                    log('CRITICAL: Link severed. Attempting reconnect...', 'log-err');
                }
                scheduleReconnect();
            };
        }

        /* ==========================================================================
           RUN / STOP / UI STATE
           ========================================================================== */

        function setRunButtonState(running) {
            const btn = document.getElementById('run-btn');
            const use = document.getElementById('run-icon');
            const label = btn.querySelector('.btn-label');
            btn.disabled = running || !isConnectionReady();
            btn.setAttribute('aria-busy', String(running));
            use.setAttribute('href', running ? '#icon-sync' : '#icon-play');
            use.classList.toggle('icon-spin', running);
            label.textContent = running ? 'Processing...' : 'Run Agent';
        }

        function resetFlow() {
            const container = document.getElementById('flow-container');
            if (!emptyStateProto) {
                emptyStateProto = document.getElementById('empty-state').cloneNode(true);
            }
            container.innerHTML = '';
            const grid = document.createElement('div');
            grid.className = 'flow-grid';
            grid.setAttribute('aria-hidden', 'true');
            const empty = emptyStateProto.cloneNode(true);
            empty.id = 'empty-state';
            container.append(grid, empty);
        }

        function clearTerminal() {
            document.getElementById('terminal-content').innerHTML = '';
        }

        function startPipeline() {
            if (state.isRunning) return;
            if (!isConnectionReady()) {
                log('WARNING: Connect to the backend with its access token before running.', 'log-warn');
                if (!state.socket || state.socket.readyState === WebSocket.CLOSED) scheduleReconnect();
                return;
            }

            const code = document.getElementById('source-input').value;
            if (!code.trim()) {
                log('WARNING: Source stream is empty.', 'log-warn');
                return;
            }

            state.isRunning = true;
            state.manualStop = false;

            resetFlow();
            clearTerminal();
            document.getElementById('code-content').textContent = '# Materializing stream...';

            log('PIPELINE: Initiation detected. Scaling agent parameters...', 'log-accent');
            announce('Run started');

            // Client -> server protocol: exactly { code }
            state.socket.send(JSON.stringify({ code: code }));

            setRunButtonState(true);
            document.getElementById('stop-btn').classList.add('visible');
        }

        function stopPipeline() {
            if (!state.isRunning) return;
            state.isRunning = false;
            state.manualStop = true;
            if (state.socket &&
                (state.socket.readyState === WebSocket.OPEN || state.socket.readyState === WebSocket.CONNECTING)) {
                state.socket.close();
            }
            log('TERMINATION: Stop requested. Closing the connection cancels the backend run.', 'log-danger');
            announce('Run stopped by user');
            resetUI();
        }

        function resetUI() {
            state.isRunning = false;
            setRunButtonState(false);
            document.getElementById('stop-btn').classList.remove('visible');
            announce('Run finished');
        }

        /* ==========================================================================
           MESSAGE HANDLING (protocol fields are load-bearing — do not rename)
           Server -> client messages carry exactly:
           { type, title, message, step_id, extra_data, is_success, icon }
           ========================================================================== */

        function logLine(title, message) {
            let cls = 'log-muted';
            const lower = String(message || '').toLowerCase();
            const t = String(title || '').toUpperCase();
            if (t === 'PERF') cls = 'log-accent';
            else if (t === 'ERR' || t === 'FATAL' || t === 'FAIL' ||
                lower.indexOf('failed') !== -1 || lower.indexOf('error') !== -1) cls = 'log-err';
            else if (lower.indexOf('success') !== -1 || lower.indexOf('passed') !== -1 ||
                lower.indexOf('done') !== -1) cls = 'log-ok';
            else if (lower.indexOf('warning') !== -1) cls = 'log-warn';
            else if (lower.indexOf('pipeline') !== -1 || lower.indexOf('system') !== -1) cls = 'log-accent';
            log('[' + title + '] ' + message, cls);
        }

        function handleMessage(data) {
            const { type, title, message, step_id, is_success, extra_data } = data;

            if (type === 'fatal') {
                resetUI();
                logLine(title || 'FATAL', message);
                announce('Run failed');
                return;
            }

            if (type === 'log') {
                logLine(title, message);
                return;
            }

            if (type === 'step_start') {
                if (step_id === 'selector') updateStep('tournament', true, 'Synchronization locked.');
                addStep(step_id, title, message, data.icon || 'fa-microchip', step_id === 'tournament');
                return;
            }

            if (type === 'step_done') {
                const ok = (is_success !== false);
                updateStep(step_id, ok, message, extra_data);
                if (step_id === 'finish' || title === 'Success' || title === 'Failed') {
                    resetUI();
                    log('PIPELINE: Terminal state reached.', ok ? 'log-ok' : 'log-danger');
                }
                return;
            }

            if (type === 'result_ir') {
                renderMarkdown('view-ir', message);
                switchTab('ir');
                return;
            }

            if (type === 'result_blueprint') {
                renderMarkdown('view-blueprint', message);
                switchTab('blueprint');
                return;
            }

            if (type === 'result_code') {
                const el = document.getElementById('code-content');
                el.textContent = message;
                el.innerHTML = highlightPython(el.textContent);
                switchTab('code');
                return;
            }

            log('SYSTEM: Unhandled message type "' + type + '".', 'log-muted');
        }

        /* ==========================================================================
           STEP CARDS (flow rendering)
           ========================================================================== */

        function addStep(id, title, desc, icon, isHighlight) {
            const empty = document.getElementById('empty-state');
            if (empty) {
                empty.classList.add('faded');
                setTimeout(function () { empty.classList.add('hidden'); }, 400);
            }
            const tpl = document.getElementById('step-template');
            const clone = tpl.content.cloneNode(true);
            const el = clone.querySelector('.step-item');
            el.id = 'step-' + id;
            el.querySelector('.step-title').textContent = title;
            el.querySelector('.step-desc').textContent = desc;
            const statusIcon = el.querySelector('.status-icon');
            statusIcon.querySelector('use').setAttribute('href', '#icon-' + iconId(icon));
            statusIcon.classList.toggle('icon-spin', !!isHighlight);
            document.getElementById('flow-container').appendChild(el);
            scrollToBottom('flow-container');
        }

        function updateStep(id, success, desc, extra) {
            const el = document.getElementById('step-' + id);
            if (!el) return;
            const icon = el.querySelector('.status-icon');
            const bg = el.querySelector('.status-bg');
            const tag = el.querySelector('.step-tag');
            icon.classList.remove('icon-spin');
            if (success) {
                icon.querySelector('use').setAttribute('href', '#icon-check');
                icon.classList.remove('fail');
                icon.classList.add('ok');
                bg.classList.remove('fail');
                bg.classList.add('ok');
                tag.textContent = 'SUCCESS';
                tag.className = 'step-tag tag-ok';
            } else {
                icon.querySelector('use').setAttribute('href', '#icon-bolt');
                icon.classList.remove('ok');
                icon.classList.add('fail');
                bg.classList.remove('ok');
                bg.classList.add('fail');
                tag.textContent = 'FAILED';
                tag.className = 'step-tag tag-fail';
            }
            if (desc) el.querySelector('.step-desc').textContent = desc;
        }

        /* ==========================================================================
           TERMINAL LOGGING (XSS-safe via textContent, capped at MAX_LOG_LINES)
           ========================================================================== */

        function log(msg, cls) {
            const box = document.getElementById('terminal-content');
            const time = new Date().toLocaleTimeString('en-US', { hour12: false });

            const div = document.createElement('div');
            div.className = 'log-line';

            const timeSpan = document.createElement('span');
            timeSpan.className = 'log-time';
            timeSpan.textContent = '[' + time + ']';

            const msgSpan = document.createElement('span');
            msgSpan.className = cls || '';
            msgSpan.textContent = msg;

            div.append(timeSpan, msgSpan);
            box.appendChild(div);

            // Cap log lines so the DOM never freezes on long runs.
            while (box.children.length > MAX_LOG_LINES) {
                box.removeChild(box.firstChild);
            }

            scrollToBottom('terminal-content');
        }

        /* ==========================================================================
           TABS & VIEWS
           ========================================================================== */

        function switchTab(t) {
            activeTab = t;
            ['code', 'blueprint', 'ir'].forEach(function (k) {
                const view = document.getElementById('view-' + k);
                const tab = document.getElementById('tab-' + k);
                view.classList.toggle('hidden', k !== t);
                tab.classList.toggle('tab-active', k === t);
                tab.setAttribute('aria-selected', String(k === t));
                tab.tabIndex = k === t ? 0 : -1;
            });
        }

        /* ==========================================================================
           CONNECTION BADGE + THEME
           ========================================================================== */

        function updateConnection(ok) {
            const dot = document.getElementById('connection-dot');
            const text = document.getElementById('connection-text');
            dot.classList.toggle('on', ok);
            text.classList.toggle('on', ok);
            text.textContent = ok ? 'Link-Active' : 'Link-Inactive';
            announce(ok ? 'Connection active' : 'Connection lost');
        }

        function toggleTheme() {
            const root = document.documentElement;
            const next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
            root.setAttribute('data-theme', next);
            document.getElementById('theme-icon').setAttribute('href', next === 'dark' ? '#icon-moon' : '#icon-sun');
            try { localStorage.setItem('evococo-theme', next); } catch (e) { /* ignore */ }
        }

        function initTheme() {
            const root = document.documentElement;
            const theme = root.getAttribute('data-theme') || 'dark';
            document.getElementById('theme-icon').setAttribute('href', theme === 'dark' ? '#icon-moon' : '#icon-sun');
        }

        /* ==========================================================================
           COPY (clipboard API with execCommand fallback for file:// contexts)
           ========================================================================== */

        function copyCurrentTab() {
            let content = '';
            const viewCode = document.getElementById('view-code');
            const viewBp = document.getElementById('view-blueprint');
            const viewIr = document.getElementById('view-ir');
            if (!viewCode.classList.contains('hidden')) content = document.getElementById('code-content').textContent;
            else if (!viewBp.classList.contains('hidden')) content = viewBp.innerText;
            else content = viewIr.innerText;
            if (!content) return;

            const flash = function (ok) {
                const btn = document.getElementById('copy-btn');
                const icon = document.getElementById('copy-icon');
                icon.setAttribute('href', ok ? '#icon-check' : '#icon-copy');
                btn.classList.toggle('ok', ok);
                btn.classList.toggle('fail', !ok);
                setTimeout(function () {
                    icon.setAttribute('href', '#icon-copy');
                    btn.classList.remove('ok', 'fail');
                }, 1500);
            };

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(content).then(function () { flash(true); })
                    .catch(function () { flash(fallbackCopy(content)); });
            } else {
                flash(fallbackCopy(content));
            }
        }

        // Returns true if the copy succeeded.
        function fallbackCopy(text) {
            const ta = document.createElement('textarea');
            ta.value = text;
            ta.setAttribute('readonly', '');
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            let ok = false;
            try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
            document.body.removeChild(ta);
            return ok;
        }

        /* ==========================================================================
           RESIZERS (drag + keyboard accessible)
           ========================================================================== */

        function initResizers() {
            const makeResizable = function (resizer, onResize, dir) {
                let startPos = 0;

                const startDrag = function (e) {
                    e.preventDefault();
                    startPos = dir === 'col' ? e.clientX : e.clientY;
                    resizer.classList.add('resizing');
                    document.body.style.userSelect = 'none';

                    const onMove = function (me) {
                        const delta = (dir === 'col' ? me.clientX : me.clientY) - startPos;
                        onResize(delta);
                        startPos = dir === 'col' ? me.clientX : me.clientY;
                    };
                    const onUp = function () {
                        resizer.classList.remove('resizing');
                        document.body.style.userSelect = '';
                        document.removeEventListener('mousemove', onMove);
                        document.removeEventListener('mouseup', onUp);
                    };
                    document.addEventListener('mousemove', onMove);
                    document.addEventListener('mouseup', onUp);
                };

                resizer.addEventListener('mousedown', startDrag);

                // Keyboard support (role="separator"): arrows resize by 10px (40px with Shift).
                resizer.addEventListener('keydown', function (e) {
                    const step = e.shiftKey ? 40 : 10;
                    let delta = 0;
                    if (dir === 'col' && e.key === 'ArrowLeft') delta = -step;
                    else if (dir === 'col' && e.key === 'ArrowRight') delta = step;
                    else if (dir === 'row' && e.key === 'ArrowUp') delta = -step;
                    else if (dir === 'row' && e.key === 'ArrowDown') delta = step;
                    if (delta) {
                        e.preventDefault();
                        onResize(delta);
                    }
                });
            };

            makeResizable(document.getElementById('resizer-left'), function (d) {
                const el = document.getElementById('panel-left');
                const w = el.offsetWidth + d;
                if (w > 250 && w < window.innerWidth - 400) el.style.width = w + 'px';
            }, 'col');

            makeResizable(document.getElementById('resizer-right'), function (d) {
                const el = document.getElementById('panel-middle');
                const w = el.offsetWidth + d;
                if (w > 250 && w < window.innerWidth - 600) el.style.width = w + 'px';
            }, 'col');

            makeResizable(document.getElementById('resizer-middle'), function (d) {
                const el = document.getElementById('panel-middle-top');
                const h = el.offsetHeight + d;
                if (h > 100 && h < window.innerHeight - 200) el.style.height = h + 'px';
            }, 'row');
        }

        /* ==========================================================================
           EVENT BINDING & INIT
           ========================================================================== */

        function bindEvents() {
            const input = document.getElementById('source-input');
            input.addEventListener('input', handleInput);
            input.addEventListener('scroll', syncScroll);
            input.addEventListener('keydown', function (e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    e.preventDefault();
                    startPipeline();
                }
            });

            document.getElementById('run-btn').addEventListener('click', startPipeline);
            document.getElementById('stop-btn').addEventListener('click', stopPipeline);
            document.getElementById('theme-btn').addEventListener('click', toggleTheme);
            document.getElementById('copy-btn').addEventListener('click', copyCurrentTab);
            document.getElementById('clear-logs-btn').addEventListener('click', clearTerminal);
            document.getElementById('access-form').addEventListener('submit', submitAccessToken);

            ['code', 'blueprint', 'ir'].forEach(function (tab) {
                document.getElementById('tab-' + tab).addEventListener('click', function () {
                    switchTab(tab);
                });
            });

            // Arrow-key navigation between tabs
            const tablist = document.getElementById('tablist');
            tablist.addEventListener('keydown', function (e) {
                const tabs = ['code', 'blueprint', 'ir'];
                const idx = tabs.indexOf(activeTab);
                let next = null;
                if (e.key === 'ArrowRight') next = tabs[(idx + 1) % tabs.length];
                else if (e.key === 'ArrowLeft') next = tabs[(idx - 1 + tabs.length) % tabs.length];
                if (next) {
                    e.preventDefault();
                    switchTab(next);
                    document.getElementById('tab-' + next).focus();
                }
            });
        }

        function init() {
            initTheme();
            document.getElementById('source-input').value = initialScript;
            handleInput();
            initResizers();
            bindEvents();
            switchTab('code');
            initAccessToken();
            connect();
        }

        document.addEventListener('DOMContentLoaded', init);

        /* ==========================================================================
           INITIAL SCRIPT (verbatim MATLAB seed content)
           ========================================================================== */
        const initialScript = `classdef NSGAIISDR < ALGORITHM
% <2019> <many> <real/integer/label/binary/permutation>
% NSGA-II with strengthened dominance relation

    methods
        function main(Algorithm,Problem)
            %% Initialization: Create initial population
            Population = Problem.Initialization();
            zmin       = min(Population.objs,[],1);
            zmax       = max(Population.objs,[],1);
            [~,FrontNo,CrowdDis] = EnvironmentalSelection(Population,Problem.N,zmin,zmax);

            %% Optimization Loop
            while Algorithm.NotTerminated(Population)
                MatingPool = TournamentSelection(2,Problem.N,FrontNo,-CrowdDis);
                Offspring  = OperatorGA(Problem,Population(MatingPool));
                zmin       = min([zmin;Offspring.objs],[],1);
                zmax       = max(Population(FrontNo==1).objs,[],1);
                [Population,FrontNo,CrowdDis] = EnvironmentalSelection([Population,Offspring],Problem.N,zmin,zmax);
            end
        end
    end
end

function [FrontNo,MaxFNo] = NDSort_SDR(PopObj,nSort)
% Non-dominated sorting based on SDR
    N      = size(PopObj,1);
    NormP  = sum(PopObj,2);
    cosine = 1 - pdist2(PopObj,PopObj,'cosine');
    cosine(logical(eye(length(cosine)))) = 0;
    Angle  = acos(cosine);

    temp  = sort(unique(min(Angle,[],2)));
    minA  = temp(min(ceil(N/2),end));
    Theta = max(1,(Angle./minA).^1);

    dominate = false(N);
    for i = 1 : N-1
        for j = i+1 : N
            if NormP(i)*Theta(i,j) < NormP(j)
                dominate(i,j) = true;
            elseif NormP(j)*Theta(j,i) < NormP(i)
                dominate(j,i) = true;
            end
        end
    end

    FrontNo = inf(1,N);
    MaxFNo  = 0;
    while sum(FrontNo~=inf) < min(nSort,N)
        MaxFNo  = MaxFNo + 1;
        current = ~any(dominate,1) & FrontNo==inf;
        FrontNo(current)    = MaxFNo;
        dominate(current,:) = false;
    end
end

function [Population,FrontNo,CrowdDis] = EnvironmentalSelection(Population,N,zmin,zmax)
% Selection logic for NSGA-II
    %% Normalize Objective values
    PopObj = Population.objs - repmat(zmin,length(Population),1);
    range  = zmax - zmin;
    if 0.05*max(range) < min(range)
        PopObj = PopObj./repmat(range,length(Population),1);
    end
    [~,x]      = unique(round(PopObj*1e6)/1e6,'rows');
    PopObj     = PopObj(x,:);
    Population = Population(x);
    N          = min(N,length(Population));

    %% Ranking via Sorting
    [FrontNo,MaxFNo] = NDSort_SDR(PopObj,N);
    Next = FrontNo < MaxFNo;

    %% Density Calculations
    CrowdDis = CrowdingDistance(PopObj,FrontNo);

    %% Finalize next population
    Last     = find(FrontNo==MaxFNo);
    [~,Rank] = sort(CrowdDis(Last),'descend');
    Next(Last(Rank(1:N-sum(Next)))) = true;

    Population = Population(Next);
    FrontNo    = FrontNo(Next);
    CrowdDis   = CrowdDis(Next);
end`;
    </script>
</body>

</html>