<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PMC Sales System</title>
    <!-- Tailwind CSS CDN for styling -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Google Fonts - Inter for general text, Share Tech Mono for calculator-ish numbers -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Share+Tech+Mono&display=swap" rel="stylesheet">
    <style>
        /* Apply Inter font, remove background for floating module */
        body {
            font-family: 'Inter', sans-serif;
            margin: 0;
            overflow: hidden; /* Prevent scrollbars if content overflows */
        }

        /* Custom styles for the main orb container */
        .orb-container {
            background-color: rgba(29, 35, 42, 0.8); /* Semi-transparent dark for frosted glass effect */
            backdrop-filter: blur(10px); /* Apply blur for the frosted glass effect */
            border: 1px solid rgba(50, 60, 70, 0.5); /* Subtle border */
            position: fixed; /* Makes the orb float relative to the viewport */
            top: 50%; /* Center vertically */
            left: 50%; /* Center horizontally */
            transform: translate(-50%, -50%); /* Adjust for exact centering */
            z-index: 1000; /* Ensure it stays on top of other content */
            transition: all 0.3s ease-in-out; /* Smooth transition for show/hide */
            border-radius: 0.5rem; /* Less rounded corners (tailwind rounded-md) */
            animation: subtle-pulse 5s infinite ease-in-out; /* Subtle pulse animation */
        }

        /* Subtle pulse animation for the orb container */
        @keyframes subtle-pulse {
            0% { transform: translate(-50%, -50%) scale(1); box-shadow: 0 0 10px rgba(0, 255, 255, 0.05); }
            50% { transform: translate(-50%, -50%) scale(1.005); box-shadow: 0 0 20px rgba(0, 255, 255, 0.1); }
            100% { transform: translate(-50%, -50%) scale(1); box-shadow: 0 0 10px rgba(0, 255, 255, 0.05); }
        }

        /* Class to hide the orb with a transformation */
        .orb-container.hidden {
            transform: translate(-50%, -50%) scale(0.5); /* Shrink and fade out from center */
            opacity: 0; /* Fade out */
            pointer-events: none; /* Disable interactions when hidden */
        }

        /* Calculator-ish font for specific elements */
        .tech-mono-font {
            font-family: 'Share Tech Mono', monospace;
        }

        /* Subtle text glow for status indicators */
        .status-indicator-text {
            animation: text-glow 3s infinite alternate ease-in-out;
        }

        @keyframes text-glow {
            0% { text-shadow: 0 0 5px rgba(255, 255, 255, 0.2); }
            100% { text-shadow: 0 0 10px rgba(255, 255, 255, 0.4); }
        }


        /* Smooth transition for progress bar fills */
        .progress-bar-inner {
            transition: width 0.5s ease-out;
            position: relative; /* For the pseudo-element light effect */
            overflow: hidden; /* To contain the swoosh effect */
        }

        /* Light swoosh effect for progress bars - always running */
        .progress-bar-inner::after {
            content: '';
            position: absolute;
            top: 0;
            width: 100%; /* Width of the swoosh */
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); /* Subtle light glare */
            animation: swoosh-ltr 1.5s infinite linear; /* Default LTR animation */
            animation-play-state: running; /* Always running */
        }

        /* RTL specific swoosh animation */
        .progress-bar-inner.rtl::after {
            animation: swoosh-rtl 1.5s infinite linear;
        }

        @keyframes swoosh-ltr {
            0% { left: -100%; }
            100% { left: 100%; } /* Move across the bar LTR */
        }

        @keyframes swoosh-rtl {
            0% { right: -100%; }
            100% { right: 100%; } /* Move across the bar RTL */
        }


        /* Styles for the custom message box overlay (replaces alert()) */
        .message-box-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6); /* Dark semi-transparent background */
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000; /* Ensure it's above everything */
            opacity: 0; /* Initially hidden */
            pointer-events: none; /* Disable interactions when hidden */
            transition: opacity 0.3s ease-in-out; /* Smooth fade in/out */
        }

        /* Class to make the message box visible */
        .message-box-overlay.visible {
            opacity: 1;
            pointer-events: auto; /* Enable interactions when visible */
        }

        /* Styles for the message box content (glassy look) */
        .message-box {
            background-color: rgba(29, 35, 42, 0.9); /* Semi-transparent dark */
            backdrop-filter: blur(15px); /* Stronger blur for glass effect */
            border: 1px solid rgba(74, 85, 104, 0.6); /* Subtle border */
            border-radius: 0.5rem; /* Less rounded corners */
            padding: 1.5rem;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.4); /* Deeper shadow */
            text-align: center;
            max-width: 400px;
            color: #e2e8f0; /* Light text color */
        }

        /* Styles for the message box buttons container */
        .message-box-buttons {
            display: flex;
            justify-content: center;
            gap: 1rem; /* Space between buttons */
            margin-top: 1rem;
        }

        /* Styles for the message box buttons */
        .message-box button {
            background-color: #4299e1; /* Blue button */
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            cursor: pointer;
            transition: background-color 0.2s; /* Smooth hover effect */
        }

        .message-box button:hover {
            background-color: #3182ce; /* Darker blue on hover */
        }

        /* Style for the cancel button */
        .message-box button.cancel-btn {
            background-color: #6b7280; /* Gray for cancel */
        }

        .message-box button.cancel-btn:hover {
            background-color: #4b5563; /* Darker gray on hover */
        }

        /* Animations for data readout rows */
        .animated-row {
            opacity: 0;
            animation-fill-mode: forwards; /* Keep the end state of the animation */
        }

        .animated-row.slide-in-left {
            transform: translateX(-50px); /* Initial position for left-to-right */
            animation: slideInLeft 0.5s ease-out forwards;
        }

        .animated-row.slide-in-right {
            transform: translateX(50px); /* Initial position for right-to-left */
            animation: slideInRight 0.5s ease-out forwards;
        }

        @keyframes slideInLeft {
            from {
                opacity: 0;
                transform: translateX(-50px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(50px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        /* Mini-graph placeholder styles */
        .mini-graph {
            width: 40px;
            height: 12px;
            background: linear-gradient(to right, #10b981, #065f46); /* Green gradient */
            border-radius: 2px;
            overflow: hidden;
            position: relative;
        }

        .mini-graph::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transform: translateX(-100%);
            animation: graph-swoosh 2s infinite linear;
        }

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

        /* Tab Navigation Buttons - Cool Looking */
        .tab-button {
            flex: 1; /* Distribute space evenly */
            padding: 0.75rem 0.5rem; /* Increased padding */
            border-radius: 0.5rem;
            cursor: pointer;
            font-weight: 600; /* Bolder font */
            color: #9ca3af; /* gray-400 */
            background-image: linear-gradient(to bottom, #2d3748, #1a202c); /* Subtle dark gradient */
            border: 1px solid #4a5568; /* Solid border */
            transition: all 0.3s ease-in-out;
            position: relative;
            overflow: hidden;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .tab-button:hover {
            color: #e5e7eb; /* lighter gray on hover */
            background-image: linear-gradient(to bottom, #3a475a, #232a36); /* Slightly lighter gradient */
            border-color: #60a5fa; /* Blue glow on hover */
            box-shadow: 0 0 15px rgba(96, 165, 250, 0.4); /* Stronger blue glow */
            transform: translateY(-1px);
        }

        .tab-button.active {
            background-image: linear-gradient(to bottom, #06b6d4, #0891b2); /* Cyan gradient for active */
            color: #ffffff; /* White text for active */
            border-color: #06b6d4; /* Cyan border */
            box-shadow: 0 0 20px rgba(6, 182, 212, 0.6), inset 0 0 10px rgba(6, 182, 212, 0.3); /* Stronger cyan glow */
            transform: translateY(-2px);
        }

        /* Optional: Add a subtle animated border on hover/active */
        .tab-button::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 0.5rem;
            border: 2px solid transparent;
            transition: all 0.3s ease-in-out;
            pointer-events: none;
            z-index: 0;
        }

        .tab-button:hover::before {
            border-color: rgba(96, 165, 250, 0.7); /* Blue border pulse */
            animation: border-pulse 1.5s infinite alternate;
        }

        @keyframes border-pulse {
            0% { transform: scale(1); opacity: 1; }
            100% { transform: scale(1.02); opacity: 0.8; }
        }
        #diagnosticOrb {
          display: none;
        }
        #diagnosticOrb.active {
          display: flex !important;
        }
        #devPasswordModalOverlay {
          display: none;
        }
        #devPasswordModalOverlay.active {
          display: flex !important;
        }
    </style>
</head>
<body class="dark">
    <!-- The PMC Sales System Diagnostic Orb Container -->
    <div id="diagnosticOrb" class="orb-container rounded-md p-4 w-80 md:w-96 flex flex-col gap-4">
        <h2 class="text-xl font-bold text-cyan-400 text-center mb-2">PMC Sales System</h2>

        <!-- Global System Info -->
        <div class="flex flex-col gap-1 text-xs text-gray-400 border-b border-gray-700 pb-2 mb-2">
            <div class="flex items-center justify-between">
                <span>Public IP:</span>
                <span id="publicIP" class="tech-mono-font text-gray-300">Fetching...</span>
            </div>
            <div class="flex items-center justify-between">
                <span>Current Time:</span>
                <span id="currentTime" class="tech-mono-font text-gray-300">Loading...</span>
            </div>
        </div>

        <!-- Tab Navigation -->
        <div class="flex justify-around bg-gray-800 rounded-md p-1 mb-2">
            <button id="tabOverview" class="tab-button active">Overview</button>
            <button id="tabNetworkDeepDive" class="tab-button">Network Deep Dive</button>
            <button id="tabSystemCore" class="tab-button">System Core</button>
        </div>

        <!-- Tab Content Containers -->
        <div id="tabContentOverview" class="tab-content">
            <!-- Top Status Indicators Section -->
            <div class="flex flex-col gap-2 text-sm text-gray-300">
                <div class="flex items-center justify-between">
                    <span>Loading Elements:</span>
                    <span id="elementsLoaded" class="font-semibold text-emerald-400 status-indicator-text tech-mono-font">0/0</span>
                </div>
                <div class="flex items-center justify-between">
                    <span>Environment Scan:</span>
                    <span id="envScanStatus" class="font-semibold text-yellow-400 status-indicator-text">Active</span>
                </div>
                <div class="flex items-center justify-between">
                    <span>Network Status:</span>
                    <span id="networkStatus" class="font-semibold text-blue-400 status-indicator-text">Stable (Ping: --ms)</span>
                    <span id="pingRating" class="ml-2"></span>
                </div>
            </div>

            <!-- Central Animation & Progress Bars Section -->
            <div class="flex gap-4 items-start mt-4">
                <!-- Central Circuit Board Animation Canvas -->
                <div class="flex-shrink-0 w-24 h-24 bg-gray-800 rounded-lg flex items-center justify-center overflow-hidden relative">
                    <canvas id="circuitBoardCanvas" width="96" height="96" class="absolute inset-0"></canvas>
                    <div class="absolute text-xs text-gray-500">Processing...</div>
                </div>

                <!-- Seven Progress Bars -->
                <div class="flex-grow flex flex-col gap-2">
                    <!-- Each progress bar consists of a label and a filled bar -->
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">App Init</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressAppInit" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Assets</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressAssets" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Data Sync</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressDataSync" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Env Check</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressEnvCheck" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Net Secure</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressNetSecure" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Server Rsp</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressServerRsp" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="progress-item">
                        <div class="text-xs text-gray-400 mb-1">Render View</div>
                        <div class="w-full bg-gray-700 rounded-full h-2">
                            <div id="progressRenderView" class="progress-bar-inner h-full rounded-full" style="width: 0%;"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Detailed Data Readouts Section -->
            <div id="dataReadoutsOverview" class="flex flex-col gap-2 text-xs text-gray-400 border-t border-gray-700 pt-3 mt-3">
                <div class="flex items-center justify-between animated-row">
                    <span>Server IP:</span>
                    <span id="serverIP" class="tech-mono-font text-gray-300">192.168.1.1</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Server Region:</span>
                    <span id="serverRegion" class="font-semibold text-gray-300">Eldoret, KE</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Server Node:</span>
                    <span id="serverNode" class="font-semibold text-gray-300">API-Cluster-03</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Location:</span>
                    <span id="location" class="font-semibold text-gray-300">Eldoret, Kenya</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Lat/Long:</span>
                    <span id="latLong" class="tech-mono-font text-gray-300">-0.51°N, 35.26°E</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Load Time:</span>
                    <span id="loadTime" class="tech-mono-font text-gray-300">0.00s</span>
                    <span id="loadTimeRating" class="ml-2"></span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>TTFB:</span>
                    <span id="ttfb" class="tech-mono-font text-gray-300">0.00s</span>
                    <span id="ttfbRating" class="ml-2"></span>
                </div>
            </div>
        </div>

        <div id="tabContentNetworkDeepDive" class="tab-content hidden">
            <h3 class="text-md font-bold text-gray-200 mb-2 text-center">Network Deep Dive</h3>
            <div id="dataReadoutsNetworkDeepDive" class="flex flex-col gap-2 text-xs text-gray-400">
                <div class="flex items-center justify-between animated-row">
                    <span>Data Timestamp:</span>
                    <span id="dataTimestamp" class="tech-mono-font text-gray-300"></span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>DNS Lookup:</span>
                    <span id="dnsLookup" class="tech-mono-font text-gray-300">0ms</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>TCP Handshake:</span>
                    <span id="tcpHandshake" class="tech-mono-font text-gray-300">0ms</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Request Start:</span>
                    <span id="requestStart" class="tech-mono-font text-gray-300">0ms</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Response End:</span>
                    <span id="responseEnd" class="tech-mono-font text-gray-300">0ms</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>DOM Interactive:</span>
                    <span id="domInteractive" class="tech-mono-font text-gray-300">0ms</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>DOM Complete:</span>
                    <span id="domComplete" class="tech-mono-font text-gray-300">0ms</span>
                </div>
            </div>
        </div>

        <div id="tabContentSystemCore" class="tab-content hidden">
            <h3 class="text-md font-bold text-gray-200 mb-2 text-center">System Core</h3>
            <div id="dataReadoutsSystemCore" class="flex flex-col gap-2 text-xs text-gray-400">
                <div class="flex items-center justify-between animated-row">
                    <span>CPU Usage:</span>
                    <span id="cpuUsage" class="tech-mono-font text-gray-300">0%</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Memory Usage:</span>
                    <span id="memoryUsage" class="tech-mono-font text-gray-300">0MB</span>
                    <div class="mini-graph"></div>
                </div>
                 <div class="flex items-center justify-between animated-row">
                    <span>Disk Read:</span>
                    <span id="diskRead" class="tech-mono-font text-gray-300">0 KB/s</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Disk Write:</span>
                    <span id="diskWrite" class="tech-mono-font text-gray-300">0 KB/s</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Net Upload:</span>
                    <span id="netUpload" class="tech-mono-font text-gray-300">0 KB/s</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Net Download:</span>
                    <span id="netDownload" class="tech-mono-font text-gray-300">0 KB/s</span>
                    <div class="mini-graph"></div>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>Process Count:</span>
                    <span id="processCount" class="tech-mono-font text-gray-300">0</span>
                </div>
                <div class="flex items-center justify-between animated-row">
                    <span>System Uptime:</span>
                    <span id="systemUptime" class="tech-mono-font text-gray-300">0h 0m 0s</span>
                </div>
                <div class="flex flex-col gap-1 animated-row">
                    <span>System Log:</span>
                    <div id="systemLog" class="bg-gray-900 p-2 rounded-md h-24 overflow-y-auto text-gray-500 tech-mono-font text-xs">
                        <!-- Log entries will appear here -->
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- Custom Message Box Overlay (for alerts and password prompts) -->
    <div id="messageBoxOverlay" class="message-box-overlay">
        <div class="message-box">
            <p id="messageBoxText" class="text-lg mb-4"></p>
            <input type="password" id="passwordInput" class="hidden w-full p-2 mb-4 bg-gray-700 text-white rounded-md border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Enter password">
            <div class="message-box-buttons">
                <button id="messageBoxCloseBtn">OK</button>
                <button id="messageBoxCancelBtn" class="cancel-btn">Cancel</button>
            </div>
        </div>
    </div>

    <!-- Password Modal -->
    <div id="devPasswordModalOverlay">
      <div id="devPasswordModal">
        <button class="close-btn" onclick="closeDevPasswordModal()">&times;</button>
        <h3>Developer Access</h3>
        <div id="devPasswordError" class="error" style="display:none;"></div>
        <input type="password" id="devPasswordInput" placeholder="Enter password..." autocomplete="off" />
        <button onclick="submitDevPassword()">Enter</button>
      </div>
    </div>

    <script>
        /**
         * Utility function to display a custom message box or password prompt.
         * @param {string} message - The message to display.
         * @param {boolean} isPasswordPrompt - If true, shows password input.
         * @param {function(string): void} [callback] - Callback for password submission.
         */
        function showMessageBox(message, isPasswordPrompt = false, callback = null) {
            const overlay = document.getElementById('messageBoxOverlay');
            const messageText = document.getElementById('messageBoxText');
            const passwordInput = document.getElementById('passwordInput');
            const submitBtn = document.getElementById('messageBoxCloseBtn'); // Renamed for clarity
            const cancelBtn = document.getElementById('messageBoxCancelBtn');

            messageText.innerHTML = message;
            passwordInput.value = ''; // Clear previous input

            // Reset button event listeners to prevent multiple bindings
            submitBtn.onclick = null;
            cancelBtn.onclick = null;

            if (isPasswordPrompt) {
                passwordInput.classList.remove('hidden');
                cancelBtn.classList.remove('hidden'); // Show cancel button
                passwordInput.focus();
                submitBtn.textContent = 'Submit';

                submitBtn.onclick = () => {
                    if (callback) {
                        callback(passwordInput.value);
                    }
                    overlay.classList.remove('visible');
                    passwordInput.classList.add('hidden');
                    cancelBtn.classList.add('hidden'); // Hide cancel button
                };

                cancelBtn.onclick = () => {
                    overlay.classList.remove('visible');
                    passwordInput.classList.add('hidden');
                    cancelBtn.classList.add('hidden'); // Hide cancel button
                };

            } else {
                passwordInput.classList.add('hidden');
                cancelBtn.classList.add('hidden'); // Ensure cancel button is hidden
                submitBtn.textContent = 'OK';
                submitBtn.onclick = () => overlay.classList.remove('visible');
            }
            overlay.classList.add('visible');
        }

        // --- Orb Visibility Logic (always visible by default) ---
        const diagnosticOrb = document.getElementById('diagnosticOrb');

        // --- Central Circuit Board Animation on Canvas ---
        const circuitCanvas = document.getElementById('circuitBoardCanvas');
        const ctx = circuitCanvas.getContext('2d');
        let animationFrameId; // To store the requestAnimationFrame ID for potential cancellation

        // Configuration for the circuit board animation
        const nodes = [];
        const numNodes = 10; // Number of animated nodes
        const nodeRadius = 2; // Radius of each node
        const lineColor = 'rgba(0, 255, 255, 0.3)'; // Cyan lines connecting nodes
        const nodeColor = 'rgba(0, 255, 255, 0.8)'; // Brighter cyan nodes
        const pulseColor = 'rgba(0, 255, 255, 0.1)'; // Fainter outer pulse around nodes

        // Initialize nodes with random positions and velocities
        for (let i = 0; i < numNodes; i++) {
            nodes.push({
                x: Math.random() * circuitCanvas.width,
                y: Math.random() * circuitCanvas.height,
                vx: (Math.random() - 0.5) * 0.5, // Random velocity in x direction
                vy: (Math.random() - 0.5) * 0.5, // Random velocity in y direction
                pulse: Math.random() * (2 * Math.PI) // Initial pulse phase
            });
        }

        /**
         * Animates the circuit board on the dedicated canvas.
         * Draws nodes, connections, and pulsing effects.
         */
        function animateCircuitBoard() {
            ctx.clearRect(0, 0, circuitCanvas.width, circuitCanvas.height); // Clear the canvas for redrawing

            // Draw connections between nearby nodes
            for (let i = 0; i < numNodes; i++) {
                for (let j = i + 1; j < numNodes; j++) {
                    // Calculate distance between nodes
                    const dist = Math.sqrt(Math.pow(nodes[i].x - nodes[j].x, 2) + Math.pow(nodes[i].y - nodes[j].y, 2));
                    if (dist < 50) { // Connect nodes if they are within a certain distance
                        ctx.beginPath();
                        ctx.moveTo(nodes[i].x, nodes[i].y);
                        ctx.lineTo(nodes[j].x, nodes[j].y);
                        ctx.strokeStyle = lineColor;
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                }
            }

            // Draw and update each node's position and pulse
            for (let i = 0; i < numNodes; i++) {
                const node = nodes[i];

                // Update node position based on velocity
                node.x += node.vx;
                node.y += node.vy;

                // Reverse velocity if node hits canvas edges (bounce effect)
                if (node.x < 0 || node.x > circuitCanvas.width) node.vx *= -1;
                if (node.y < 0 || node.y > circuitCanvas.height) node.vy *= -1;

                // Update pulse phase for animation
                node.pulse = (node.pulse + 0.05) % (2 * Math.PI); // Cycle pulse from 0 to 2*PI

                // Draw the main pulsing circle
                ctx.beginPath();
                ctx.arc(node.x, node.y, nodeRadius + Math.sin(node.pulse) * 2, 0, Math.PI * 2);
                ctx.fillStyle = nodeColor;
                ctx.fill();

                // Draw a fainter, larger outer pulse
                ctx.beginPath();
                ctx.arc(node.x, node.y, nodeRadius + 5 + Math.sin(node.pulse * 0.8) * 3, 0, Math.PI * 2);
                ctx.fillStyle = pulseColor;
                ctx.fill();
            }

            // Request the next animation frame
            animationFrameId = requestAnimationFrame(animateCircuitBoard);
        }

        // --- Progress Bar & Data Simulation Logic ---
        // Array defining each progress bar's properties and their new gradient colors (reds)
        const progressBars = [
            { id: 'progressAppInit', label: 'App Init', target: 95, current: 0, speed: 0, color: '#f87171', direction: 'ltr' }, // red-400
            { id: 'progressAssets', label: 'Assets', target: 80, current: 0, speed: 0, color: '#ef4444', direction: 'rtl' }, // red-500
            { id: 'progressDataSync', target: 70, current: 0, speed: 0, color: '#dc2626', direction: 'ltr' }, // red-600
            { id: 'progressEnvCheck', label: 'Env Check', target: 90, current: 0, speed: 0, color: '#b91c1c', direction: 'rtl' }, // red-700
            { id: 'progressNetSecure', label: 'Net Secure', target: 100, current: 0, speed: 0, color: '#991b1b', direction: 'ltr' }, // red-800
            { id: 'progressServerRsp', label: 'Server Rsp', target: 60, current: 0, speed: 0, color: '#7f1d1d', direction: 'rtl' }, // red-900
            { id: 'progressRenderView', label: 'Render View', target: 100, current: 0, speed: 0, color: '#450a0a', direction: 'ltr' }  // red-950 (very dark)
        ];

        // Get references to HTML elements for dynamic updates
        const publicIPEl = document.getElementById('publicIP');
        const currentTimeEl = document.getElementById('currentTime');
        const elementsLoadedEl = document.getElementById('elementsLoaded');
        const networkStatusEl = document.getElementById('networkStatus');
        const loadTimeEl = document.getElementById('loadTime');
        const ttfbEl = document.getElementById('ttfb');
        const serverIPEl = document.getElementById('serverIP');
        const serverRegionEl = document.getElementById('serverRegion');
        const serverNodeEl = document.getElementById('serverNode');
        const locationEl = document.getElementById('location');
        const latLongEl = document.getElementById('latLong');

        const pingRatingEl = document.getElementById('pingRating');
        const loadTimeRatingEl = document.getElementById('loadTimeRating');
        const ttfbRatingEl = document.getElementById('ttfbRating');

        // Advanced Analytics Elements (Network Deep Dive)
        const dataTimestampEl = document.getElementById('dataTimestamp');
        const dnsLookupEl = document.getElementById('dnsLookup');
        const tcpHandshakeEl = document.getElementById('tcpHandshake');
        const requestStartEl = document.getElementById('requestStart');
        const responseEndEl = document.getElementById('responseEnd');
        const domInteractiveEl = document.getElementById('domInteractive');
        const domCompleteEl = document.getElementById('domComplete');

        // Super Advanced Analytics Elements (System Core)
        const cpuUsageEl = document.getElementById('cpuUsage');
        const memoryUsageEl = document.getElementById('memoryUsage');
        const diskReadEl = document.getElementById('diskRead');
        const diskWriteEl = document.getElementById('diskWrite');
        const netUploadEl = document.getElementById('netUpload');
        const netDownloadEl = document.getElementById('netDownload');
        const processCountEl = document.getElementById('processCount');
        const systemUptimeEl = document.getElementById('systemUptime');
        const activeConnectionsEl = document.getElementById('activeConnections');
        const systemLogEl = document.getElementById('systemLog');


        let totalElements = 100; // Total elements to load
        let loadedElements = 0; // Currently loaded elements
        let loadStartTime = performance.now(); // Start time for load duration calculation
        let simulationTimer; // To store the interval ID
        const simulationDuration = 7000; // 7 seconds
        const updateInterval = 100; // 100 milliseconds

        // Store initial page load metrics
        let initialLoadTime = '0.00s';
        let initialTTFB = '0.00s';

        // Simulated server data (cannot get real internal server names from client-side)
        const simulatedServers = [
            { name: 'Safaricom-Web-01', ip: '10.0.1.5', region: 'Nairobi, KE' },
            { name: 'Safaricom-API-02', ip: '10.0.2.10', region: 'Mombasa, KE' },
            { name: 'Safaricom-DB-03', ip: '10.0.3.15', region: 'Kisumu, KE' },
            { name: 'Safaricom-CDN-04', ip: '10.0.4.20', region: 'Eldoret, KE' },
            { name: 'Safaricom-Auth-05', ip: '10.0.5.25', region: 'Nakuru, KE' }
        ];
        let currentServerIndex = 0;

        // --- Tab Management ---
        const tabs = {
            overview: {
                button: document.getElementById('tabOverview'),
                content: document.getElementById('tabContentOverview'),
                password: null,
                animatedRows: document.querySelectorAll('#dataReadoutsOverview .animated-row')
            },
            networkDeepDive: {
                button: document.getElementById('tabNetworkDeepDive'),
                content: document.getElementById('tabContentNetworkDeepDive'),
                password: '2012',
                animatedRows: document.querySelectorAll('#dataReadoutsNetworkDeepDive .animated-row')
            },
            systemCore: {
                button: document.getElementById('tabSystemCore'),
                content: document.getElementById('tabContentSystemCore'),
                password: '2020',
                animatedRows: document.querySelectorAll('#dataReadoutsSystemCore .animated-row')
            }
        };
        let activeTab = 'overview'; // Default active tab

        /**
         * Switches the active tab, handling password protection.
         * @param {string} tabName - The name of the tab to switch to ('overview', 'networkDeepDive', 'systemCore').
         */
        function switchTab(tabName) {
            const targetTab = tabs[tabName];

            if (targetTab.password && !sessionStorage.getItem(`unlocked_${tabName}`)) {
                showMessageBox(`Enter password for ${targetTab.button.textContent} section:`, true, (password) => {
                    if (password === targetTab.password) {
                        sessionStorage.setItem(`unlocked_${tabName}`, 'true'); // Store unlock status
                        setActiveTab(tabName);
                    } else {
                        showMessageBox('Incorrect password!');
                    }
                });
            } else {
                setActiveTab(tabName);
            }
        }

        /**
         * Sets the active tab visually and content-wise.
         * @param {string} tabName - The name of the tab to activate.
         */
        function setActiveTab(tabName) {
            // Deactivate current tab button and hide its content
            tabs[activeTab].button.classList.remove('active');
            tabs[activeTab].content.classList.add('hidden');

            // Activate new tab button and show its content
            activeTab = tabName;
            tabs[activeTab].button.classList.add('active');
            tabs[activeTab].content.classList.remove('hidden');

            // Re-run animations for the newly active tab's rows
            animateDataReadoutRows(tabs[activeTab].animatedRows);

            // Update specific metrics if needed for the activated tab
            if (activeTab === 'networkDeepDive') {
                 dataTimestampEl.textContent = new Date().toLocaleString();
                 updateAdvancedMetrics();
            } else if (activeTab === 'systemCore') {
                updateSuperAdvancedMetrics();
            }
        }

        // Add event listeners for tab buttons
        tabs.overview.button.addEventListener('click', () => switchTab('overview'));
        tabs.networkDeepDive.button.addEventListener('click', () => switchTab('networkDeepDive'));
        tabs.systemCore.button.addEventListener('click', () => switchTab('systemCore'));


        /**
         * Determines if a metric value is "good" or "bad" based on thresholds.
         * @param {number} value - The metric value.
         * @param {number} goodThreshold - Value below which it's considered good.
         * @returns {string} - Emoji (✅ or ❌).
         */
        function getRatingEmoji(value, goodThreshold) {
            return value <= goodThreshold ? '✅' : '❌';
        }

        /**
         * Measures the round-trip time (ping) to a given URL.
         * @param {string} url - The URL to ping.
         * @returns {Promise<number|string>} - The ping in ms or 'N/A' on error.
         */
        async function measurePing(url) {
            const start = performance.now();
            try {
                // Using a small, publicly accessible image to measure network latency
                await fetch(url, { mode: 'no-cors', cache: 'no-store' });
                const end = performance.now();
                const pingValue = (end - start).toFixed(0);
                pingRatingEl.textContent = getRatingEmoji(parseInt(pingValue), 50); // Good if ping < 50ms
                return pingValue;
            } catch (error) {
                console.error("Ping failed:", error);
                pingRatingEl.textContent = '❌';
                return 'N/A';
            }
        }

        /**
         * Fetches and displays the machine's public IP address.
         */
        async function getPublicIP() {
            try {
                const response = await fetch('https://api.ipify.org?format=json');
                const data = await response.json();
                publicIPEl.textContent = data.ip;
            } catch (error) {
                console.error("Failed to fetch public IP:", error);
                publicIPEl.textContent = 'N/A';
            }
        }

        /**
         * Updates the current date and time displayed.
         */
        function updateCurrentTime() {
            currentTimeEl.textContent = new Date().toLocaleString();
        }

        /**
         * Captures initial page load metrics using PerformanceTiming API.
         */
        function captureInitialLoadMetrics() {
            if (performance.timing) {
                const timing = performance.timing;
                const loadTimeValue = ((timing.loadEventEnd - timing.navigationStart) / 1000).toFixed(2);
                const ttfbValue = ((timing.responseStart - timing.requestStart) / 1000).toFixed(2);

                initialLoadTime = loadTimeValue;
                initialTTFB = ttfbValue;

                loadTimeEl.textContent = `${initialLoadTime}s`;
                ttfbEl.textContent = `${initialTTFB}s`;

                loadTimeRatingEl.textContent = getRatingEmoji(parseFloat(initialLoadTime), 3.0); // Good if load time < 3.0s
                ttfbRatingEl.textContent = getRatingEmoji(parseFloat(initialTTFB), 0.5); // Good if TTFB < 0.5s

                // Advanced metrics based on PerformanceTiming
                dnsLookupEl.textContent = `${(timing.domainLookupEnd - timing.domainLookupStart).toFixed(0)}ms`;
                tcpHandshakeEl.textContent = `${(timing.connectEnd - timing.connectStart).toFixed(0)}ms`;
                requestStartEl.textContent = `${(timing.requestStart - timing.navigationStart).toFixed(0)}ms`;
                responseEndEl.textContent = `${(timing.responseEnd - timing.navigationStart).toFixed(0)}ms`;
                domInteractiveEl.textContent = `${(timing.domInteractive - timing.navigationStart).toFixed(0)}ms`;
                domCompleteEl.textContent = `${(timing.domComplete - timing.navigationStart).toFixed(0)}ms`;

            } else {
                console.warn("PerformanceTiming API not supported.");
                loadTimeRatingEl.textContent = '❓'; // Unknown
                ttfbRatingEl.textContent = '❓'; // Unknown
                dnsLookupEl.textContent = 'N/A';
                tcpHandshakeEl.textContent = 'N/A';
                requestStartEl.textContent = 'N/A';
                responseEndEl.textContent = 'N/A';
                domInteractiveEl.textContent = 'N/A';
                domCompleteEl.textContent = 'N/A';
            }
        }

        /**
         * Updates advanced analytics metrics (simulated if not directly available).
         */
        function updateAdvancedMetrics() {
            // Re-capture and display timestamp
            dataTimestampEl.textContent = new Date().toLocaleString();
            // Re-capture performance timing
            captureInitialLoadMetrics();
        }

        let systemUptimeSeconds = 0;
        let lastSystemCoreUpdate = performance.now();

        /**
         * Updates super advanced analytics metrics (simulated).
         */
        function updateSuperAdvancedMetrics() {
            const now = performance.now();
            const deltaTime = (now - lastSystemCoreUpdate) / 1000; // in seconds
            lastSystemCoreUpdate = now;

            // Simulate CPU and Memory usage
            cpuUsageEl.textContent = `${(Math.random() * 20 + 10).toFixed(0)}%`; // 10-30%
            memoryUsageEl.textContent = `${(Math.random() * 200 + 500).toFixed(0)}MB`; // 500-700MB

            // Simulate Disk I/O (KB/s)
            diskReadEl.textContent = `${(Math.random() * 500 + 100).toFixed(0)} KB/s`;
            diskWriteEl.textContent = `${(Math.random() * 300 + 50).toFixed(0)} KB/s`;

            // Simulate Network Throughput (KB/s)
            netUploadEl.textContent = `${(Math.random() * 100 + 20).toFixed(0)} KB/s`;
            netDownloadEl.textContent = `${(Math.random() * 500 + 100).toFixed(0)} KB/s`;

            processCountEl.textContent = `${(Math.random() * 50 + 100).toFixed(0)}`; // 100-150 processes
            activeConnectionsEl.textContent = `${(Math.random() * 50 + 100).toFixed(0)}`; // 100-150 connections

            // Update system uptime
            systemUptimeSeconds += deltaTime;
            const hours = Math.floor(systemUptimeSeconds / 3600);
            const minutes = Math.floor((systemUptimeSeconds % 3600) / 60);
            const seconds = Math.floor(systemUptimeSeconds % 60);
            systemUptimeEl.textContent = `${hours}h ${minutes}m ${seconds}s`;


            // Simulate system log entries
            const logEntries = [
                `[${new Date().toLocaleTimeString()}] System check initiated.`,
                `[${new Date().toLocaleTimeString()}] Process ID ${Math.floor(Math.random() * 9000) + 1000} started.`,
                `[${new Date().toLocaleTimeString()}] Network activity spike detected.`,
                `[${new Date().toLocaleTimeString()}] Memory usage nominal.`,
                `[${new Date().toLocaleTimeString()}] Disk I/O normal.`,
                `[${new Date().toLocaleTimeString()}] Security scan complete.`,
                `[${new Date().toLocaleTimeString()}] Data integrity verified.`,
                `[${new Date().toLocaleTimeString()}] New connection established.`,
                `[${new Date().toLocaleTimeString()}] CPU load fluctuating.`,
                `[${new Date().toLocaleTimeString()}] Background process optimized.`,
            ];
            // Add a new log entry only if the log is not full or at random intervals
            if (systemLogEl.children.length < 10 || Math.random() < 0.2) { // Add new entry if less than 10 or 20% chance
                const newLogEntry = document.createElement('div');
                newLogEntry.classList.add('text-gray-500');
                newLogEntry.textContent = logEntries[Math.floor(Math.random() * logEntries.length)];
                systemLogEl.appendChild(newLogEntry);
                systemLogEl.scrollTop = systemLogEl.scrollHeight; // Scroll to bottom
            }
            // Keep log size manageable
            while (systemLogEl.children.length > 15) {
                systemLogEl.removeChild(systemLogEl.firstChild);
            }
        }


        /**
         * Starts or restarts the 7-second diagnostic simulation.
         */
        async function startSimulation() {
            loadStartTime = performance.now();
            // Clear any existing interval to prevent multiple simultaneous simulations
            if (simulationTimer) {
                clearInterval(simulationTimer);
            }

            // Reset all progress bars to 0 and calculate their new speeds
            progressBars.forEach(bar => {
                bar.current = 0;
                // Calculate speed to reach target in simulationDuration / updateInterval steps
                bar.speed = bar.target / (simulationDuration / updateInterval);
                const barElement = document.getElementById(bar.id);
                barElement.style.width = `0%`; // Reset visual
                barElement.style.backgroundColor = bar.color; // Set the new gradient color

                // Apply RTL/LTR class for swoosh animation
                if (bar.direction === 'rtl') {
                    barElement.classList.add('rtl');
                } else {
                    barElement.classList.remove('rtl');
                }
            });
            loadedElements = 0; // Reset loaded elements
            elementsLoadedEl.textContent = `0/${totalElements}`;
            networkStatusEl.textContent = `Measuring...`;
            
            // Update simulated server and location details
            currentServerIndex = (currentServerIndex + 1) % simulatedServers.length;
            const currentServer = simulatedServers[currentServerIndex];
            serverIPEl.textContent = currentServer.ip;
            serverRegionEl.textContent = currentServer.region;
            serverNodeEl.textContent = currentServer.name;
            locationEl.textContent = `${currentServer.region.split(',')[0]}, Kenya`; // Extract city for location
            latLongEl.textContent = '-0.51°N, 35.26°E'; // Keep static for simplicity

            // Start the simulation interval
            simulationTimer = setInterval(updateProgressAndData, updateInterval);

            // Periodically update ping
            await updatePing(); // Initial ping
            setInterval(updatePing, 2000); // Update ping every 2 seconds

            // Update global time every second
            setInterval(updateCurrentTime, 1000);

            // Update advanced and super advanced metrics
            updateAdvancedMetrics();
            updateSuperAdvancedMetrics();
            setInterval(updateSuperAdvancedMetrics, 1000); // Update super advanced every 1 second for more dynamic log/uptime
        }

        /**
         * Updates the progress bars and simulates diagnostic data.
         * This function runs repeatedly during the simulation.
         */
        function updateProgressAndData() {
            const currentTime = performance.now();
            const elapsedTime = currentTime - loadStartTime;
            let allProgressBarsComplete = true;

            // Update each progress bar's current value towards its target
            progressBars.forEach(bar => {
                if (bar.current < bar.target) {
                    bar.current = Math.min(bar.current + bar.speed, bar.target); // Increment current, cap at target
                    const barElement = document.getElementById(bar.id);
                    barElement.style.width = `${bar.current}%`; // Update CSS width
                    allProgressBarsComplete = false; // If any bar is not complete, set flag to false
                }
            });

            // Simulate loading elements (more gradual)
            if (loadedElements < totalElements) {
                loadedElements = Math.min(loadedElements + Math.floor(Math.random() * 2) + 1, totalElements); // Add 1-2 elements
                elementsLoadedEl.textContent = `${loadedElements}/${totalElements}`;
            }

            // Update load time based on elapsed time only if still simulating
            if (elapsedTime < simulationDuration) {
                const currentSimulatedLoadTime = (elapsedTime / 1000).toFixed(2);
                loadTimeEl.textContent = `${currentSimulatedLoadTime}s`;
                loadTimeRatingEl.textContent = getRatingEmoji(parseFloat(currentSimulatedLoadTime), 3.0);
            }


            // Stop simulation if elapsed time exceeds duration or all bars are complete
            if (elapsedTime >= simulationDuration || (allProgressBarsComplete && loadedElements >= totalElements)) {
                clearInterval(simulationTimer); // Stop the interval
                // Ensure all bars are at 100% and final values are set
                progressBars.forEach(bar => {
                    bar.current = bar.target;
                    document.getElementById(bar.id).style.width = `${bar.target}%`;
                });
                elementsLoadedEl.textContent = `${totalElements}/${totalElements}`;
                loadTimeEl.textContent = `${(simulationDuration / 1000).toFixed(2)}s`; // Ensure final time is 7.00s
                // TTFB and ping are updated by separate functions, so their ratings are already set
            }
        }


        /**
         * Animates the data readout rows to slide in from alternating directions.
         * @param {NodeListOf<Element>} rows - The collection of rows to animate.
         */
        function animateDataReadoutRows(rows) {
            rows.forEach((row, index) => {
                // Reset animation state
                row.style.opacity = '0';
                row.classList.remove('slide-in-left', 'slide-in-right');

                // Trigger reflow to restart animation
                void row.offsetWidth;

                // Apply animation with delay
                setTimeout(() => {
                    if (index % 2 === 0) {
                        row.classList.add('slide-in-left');
                    } else {
                        row.classList.add('slide-in-right');
                    }
                }, index * 100); // Staggered animation
            });
        }


        // --- Initialization on Window Load ---
        // REMOVE this block to prevent auto-showing the orb
        // window.onload = function() {
        //     animateCircuitBoard(); // Start the circuit board animation loop
        //     diagnosticOrb.classList.remove('hidden'); // Ensure the orb is visible on load
        //     getPublicIP(); // Fetch public IP
        //     updateCurrentTime(); // Initial time update
        //     captureInitialLoadMetrics(); // Capture real page load metrics once
        //     startSimulation(); // Start the 7-second simulation immediately on load
        //     setActiveTab('overview'); // Ensure initial tab is active and its rows animate
        // };

        // Instead, only show the orb when showDevOrb() is called (after password)
        // Make sure orb is hidden by default
        var diagnosticOrb = document.getElementById('diagnosticOrb');
        if (diagnosticOrb) diagnosticOrb.classList.add('hidden');
        // When showing, also run the initialization logic
        function showDevOrb() {
          var orb = document.getElementById('diagnosticOrb');
          if(orb) {
            orb.classList.remove('hidden');
            animateCircuitBoard();
            getPublicIP();
            updateCurrentTime();
            captureInitialLoadMetrics();
            startSimulation();
            setActiveTab('overview');
          }
        }

        // --- Password Modal Logic ---
        function openDevPasswordModal() {
            document.getElementById('devPasswordInput').value = '';
            document.getElementById('devPasswordError').style.display = 'none';
            document.getElementById('devPasswordModalOverlay').classList.add('active');
            setTimeout(function(){ document.getElementById('devPasswordInput').focus(); }, 100);
        }
        function closeDevPasswordModal() {
            document.getElementById('devPasswordModalOverlay').classList.remove('active');
        }
        function submitDevPassword() {
            var val = document.getElementById('devPasswordInput').value;
            if(val === '2012') {
                closeDevPasswordModal();
                showDevOrb();
            } else {
                var err = document.getElementById('devPasswordError');
                err.textContent = 'Incorrect password!';
                err.style.display = 'block';
            }
        }
        // Close modal on outside click
        window.addEventListener('mousedown', function(e) {
            var overlay = document.getElementById('devPasswordModalOverlay');
            var modal = document.getElementById('devPasswordModal');
            if(overlay.classList.contains('active') && !modal.contains(e.target)) {
                closeDevPasswordModal();
            }
        });
        // Enter key submits
        window.addEventListener('keydown', function(e) {
            if(document.getElementById('devPasswordModalOverlay').classList.contains('active') && e.key === 'Enter') {
                submitDevPassword();
            }
        });
        // Expose for Dev button
        window.showDevPopupWithPassword = function() {
            openDevPasswordModal();
        };
        // Show/hide orb
        function hideDevOrb() {
            var orb = document.getElementById('diagnosticOrb');
            if(orb) orb.classList.add('hidden');
        }
        // Close orb on outside click
        window.addEventListener('mousedown', function(e) {
            var orb = document.getElementById('diagnosticOrb');
            if(orb && orb.classList.contains('active') && !orb.contains(e.target)) {
                hideDevOrb();
            }
        });

        // Add Email Testing and Darja Portal Tabs
        document.addEventListener('DOMContentLoaded', function() {
            var orb = document.getElementById('diagnosticOrb');
            if(!orb) return;
            // Add tabs
            var tabBar = document.createElement('div');
            tabBar.className = 'dev-tabs';
            tabBar.innerHTML = `
                <button class="dev-tab-btn active" data-tab="overview">Overview</button>
                <button class="dev-tab-btn" data-tab="email">Email Testing</button>
                <button class="dev-tab-btn" data-tab="darja">Darja Portal</button>
            `;
            orb.insertBefore(tabBar, orb.children[1]);
            // Add tab content wrappers
            var emailTab = document.createElement('div');
            emailTab.className = 'dev-tab-content';
            emailTab.id = 'devTabEmail';
            emailTab.innerHTML = `
                <form class="email-test-form">
                    <input type="email" id="testEmailInput" placeholder="Enter email to test..." required />
                    <button type="submit">Test Email Deliverability</button>
                    <div class="email-test-result" id="emailTestResult"></div>
                </form>
            `;
            var darjaTab = document.createElement('div');
            darjaTab.className = 'dev-tab-content';
            darjaTab.id = 'devTabDarja';
            darjaTab.innerHTML = `
                <div style="margin-bottom:10px;">Test connection to Darja Portal:</div>
                <button id="testDarjaBtn" style="width:100%;padding:8px 10px;border-radius:6px;background:linear-gradient(90deg,#00f1ff 0%,#a5b4fc 100%);color:#fff;font-weight:600;border:none;">Test Darja Connection</button>
                <div class="email-test-result" id="darjaTestResult"></div>
            `;
            orb.appendChild(emailTab);
            orb.appendChild(darjaTab);
            // Tab switching logic
            var tabBtns = tabBar.querySelectorAll('.dev-tab-btn');
            var tabContents = orb.querySelectorAll('.dev-tab-content');
            function showTab(tab) {
                tabBtns.forEach(btn => btn.classList.toggle('active', btn.dataset.tab === tab));
                tabContents.forEach(tc => tc.classList.toggle('active', tc.id === 'devTab' + tab.charAt(0).toUpperCase() + tab.slice(1)));
                // Overview is the default/original content
                orb.querySelector('.tab-content').style.display = (tab === 'overview') ? '' : 'none';
            }
            tabBtns.forEach(btn => btn.addEventListener('click', function(){ showTab(this.dataset.tab); }));
            // Default to overview
            showTab('overview');
            // Email test form handler (dummy, real test would require backend)
            orb.querySelector('.email-test-form').addEventListener('submit', function(e){
                e.preventDefault();
                var email = document.getElementById('testEmailInput').value;
                var result = document.getElementById('emailTestResult');
                result.textContent = 'Testing deliverability for ' + email + '...';
                setTimeout(function(){
                    result.textContent = 'Deliverability test for ' + email + ': (Simulated) Looks good!';
                }, 1200);
            });
            // Darja test button handler (dummy, real test would require backend)
            document.getElementById('testDarjaBtn').addEventListener('click', function(e){
                e.preventDefault();
                var result = document.getElementById('darjaTestResult');
                result.textContent = 'Testing connection to Darja Portal...';
                setTimeout(function(){
                    result.textContent = 'Darja Portal connection: (Simulated) Success!';
                }, 1200);
            });
        });
    </script>
</body>
</html>
