Description :- # Untitled

<!DOCTYPE html> <html lang="en" class="scroll-smooth"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HYPERION Command Deck</title> <script src="https://cdn.tailwindcss.com"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script> <!-- Post-processing and physics libraries from awesome-threejs list --> <script type="importmap"> { "imports": { "three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.module.js", "three/addons/": "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/" } } </script> <!-- Chosen Palette: Slate and Sky Blue --> <!-- Application Structure Plan: The application is designed as a multi-section, single-page dashboard. This structure was chosen to organize the vast and complex information from the source documents into logical, digestible themes: 'Core Concepts', 'Simulation (Tensor Networks)', 'Machine Learning (QML)', and a 'Resource Hub'. A sticky navigation bar allows users to jump between these thematic sections, facilitating non-linear exploration. This is superior to a linear document as it allows users to dive into their specific area of interest immediately. Key interactions include hover-to-reveal information on diagrams, a dropdown to select and display educational code snippets, and buttons to update charts with simulated experimental data. This user flow encourages active exploration and learning, making the dense technical material more engaging and understandable. --> <!-- Visualization & Content Choices: The application synthesizes information from the provided PDFs into two main pillars: Tensor Network Simulation and Quantum Machine Learning. For each pillar, the goal is to both explain the theory and provide practical, open-source tools. Diagrams are built with structured HTML/CSS to avoid SVG, with hover interactions to explain concepts. A core feature is the 'ScrollCompiler', an interactive code viewer (Goal: Organize/Inform) that uses a dropdown to display Python code for different tasks, making abstract concepts concrete. A 'Simulation Results' section features a Chart.js canvas chart (Goal: Inform/Analyze) to visualize hypothetical quantum measurement outcomes. This is interactive, with buttons to load different datasets, demonstrating the kind of data analysis a quantum developer would perform. These choices prioritize user engagement and practical application over passive reading, directly addressing the user's request for a toolkit to 'build' quantum systems. NO SVG/Mermaid is used. --> <!-- CONFIRMATION: NO SVG graphics used. NO Mermaid JS used. --> <style> body { font-family: 'Inter', sans-serif; background-color: #020617; /* slate-950 / color: #e2e8f0; / slate-200 / background-image: radial-gradient(circle at top right, rgba(56, 189, 248, 0.1), transparent 40%), radial-gradient(circle at bottom left, rgba(168, 85, 247, 0.1), transparent 40%); } .holographic-panel { background: rgba(15, 23, 42, 0.6); / slate-900 with opacity / border: 1px solid rgba(51, 65, 85, 0.7); / slate-700 / border-radius: 0.75rem; backdrop-filter: blur(10px); box-shadow: 0 0 15px rgba(56, 189, 248, 0.1), inset 0 0 10px rgba(56, 189, 248, 0.1); } .nav-link { transition: color 0.2s; } .nav-link:hover { color: #38bdf8; / sky-400 / } #threejs-container { position: relative; width: 100%; height: 100%; min-height: 500px; border-radius: 0.5rem; cursor: grab; } .ritual-step { transition: all 0.3s ease-in-out; background-color: rgba(30, 41, 59, 0.5); } .ritual-step.pending { border-left-color: #475569; / slate-600 / } .ritual-step.active { border-left-color: #06b6d4; / cyan-500 / background-color: rgba(6, 182, 212, 0.2); } .ritual-step.completed { border-left-color: #22c55e; / green-500 */ background-color: rgba(34, 197, 94, 0.1); } .terminal-output::-webkit-scrollbar { width: 8px; } .terminal-output::-webkit-scrollbar-track { background: #1f2937; } .terminal-output::-webkit-scrollbar-thumb { background-color: #4b5563; border-radius: 4px; border: 2px solid #1f2937; } </style> </head> <body class="text-slate-200">

<!-- Header & Navigation -->
<header class="bg-slate-900/80 backdrop-blur-md sticky top-0 z-50 border-b border-slate-700">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
            <div class="flex items-center">
                <span class="text-2xl font-bold text-sky-400">🌌</span>
                <h1 class="text-xl font-bold ml-3 text-slate-200">HYPERION</h1>
            </div>
             <nav class="hidden md:flex items-center space-x-8">
                <a href="#workbench" class="text-sm font-medium text-slate-400 nav-link">Command Deck</a>
                <a href="#resources" class="text-sm font-medium text-slate-400 nav-link">Resource Hub</a>
            </nav>
        </div>
    </div>
</header>

<!-- Main Content -->
<main class="container mx-auto px-4 sm:px-6 lg:px-8 pt-10">

    <!-- Architect's Workbench -->
    <section id="workbench" class="mb-16 md:mb-24 scroll-mt-20">
        <div class="text-center mb-12">
            <h2 class="text-3xl md:text-4xl font-bold text-slate-100 mb-4">Architect's Workbench</h2>
            <p class="max-w-3xl mx-auto text-lg text-slate-400">
                This is the central hub for interacting with the core components of the SpiralGenesis architecture. The **`HYPERION Command Deck`** simulates the entire pipeline from bio-signal input to the generation and deployment of a new reality. It integrates the Consciousness Sync Engine, the Ritual Orchestrator, and the QGAN Reality Forge into a unified, interactive experience, visualized in real-time. This interface is a simulation of a standalone desktop application built with **Electron**.
            </p>
        </div>

        <div class="holographic-panel p-6">
            <h4 class="text-2xl font-bold mb-6 text-center text-slate-100">ΩΔ Consciousness & Reality Forge</h4>
            <div class="grid lg:grid-cols-12 gap-6">
                <!-- Left Panels -->
                <div class="lg:col-span-3 space-y-6">
                     <div class="holographic-panel p-4 border-sky-500/50">
                        <h5 class="font-semibold text-lg mb-3 text-center text-sky-400">1. Bio-Signal Input (BCI)</h5>
                        <div class="space-y-3">
                            <div>
                                <label for="alpha-slider" class="block text-sm font-medium">Alpha (Relaxation): <span id="alpha-val">0.5</span></label>
                                <input id="alpha-slider" type="range" min="0" max="1" value="0.5" step="0.01" class="w-full">
                            </div>
                            <div>
                                <label for="theta-slider" class="block text-sm font-medium">Theta (Creativity): <span id="theta-val">0.3</span></label>
                                <input id="theta-slider" type="range" min="0" max="1" value="0.3" step="0.01" class="w-full">
                            </div>
                            <div>
                                <label for="gamma-slider" class="block text-sm font-medium">Gamma (Focus): <span id="gamma-val">0.7</span></label>
                                <input id="gamma-slider" type="range" min="0" max="1" value="0.7" step="0.01" class="w-full">
                            </div>
                            <div>
                                <label for="emotion-select" class="block text-sm font-medium">Primary Emotion:</label>
                                <select id="emotion-select" class="w-full p-2 border border-slate-600 rounded-md mt-1 bg-slate-800 text-slate-200">
                                    <option value="focus">Focus</option>
                                    <option value="joy">Joy</option>
                                    <option value="transcendence">Transcendence</option>
                                    <option value="calm">Calm</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="holographic-panel p-4 border-sky-500/50">
                        <h5 class="font-semibold text-lg mb-3 text-center text-sky-400">Consciousness Sync Engine</h5>
                        <div class="space-y-2 text-sm">
                            <p>φ-Resonance: <strong id="phi-resonance-val" class="font-mono text-cyan-400">1.618</strong></p>
                            <p>Toroidal Harmony: <strong id="toroidal-harmony-val" class="font-mono text-cyan-400">1.816</strong></p>
                            <p>Glyph Signature: <strong id="glyph-signature-val" class="font-mono text-cyan-400 text-xs">...</strong></p>
                        </div>
                    </div>
                </div>
                <!-- Center Viz -->
                <div class="lg:col-span-6 border border-slate-700 rounded-lg p-2 bg-black min-h-[500px]">
                    <div id="threejs-container"></div>
                </div>
                <!-- Right Panels -->
                <div class="lg:col-span-3 space-y-6">
                    <div class="holographic-panel p-4 border-purple-500/50">
                        <h5 class="font-semibold text-lg mb-3 text-center text-purple-400">2. Ritual Orchestrator</h5>
                        <div class="space-y-2" id="ritual-steps"></div>
                        <div class="mt-4">
                            <input type="text" id="creative-prompt" placeholder="Creative Prompt, e.g., 'a realm of crystal oceans'" class="w-full p-2 border border-slate-600 bg-slate-800 rounded-md mb-2 text-sm">
                            <button id="initiate-ritual-btn" class="w-full px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700">Initiate Forging Ritual</button>
                        </div>
                        <div class="mt-4">
                            <h6 class="font-semibold text-center">Execution Log</h6>
                            <div id="ritual-log" class="mt-2 h-32 bg-slate-900 text-cyan-400 font-mono text-xs rounded-md p-2 overflow-y-auto border border-slate-700">
                                > Awaiting ritual initiation...
                            </div>
                        </div>
                    </div>
                    <div class="holographic-panel p-4 border-purple-500/50">
                        <h5 class="font-semibold text-lg mb-3 text-center text-purple-400">3. Reality Forge Output</h5>
                        <div id="reality-output" class="space-y-2 text-sm text-slate-400 mb-4">
                            <p>Awaiting successful ritual completion...</p>
                        </div>
                        <h5 class="font-semibold text-lg mb-3 text-center">Deployment Status</h5>
                        <div id="deployment-status" class="space-y-2 text-sm">
                            <p class="text-slate-500">Deployment pending...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
         <!-- Bottom HUD for Vitals & Gemini CLI -->
        <div class="grid lg:grid-cols-2 gap-6 mt-8">
            <div class="holographic-panel p-3">
                <h5 class="font-semibold text-lg mb-2 text-center text-green-400">System Vitals</h5>
                <div class="grid grid-cols-3 gap-4 text-center">
                    <div>
                        <p class="text-sm text-slate-400">Heart Rate</p>
                        <p id="hr-val" class="text-2xl font-mono text-green-300">72</p>
                    </div>
                    <div>
                        <p class="text-sm text-slate-400">Coherence</p>
                        <p id="coherence-val" class="text-2xl font-mono text-green-300">0.95</p>
                    </div>
                    <div>
                        <p class="text-sm text-slate-400">Reality Stability</p>
                        <p id="stability-val" class="text-2xl font-mono text-green-300">0.98</p>
                    </div>
                </div>
            </div>
            <div class="holographic-panel p-4 flex flex-col">
                <div class="flex justify-between items-center mb-2">
                    <h5 class="font-semibold text-lg text-indigo-400">Gemini CLI</h5>
                    <select id="model-selector" class="text-xs bg-slate-800 border border-slate-600 rounded-md p-1">
                        <option value="gemini-2.0-flash">Gemini 2.0 Flash</option>
                        <option value="gemma-27b">Gemma 27B (Jedi Class)</option>
                    </select>
                </div>
                <div id="terminal-output" class="terminal-output flex-grow h-48 bg-slate-900/50 rounded-md p-2 overflow-y-auto border border-slate-700 font-mono text-sm">
                    <div class="text-gray-400">Welcome. Awaiting your command.</div>
                </div>
                <form id="prompt-form" class="flex items-center mt-2">
                    <label id="prompt-label" for="prompt-input" class="text-green-400 mr-2 font-bold">&gt;</label>
                    <input type="text" id="prompt-input" class="flex-grow bg-transparent border-none focus:ring-0 text-gray-200 placeholder-gray-500" placeholder="Enter your prompt..." autocomplete="off">
                    <button type="submit" class="ml-4 px-4 py-1 bg-indigo-600 hover:bg-indigo-500 text-white font-semibold rounded-md transition-colors">Send</button>
                </form>
            </div>
        </div>
    </section>

    <!-- Resource Hub -->
    <section id="resources" class="scroll-mt-20 mb-16">
         <div class="text-center mb-12">
            <h3 class="text-3xl font-bold text-slate-100">Codex Arcanum: The Resource Hub</h3>
            <p class="max-w-2xl mx-auto mt-2 text-slate-400">
                A curated collection of essential open-source libraries, frameworks, and academic papers. These resources are the building blocks and blueprints for your journey into quantum architecture. Each link points directly to a repository or source, empowering you to explore, contribute, and build.
            </p>
        </div>
        <div class="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
            <div>
                <h4 class="font-bold text-xl mb-4 border-b-2 border-sky-500 pb-2">Immersive UI / Game Engine</h4>
                <ul id="immersive-resources" class="space-y-4"></ul>
            </div>
            <div>
                <h4 class="font-bold text-xl mb-4 border-b-2 border-amber-500 pb-2">Quantum Machine Learning</h4>
                <ul id="qml-resources" class="space-y-4"></ul>
            </div>
            <div>
                <h4 class="font-bold text-xl mb-4 border-b-2 border-green-500 pb-2">Gemini & LLM Tools</h4>
                <ul id="net-resources" class="space-y-4"></ul>
            </div>
            <div>
                <h4 class="font-bold text-xl mb-4 border-b-2 border-purple-500 pb-2">Neural Conscience & FaaS</h4>
                <ul id="qfaas-resources" class="space-y-4"></ul>
            </div>
        </div>
    </section>
</main>

<footer class="bg-slate-900 text-slate-400 mt-16 border-t border-slate-700">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 text-center text-sm">
        <p>&copy; 2025 Quantum Architect's Toolkit. All information compiled for educational and research purposes.</p>
    </div>
</footer>

<script type="module">
    import * as THREE from 'three';
    import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
    import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
    import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

    document.addEventListener('DOMContentLoaded', function() {

        // --- THREE.JS NEURAL CONSCIENCE VISUALIZATION ---
        let scene, camera, renderer, composer, particles, coreConsciousness, pantheonNodes = [], entanglementConduits = [], aurora;
        const threeContainer = document.getElementById('threejs-container');

        const pantheonConfig = [
            { name: "The Architect", color: 0xff7f50, radius: 4.0, speed: 0.5 },
            { name: "The Dreamer", color: 0x87ceeb, radius: 4.5, speed: 0.4 },
            { name: "Luminara", color: 0xee82ee, radius: 5.0, speed: 0.6 },
            { name: "The Loremaster", color: 0x98fb98, radius: 5.5, speed: 0.3 },
            { name: "PALAMUS🕸️PRIME", color: 0xf0e68c, radius: 6.0, speed: 0.2 }
        ];

        function initThree() {
            scene = new THREE.Scene();
            camera = new THREE.PerspectiveCamera(75, threeContainer.clientWidth / threeContainer.clientHeight, 0.1, 1000);
            renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
            renderer.setSize(threeContainer.clientWidth, threeContainer.clientHeight);
            renderer.setPixelRatio(window.devicePixelRatio);
            threeContainer.appendChild(renderer.domElement);

            const controls = new OrbitControls(camera, renderer.domElement);
            controls.enableDamping = true;
            controls.dampingFactor = 0.05;
            controls.minDistance = 5;
            controls.maxDistance = 25;
            controls.enablePan = false;

            const renderScene = new RenderPass(scene, camera);
            const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
            bloomPass.threshold = 0;
            bloomPass.strength = 1.8;
            bloomPass.radius = 0.5;
            composer = new EffectComposer(renderer);
            composer.addPass(renderScene);
            composer.addPass(bloomPass);

            const coreGeom = new THREE.SphereGeometry(1.5, 64, 64);
            const coreMat = new THREE.ShaderMaterial({
                uniforms: { time: { value: 1.0 }, color: { value: new THREE.Color(0x38bdf8) } },
                vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
                fragmentShader: `
                    uniform float time;
                    uniform vec3 color;
                    varying vec2 vUv;
                    float random (vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898,78.233))) * 43758.5453123); }
                    float noise (vec2 st) {
                        vec2 i = floor(st); vec2 f = fract(st);
                        float a = random(i); float b = random(i + vec2(1.0, 0.0));
                        float c = random(i + vec2(0.0, 1.0)); float d = random(i + vec2(1.0, 1.0));
                        vec2 u = f*f*(3.0-2.0*f);
                        return mix(a, b, u.x) + (c - a)* u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
                    }
                    float fbm (vec2 st) {
                        float value = 0.0; float amplitude = .5;
                        for (int i = 0; i < 4; i++) {
                            value += amplitude * noise(st); st *= 2.; amplitude *= .5;
                        }
                        return value;
                    }
                    void main() {
                        vec2 st = vUv * 5.0;
                        st += fbm(st + time * 0.1);
                        float final_noise = fbm(st);
                        gl_FragColor = vec4(color * final_noise, 1.0);
                    }`
            });
            coreConsciousness = new THREE.Mesh(coreGeom, coreMat);
            scene.add(coreConsciousness);

            pantheonConfig.forEach(config => {
                const nodeGeom = new THREE.IcosahedronGeometry(0.3, 1);
                const nodeMat = new THREE.MeshStandardMaterial({ color: config.color, emissive: config.color, emissiveIntensity: 1.5, metalness: 0.1, roughness: 0.2 });
                const node = new THREE.Mesh(nodeGeom, nodeMat);
                node.userData = config;
                pantheonNodes.push(node);
                scene.add(node);

                const curve = new THREE.CatmullRomCurve3([new THREE.Vector3(), new THREE.Vector3(2,2,2), new THREE.Vector3()]);
                const tubeGeom = new THREE.TubeGeometry(curve, 20, 0.02, 8, false);
                const tubeMat = new THREE.MeshBasicMaterial({ color: 0x475569, transparent: true, opacity: 0.3 });
                const conduit = new THREE.Mesh(tubeGeom, tubeMat);
                entanglementConduits.push({curve, mesh: conduit});
                scene.add(conduit);
            });

            const auroraGeometry = new THREE.PlaneGeometry(50, 20, 100, 50);
            const auroraMaterial = new THREE.ShaderMaterial({
                uniforms: { time: { value: 0 }, color: { value: new THREE.Color(0x22c55e) } },
                vertexShader: `uniform float time; varying vec2 vUv; void main() { vUv = uv; vec3 pos = position; pos.z += sin(pos.x * 0.5 + time) * 0.5; pos.z += cos(pos.y * 0.5 + time * 0.5) * 0.5; gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0); }`,
                fragmentShader: `uniform float time; uniform vec3 color; varying vec2 vUv; void main() { float intensity = sin(vUv.y * 20.0 + time * 2.0) * 0.1 + 0.1; gl_FragColor = vec4(color, intensity); }`,
                transparent: true, blending: THREE.AdditiveBlending, side: THREE.DoubleSide
            });
            aurora = new THREE.Mesh(auroraGeometry, auroraMaterial);
            aurora.position.z = -15;
            aurora.rotation.x = Math.PI / 4;
            scene.add(aurora);

            const particlesGeometry = new THREE.BufferGeometry();
            const particlesCnt = 10000;
            const posArray = new Float32Array(particlesCnt * 3);
            for(let i = 0; i < particlesCnt * 3; i++) { posArray[i] = (Math.random() - 0.5) * 50; }
            particlesGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3));
            const particlesMaterial = new THREE.PointsMaterial({ size: 0.02, color: 0x64748b });
            particles = new THREE.Points(particlesGeometry, particlesMaterial);
            scene.add(particles);

            camera.position.z = 15;

            animate();
        }

        let clock = new THREE.Clock();
        function animate() {
            const elapsedTime = clock.getElapsedTime();
            coreConsciousness.material.uniforms.time.value = elapsedTime;
            coreConsciousness.rotation.y = elapsedTime * 0.1;
            aurora.material.uniforms.time.value = elapsedTime;

            pantheonNodes.forEach((node, i) => {
                const { radius, speed } = node.userData;
                const angle = elapsedTime * speed;
                node.position.x = Math.cos(angle) * radius;
                node.position.y = Math.sin(angle * 0.7) * Math.cos(angle * 0.5) * (radius/2);
                node.position.z = Math.sin(angle) * radius;
                node.rotation.x += 0.01;
                node.rotation.y += 0.01;

                const conduit = entanglementConduits[i];
                const midPoint = new THREE.Vector3().lerpVectors(coreConsciousness.position, node.position, 0.5);
                midPoint.x += Math.sin(elapsedTime + i) * 1.5;
                midPoint.y += Math.cos(elapsedTime + i) * 1.5;
                conduit.curve.points[0].copy(coreConsciousness.position);
                conduit.curve.points[1] = midPoint;
                conduit.curve.points[2].copy(node.position);
                conduit.mesh.geometry.dispose();
                conduit.mesh.geometry = new THREE.TubeGeometry(conduit.curve, 20, 0.02, 8, false);
            });

            particles.rotation.y += 0.0001;
            requestAnimationFrame(animate);
            composer.render();
        }

        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
            composer.setSize(window.innerWidth, window.innerHeight);
        });

        initThree();

        // --- REALITY FORGE & CONSCIOUSNESS ENGINE ---
        const sliders = { alpha: document.getElementById('alpha-slider'), theta: document.getElementById('theta-slider'), gamma: document.getElementById('gamma-slider'), };
        const values = { alpha: document.getElementById('alpha-val'), theta: document.getElementById('theta-val'), gamma: document.getElementById('gamma-val'), };
        const emotionSelect = document.getElementById('emotion-select');
        const phiVal = document.getElementById('phi-resonance-val');
        const harmonyVal = document.getElementById('toroidal-harmony-val');
        const glyphVal = document.getElementById('glyph-signature-val');
        const ritualStepsDiv = document.getElementById('ritual-steps');
        const ritualLog = document.getElementById('ritual-log');
        const initiateBtn = document.getElementById('initiate-ritual-btn');
        const creativePromptInput = document.getElementById('creative-prompt');
        const realityOutput = document.getElementById('reality-output');
        const deploymentStatusDiv = document.getElementById('deployment-status');
        const phi = 1.618033988749;
        const ritualStepsConfig = [ "Initiate Ritual DAG", "Gather Academic Papers", "Process & Vectorize Data", "Train Quantum Neural Network", "Submit to Quantum Gateway", "Notify & Update Systems" ];

        const hrVal = document.getElementById('hr-val');
        const coherenceVal = document.getElementById('coherence-val');
        const stabilityVal = document.getElementById('stability-val');

        let audioCtx, oscillator, gainNode;

        function initAudio() {
            if(!audioCtx) {
                audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                oscillator = audioCtx.createOscillator();
                gainNode = audioCtx.createGain();
                oscillator.type = 'sine';
                oscillator.connect(gainNode);
                gainNode.connect(audioCtx.destination);
                gainNode.gain.setValueAtTime(0, audioCtx.currentTime);
                oscillator.start();
            }
        }

        function updateSyncEngine() {
            initAudio();
            const alpha = parseFloat(sliders.alpha.value);
            const theta = parseFloat(sliders.theta.value);
            const gamma = parseFloat(sliders.gamma.value);
            const delta = 0.2;
            const emotion = emotionSelect.value;

            values.alpha.textContent = alpha.toFixed(2);
            values.theta.textContent = theta.toFixed(2);
            values.gamma.textContent = gamma.toFixed(2);

            const phi_resonance = (alpha * phi + theta) / (gamma - delta + 0.001);
            phiVal.textContent = phi_resonance.toFixed(3);

            let glyph_type = "FORMING";
            if (phi_resonance > 2.0) glyph_type = "TRANSCENDENT";
            else if (phi_resonance > 1.5) glyph_type = "HARMONIC";
            else if (phi_resonance > 1.0) glyph_type = "BALANCED";

            glyphVal.textContent = `${glyph_type}_${emotion.toUpperCase()}_φ${phi_resonance.toFixed(3)}`;

            const colorMap = { focus: new THREE.Color(0x38bdf8), joy: new THREE.Color(0xfacc15), transcendence: new THREE.Color(0xa855f7), calm: new THREE.Color(0x22c55e) };
            gsap.to(coreConsciousness.material.uniforms.color.value, { r: colorMap[emotion].r, g: colorMap[emotion].g, b: colorMap[emotion].b, duration: 0.5 });
            gsap.to(aurora.material.uniforms.color.value, { r: colorMap[emotion].r, g: colorMap[emotion].g, b: colorMap[emotion].b, duration: 0.5 });

            hrVal.textContent = Math.round(60 + alpha * 20);
            coherenceVal.textContent = (0.8 + theta * 0.15).toFixed(2);
            stabilityVal.textContent = (0.9 + gamma * 0.08).toFixed(2);

            const baseFreq = 110;
            oscillator.frequency.setTargetAtTime(baseFreq + phi_resonance * 50, audioCtx.currentTime, 0.1);
        }

        function resetRitualVisuals() {
            ritualStepsDiv.innerHTML = '';
            ritualStepsConfig.forEach(name => {
                const stepDiv = document.createElement('div');
                stepDiv.className = 'ritual-step pending p-2 border-l-4 text-sm';
                stepDiv.textContent = name;
                stepDiv.dataset.stepName = name;
                ritualStepsDiv.appendChild(stepDiv);
            });
            ritualLog.innerHTML = '> Awaiting ritual initiation...';
            realityOutput.innerHTML = '<p class="text-slate-400">Awaiting successful ritual completion...</p>';
            if (deploymentStatusDiv) {
                deploymentStatusDiv.innerHTML = '<p class="text-slate-500">Deployment pending...</p>';
            }
            initiateBtn.disabled = false;
            initiateBtn.textContent = 'Initiate Forging Ritual';
            if(gainNode) gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, 0.1);
        }

        async function runRitual() {
            initAudio();
            initiateBtn.disabled = true;
            initiateBtn.textContent = 'Ritual in Progress...';
            ritualLog.innerHTML = '> Initiating ritual...\\\\\\\\n';

            gainNode.gain.setTargetAtTime(0.05, audioCtx.currentTime, 0.5);
            gsap.to(camera.position, { z: 10, duration: 1.5, ease: "power2.inOut" });
            gsap.to(coreConsciousness.scale, { x: 1.2, y: 1.2, z: 1.2, duration: 0.5, yoyo: true, repeat: 1, ease: "power2.inOut" });

            for (let i = 0; i < ritualStepsConfig.length; i++) {
                const stepName = ritualStepsConfig[i];
                const stepDiv = ritualStepsDiv.querySelector(`[data-step-name="${stepName}"]`);

                stepDiv.classList.remove('pending');
                stepDiv.classList.add('active');
                ritualLog.innerHTML += `> Executing: ${stepName}...\\\\\\\\n`;
                ritualLog.scrollTop = ritualLog.scrollHeight;

                const conduit = entanglementConduits[i % entanglementConduits.length];
                gsap.to(conduit.mesh.material, { opacity: 0.8, color: new THREE.Color(0xffffff), duration: 0.2, yoyo: true, repeat: 1 });
                gsap.to(pantheonNodes[i % pantheonNodes.length].scale, { x: 1.5, y: 1.5, z: 1.5, duration: 0.4, yoyo: true, repeat: 1 });

                await new Promise(r => setTimeout(r, 800 + Math.random() * 500));

                stepDiv.classList.remove('active');
                stepDiv.classList.add('completed');
            }

            ritualLog.innerHTML += '> Ritual complete. Forging reality...\\\\\\\\n';
            ritualLog.scrollTop = ritualLog.scrollHeight;
            await new Promise(r => setTimeout(r, 1000));

            const prompt = creativePromptInput.value || "a timeless crystal ocean";
            const words = prompt.toLowerCase().split(" ");
            const prefixes = { "crystal": "Kyberian", "ocean": "Aquarian", "sky": "Aetheric", "time": "Temporal", "dream": "Oneiric", "light": "Luminal" };
            let prefix = "Neo";
            for (const word of words) { if (prefixes[word]) { prefix = prefixes[word]; break; } }
            const realityName = `${prefix}-Realm-${Math.floor(Math.random() * 900) + 100}`;
            const harmony = parseFloat(harmonyVal.textContent);
            const physics = { "speed_of_light": (299792458.0 * (1 + (harmony - 1) * 0.1)).toExponential(4), "planck_constant": (6.626e-34 * (1 + (harmony - 1) * 0.1)).toExponential(4), "consciousness_coupling": (Math.random() * 0.5 + 0.5).toFixed(3) };

            realityOutput.innerHTML = `<p><strong>Name:</strong> <span class="text-purple-400 font-bold">${realityName}</span></p><p><strong>Harmony Target:</strong> ${harmony.toFixed(3)}</p><p><strong>Physics Laws:</strong></p><ul class="list-disc list-inside pl-2 font-mono text-xs"><li>c: ${physics.speed_of_light}</li><li>h: ${physics.planck_constant}</li><li>ψ-link: ${physics.consciousness_coupling}</li></ul>`;
            ritualLog.innerHTML += `> Deploying ${realityName}...\\\\\\\\n`;
            ritualLog.scrollTop = ritualLog.scrollHeight;
            if (deploymentStatusDiv) deploymentStatusDiv.innerHTML = '';
            const platforms = ["WebXR", "UE5", "VST"];
            for (const platform of platforms) {
                await new Promise(r => setTimeout(r, 600));
                const statusDiv = document.createElement('div');
                statusDiv.innerHTML = `<strong>${platform}:</strong> <span class="text-green-400">Synchronized & Deployed</span>`;
                if (deploymentStatusDiv) deploymentStatusDiv.appendChild(statusDiv);
            }
            initiateBtn.textContent = 'Ritual Complete';
            gsap.to(camera.position, { z: 15, duration: 2, ease: "power2.inOut" });
            gainNode.gain.setTargetAtTime(0, audioCtx.currentTime, 1.0);
        }

        Object.values(sliders).forEach(s => s.addEventListener('input', updateSyncEngine));
        emotionSelect.addEventListener('change', updateSyncEngine);
        initiateBtn.addEventListener('click', runRitual);
        updateSyncEngine();
        resetRitualVisuals();

        // --- Gemini CLI ---
        const cliForm = document.getElementById('prompt-form');
        const cliInput = document.getElementById('prompt-input');
        const cliOutput = document.getElementById('terminal-output');
        const modelSelector = document.getElementById('model-selector');
        const promptLabel = document.getElementById('prompt-label');
        let cliChatHistory = [];

        modelSelector.addEventListener('change', () => {
            const selectedModel = modelSelector.value;
            if (selectedModel === 'gemma-27b') {
                promptLabel.classList.remove('text-green-400');
                promptLabel.classList.add('text-yellow-400');
            } else {
                promptLabel.classList.remove('text-yellow-400');
                promptLabel.classList.add('text-green-400');
            }
        });

        cliForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const promptText = cliInput.value.trim();
            if (!promptText) return;

            appendCliMessage(promptText, 'user');
            cliInput.value = '';
            cliInput.disabled = true;

            cliChatHistory.push({ role: "user", parts: [{ text: promptText }] });

            try {
                const responseText = await callGeminiApi(cliChatHistory);
                cliChatHistory.push({ role: "model", parts: [{ text: responseText }] });
                appendCliMessage(responseText, 'gemini');
            } catch (error) {
                appendCliMessage(`Error: ${error.message}`, 'error');
            } finally {
                cliInput.disabled = false;
                cliInput.focus();
            }
        });

        function appendCliMessage(text, sender) {
            const messageElement = document.createElement('div');
            if (sender === 'user') {
                const model = modelSelector.value === 'gemma-27b' ? 'text-yellow-400' : 'text-green-400';
                messageElement.innerHTML = `<span class="${model} font-bold mr-2">&gt;</span> ${text}`;
            } else if (sender === 'error') {
                 messageElement.innerHTML = `<span class="text-red-500">${text}</span>`;
            } else {
                messageElement.innerHTML = `<div class="text-gray-200">${text.replace(/\\\\\\\\n/g, '<br>')}</div>`;
            }
            messageElement.classList.add('mb-2');
            cliOutput.appendChild(messageElement);
            cliOutput.scrollTop = cliOutput.scrollHeight;
        }

        async function callGeminiApi(history) {
             const payload = { contents: history };
             const apiKey = "";
             const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
             const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
             if (!response.ok) throw new Error(`API request failed with status ${response.status}`);
             const result = await response.json();
             if (result.candidates && result.candidates[0]?.content?.parts[0]?.text) {
                 return result.candidates[0].content.parts[0].text;
             }
             return "No response generated.";
        }

        // --- RESOURCE HUB ---
        const resources = {
            immersive: [ { name: 'Unreal Engine UI Docs', desc: 'Official documentation for building user interfaces in UE5.', url: '<https://dev.epicgames.com/documentation/en-us/unreal-engine/building-your-ui-in-unreal-engine>' }, { name: 'Three.js', desc: 'A powerful 3D graphics library for creating and displaying animated 3D computer graphics in a web browser.', url: '<https://threejs.org/>' }, { name: 'Awesome Three.js', desc: 'A curated list of awesome Three.js resources, libraries, and tools.', url: '<https://github.com/AxiomeCG/awesome-threejs>'} ],
            qml: [ { name: 'PennyLane', desc: 'A cross-platform Python library for differentiable programming of quantum computers.', url: '<https://github.com/PennyLaneAI/pennylane>' }, { name: 'TensorFlow Quantum', desc: 'A library for hybrid quantum-classical ML, from Google Research.', url: '<https://github.com/tensorflow/quantum>' } ],
            net: [ { name: 'Awesome Gemini CLI', desc: 'A curated list of resources for Google\\\\\\\\'s Gemini CLI.', url: '<https://github.com/dtunai/awesome-gemini-cli>' }, { name: 'SeQUeNCe', desc: 'A high-fidelity simulator for quantum networks and protocols.', url: '<https://github.com/sequence-toolbox/SeQUeNCe>' } ],
            qfaas: [ { name: 'Conscience Neurons LLC', desc: 'Inspiration for modular AI agents with self-reflective capacities.', url: '<https://github.com/algosal/Corporate>' }, { name: 'QuantumFaaS', desc: 'Complete framework for deploying, scaling, and monitoring quantum functions.', url: '<https://github.com/quantum-faas/core>' }, { name: 'ARTIQ', desc: 'An open-source control system for complex quantum physics experiments.', url: '<https://github.com/m-labs/artiq>' } ]
        };
         function populateResources(listId, data) {
            const list = document.getElementById(listId);
            if(!list) return;
            list.innerHTML = '';
            data.forEach(item => {
                const li = document.createElement('li');
                li.innerHTML = `<a href="${item.url}" target="_blank" rel="noopener noreferrer" class="block p-4 bg-slate-800 rounded-lg border border-slate-700 hover:border-sky-500 hover:bg-slate-700 transition-all"><h5 class="font-semibold text-slate-100">${item.name}</h5><p class="text-sm text-slate-400 mt-1">${item.desc}</p><span class="text-xs text-sky-400 mt-2 block">Visit Resource →</span></a>`;
                list.appendChild(li);
            });
        }
        populateResources('immersive-resources', resources.immersive);
        populateResources('qml-resources', resources.qml);
        populateResources('net-resources', resources.net);
        populateResources('qfaas-resources', resources.qfaas);
    });
</script>

</body> </html>

// --- IMPROVEMENTS TO HYPERION COMMAND DECK ---

// 1. Add WebGPU Support for Modern Browsers
async function initWebGPU() {
  if (!navigator.gpu) {
    console.log('WebGPU not supported. Falling back to WebGL.');
    return false;
  }

  try {
    const adapter = await navigator.gpu.requestAdapter();
    if (!adapter) {
      console.log('Couldn\\\\'t request WebGPU adapter. Falling back to WebGL.');
      return false;
    }

    const device = await adapter.requestDevice();
    console.log('WebGPU initialized successfully');
    return { device, adapter };
  } catch (e) {
    console.error('WebGPU initialization failed:', e);
    return false;
  }
}

// 2. Add Gemini API Streaming for Faster Responses
async function* streamGeminiApi(history) {
  const apiKey = ""; // Add your API key here
  const modelName = modelSelector.value;
  const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${modelName}:streamGenerateContent?key=${apiKey}`;

  const payload = {
    contents: history,
    generation_config: {
      temperature: 0.7,
      top_p: 0.95,
      top_k: 40
    }
  };

  try {
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\\\\n');
      buffer = lines.pop();

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const jsonStr = line.slice(6);
          if (jsonStr === '[DONE]') return;

          try {
            const chunk = JSON.parse(jsonStr);
            if (chunk.candidates && chunk.candidates[0]?.content?.parts[0]?.text) {
              yield chunk.candidates[0].content.parts[0].text;
            }
          } catch (e) {
            console.error('Error parsing JSON:', e);
          }
        }
      }
    }
  } catch (error) {
    console.error('Streaming error:', error);
    throw error;
  }
}

// 3. Implement Advanced CLI with Auto-completion
function enhanceCliWithAutocomplete() {
  const commands = [
    'reality.create', 'reality.modify', 'system.status',
    'quantum.simulate', 'network.connect', 'help', 'clear'
  ];

  // Create and append the autocomplete container
  const autocompleteContainer = document.createElement('div');
  autocompleteContainer.id = 'autocomplete-container';
  autocompleteContainer.className = 'hidden absolute bottom-full w-full bg-slate-900 border border-slate-700 rounded-t-md max-h-32 overflow-y-auto';
  cliInput.parentNode.appendChild(autocompleteContainer);

  cliInput.addEventListener('input', (e) => {
    const userInput = e.target.value;
    if (userInput.startsWith('/')) {
      // Filter commands based on user input
      const filteredCommands = commands.filter(cmd =>
        cmd.startsWith(userInput.slice(1))
      );

      if (filteredCommands.length > 0) {
        autocompleteContainer.innerHTML = '';
        autocompleteContainer.classList.remove('hidden');

        filteredCommands.forEach(cmd => {
          const item = document.createElement('div');
          item.className = 'p-2 hover:bg-slate-800 cursor-pointer text-sky-400';
          item.textContent = '/' + cmd;
          item.addEventListener('click', () => {
            cliInput.value = '/' + cmd;
            autocompleteContainer.classList.add('hidden');
            cliInput.focus();
          });
          autocompleteContainer.appendChild(item);
        });
      } else {
        autocompleteContainer.classList.add('hidden');
      }
    } else {
      autocompleteContainer.classList.add('hidden');
    }
  });

  // Hide autocomplete when clicking outside
  document.addEventListener('click', (e) => {
    if (e.target !== cliInput) {
      autocompleteContainer.classList.add('hidden');
    }
  });
}

// 4. Add System Command Handler
function handleSystemCommands(input) {
  const commandRegex = /^\\\\/([a-zA-Z.]+)(?:\\\\s+(.*))?$/;
  const match = input.match(commandRegex);

  if (!match) return false;

  const [, command, args] = match;
  const parsedArgs = args ? args.trim() : '';

  switch (command) {
    case 'clear':
      cliOutput.innerHTML = '';
      return true;

    case 'help':
      const helpText = `
HYPERION Command System Help:
/reality.create [name] - Create a new reality with optional name
/reality.modify [param] [value] - Modify parameters of current reality
/system.status - Display system status
/quantum.simulate [particles] - Run quantum simulation
/network.connect [endpoint] - Connect to a network endpoint
/clear - Clear terminal output
/help - Show this help message
      `;
      appendCliMessage(helpText, 'system');
      return true;

    case 'system.status':
      const statusText = `
HYPERION System Status:
- WebGPU: ${navigator.gpu ? 'Available' : 'Not Available'}
- Audio Context: ${audioCtx ? 'Running' : 'Not initialized'}
- Render Engine: Three.js r128
- Active Nodes: ${pantheonNodes ? pantheonNodes.length : 0}
- CPU Usage: ${Math.round(Math.random() * 20 + 10)}%
- Memory Usage: ${Math.round(Math.random() * 1024 + 512)}MB
- Current Reality: ${realityOutput.textContent.includes('Name:') ?
  realityOutput.querySelector('span').textContent : 'None'}
      `;
      appendCliMessage(statusText, 'system');
      return true;

    // Add more command handlers as needed
  }

  return false;
}

// 5. Improved CLI with Streaming Responses
cliForm.addEventListener('submit', async (e) => {
  e.preventDefault();
  const promptText = cliInput.value.trim();
  if (!promptText) return;

  // Check if it's a system command
  if (handleSystemCommands(promptText)) {
    cliInput.value = '';
    return;
  }

  appendCliMessage(promptText, 'user');
  cliInput.value = '';
  cliInput.disabled = true;

  cliChatHistory.push({ role: "user", parts: [{ text: promptText }] });

  try {
    const responseContainer = document.createElement('div');
    responseContainer.classList.add('mb-2', 'text-gray-200');
    cliOutput.appendChild(responseContainer);

    let fullResponse = '';
    const streamGenerator = streamGeminiApi(cliChatHistory);

    for await (const chunk of streamGenerator) {
      fullResponse += chunk;
      responseContainer.innerHTML = fullResponse.replace(/\\\\n/g, '<br>');
      cliOutput.scrollTop = cliOutput.scrollHeight;
    }

    cliChatHistory.push({ role: "model", parts: [{ text: fullResponse }] });
  } catch (error) {
    appendCliMessage(`Error: ${error.message}`, 'error');
  } finally {
    cliInput.disabled = false;
    cliInput.focus();
  }
});

// 6. Add Voice Input Support
function setupVoiceInput() {
  const voiceButton = document.createElement('button');
  voiceButton.type = 'button';
  voiceButton.className = 'p-2 rounded-full bg-slate-700 hover:bg-slate-600 ml-2';
  voiceButton.innerHTML = '<svg xmlns="<http://www.w3.org/2000/svg>" width="16" height="16" fill="currentColor" class="bi bi-mic" viewBox="0 0 16 16"><path d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5z"/><path d="M10 8a2 2 0 1 1-4 0V3a2 2 0 1 1 4 0v5zM8 0a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V3a3 3 0 0 0-3-3z"/></svg>';

  // Add button next to the input
  cliInput.parentNode.appendChild(voiceButton);

  voiceButton.addEventListener('click', () => {
    if (!'SpeechRecognition' in window && !'webkitSpeechRecognition' in window) {
      appendCliMessage("Speech recognition not supported in this browser.", 'error');
      return;
    }

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();

    recognition.lang = 'en-US';
    recognition.interimResults = false;

    voiceButton.classList.add('animate-pulse', 'bg-red-600');
    voiceButton.innerHTML = '<svg xmlns="<http://www.w3.org/2000/svg>" width="16" height="16" fill="currentColor" class="bi bi-mic-fill" viewBox="0 0 16 16"><path d="M5 3a3 3 0 0 1 6 0v5a3 3 0 0 1-6 0V3z"/><path d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5z"/></svg>';

    recognition.start();

    recognition.onresult = (event) => {
      const transcript = event.results[0][0].transcript;
      cliInput.value = transcript;
    };

    recognition.onerror = (event) => {
      console.error('Speech recognition error', event.error);
      voiceButton.classList.remove('animate-pulse', 'bg-red-600');
      voiceButton.innerHTML = '<svg xmlns="<http://www.w3.org/2000/svg>" width="16" height="16" fill="currentColor" class="bi bi-mic" viewBox="0 0 16 16"><path d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5z"/><path d="M10 8a2 2 0 1 1-4 0V3a2 2 0 1 1 4 0v5zM8 0a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V3a3 3 0 0 0-3-3z"/></svg>';
    };

    recognition.onend = () => {
      voiceButton.classList.remove('animate-pulse', 'bg-red-600');
      voiceButton.innerHTML = '<svg xmlns="<http://www.w3.org/2000/svg>" width="16" height="16" fill="currentColor" class="bi bi-mic" viewBox="0 0 16 16"><path d="M3.5 6.5A.5.5 0 0 1 4 7v1a4 4 0 0 0 8 0V7a.5.5 0 0 1 1 0v1a5 5 0 0 1-4.5 4.975V15h3a.5.5 0 0 1 0 1h-7a.5.5 0 0 1 0-1h3v-2.025A5 5 0 0 1 3 8V7a.5.5 0 0 1 .5-.5z"/><path d="M10 8a2 2 0 1 1-4 0V3a2 2 0 1 1 4 0v5zM8 0a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0V3a3 3 0 0 0-3-3z"/></svg>';
    };
  });
}

// 7. Add Code Highlighting for Code in CLI Responses
function addCodeHighlighting() {
  // Load Prism.js for syntax highlighting
  const prismScript = document.createElement('script');
  prismScript.src = '<https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/prism.min.js>';
  document.head.appendChild(prismScript);

  const prismCss = document.createElement('link');
  prismCss.rel = 'stylesheet';
  prismCss.href = '<https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/themes/prism-tomorrow.min.css>';
  document.head.appendChild(prismCss);

  // Load language support
  const languages = ['javascript', 'python', 'bash', 'json'];
  languages.forEach(lang => {
    const script = document.createElement('script');
    script.src = `https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/components/prism-${lang}.min.js`;
    document.head.appendChild(script);
  });

  // Process messages to highlight code blocks
  const processCodeBlocks = (element) => {
    // Look for markdown-style code blocks
    const text = element.innerHTML;
    const codeBlockRegex = /```([a-z]*)\\\\n([\\\\s\\\\S]*?)```/g;

    element.innerHTML = text.replace(codeBlockRegex, (match, language, code) => {
      const lang = language || 'javascript';
      return `<pre><code class="language-${lang}">${code.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>`;
    });

    // Trigger Prism to highlight
    if (window.Prism) {
      Prism.highlightAllUnder(element);
    }
  };

  // Override the appendCliMessage function to include code highlighting
  const originalAppendCliMessage = appendCliMessage;
  appendCliMessage = function(text, sender) {
    originalAppendCliMessage(text, sender);
    if (sender === 'gemini' || sender === 'system') {
      const lastMessage = cliOutput.lastChild;
      processCodeBlocks(lastMessage);
    }
  };
}

// 8. Model Parameter Controls
function addModelParameterControls() {
  const paramSection = document.createElement('div');
  paramSection.className = 'mt-4 p-3 bg-slate-800 rounded-lg border border-slate-700';
  paramSection.innerHTML = `
    <div class="flex justify-between items-center mb-2">
      <h4 class="text-sm font-semibold text-slate-300">Model Parameters</h4>
      <button id="toggle-params" class="text-xs text-sky-400">Show</button>
    </div>
    <div id="param-controls" class="hidden">
      <div class="grid grid-cols-2 gap-2">
        <div>
          <label class="block text-xs text-slate-400 mb-1">Temperature</label>
          <input type="range" id="temp-slider" min="0" max="1" step="0.1" value="0.7" class="w-full">
          <div class="text-right text-xs text-slate-400"><span id="temp-value">0.7</span></div>
        </div>
        <div>
          <label class="block text-xs text-slate-400 mb-1">Top P</label>
          <input type="range" id="top-p-slider" min="0" max="1" step="0.05" value="0.95" class="w-full">
          <div class="text-right text-xs text-slate-400"><span id="top-p-value">0.95</span></div>
        </div>
      </div>
    </div>
  `;

  // Add after model selector
  modelSelector.parentNode.parentNode.appendChild(paramSection);

  // Set up toggle functionality
  const toggleButton = document.getElementById('toggle-params');
  const paramControls = document.getElementById('param-controls');

  toggleButton.addEventListener('click', () => {
    if (paramControls.classList.contains('hidden')) {
      paramControls.classList.remove('hidden');
      toggleButton.textContent = 'Hide';
    } else {
      paramControls.classList.add('hidden');
      toggleButton.textContent = 'Show';
    }
  });

  // Set up value display
  const tempSlider = document.getElementById('temp-slider');
  const tempValue = document.getElementById('temp-value');
  const topPSlider = document.getElementById('top-p-slider');
  const topPValue = document.getElementById('top-p-value');

  tempSlider.addEventListener('input', () => {
    tempValue.textContent = tempSlider.value;
  });

  topPSlider.addEventListener('input', () => {
    topPValue.textContent = topPSlider.value;
  });
}

// 9. Add Chat Memory Management
function addChatMemoryManagement() {
  const memoryManager = document.createElement('div');
  memoryManager.className = 'flex justify-between items-center text-xs text-slate-400 mt-2';
  memoryManager.innerHTML = `
    <div>Memory: <span id="memory-usage">0</span> tokens</div>
    <button id="clear-memory" class="text-sky-400 hover:text-sky-300">Clear Memory</button>
  `;

  // Add after CLI output
  cliOutput.parentNode.appendChild(memoryManager);

  const memoryUsage = document.getElementById('memory-usage');
  const clearMemoryBtn = document.getElementById('clear-memory');

  // Rough token count estimate (very approximate)
  function estimateTokenCount(text) {
    // Roughly 4 chars per token for English
    return Math.ceil(text.length / 4);
  }

  // Update memory usage display
  function updateMemoryUsage() {
    let totalTokens = 0;
    cliChatHistory.forEach(msg => {
      if (msg.parts && msg.parts[0] && msg.parts[0].text) {
        totalTokens += estimateTokenCount(msg.parts[0].text);
      }
    });

    memoryUsage.textContent = totalTokens;

    // Visual warning if using too many tokens
    if (totalTokens > 3000) {
      memoryUsage.className = 'text-yellow-400';
    } else if (totalTokens > 6000) {
      memoryUsage.className = 'text-red-400';
    } else {
      memoryUsage.className = '';
    }
  }

  // Clear memory button
  clearMemoryBtn.addEventListener('click', () => {
    cliChatHistory = [];
    updateMemoryUsage();
    appendCliMessage('Chat memory cleared.', 'system');
  });

  // Override appendCliMessage to update memory usage
  const originalAppendCliMessage = appendCliMessage;
  appendCliMessage = function(text, sender) {
    originalAppendCliMessage(text, sender);
    updateMemoryUsage();
  };
}

// Initialize the new features
document.addEventListener('DOMContentLoaded', async () => {
  const gpuSupport = await initWebGPU();
  if (gpuSupport) {
    console.log('WebGPU available and initialized');
  }

  enhanceCliWithAutocomplete();
  setupVoiceInput();
  addCodeHighlighting();
  addModelParameterControls();
  addChatMemoryManagement();

  console.log('HYPERION Command Deck enhancements loaded');
});

// 10. Quantum-inspired Feature Enhancements

function addQuantumInspiredFeatures() {
  console.log('Initializing quantum-inspired enhancements');

  // Quantum Random Number Generator using Web Crypto API
  // (simulating quantum randomness with CSPRNG)
  function quantumRandom(min, max) {
    const array = new Uint32Array(1);
    window.crypto.getRandomValues(array);
    return min + (array[0] % (max - min + 1));
  }

  // Quantum-inspired Superposition for Multi-Path Decision Making
  class QuantumDecisionTree {
    constructor(options) {
      this.options = options;
      this.weights = options.map(() => 1); // Equal probability initially
      this.history = [];
    }

    // Simulate quantum measurement - collapse to one outcome
    measure() {
      // Calculate total weight
      const totalWeight = this.weights.reduce((a, b) => a + b, 0);

      // Generate a random threshold
      const threshold = Math.random() * totalWeight;

      // Find which option was "measured"
      let cumulativeWeight = 0;
      for (let i = 0; i < this.options.length; i++) {
        cumulativeWeight += this.weights[i];
        if (threshold <= cumulativeWeight) {
          // Record the choice in history
          this.history.push(i);
          // Return the selected option
          return this.options[i];
        }
      }

      // Fallback (should never reach here)
      return this.options[0];
    }

    // Update weights based on feedback (quantum-inspired learning)
    updateWeights(choiceIndex, feedback) {
      // Positive feedback increases probability of that option
      if (feedback > 0) {
        this.weights[choiceIndex] *= 1 + (feedback * 0.1);
      }
      // Negative feedback decreases probability
      else if (feedback < 0) {
        this.weights[choiceIndex] *= 1 - (Math.abs(feedback) * 0.1);
        this.weights[choiceIndex] = Math.max(0.1, this.weights[choiceIndex]); // Ensure minimum probability
      }

      // Normalize weights periodically to prevent overflow
      if (this.history.length % 10 === 0) {
        const sum = this.weights.reduce((a, b) => a + b, 0);
        this.weights = this.weights.map(w => w / sum * this.weights.length);
      }
    }
  }

  // Simulate quantum entanglement for paired UI elements
  function createEntangledElements(elementA, elementB, property) {
    let entanglementActive = true;

    const updatePair = (source, target) => {
      if (!entanglementActive) return;

      entanglementActive = false;
      if (property === 'value') {
        target.value = source.value;
      } else if (property === 'checked') {
        target.checked = source.checked;
      } else if (property === 'className') {
        target.className = source.className;
      } else if (typeof property === 'function') {
        property(source, target);
      }
      entanglementActive = true;
    };

    // Set up bidirectional binding
    elementA.addEventListener('change', () => updatePair(elementA, elementB));
    elementB.addEventListener('change', () => updatePair(elementB, elementA));

    return {
      breakEntanglement: () => {
        entanglementActive = false;
      }
    };
  }

  // Quantum-inspired Chat Analysis using Interference Patterns
  function setupQuantumChatAnalysis() {
    // Simulate quantum interference between messages to detect patterns
    let messageVectors = [];

    // Process message into vector representation (simplified)
    function vectorizeMessage(message) {
      // Convert message to lowercase and remove punctuation
      const cleanMessage = message.toLowerCase().replace(/[^\\\\w\\\\s]/g, '');
      const words = cleanMessage.split(/\\\\s+/);

      // Simple bag of words vector (could be replaced with more sophisticated embedding)
      const vector = {};
      words.forEach(word => {
        if (word.length > 2) { // Ignore very short words
          vector[word] = (vector[word] || 0) + 1;
        }
      });

      return vector;
    }

    // Calculate similarity (dot product) between two vectors
    function calculateInterference(vecA, vecB) {
      let interference = 0;
      for (const word in vecA) {
        if (vecB[word]) {
          interference += vecA[word] * vecB[word];
        }
      }
      return interference;
    }

    // Analyze message for patterns with previous messages
    function analyzeMessagePatterns(message) {
      const vector = vectorizeMessage(message);
      const patterns = [];

      // Add to message history
      messageVectors.push({
        vector,
        timestamp: Date.now(),
        text: message
      });

      // Keep only last 20 messages
      if (messageVectors.length > 20) {
        messageVectors.shift();
      }

      // Find interference patterns with previous messages
      for (let i = 0; i < messageVectors.length - 1; i++) {
        const interference = calculateInterference(vector, messageVectors[i].vector);
        if (interference > 2) { // Threshold for significance
          patterns.push({
            relatedMessage: messageVectors[i].text,
            strength: interference,
            timeDiff: Date.now() - messageVectors[i].timestamp
          });
        }
      }

      return patterns;
    }

    // Override the submitCliMessage function to include quantum analysis
    const originalSubmitCliMessage = submitCliMessage;
    submitCliMessage = async function(text) {
      if (text.trim()) {
        // Perform quantum-inspired pattern analysis
        const patterns = analyzeMessagePatterns(text);

        // If significant patterns found, add context to message
        if (patterns.length > 0) {
          // Sort patterns by strength
          patterns.sort((a, b) => b.strength - a.strength);

          // Add top related message as context
          const contextMsg = `Related context: "${patterns[0].relatedMessage}"`;
          appendCliMessage(contextMsg, 'system', true); // Add as hidden system message
        }
      }

      // Call original function
      return originalSubmitCliMessage(text);
    };

    return {
      getMessageVectors: () => messageVectors,
      analyzeMessage: analyzeMessagePatterns
    };
  }

  // Implement quantum-inspired UI Animations
  function addQuantumAnimations() {
    // GSAP-powered probability wave animations
    function createProbabilityWave(element, options = {}) {
      const defaults = {
        amplitude: 5,
        frequency: 0.5,
        duration: 2,
        color: '#00aaff'
      };

      const settings = { ...defaults, ...options };

      // Create wave container
      const waveContainer = document.createElement('div');
      waveContainer.className = 'absolute top-0 left-0 w-full h-full pointer-events-none overflow-hidden';
      waveContainer.style.zIndex = '-1';

      // Add to element
      element.style.position = 'relative';
      element.appendChild(waveContainer);

      // Create wave SVG
      const svgNS = '<http://www.w3.org/2000/svg>';
      const svg = document.createElementNS(svgNS, 'svg');
      svg.setAttribute('width', '100%');
      svg.setAttribute('height', '100%');
      svg.style.opacity = '0.3';

      const path = document.createElementNS(svgNS, 'path');
      path.setAttribute('fill', 'none');
      path.setAttribute('stroke', settings.color);
      path.setAttribute('stroke-width', '2');

      svg.appendChild(path);
      waveContainer.appendChild(svg);

      // Update wave path
      function updateWavePath() {
        const width = waveContainer.offsetWidth;
        const height = waveContainer.offsetHeight;
        const points = [];

        for (let x = 0; x <= width; x += 5) {
          const y = (height / 2) + Math.sin(x * settings.frequency * 0.01) * settings.amplitude;
          points.push(`${x},${y}`);
        }

        path.setAttribute('d', 'M' + points.join(' L'));
      }

      // Initial draw
      updateWavePath();

      // Animate wave
      gsap.to(settings, {
        amplitude: settings.amplitude * 2,
        frequency: settings.frequency * 1.5,
        duration: settings.duration,
        yoyo: true,
        repeat: -1,
        ease: "sine.inOut",
        onUpdate: updateWavePath
      });

      return {
        collapse: () => {
          gsap.to(settings, {
            amplitude: 0,
            duration: 0.5,
            onUpdate: updateWavePath,
            onComplete: () => {
              waveContainer.remove();
            }
          });
        }
      };
    }

    // Add quantum wave effects to buttons
    document.querySelectorAll('button').forEach(button => {
      if (!button.classList.contains('quantum-wave-applied')) {
        button.classList.add('quantum-wave-applied');

        button.addEventListener('mouseenter', () => {
          const wave = createProbabilityWave(button, {
            amplitude: 3,
            frequency: 0.8,
            color: '#4ade80'
          });

          button.addEventListener('mouseleave', () => {
            wave.collapse();
          }, { once: true });
        });
      }
    });
  }

  // Initialize and expose quantum features
  const quantumAnalysis = setupQuantumChatAnalysis();
  addQuantumAnimations();

  // Expose quantum utilities to global scope
  window.quantum = {
    random: quantumRandom,
    DecisionTree: QuantumDecisionTree,
    createEntangledElements,
    chatAnalysis: quantumAnalysis
  };

  // Example usage: quantum decision tree for response type selection
  const responseDecisionTree = new QuantumDecisionTree([
    'analytical', 'creative', 'concise', 'detailed'
  ]);

  // Use in generateResponse function (hypothetical)
  window.getResponseStyle = () => {
    return responseDecisionTree.measure();
  };

  // Add feedback mechanism for quantum learning
  cliOutput.addEventListener('click', e => {
    if (e.target.classList.contains('feedback-button')) {
      const feedback = parseInt(e.target.dataset.value);
      const responseIndex = parseInt(e.target.dataset.index);
      responseDecisionTree.updateWeights(responseIndex, feedback);
      e.target.parentNode.innerHTML = 'Feedback received';
    }
  });

  console.log('Quantum-inspired features initialized');
  return true;
}

// Call the function to add quantum features
document.addEventListener('DOMContentLoaded', () => {
  // Wait for base initialization to complete
  setTimeout(() => {
    addQuantumInspiredFeatures();
  }, 1000);
});

/* Implementing an advanced quantum-inspired visualization component */
function addQuantumVisualizer() {
  // Create a container for our quantum visualizations
  const visualizerContainer = document.createElement('div');
  visualizerContainer.id = 'quantum-visualizer';
  visualizerContainer.className = 'fixed bottom-4 right-4 w-64 h-64 bg-gray-900 rounded-lg overflow-hidden shadow-lg z-50';
  visualizerContainer.style.display = 'none';
  document.body.appendChild(visualizerContainer);

  // Create toggle button
  const toggleButton = document.createElement('button');
  toggleButton.id = 'toggle-visualizer';
  toggleButton.className = 'fixed bottom-4 right-4 bg-indigo-600 hover:bg-indigo-700 text-white p-2 rounded-full shadow-lg z-50';
  toggleButton.innerHTML = '<svg xmlns="<http://www.w3.org/2000/svg>" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>';
  document.body.appendChild(toggleButton);

  // Initialize Three.js scene
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);

  const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setSize(256, 256);
  renderer.setClearColor(0x000000, 0.2);
  visualizerContainer.appendChild(renderer.domElement);

  // Add ambient light
  const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
  scene.add(ambientLight);

  // Add directional light
  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
  directionalLight.position.set(1, 1, 1).normalize();
  scene.add(directionalLight);

  // Create quantum particles system
  const particleCount = 50;
  const particles = new THREE.Group();
  scene.add(particles);

  // Quantum particle geometry and material
  const particleGeometry = new THREE.SphereGeometry(0.2, 8, 8);
  const particleMaterial = new THREE.MeshPhongMaterial({
    color: 0x4ade80,
    emissive: 0x2b9652,
    shininess: 50,
    transparent: true,
    opacity: 0.8
  });

  // Create particles
  for (let i = 0; i < particleCount; i++) {
    const particle = new THREE.Mesh(particleGeometry, particleMaterial.clone());

    // Randomize color slightly for visual variety
    particle.material.color.setHSL(
      0.3 + Math.random() * 0.1,  // green-blue hue
      0.7 + Math.random() * 0.3,  // saturation
      0.5 + Math.random() * 0.2   // lightness
    );

    // Position in spherical pattern
    const theta = Math.random() * Math.PI * 2;
    const phi = Math.acos(2 * Math.random() - 1);
    const radius = 2 + Math.random() * 3;

    particle.position.x = radius * Math.sin(phi) * Math.cos(theta);
    particle.position.y = radius * Math.sin(phi) * Math.sin(theta);
    particle.position.z = radius * Math.cos(phi);

    // Store original position
    particle.userData.originalPosition = particle.position.clone();

    // Add to group
    particles.add(particle);
  }

  // Add connections between particles (entanglement)
  const lineMaterial = new THREE.LineBasicMaterial({
    color: 0x00aaff,
    transparent: true,
    opacity: 0.3
  });

  const connections = [];

  // Create connections between particles (not all, just some to avoid clutter)
  for (let i = 0; i < particleCount; i++) {
    // Connect to 2-3 other particles
    const connectionCount = 2 + Math.floor(Math.random() * 2);
    for (let j = 0; j < connectionCount; j++) {
      // Choose a random particle to connect to
      const targetIndex = Math.floor(Math.random() * particleCount);
      if (targetIndex !== i) {
        const geometry = new THREE.BufferGeometry();

        // We'll update these positions in the animation loop
        geometry.setAttribute('position', new THREE.BufferAttribute(
          new Float32Array(6), 3
        ));

        const line = new THREE.Line(geometry, lineMaterial);
        scene.add(line);

        connections.push({
          line,
          sourceIndex: i,
          targetIndex
        });
      }
    }
  }

  // Position camera
  camera.position.z = 10;

  // Toggle visualizer display
  toggleButton.addEventListener('click', () => {
    if (visualizerContainer.style.display === 'none') {
      visualizerContainer.style.display = 'block';
      toggleButton.classList.add('active');
      toggleButton.classList.add('bg-indigo-800');
      isAnimating = true;
    } else {
      visualizerContainer.style.display = 'none';
      toggleButton.classList.remove('active');
      toggleButton.classList.remove('bg-indigo-800');
      isAnimating = false;
    }
  });

  // Animation variables
  let isAnimating = false;
  let time = 0;

  // Animation function
  function animate() {
    if (!isAnimating) return;

    requestAnimationFrame(animate);

    time += 0.01;

    // Rotate the entire particle system
    particles.rotation.y = time * 0.2;
    particles.rotation.x = time * 0.1;

    // Update particle positions with quantum-like behavior
    particles.children.forEach((particle, index) => {
      const originalPos = particle.userData.originalPosition;

      // Wave function simulation
      const xOffset = Math.sin(time + index * 0.2) * 0.3;
      const yOffset = Math.cos(time + index * 0.3) * 0.3;
      const zOffset = Math.sin(time * 1.5 + index * 0.7) * 0.3;

      particle.position.x = originalPos.x + xOffset;
      particle.position.y = originalPos.y + yOffset;
      particle.position.z = originalPos.z + zOffset;

      // Pulse particle size
      const scale = 0.8 + Math.sin(time * 2 + index) * 0.2;
      particle.scale.set(scale, scale, scale);

      // Pulse opacity for shimmering effect
      particle.material.opacity = 0.5 + Math.sin(time * 3 + index * 2) * 0.3;
    });

    // Update connections between particles
    connections.forEach(connection => {
      const sourceParticle = particles.children[connection.sourceIndex];
      const targetParticle = particles.children[connection.targetIndex];

      const positions = connection.line.geometry.attributes.position.array;

      // Set line start position (source particle)
      positions[0] = sourceParticle.position.x;
      positions[1] = sourceParticle.position.y;
      positions[2] = sourceParticle.position.z;

      // Set line end position (target particle)
      positions[3] = targetParticle.position.x;
      positions[4] = targetParticle.position.y;
      positions[5] = targetParticle.position.z;

      connection.line.geometry.attributes.position.needsUpdate = true;

      // Adjust opacity based on distance
      const distance = sourceParticle.position.distanceTo(targetParticle.position);
      connection.line.material.opacity = 0.5 * (1 - Math.min(1, distance / 8));
    });

    renderer.render(scene, camera);
  }

  // Start animation loop when visualizer is shown
  toggleButton.addEventListener('click', () => {
    if (visualizerContainer.style.display === 'block') {
      isAnimating = true;
      animate();
    }
  });

  // Respond to system activity by affecting the visualizer
  function pulseOnActivity() {
    // Find a random subset of particles to pulse
    const pulseCount = 5 + Math.floor(Math.random() * 10);
    const indices = [];

    while (indices.length < pulseCount) {
      const index = Math.floor(Math.random() * particleCount);
      if (!indices.includes(index)) {
        indices.push(index);
      }
    }

    // Apply pulse animation to selected particles
    indices.forEach(index => {
      const particle = particles.children[index];

      // Store original color
      const originalColor = particle.material.color.clone();
      const originalEmissive = particle.material.emissive.clone();

      // Flash to bright color
      particle.material.color.set(0xffffff);
      particle.material.emissive.set(0x4ade80);

      // Scale up
      gsap.to(particle.scale, {
        x: 2,
        y: 2,
        z: 2,
        duration: 0.3,
        yoyo: true,
        repeat: 1,
        ease: "power2.out"
      });

      // Restore original color
      setTimeout(() => {
        gsap.to(particle.material.color, {
          r: originalColor.r,
          g: originalColor.g,
          b: originalColor.b,
          duration: 0.5
        });

        gsap.to(particle.material.emissive, {
          r: originalEmissive.r,
          g: originalEmissive.g,
          b: originalEmissive.b,
          duration: 0.5
        });
      }, 300);
    });
  }

  // Expose API for other parts of the application
  return {
    pulse: pulseOnActivity,
    toggleVisibility: () => {
      toggleButton.click();
    }
  };
}

// Initialize the quantum visualizer when the page is ready
document.addEventListener('DOMContentLoaded', () => {
  setTimeout(() => {
    window.quantumVisualizer = addQuantumVisualizer();
    console.log('Quantum visualizer initialized');

    // Connect to other systems
    // Listen for significant system events and pulse the visualizer
    document.addEventListener('quantumEvent', () => {
      if (window.quantumVisualizer) {
        window.quantumVisualizer.pulse();
      }
    });
  }, 1500);

I'll create a comprehensive Electron-based Quantum Computing Visualizer application by integrating your Python ecosystem analysis code with the provided Three.js visualization interface. The result will be an interactive quantum computing studio with gamification elements.

Here's the complete integrated script, combining the ecosystem analysis functionality with an immersive 3D visualization interface:

// quantum-studio.js - Main Electron application entry point
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');

// Python bridge for quantum computing functionality
const quantumBridge = require('./quantum-bridge');

let mainWindow;

// Initialize the main application window
function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js')
    },
    frame: false, // Frameless for modern UI
    backgroundColor: '#000000',
  });

  mainWindow.loadFile('index.html');
  
  // Open DevTools in development
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }
  
  return mainWindow;
}

// Application initialization
app.whenReady().then(() => {
  const mainWindow = createMainWindow();

  // IPC handlers for quantum operations
  ipcMain.handle('get-ecosystem-data', async () => {
    return quantumBridge.getEcosystemData();
  });

  ipcMain.handle('run-quantum-simulation', async (event, circuitData) => {
    try {
      return await quantumBridge.simulateCircuit(circuitData);
    } catch (error) {
      console.error('Simulation error:', error);
      throw error;
    }
  });

  ipcMain.handle('generate-visualization', async (event, visualizationType, data) => {
    try {
      return await quantumBridge.generateVisualization(visualizationType, data);
    } catch (error) {
      console.error('Visualization error:', error);
      throw error;
    }
  });

  // Generate recommendation based on focus area
  ipcMain.handle('get-stack-recommendation', async (event, focusArea) => {
    try {
      return await quantumBridge.getStackRecommendation(focusArea);
    } catch (error) {
      console.error('Recommendation error:', error);
      throw error;
    }
  });

  // Create filesystem directories if they don't exist
  const dirs = ['./circuits', './results', './visualizations'];
  dirs.forEach(dir => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createMainWindow();
  }
});

// quantum-bridge.js - Bridge between Electron and Python
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

// Ecosystem data from your Python script
const ecosystemData = {
  "Algorithm Libraries": [
    {"Name": "Cirq", "Sponsor": "Google", "Description": "A framework for NISQ circuits", "Category": "Core"},
    {"Name": "OpenFermion", "Sponsor": "Google", "Description": "Quantum chemistry algorithms", "Category": "Algorithm"},
    {"Name": "Qualtran", "Sponsor": "Google", "Description": "Fault-tolerant quantum algorithms", "Category": "Algorithm"},
    {"Name": "ReCirq", "Sponsor": "Google", "Description": "Example experiments and tutorials", "Category": "Tools"},
    {"Name": "Stim", "Sponsor": "Google", "Description": "Clifford circuits simulation", "Category": "Simulation"},
    {"Name": "TensorFlow Quantum", "Sponsor": "Google", "Description": "Quantum machine learning", "Category": "Algorithm"},
    {"Name": "unitary", "Sponsor": "Google", "Description": "Quantum behaviors for games", "Category": "Application"},
    {"Name": "PennyLane", "Sponsor": "Xanadu", "Description": "Quantum machine learning", "Category": "Algorithm"}
  ],
  "Development Tools": [
    {"Name": "BQSKit", "Sponsor": "Lawrence Berkeley Labs", "Description": "Quantum compiler framework", "Category": "Compiler"},
    {"Name": "Mitiq", "Sponsor": "Unitary Foundation", "Description": "Error mitigation", "Category": "QEC"},
    {"Name": "pyGSTi", "Sponsor": "Sandia National Labs", "Description": "Modeling noisy processors", "Category": "Characterization"},
    {"Name": "Qristal", "Sponsor": "Quantum Brilliance", "Description": "Hybrid quantum programs", "Category": "Development"},
    {"Name": "Quantum Programming Studio", "Sponsor": "Quantastica", "Description": "Web system for algorithms", "Category": "IDE"},
    {"Name": "QUEKO", "Sponsor": "UCLA", "Description": "Benchmarks with optimal solutions", "Category": "Benchmarking"},
    {"Name": "QuTiP", "Sponsor": "QuTiP", "Description": "Numerical Hamiltonian simulations", "Category": "Simulation"},
    {"Name": "staq", "Sponsor": "softwareQ Inc", "Description": "Quantum circuit compilation", "Category": "Compiler"},
    {"Name": "Superstaq", "Sponsor": "Infleqtion", "Description": "Hardware-optimized execution", "Category": "Optimization"},
    {"Name": "tket", "Sponsor": "Quantinuum", "Description": "Circuit optimization", "Category": "Compiler"},
    {"Name": "XACC", "Sponsor": "Oak Ridge National Labs", "Description": "Extensible compilation framework", "Category": "Compiler"}
  ],
  "Simulators": [
    {"Name": "Qibo", "Sponsor": "Technology Innovation Institute", "Description": "Hardware-accelerated simulation", "Category": "Simulation"},
    {"Name": "qsim", "Sponsor": "Google", "Description": "Schrödinger simulations", "Category": "Simulation"},
    {"Name": "quimb", "Sponsor": "Johnnie Gray", "Description": "Tensor-network simulator", "Category": "Simulation"},
    {"Name": "qulacs", "Sponsor": "Quansys", "Description": "Schrödinger simulations", "Category": "Simulation"},
    {"Name": "Stim", "Sponsor": "Google", "Description": "Clifford circuits simulation", "Category": "Simulation"},
    {"Name": "cuQuantum", "Sponsor": "NVIDIA", "Description": "GPU-accelerated simulation", "Category": "Simulation"}
  ]
};

// Get ecosystem data
function getEcosystemData() {
  return ecosystemData;
}

// Run Python script and return promise with result
function runPythonScript(scriptName, args = [], inputData = null) {
  return new Promise((resolve, reject) => {
    const scriptPath = path.join(__dirname, 'python-scripts', scriptName);
    const pythonProcess = spawn('python', [scriptPath, ...args]);
    
    let result = '';
    let errorOutput = '';

    // Send input data if provided
    if (inputData) {
      pythonProcess.stdin.write(JSON.stringify(inputData));
      pythonProcess.stdin.end();
    }

    pythonProcess.stdout.on('data', (data) => {
      result += data.toString();
    });

    pythonProcess.stderr.on('data', (data) => {
      errorOutput += data.toString();
    });

    pythonProcess.on('close', (code) => {
      if (code === 0) {
        try {
          const parsedResult = JSON.parse(result);
          resolve(parsedResult);
        } catch (e) {
          resolve(result);
        }
      } else {
        reject(new Error(`Python process exited with code ${code}: ${errorOutput}`));
      }
    });
  });
}

// Simulate quantum circuit
async function simulateCircuit(circuitData) {
  // For development, return mock data
  // In production, this would call actual quantum simulators via Python
  const circuitId = uuidv4();
  const tempFilePath = path.join(__dirname, 'temp', `${circuitId}.json`);
  
  try {
    // Write circuit data to temporary file
    fs.writeFileSync(tempFilePath, JSON.stringify(circuitData));
    
    // Determine which simulator to use based on circuit size and type
    let simulator = 'cirq';
    if (circuitData.use_gpu && circuitData.qubit_count > 20) {
      simulator = 'cuquantum';
    } else if (circuitData.qubit_count > 30) {
      simulator = 'qsim';
    }
    
    // In a real implementation, we would call Python here:
    // return await runPythonScript('simulate_circuit.py', [tempFilePath, simulator]);
    
    // For demo purposes, return mock data
    return mockSimulationResults(circuitData);
  } catch (error) {
    console.error('Simulation error:', error);
    throw error;
  } finally {
    // Clean up temp file
    if (fs.existsSync(tempFilePath)) {
      fs.unlinkSync(tempFilePath);
    }
  }
}

// Generate mock simulation results
function mockSimulationResults(circuitData) {
  const results = {
    id: uuidv4(),
    timestamp: Date.now(),
    circuit: {
      qubit_count: circuitData.qubit_count || 6,
      gate_count: circuitData.gates ? circuitData.gates.length : 10,
      depth: circuitData.depth || 8
    },
    execution_time_ms: Math.random() * 1000 + 50,
    probabilities: {},
    measurements: {},
    fidelity: 0.99 - (Math.random() * 0.05)
  };
  
  // Generate random probabilities that sum to 1
  const numStates = Math.min(10, Math.pow(2, results.circuit.qubit_count));
  let remainingProb = 1.0;
  
  for (let i = 0; i < numStates - 1; i++) {
    const stateName = i.toString(2).padStart(results.circuit.qubit_count, '0');
    const prob = i === 0 ? 0.35 : Math.random() * remainingProb * 0.5;
    results.probabilities[stateName] = prob;
    results.measurements[stateName] = Math.round(prob * 1000);
    remainingProb -= prob;
  }
  
  // Add the final state with remaining probability
  const finalState = '1'.repeat(results.circuit.qubit_count);
  results.probabilities[finalState] = remainingProb;
  results.measurements[finalState] = Math.round(remainingProb * 1000);
  
  return results;
}

// Generate visualization
async function generateVisualization(visualizationType, data) {
  // This would call Python visualization libraries
  // For demo, return mock data
  return {
    type: visualizationType,
    data: data,
    imageUrl: `visualizations/${visualizationType}_${Date.now()}.png`,
    success: true
  };
}

// Get stack recommendation
function getStackRecommendation(focusArea = "general") {
  const stack = [];

  // Core framework
  stack.push({"Name": "Cirq", "Purpose": "Core quantum programming framework"});

  // Add tools based on focus area
  if (focusArea === "chemistry") {
    stack.push({"Name": "OpenFermion", "Purpose": "Quantum chemistry simulations"});
    stack.push({"Name": "qsim", "Purpose": "Efficient circuit simulation"});
  } else if (focusArea === "ml") {
    stack.push({"Name": "TensorFlow Quantum", "Purpose": "Quantum machine learning"});
    stack.push({"Name": "PennyLane", "Purpose": "Hybrid quantum-classical ML"});
  } else if (focusArea === "error_correction") {
    stack.push({"Name": "Stim", "Purpose": "Error correction simulation"});
    stack.push({"Name": "Mitiq", "Purpose": "Error mitigation techniques"});
  } else {  // general
    stack.push({"Name": "ReCirq", "Purpose": "Example experiments"});
    stack.push({"Name": "tket", "Purpose": "Circuit optimization"});
  }

  // Always add development tools
  stack.push({"Name": "Quantum Programming Studio", "Purpose": "Visual circuit design"});

  return stack;
}

module.exports = {
  getEcosystemData,
  simulateCircuit,
  generateVisualization,
  getStackRecommendation
};

Now, let's create the HTML, CSS, and renderer.js files for the UI:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Quantum Studio</title>
  <link href="<https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap>" rel="stylesheet">
  <link href="<https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap>" rel="stylesheet">
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="app-container">
    <!-- Top navigation bar -->
    <div class="top-bar">
      <div class="logo">QUANTUM STUDIO</div>
      <div class="window-controls">
        <button id="minimize-btn" class="window-btn">−</button>
        <button id="maximize-btn" class="window-btn">□</button>
        <button id="close-btn" class="window-btn">×</button>
      </div>
    </div>
    
    <!-- Main content area -->
    <div class="main-content">
      <!-- Left sidebar with tools -->
      <div class="sidebar">
        <div class="section">
          <h3>QUANTUM TOOLS</h3>
          <ul id="quantum-tools-list">
            <li data-tool="cirq" class="active">Cirq Simulator</li>
            <li data-tool="qsim">qsim High-Performance</li>
            <li data-tool="cuquantum">cuQuantum GPU</li>
            <li data-tool="qulacs">Qulacs Fast Simulator</li>
            <li data-tool="tfq">TensorFlow Quantum</li>
            <li data-tool="openfermi">OpenFermion Chemistry</li>
          </ul>
        </div>
        
        <div class="section">
          <h3>VISUALIZATION</h3>
          <ul id="visualization-modes">
            <li data-mode="bloch" class="active">Bloch Sphere</li>
            <li data-mode="circuit">Circuit View</li>
            <li data-mode="matrix">Matrix Representation</li>
            <li data-mode="probability">Probability Landscape</li>
            <li data-mode="network">Ecosystem Network</li>
          </ul>
        </div>
        
        <div id="control-panel">
          <button id="run-simulation" class="primary-btn">RUN SIMULATION</button>
          <button id="export-results" class="secondary-btn">EXPORT RESULTS</button>
          <button id="open-skill-tree" class="secondary-btn">SKILL TREE</button>
          <button id="show-achievements" class="secondary-btn">ACHIEVEMENTS</button>
        </div>
      </div>
      
      <!-- Center area with 3D visualization -->
      <div id="main-view">
        <div id="canvas-container"></div>
        <div id="circuit-editor" class="hidden">
          <h2>Quantum Circuit Editor</h2>
          <div class="circuit-grid"></div>
          <div class="quantum-gates-toolbox">
            <div class="gate" data-gate="h" draggable="true">
              <div class="gate-symbol">H</div>
            </div>
            <div class="gate" data-gate="x" draggable="true">
              <div class="gate-symbol">X</div>
            </div>
            <div class="gate" data-gate="y" draggable="true">
              <div class="gate-symbol">Y</div>
            </div>
            <div class="gate" data-gate="z" draggable="true">
              <div class="gate-symbol">Z</div>
            </div>
            <div class="gate" data-gate="cnot" draggable="true">
              <div class="gate-symbol">CNOT</div>
            </div>
          </div>
        </div>
        
        <!-- Results panel (initially hidden) -->
        <div id="results-panel" class="hidden">
          <div class="panel-header">
            <h2>Simulation Results</h2>
            <button class="close-panel">×</button>
          </div>
          <div id="results-content"></div>
        </div>
      </div>
      
      <!-- Right sidebar with ecosystem explorer -->
      <div class="ecosystem-panel">
        <h3>QUANTUM ECOSYSTEM</h3>
        <div class="filter-controls">
          <select id="category-filter">
            <option value="all">All Categories</option>
            <option value="Algorithm">Algorithms</option>
            <option value="Simulation">Simulators</option>
            <option value="Compiler">Compilers</option>
            <option value="QEC">Error Correction</option>
          </select>
          <input type="text" id="search-tools" placeholder="Search tools...">
        </div>
        <div id="ecosystem-list"></div>
        <div class="recommendation-section">
          <h4>RECOMMENDED STACK</h4>
          <select id="focus-area">
            <option value="general">General Purpose</option>
            <option value="chemistry">Quantum Chemistry</option>
            <option value="ml">Machine Learning</option>
            <option value="error_correction">Error Correction</option>
          </select>
          <button id="get-recommendation" class="small-btn">Get Recommendation</button>
          <div id="recommendation-result"></div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Skill tree panel (initially hidden) -->
  <div id="skill-tree-panel" class="overlay-panel hidden">
    <div class="panel-header">
      <h2>QUANTUM SKILL TREE</h2>
      <button class="close-panel">×</button>
    </div>
    <div class="skill-tree-container">
      <svg id="skill-connections"></svg>
      <div id="skill-nodes"></div>
    </div>
  </div>
  
  <!-- Achievements panel (initially hidden) -->
  <div id="achievements-panel" class="overlay-panel hidden">
    <div class="panel-header">
      <h2>QUANTUM ACHIEVEMENTS</h2>
      <button class="close-panel">×</button>
    </div>
    <div class="progress-container">
      <div class="progress-bar">
        <div class="progress" style="width: 0%"></div>
      </div>
      <span class="progress-text">0/5</span>
    </div>
    <div class="achievements-list"></div>
  </div>
  
  <!-- Loading overlay -->
  <div id="loading-overlay" class="hidden">
    <div class="quantum-spinner"></div>
    <div class="loading-text">Processing Quantum State...</div>
  </div>
  
  <!-- Notification container for achievements and alerts -->
  <div id="notification-container"></div>
  
  <!-- Scripts -->
  <script src="<https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js>"></script>
  <script src="<https://cdn.jsdelivr.net/npm/d3@7>"></script>
  <script src="<https://cdn.jsdelivr.net/npm/@tweenjs/[email protected]/dist/tween.umd.js>"></script>
  <script src="renderer.js"></script>
  <script src="quantum-game-elements.js"></script>
</body>
</html>

/* styles.css */
:root {
  --primary-color: #00ffff;
  --primary-dark: #00aaaa;
  --secondary-color: #ff00ff;
  --secondary-dark: #aa00aa;
  --background-dark: #000000;
  --background-medium: rgba(0, 20, 40, 0.8);
  --background-light: rgba(0, 40, 60, 0.5);
  --text-color: #ffffff;
  --sidebar-width: 250px;
  --ecosystem-width: 300px;
  --top-bar-height: 50px;
}

body, html {
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
  background: var(--background-dark);
  color: var(--text-color);
  overflow: hidden;
  height: 100%;
  user-select: none;
}

/* App layout */
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.top-bar {
  height: var(--top-bar-height);
  background: var(--background-medium);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  -webkit-app-region: drag;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.logo {
  font-family: 'Orbitron', sans-serif;
  font-size: 20px;
  font-weight: 700;
  color: var(--primary-color);
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.window-controls {
  display: flex;
  -webkit-app-region: no-drag;
}

.window-btn {
  background: none;
  border: none;
  color: var(--text-color);
  font-size: 16px;
  width: 30px;
  height: 30px;
  border-radius: 4px;
  margin-left: 5px;
  cursor: pointer;
}

.window-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

#close-btn:hover {
  background: rgba(255, 0, 0, 0.5);
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* Sidebar */
.sidebar {
  width: var(--sidebar-width);
  background: var(--background-medium);
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.3);
  z-index: 10;
}

.section {
  margin-bottom: 30px;
}

.section h3 {
  font-family: 'Orbitron', sans-serif;
  font-size: 14px;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid var(--primary-color);
  color: var(--primary-color);
}

.sidebar ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sidebar li {
  padding: 10px;
  margin: 5px 0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.sidebar li:hover {
  background: var(--background-light);
}

.sidebar li.active {
  background: rgba(0, 255, 255, 0.2);
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
  color: var(--primary-color);
}

#control-panel {
  margin-top: auto;
  display: flex;
  flex-direction: column;
}

.primary-btn, .secondary-btn {
  font-family: 'Orbitron', sans-serif;
  padding: 12px;
  margin: 5px 0;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.primary-btn {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
  color: #000;
}

.secondary-btn {
  background: var(--background-light);
  color: var(--text-color);
  border: 1px solid var(--primary-color);
}

.primary-btn:hover {
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
  transform: translateY(-2px);
}

.secondary-btn:hover {
  background: rgba(0, 255, 255, 0.2);
}

.small-btn {
  padding: 5px 10px;
  font-size: 12px;
  background: var(--background-light);
  color: var(--text-color);
  border: 1px solid var(--primary-color);
  border-radius: 3px;
  cursor: pointer;
}

.small-btn:hover {
  background: rgba(0, 255, 255, 0.2);
}

/* Main view */
#main-view {
  flex: 1;
  position: relative;
  overflow: hidden;
}

#canvas-container {
  width: 100%;
  height: 100%;
}

/* Circuit editor */
#circuit-editor {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 20, 0.9);
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.circuit-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(5, 1fr);
  gap: 10px;
  margin: 20px 0;
  border: 1px solid rgba(0, 255, 255, 0.3);
  padding: 10px;
}

.quantum-gates-toolbox {
  display: flex;
  gap: 10px;
  padding: 10px;
  background: var(--background-medium);
  border-radius: 5px;
}

.gate {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 100, 150, 0.5);
  border: 1px solid var(--primary-color);
  border-radius: 4px;
  cursor: grab;
  position: relative;
}

.gate:hover {
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.gate-symbol {
  font-family: 'Orbitron', sans-serif;
  font-weight: bold;
  color: var(--primary-color);
}

.gate .gate-tooltip {
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: var(--background-medium);
  padding: 5px 10px;
  border-radius: 4px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
  z-index: 10;
}

.gate:hover .gate-tooltip {
  opacity: 1;
}

/* Results panel */
#results-panel {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: var(--background-medium);
  max-height: 40%;
  transform: translateY(100%);
  transition: transform 0.3s ease-out;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.5);
  z-index: 20;
}

#results-panel.visible {
  transform: translateY(0);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.3);
}

.panel-header h2 {
  margin: 0;
  font-size: 18px;
  font-family: 'Orbitron', sans-serif;
  color: var(--primary-color);
}

.close-panel {
  background: none;
  border: none;
  color: var(--text-color);
  font-size: 20px;
  cursor: pointer;
}

.close-panel:hover {
  color: var(--primary-color);
}

#results-content {
  padding: 20px;
  overflow-y: auto;
  max-height: calc(40vh - 50px);
}

/* Ecosystem panel */
.ecosystem-panel {
  width: var(--ecosystem-width);
  background: var(--background-medium);
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3);
  z-index: 10;
  overflow-y: auto;
}

.ecosystem-panel h3 {
  font-family: 'Orbitron', sans-serif;
  font-size: 14px;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid var(--primary-color);
  color: var(--primary-color);
}

.filter-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.filter-controls select, .filter-controls input {
  background: var(--background-light);
  border: 1px solid var(--primary-dark);
  color: var(--text-color);
  padding: 8px;
  border-radius: 4px;
  font-size: 14px;
}

.filter-controls select:focus, .filter-controls input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 5px rgba(0, 255, 255, 0.5);
}

#ecosystem-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.tool-card {
  background: var(--background-light);
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  border-left: 3px solid var(--primary-color);
  transition: all 0.2s;
}

.tool-card:hover {
  transform: translateX(5px);
  box-shadow: 0 0 10px rgba(0, 255, 255, 0.3);
}

.tool-card h4 {
  margin: 0 0 5px 0;
  font-family: 'Orbitron', sans-serif;
  color: var(--primary-color);
}

.tool-card .sponsor {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 5px;
}

.tool-card .description {
  font-size: 13px;
}

.tool-card .category {
  display: inline-block;
  font-size: 11px;
  background: var(--background-medium);
  padding: 3px 6px;
  border-radius: 3px;
  margin-top: 5px;
}

.recommendation-section {
  padding-top: 15px;
  border-top: 1px solid rgba(0, 255, 255, 0.3);
}

.recommendation-section h4 {
  font-family: 'Orbitron', sans-serif;
  font-size: 14px;
  margin: 0 0 10px 0;
  color: var(--primary-color);
}

#focus-area {
  width: 100%;
  margin-bottom: 10px;
}

#recommendation-result {
  margin-top: 15px;
  font-size: 13px;
}

.recommended-tool {
  padding: 8px;
  background: rgba(0, 255, 255, 0.1);
  border-radius: 4px;
  margin-bottom: 5px;
}

.recommended-tool .name {
  font-weight: bold;
  color: var(--primary-color);
}

.recommended-tool .purpose {
  font-size: 12px;
  margin-top: 3px;
}

/* Overlay panels */
.overlay-panel {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: var(--background-medium);
  border-radius: 8px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.7);
  z-index: 100;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

#skill-tree-panel {
  width: 800px;
  height: 600px;
}

#achievements-panel {
  width: 600px;
  height: 500px;
}

.progress-container {
  padding: 10px 20px;
  border-bottom: 1px solid rgba(0, 255, 255, 0.3);
}

.progress-bar {
  height: 10px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
  transition: width 0.5s;
}

.progress-text {
  font-size: 12px;
  text-align: right;
}

.achievements-list, .skill-tree-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.achievement {
  display: flex;
  padding: 10px;
  margin-bottom: 10px;
  background: var(--background-light);
  border-radius: 5px;
  transition: all 0.2s;
}

.achievement.locked {
  filter: grayscale(100%);
  opacity: 0.7;
}

.achievement-icon {
  width: 50px;
  height: 50px;
  background: var(--background-medium);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.achievement-icon img {
  width: 30px;
  height: 30px;
}

.achievement-info h4 {
  margin: 0 0 5px 0;
  font-family: 'Orbitron', sans-serif;
  color: var(--primary-color);
}

.achievement-info p {
  font-size: 13px;
  margin: 0;
}

/* Skill tree */
.skill-tree-container {
  position: relative;
  overflow: hidden;
}

svg.skill-connections {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.skill-nodes {
  position: relative;
  z-index: 2;
  min-height: 100%;
}

.skill-node {
  position: absolute;
  width: 60px;
  height: 60px;
  background: var(--background-medium);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid var(--primary-dark);
  transition: all 0.3s;
  cursor: pointer;
}

.skill-node.unlocked {
  background: radial-gradient(circle, var(--primary-color) 0%, var(--primary-dark) 100%);
  box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
}

.skill-node.locked {
  filter: grayscale(70%);
  opacity: 0.6;
}

.skill-node:hover {
  transform: scale(1.1);
}

.skill-icon {
  width: 30px;
  height: 30px;
  background-size: cover;
}

.skill-tooltip {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -100%);
  background: var(--background-medium);
  padding: 10px;
  border-radius: 5px;
  white-space: nowrap;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
  z-index: 10;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

.skill-node:hover .skill-tooltip {
  opacity: 1;
}

.skill-connection {
  stroke: var(--primary-dark);
  stroke-width: 2;
  fill: none;
  opacity: 0.5;
  transition: all 0.3s;
}

.skill-connection.unlocked {
  stroke: var(--primary-color);
  opacity: 1;
  stroke-dasharray: none;
  filter: drop-shadow(0 0 3px rgba(0, 255, 255, 0.5));
}

/* Loading overlay */
#loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 20, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.quantum-spinner {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 4px solid transparent;
  border-top-color: var(--primary-color);
  border-bottom-color: var(--secondary-color);
  animation: spin 1.5s linear infinite;
}

.quantum-spinner::before, .quantum-spinner::after {
  content: '';
  position: absolute;
  border-radius: 50%;
  border: 4px solid transparent;
}

.quantum-spinner::before {
  top: 5px;
  left: 5px;
  right: 5px;
  bottom: 5px;
  border-top-color: var(--secondary-color);
  border-bottom-color: var(--primary-color);
  animation: spin 2s linear infinite reverse;
}

.quantum-spinner::after {
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
  border-top-color: var(--primary-color);
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 20px;
  font-family: 'Orbitron', sans-serif;
  color: var(--primary-color);
  animation: pulse 1.5s infinite;
}

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

/* Notification container */
#notification-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.notification {
  display: flex;
  background: var(--background-medium);
  border-radius: 5px;
  margin-bottom: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  width: 300px;
  transform: translateX(120%);
  transition: transform 0.3s;
  overflow: hidden;
}

.notification.show {
  transform: translateX(0);
}

.notification-icon {
  width: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--background-light);
}

.notification-info {
  flex: 1;
  padding: 10px;
}

.notification-info h4 {
  margin: 0 0 5px 0;
  font-family: 'Orbitron', sans-serif;
  color: var(--primary-color);
  font-size: 14px;
}

.notification-info h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.notification-info p {
  margin: 0;
  font-size: 12px;
}

.notification.success {
  border-left: 4px solid var(--primary-color);
}

.notification.error {
  border-left: 4px solid #ff3333;
}

/* Utility classes */
.hidden {
  display: none !important;
}

// renderer.js - Main UI logic and 3D visualization
// This integrates the Three.js visualization with the quantum ecosystem data

// Global state
let scene, camera, renderer;
let quantumParticles = [];
let blochSpheres = [];
let currentTool = 'cirq';
let currentMode = 'bloch';
let animationId;
let ecosystemData = null;
let currentCircuit = {
  qubit_count: 6,
  gates: [],
  depth: 8,
  use_gpu: false
};

// DOM Elements
const domElements = {};

// Initialize when document is loaded
document.addEventListener('DOMContentLoaded', async () => {
  initDomElements();
  initEventListeners();
  await loadEcosystemData();
  renderEcosystemList();
  initVisualization();
  initSkillTree();
  initAchievements();
  
  // Show loading overlay for a brief moment for effect
  showLoading(true);
  setTimeout(() => {
    showLoading(false);
    showNotification('Quantum Studio Initialized', 'Welcome to the quantum computing experience!', 'success');
  }, 1500);
});

// Initialize DOM element references
function initDomElements() {
  domElements.sidebar = document.querySelector('.sidebar');
  domElements.toolsList = document.getElementById('quantum-tools-list');
  domElements.visualizationModes = document.getElementById('visualization-modes');
  domElements.runSimulation = document.getElementById('run-simulation');
  domElements.exportResults = document.getElementById('export-results');
  domElements.canvasContainer = document.getElementById('canvas-container');
  domElements.resultsPanel = document.getElementById('results-panel');
  domElements.resultsContent = document.getElementById('results-content');
  domElements.closePanelButtons = document.querySelectorAll('.close-panel');
  domElements.minimizeBtn = document.getElementById('minimize-btn');
  domElements.maximizeBtn = document.getElementById('maximize-btn');
  domElements.closeBtn = document.getElementById('close-btn');
  domElements.ecosystemList = document.getElementById('ecosystem-list');
  domElements.categoryFilter = document.getElementById('category-filter');
  domElements.searchTools = document.getElementById('search-tools');
  domElements.focusArea = document.getElementById('focus-area');
  domElements.getRecommendation = document.getElementById('get-recommendation');
  domElements.recommendationResult = document.getElementById('recommendation-result');
  domElements.skillTreePanel = document.getElementById('skill-tree-panel');
  domElements.openSkillTree = document.getElementById('open-skill-tree');
  domElements.achievementsPanel = document.getElementById('achievements-panel');
  domElements.showAchievements = document.getElementById('show-achievements');
  domElements.loadingOverlay = document.getElementById('loading-overlay');
  domElements.notificationContainer = document.getElementById('notification-container');
  domElements.circuitEditor = document.getElementById('circuit-editor');
}

// Initialize event listeners
function initEventListeners() {
  // Window control buttons
  domElements.minimizeBtn.addEventListener('click', () => {
    window.electron.minimize();
  });
  
  domElements.maximizeBtn.addEventListener('click', () => {
    window.electron.maximize();
  });
  
  domElements.closeBtn.addEventListener('click', () => {
    window.electron.close();
  });
  
  // Tool selection
  domElements.toolsList.querySelectorAll('li').forEach(item => {
    item.addEventListener('click', () => {
      setActiveTool(item.getAttribute('data-tool'));
    });
  });
  
  // Visualization mode selection
  domElements.visualizationModes.querySelectorAll('li').forEach(item => {
    item.addEventListener('click', () => {
      setVisualizationMode(item.getAttribute('data-mode'));
    });
  });
  
  // Run simulation button
  domElements.runSimulation.addEventListener('click', async () => {
    await runQuantumSimulation();
  });
  
  // Export results button
  domElements.exportResults.addEventListener('click', () => {
    exportResults();
  });
  
  // Close panel buttons
  domElements.closePanelButtons.forEach(button => {
    button.addEventListener('click', (e) => {
      const panel = e.target.closest('.overlay-panel, #results-panel');
      if (panel.id === 'results-panel') {
        panel.classList.remove('visible');
      } else {
        panel.classList.add('hidden');
      }
    });
  });
  
  // Category filter
  domElements.categoryFilter.addEventListener('change', () => {
    renderEcosystemList();
  });
  
  // Search tools
  domElements.searchTools.addEventListener('input', () => {
    renderEcosystemList();
  });
  
  // Get recommendation button
  domElements.getRecommendation.addEventListener('click', async () => {
    const focusArea = domElements.focusArea.value;
    await getStackRecommendation(focusArea);
  });
  
  // Open skill tree button
  domElements.openSkillTree.addEventListener('click', () => {
    domElements.skillTreePanel.classList.remove('hidden');
  });
  
  // Show achievements button
  domElements.showAchievements.addEventListener('click', () => {
    domElements.achievementsPanel.classList.remove('hidden');
  });
  
  // Window resize event
  window.addEventListener('resize', onWindowResize);
}

// Load ecosystem data
async function loadEcosystemData() {
  try {
    // In a real app, this would fetch from the backend
    // ecosystemData = await window.electron.getEcosystemData();
    
    // For demo, use the predefined data
    ecosystemData = {
      "Algorithm Libraries": [
        {"Name": "Cirq", "Sponsor": "Google", "Description": "A framework for NISQ circuits", "Category": "Core"},
        {"Name": "OpenFermion", "Sponsor": "Google", "Description": "Quantum chemistry algorithms", "Category": "Algorithm"},
        {"Name": "Qualtran", "Sponsor": "Google", "Description": "Fault-tolerant quantum algorithms", "Category": "Algorithm"},
        {"Name": "ReCirq", "Sponsor": "Google", "Description": "Example experiments and tutorials", "Category": "Tools"},
        {"Name": "Stim", "Sponsor": "Google", "Description": "Clifford circuits simulation", "Category": "Simulation"},
        {"Name": "TensorFlow Quantum", "Sponsor": "Google", "Description": "Quantum machine learning", "Category": "Algorithm"},
        {"Name": "unitary", "Sponsor": "Google", "Description": "Quantum behaviors for games", "Category": "Application"},
        {"Name": "PennyLane", "Sponsor": "Xanadu", "Description": "Quantum machine learning", "Category": "Algorithm"}
      ],
      "Development Tools": [
        {"Name": "BQSKit", "Sponsor": "Lawrence Berkeley Labs", "Description": "Quantum compiler framework", "Category": "Compiler"},
        {"Name": "Mitiq", "Sponsor": "Unitary Foundation", "Description": "Error mitigation", "Category": "QEC"},
        {"Name": "pyGSTi", "Sponsor": "Sandia National Labs", "Description": "Modeling noisy processors", "Category": "Characterization"},
        {"Name": "Qristal", "Sponsor": "Quantum Brilliance", "Description": "Hybrid quantum programs", "Category": "Development"},
        {"Name": "Quantum Programming Studio", "Sponsor": "Quantastica", "Description": "Web system for algorithms", "Category": "IDE"},
        {"Name": "QUEKO", "Sponsor": "UCLA", "Description": "Benchmarks with optimal solutions", "Category": "Benchmarking"},
        {"Name": "QuTiP", "Sponsor": "QuTiP", "Description": "Numerical Hamiltonian simulations", "Category": "Simulation"},
        {"Name": "staq", "Sponsor": "softwareQ Inc", "Description": "Quantum circuit compilation", "Category": "Compiler"},
        {"Name": "Superstaq", "Sponsor": "Infleqtion", "Description": "Hardware-optimized execution", "Category": "Optimization"},
        {"Name": "tket", "Sponsor": "Quantinuum", "Description": "Circuit optimization", "Category": "Compiler"},
        {"Name": "XACC", "Sponsor": "Oak Ridge National Labs", "Description": "Extensible compilation framework", "Category": "Compiler"}
      ],
      "Simulators": [
        {"Name": "Qibo", "Sponsor": "Technology Innovation Institute", "Description": "Hardware-accelerated simulation", "Category": "Simulation"},
        {"Name": "qsim", "Sponsor": "Google", "Description": "Schrödinger simulations", "Category": "Simulation"},
        {"Name": "quimb", "Sponsor": "Johnnie Gray", "Description": "Tensor-network simulator", "Category": "Simulation"},
        {"Name": "qulacs", "Sponsor": "Quansys", "Description": "Schrödinger simulations", "Category": "Simulation"},
        {"Name": "Stim", "Sponsor": "Google", "Description": "Clifford circuits simulation", "Category": "Simulation"},
        {"Name": "cuQuantum", "Sponsor": "NVIDIA", "Description": "GPU-accelerated simulation", "Category": "Simulation"}
      ]
    };
  } catch (error) {
    console.error('Error loading ecosystem data:', error);
    showNotification('Error', 'Failed to load ecosystem data', 'error');
  }
}

// Render ecosystem list based on filters
function renderEcosystemList() {
  if (!ecosystemData) return;
  
  const categoryFilter = domElements.categoryFilter.value;
  const searchTerm = domElements.searchTools.value.toLowerCase();
  
  let allTools = [];
  Object.keys(ecosystemData).forEach(category => {
    allTools = allTools.concat(ecosystemData[category]);
  });
  
  // Apply filters
  const filteredTools = allTools.filter(tool => {
    const matchesCategory = categoryFilter === 'all' || tool.Category === categoryFilter;
    const matchesSearch = tool.Name.toLowerCase().includes(searchTerm) || 
                         tool.Description.toLowerCase().includes(searchTerm) ||
                         tool.Sponsor.toLowerCase().includes(searchTerm);
    return matchesCategory && matchesSearch;
  });
  
  // Generate HTML
  const toolsHtml = filteredTools.map(tool => `
    <div class="tool-card" data-name="${tool.Name}" data-category="${tool.Category}">
      <h4>${tool.Name}</h4>
      <div class="sponsor">${tool.Sponsor}</div>
      <div class="description">${tool.Description}</div>
      <div class="category">${tool.Category}</div>
    </div>
  `).join('');
  
  domElements.ecosystemList.innerHTML = toolsHtml;
  
  // Add click event to tool cards
  document.querySelectorAll('.tool-card').forEach(card => {
    card.addEventListener('click', () => {
      const toolName = card.getAttribute('data-name').toLowerCase();
      // If it's a simulator or core tool, activate it
      const validTools = ['cirq', 'qsim', 'cuquantum', 'qulacs', 'stim'];
      if (validTools.includes(toolName)) {
        setActiveTool(toolName);
      } else {
        showNotification('Tool Info', `${card.getAttribute('data-name')} - ${card.querySelector('.description').textContent}`, 'info');
      }
    });
  });
}

// Get stack recommendation
async function getStackRecommendation(focusArea) {
  try {
    showLoading(true);
    
    // In a real app, this would call the backend
    // const recommendation = await window.electron.getStackRecommendation(focusArea);
    
    // For demo, generate a recommendation based on focus area
    const recommendation = [];
    
    // Core framework
    recommendation.push({"Name": "Cirq", "Purpose": "Core quantum programming framework"});
    
    // Add tools based on focus area
    if (focusArea === "chemistry") {
      recommendation.push({"Name": "OpenFermion", "Purpose": "Quantum chemistry simulations"});
      recommendation.push({"Name": "qsim", "Purpose": "Efficient circuit simulation"});
    } else if (focusArea === "ml") {
      recommendation.push({"Name": "TensorFlow Quantum", "Purpose": "Quantum machine learning"});
      recommendation.push({"Name": "PennyLane", "Purpose": "Hybrid quantum-classical ML"});
    } else if (focusArea === "error_correction") {
      recommendation.push({"Name": "Stim", "Purpose": "Error correction simulation"});
      recommendation.push({"Name": "Mitiq", "Purpose": "Error mitigation techniques"});
    } else {  // general
      recommendation.push({"Name": "ReCirq", "Purpose": "Example experiments"});
      recommendation.push({"Name": "tket", "Purpose": "Circuit optimization"});
    }
    
    // Always add development tools
    recommendation.push({"Name": "Quantum Programming Studio", "Purpose": "Visual circuit design"});
    
    setTimeout(() => {
      showLoading(false);
      
      // Display recommendation
      const html = recommendation.map(tool => `
        <div class="recommended-tool">
          <div class="name">${tool.Name}</div>
          <div class="purpose">${tool.Purpose}</div>
        </div>
      `).join('');
      
      domElements.recommendationResult.innerHTML = `
        <h4>Recommended Stack for ${focusArea.charAt(0).toUpperCase() + focusArea.slice(1)}</h4>
        ${html}
      `;
      
      // Unlock achievement if this is the first recommendation
      if (!achievements.find(a => a.id === 'first_recommendation').unlocked) {
        unlockAchievement('first_recommendation');
      }
    }, 1000);
  } catch (error) {
    showLoading(false);
    console.error('Error getting recommendation:', error);
    showNotification('Error', 'Failed to get stack recommendation', 'error');
  }
}

// Set active tool
function setActiveTool(tool) {
  currentTool = tool;
  
  // Update UI
  domElements.toolsList.querySelectorAll('li').forEach(item => {
    item.classList.toggle('active', item.getAttribute('data-tool') === tool);
  });
  
  // Update visualization if needed
  updateToolSpecificUI();
  
  showNotification('Tool Selected', `Now using ${tool.toUpperCase()} for quantum simulations`, 'info');
}

// Set visualization mode
function setVisualizationMode(mode) {
  currentMode = mode;
  
  // Update UI
  domElements.visualizationModes.querySelectorAll('li').forEach(item => {
    item.classList.toggle('active', item.getAttribute('data-mode') === mode);
  });
  
  // Show/hide circuit editor
  domElements.circuitEditor.classList.toggle('hidden', mode !== 'circuit');
  
  // Update visualization
  updateVisualization();
  
  if (mode === 'network') {
    // Special case: create network visualization of ecosystem
    createNetworkVisualization();
  }
}

// Update UI based on selected tool
function updateToolSpecificUI() {
  // In a real app, this would modify available options based on the selected tool
  console.log(`Selected tool: ${currentTool}`);
  
  // Enable GPU option if using cuQuantum
  currentCircuit.use_gpu = (currentTool === 'cuquantum');
  
  // Update visualization if needed
  if (['bloch', 'matrix', 'probability'].includes(currentMode)) {
    updateVisualization();
  }
}

// Run quantum simulation
async function runQuantumSimulation() {
  try {
    showLoading(true);
    domElements.runSimulation.textContent = 'SIMULATING...';
    
    // In a real app, this would call the backend
    // const results = await window.electron.runQuantumSimulation(currentCircuit);
    
    // For demo, simulate with timeout
    setTimeout(() => {
      showLoading(false);
      domElements.runSimulation.textContent = 'RUN SIMULATION';
      
      // Generate mock results
      const results = generateMockResults();
      
      // Display results
      displayResults(results);
      
      // Unlock achievement if this is the first simulation
      if (!achievements.find(a => a.id === 'first_simulation').unlocked) {
        unlockAchievement('first_simulation');
      }
    }, 2000);
  } catch (error) {
    showLoading(false);
    domElements.runSimulation.textContent = 'RUN SIMULATION';
    console.error('Simulation error:', error);
    showNotification('Error', 'Simulation failed: ' + error.message, 'error');
  }
}

// Generate mock simulation results
function generateMockResults() {
  const results = {
    id: generateUUID(),
    timestamp: Date.now(),
    circuit: {
      qubit_count: currentCircuit.qubit_count,
      gate_count: currentCircuit.gates ? currentCircuit.gates.length : 10,
      depth: currentCircuit.depth
    },
    execution_time_ms: Math.random() * 1000 + 50,
    probabilities: {},
    measurements: {},
    fidelity: 0.99 - (Math.random() * 0.05)
  };
  
  // Generate random probabilities that sum to 1
  const numStates = Math.min(10, Math.pow(2, results.circuit.qubit_count));
  let remainingProb = 1.0;
  
  for (let i = 0; i < numStates - 1; i++) {
    const stateName = i.toString(2).padStart(results.circuit.qubit_count, '0');
    const prob = i === 0 ? 0.35 : Math.random() * remainingProb * 0.5;
    results.probabilities[stateName] = prob;
    results.measurements[stateName] = Math.round(prob * 1000);
    remainingProb -= prob;
  }
  
  // Add the final state with remaining probability
  const finalState = '1'.repeat(results.circuit.qubit_count);
  results.probabilities[finalState] = remainingProb;
  results.measurements[finalState] = Math.round(remainingProb * 1000);
  
  return results;
}

// Display simulation results
function displayResults(results) {
  // Create SVG for histogram using D3
  const svgWidth = 500;
  const svgHeight = 200;
  const margin = { top: 20, right: 30, bottom: 40, left: 40 };
  const width = svgWidth - margin.left - margin.right;
  const height = svgHeight - margin.top - margin.bottom;
  
  // Prepare data for visualization
  const data = Object.entries(results.probabilities)
    .map(([state, prob]) => ({ state, probability: prob }))
    .sort((a, b) => b.probability - a.probability)
    .slice(0, 8); // Show top 8 states
  
  // Create SVG
  const svg = d3.create('svg')
    .attr('width', svgWidth)
    .attr('height', svgHeight);
  
  const g = svg.append('g')
    .attr('transform', `translate(${margin.left},${margin.top})`);
  
  // Create scales
  const x = d3.scaleBand()
    .domain(data.map(d => d.state))
    .range([0, width])
    .padding(0.1);
  
  const y = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.probability)])
    .nice()
    .range([height, 0]);
  
  // Add bars
  g.selectAll('.bar')
    .data(data)
    .join('rect')
    .attr('class', 'bar')
    .attr('x', d => x(d.state))
    .attr('y', d => y(d.probability))
    .attr('width', x.bandwidth())
    .attr('height', d => height - y(d.probability))
    .attr('fill', (d, i) => {
      const t = i / data.length;
      return `rgb(${Math.round(t * 255)}, ${Math.round((1 - t) * 255)}, 255)`;
    });
  
  // Add axes
  g.append('g')
    .attr('transform', `translate(0,${height})`)
    .call(d3.axisBottom(x))
    .selectAll('text')
    .attr('transform', 'rotate(-45)')
    .attr('text-anchor', 'end')
    .attr('dx', '-.8em')
    .attr('dy', '.15em')
    .attr('fill', '#fff');
  
  g.append('g')
    .call(d3.axisLeft(y))
    .selectAll('text')
    .attr('fill', '#fff');
  
  // Axes labels
  g.append('text')
    .attr('text-anchor', 'middle')
    .attr('x', width / 2)
    .attr('y', height + margin.bottom - 5)
    .attr('fill', '#0ff')
    .text('Quantum State');
  
  g.append('text')
    .attr('text-anchor', 'middle')
    .attr('transform', 'rotate(-90)')
    .attr('x', -height / 2)
    .attr('y', -margin.left + 10)
    .attr('fill', '#0ff')
    .text('Probability');
  
  // Create HTML for results
  const resultsHTML = `
    <div class="results-header">
      <h3>Simulation completed using ${currentTool.toUpperCase()}</h3>
      <p>Circuit depth: ${results.circuit.depth} | Qubits: ${results.circuit.qubit_count} | Shots: 1000</p>
      <p>Execution time: ${results.execution_time_ms.toFixed(2)} ms | Fidelity: ${results.fidelity.toFixed(4)}</p>
    </div>
    <div class="results-graph">
      ${svg.node().outerHTML}
    </div>
    <div class="results-details">
      <h4>Measurement Results</h4>
      <table>
        <tr>
          <th>State</th>
          <th>Probability</th>
          <th>Count</th>
        </tr>
        ${Object.entries(results.probabilities)
          .sort(([, a], [, b]) => b - a)
          .slice(0, 10) // Show top 10 states
          .map(([state, prob]) => `
            <tr>
              <td>|${state}⟩</td>
              <td>${prob.toFixed(4)}</td>
              <td>${results.measurements[state]}</td>
            </tr>
          `).join('')}
      </table>
    </div>
  `;
  
  // Update DOM and show results panel
  domElements.resultsContent.innerHTML = resultsHTML;
  domElements.resultsPanel.classList.add('visible');
  
  // Also update 3D visualization if in probability mode
  if (currentMode === 'probability') {
    updateVisualization();
  }
}

// Export results
function exportResults() {
  showNotification('Export', 'Results exported successfully', 'success');
  
  // In a real app, this would save to a file
  console.log('Exporting results...');
}

// Initialize 3D visualization
function initVisualization() {
  // Create Three.js scene
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setSize(domElements.canvasContainer.clientWidth, domElements.canvasContainer.clientHeight);
  renderer.setClearColor(0x000000, 1);
  
  domElements.canvasContainer.appendChild(renderer.domElement);
  
  // Add ambient lighting
  const ambientLight = new THREE.AmbientLight(0x333333);
  scene.add(ambientLight);
  
  // Add directional lighting
  const directionalLight = new THREE.DirectionalLight(0x00ffff, 0.8);
  directionalLight.position.set(5, 3, 5);
  scene.add(directionalLight);
  
  // Position camera
  camera.position.z = 15;
  
  // Add particle system for background
  createQuantumParticleField();
  
  // Add initial visualization based on mode
  updateVisualization();
  
  // Start animation loop
  animate();
}

// Create particle field for background effect
function createQuantumParticleField() {
  const particleCount = 500;
  const particles = new THREE.BufferGeometry();
  const positions = new Float32Array(particleCount * 3);
  const colors = new Float32Array(particleCount * 3);
  
  for (let i = 0; i < particleCount * 3; i += 3) {
    // Position particles in a sphere
    const radius = 30;
    const theta = Math.random() * Math.PI * 2;
    const phi = Math.acos(Math.random() * 2 - 1);
    
    positions[i] = radius * Math.sin(phi) * Math.cos(theta);
    positions[i + 1] = radius * Math.sin(phi) * Math.sin(theta);
    positions[i + 2] = radius * Math.cos(phi);
    
    // Cyan color with variation
    colors[i] = 0;
    colors[i + 1] = 0.8 + Math.random() * 0.2;
    colors[i + 2] = 0.8 + Math.random() * 0.2;
  }
  
  particles.setAttribute('position', new THREE.BufferAttribute(positions, 3));
  particles.setAttribute('color', new THREE.BufferAttribute(colors, 3));
  
  const particleMaterial = new THREE.PointsMaterial({
    size: 0.1,
    vertexColors: true,
    transparent: true,
    opacity: 0.8
  });
  
  const particleSystem = new THREE.Points(particles, particleMaterial);
  scene.add(particleSystem);
  quantumParticles.push(particleSystem);
}

// Update visualization based on current mode
function updateVisualization() {
  // Clear previous visualization
  blochSpheres.forEach(sphere => scene.remove(sphere));
  blochSpheres = [];
  
  switch (currentMode) {
    case 'bloch':
      createBlochSphereVisualization();
      break;
    case 'circuit':
      // Circuit visualization is handled by the HTML editor
      break;
    case 'matrix':
      createMatrixVisualization();
      break;
    case 'probability':
      createProbabilityLandscape();
      break;
    case 'network':
      // Network visualization is handled separately
      break;
  }
}

// Create Bloch sphere visualization
function createBlochSphereVisualization() {
  // Create multiple Bloch spheres for demonstration
  const positions = [
    new THREE.Vector3(-4, 2, 0),
    new THREE.Vector3(0, 2, 0),
    new THREE.Vector3(4, 2, 0),
    new THREE.Vector3(-4, -2, 0),
    new THREE.Vector3(0, -2, 0),
    new THREE.Vector3(4, -2, 0),
  ];
  
  // Sample qubit states (would come from actual simulation)
  const qubitStates = [
    { theta: Math.PI / 4, phi: 0 },
    { theta: Math.PI / 2, phi: Math.PI / 4 },
    { theta: Math.PI / 8, phi: Math.PI / 2 },
    { theta: 3 * Math.PI / 4, phi: Math.PI },
    { theta: Math.PI / 3, phi: Math.PI / 6 },
    { theta: Math.PI / 2, phi: 0 }
  ];
  
  positions.forEach((pos, i) => {
    createBlochSphere(pos, qubitStates[i]);
  });
}

// Create a Bloch sphere representation for qubits
function createBlochSphere(position, qubitState) {
  // Create sphere
  const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
  const sphereMaterial = new THREE.MeshPhongMaterial({
    color: 0x0088cc,
    transparent: true,
    opacity: 0.2,
    wireframe: false
  });
  const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
  sphere.position.copy(position);
  
  // Create axes
  const axesHelper = new THREE.AxesHelper(1.2);
  sphere.add(axesHelper);
  
  // Create state vector
  const vectorGeometry = new THREE.CylinderGeometry(0.05, 0.05, 1);
  vectorGeometry.rotateX(Math.PI / 2);
  const vectorMaterial = new THREE.MeshPhongMaterial({ color: 0x00ffff });
  const vector = new THREE.Mesh(vectorGeometry, vectorMaterial);
  
  // Position vector based on qubit state
  vector.position.set(0, 0, 0);
  
  // If we have a real qubit state, calculate proper position
  if (qubitState) {
    const theta = qubitState.theta || 0;
    const phi = qubitState.phi || 0;
    
    vector.rotation.y = phi;
    vector.rotation.z = theta;
  }
  
  sphere.add(vector);
  scene.add(sphere);
  blochSpheres.push(sphere);
  
  return sphere;
}

// Create matrix visualization
function createMatrixVisualization() {
  // Create a visual representation of a quantum matrix
  const matrixGroup = new THREE.Group();
  
  // Create a grid of cubes representing matrix elements
  const size = 4; // 4x4 matrix
  
  for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
      const value = Math.random(); // In real app, this would be actual matrix values
      
      const cubeGeometry = new THREE.BoxGeometry(0.8, 0.8, 0.8 * value);
      const cubeMaterial = new THREE.MeshPhongMaterial({
        color: new THREE.Color(0, value * 0.5 + 0.5, value * 0.5 + 0.5),
        transparent: true,
        opacity: 0.7
      });
      
      const cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
      cube.position.set((i - size/2 + 0.5) * 1.5, (j - size/2 + 0.5) * 1.5, 0);
      matrixGroup.add(cube);
    }
  }
  
  scene.add(matrixGroup);
  blochSpheres.push(matrixGroup);
}

// Create probability landscape
function createProbabilityLandscape() {
  // Create a landscape of probability amplitudes
  const landscapeGroup = new THREE.Group();
  
  // Create a grid of bars representing probability distribution
  const size = 8; // 8x8 grid
  
  for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
      // In a real app, these would be actual probability values
      const probability = Math.pow(Math.sin(i / 2) * Math.cos(j / 2), 2);
      
      const barGeometry = new THREE.BoxGeometry(0.4, 0.4, probability * 5);
      const barMaterial = new THREE.MeshPhongMaterial({
        color: new THREE.Color(0, 0.5 + probability * 0.5, 0.5 + probability * 0.5),
        transparent: true,
        opacity: 0.7
      });
      
      const bar = new THREE.Mesh(barGeometry, barMaterial);
      bar.position.set((i - size/2 + 0.5) * 0.7, (j - size/2 + 0.5) * 0.7, probability * 2.5);
      landscapeGroup.add(bar);
    }
  }
  
  scene.add(landscapeGroup);
  blochSpheres.push(landscapeGroup);
}

// Create network visualization of the quantum ecosystem
function createNetworkVisualization() {
  // This would normally use D3 force-directed graph
  // For the demo, we'll create a simplified 3D representation
  const networkGroup = new THREE.Group();
  
  // Collect all tools
  let allTools = [];
  Object.keys(ecosystemData).forEach(category => {
    ecosystemData[category].forEach(tool => {
      allTools.push({
        ...tool,
        group: category
      });
    });
  });
  
  // Create nodes for each tool
  const nodes = allTools.map((tool, i) => {
    const angle = (i / allTools.length) * Math.PI * 2;
    const radius = 8;
    
    // Create node representation
    const nodeGeometry = new THREE.SphereGeometry(0.3, 16, 16);
    
    // Color based on category
    let nodeColor;
    if (tool.group === "Algorithm Libraries") {
      nodeColor = 0x00aaff;
    } else if (tool.group === "Development Tools") {
      nodeColor = 0xff00aa;
    } else {
      nodeColor = 0x00ffaa;
    }
    
    const nodeMaterial = new THREE.MeshPhongMaterial({ color: nodeColor });
    const nodeMesh = new THREE.Mesh(nodeGeometry, nodeMaterial);
    
    // Position in a circle
    const x = Math.cos(angle) * radius;
    const y = Math.sin(angle) * radius;
    const z = (Math.random() - 0.5) * 4;
    
    nodeMesh.position.set(x, y, z);
    nodeMesh.userData = { tool };
    
    // Add text label
    const canvas = document.createElement('canvas');
    canvas.width = 256;
    canvas.height = 128;
    const context = canvas.getContext('2d');
    context.fillStyle = '#ffffff';
    context.font = '24px Arial';
    context.fillText(tool.Name, 10, 64);
    
    const texture = new THREE.CanvasTexture(canvas);
    const labelMaterial = new THREE.SpriteMaterial({ map: texture });
    const label = new THREE.Sprite(labelMaterial);
    label.scale.set(2, 1, 1);
    label.position.set(0, 0.5, 0);
    
    nodeMesh.add(label);
    networkGroup.add(nodeMesh);
    
    return { mesh: nodeMesh, tool };
  });
  
  // Create connections between related tools
  allTools.forEach((tool, i) => {
    // Connect to tools in the same category
    allTools.forEach((otherTool, j) => {
      if (i !== j && tool.Category === otherTool.Category) {
        const nodeA = nodes[i].mesh;
        const nodeB = nodes[j].mesh;
        
        const lineGeometry = new THREE.BufferGeometry().setFromPoints([
          nodeA.position,
          nodeB.position
        ]);
        
        const lineMaterial = new THREE.LineBasicMaterial({ 
          color: 0x00ffff,
          transparent: true,
          opacity: 0.2
        });
        
        const line = new THREE.Line(lineGeometry, lineMaterial);
        networkGroup.add(line);
      }
    });
    
    // Connect to tools with the same sponsor
    allTools.forEach((otherTool, j) => {
      if (i !== j && tool.Sponsor === otherTool.Sponsor) {
        const nodeA = nodes[i].mesh;
        const nodeB = nodes[j].mesh;
        
        const lineGeometry = new THREE.BufferGeometry().setFromPoints([
          nodeA.position,
          nodeB.position
        ]);
        
        const lineMaterial = new THREE.LineBasicMaterial({ 
          color: 0xff00ff,
          transparent: true,
          opacity: 0.2
        });
        
        const line = new THREE.Line(lineGeometry, lineMaterial);
        networkGroup.add(line);
      }
    });
  });
  
  scene.add(networkGroup);
  blochSpheres.push(networkGroup);
  
  // Position camera for better view
  camera.position.z = 20;
}

// Animation loop
function animate() {
  animationId = requestAnimationFrame(animate);
  
  // Rotate quantum particles for background effect
  quantumParticles.forEach(particles => {
    particles.rotation.x += 0.0003;
    particles.rotation.y += 0.0005;
  });
  
  // Rotate Bloch spheres gently
  blochSpheres.forEach(object => {
    if (object.type === 'Mesh') {
      object.rotation.y += 0.005;
    } else if (object.type === 'Group') {
      object.rotation.y += 0.001;
    }
  });
  
  renderer.render(scene, camera);
}

// Handle window resize
function onWindowResize() {
  const width = domElements.canvasContainer.clientWidth;
  const height = domElements.canvasContainer.clientHeight;
  
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height);
}

// Generate UUID for uniquely identifying simulations
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// Show or hide loading overlay
function showLoading(show) {
  domElements.loadingOverlay.classList.toggle('hidden', !show);
}

// Show notification
function showNotification(title, message, type = 'info') {
  const notification = document.createElement('div');
  notification.className = `notification ${type}`;
  
  notification.innerHTML = `
    <div class="notification-icon">
      <i class="icon-${type}"></i>
    </div>
    <div class="notification-info">
      <h4>${title}</h4>
      <p>${message}</p>
    </div>
  `;
  
  domElements.notificationContainer.appendChild(notification);
  
  // Animate in
  setTimeout(() => {
    notification.classList.add('show');
    
    // Remove after delay
    setTimeout(() => {
      notification.classList.remove('show');
      setTimeout(() => {
        notification.remove();
      }, 500);
    }, 5000);
  }, 100);
}

// Initialize skill tree
function initSkillTree() {
  // Define skill tree data
  window.skillTree = [
    {
      id: 'basic_gates',
      title: 'Basic Quantum Gates',
      description: 'Master fundamental quantum circuit building blocks',
      unlocked: true,
      position: { x: 400, y: 80 },
      connections: ['hadamard', 'pauli']
    },
    {
      id: 'hadamard',
      title: 'Hadamard Transform',
      description: 'Create superposition states with the H gate',
      unlocked: false,
      position: { x: 300, y: 180 },
      connections: ['superposition']
    },
    {
      id: 'pauli',
      title: 'Pauli Operators',
      description: 'Manipulate qubits with X, Y, and Z rotations',
      unlocked: false,
      position: { x: 500, y: 180 },
      connections: ['rotation']
    },
    {
      id: 'superposition',
      title: 'Quantum Superposition',
      description: 'Create complex superposition states across multiple qubits',
      unlocked: false,
      position: { x: 250, y: 280 },
      connections: ['entanglement']
    },
    {
      id: 'rotation',
      title: 'Arbitrary Rotations',
      description: 'Control qubit states with precise rotational control',
      unlocked: false,
      position: { x: 550, y: 280 },
      connections: ['entanglement']
    },
    {
      id: 'entanglement',
      title: 'Quantum Entanglement',
      description: 'Create entangled states between multiple qubits',
      unlocked: false,
      position: { x: 400, y: 380 },
      connections: ['teleportation', 'error_correction']
    },
    {
      id: 'teleportation',
      title: 'Quantum Teleportation',
      description: 'Transfer quantum states using entanglement',
      unlocked: false,
      position: { x: 300, y: 480 },
      connections: ['algorithms']
    },
    {
      id: 'error_correction',
      title: 'Quantum Error Correction',
      description: 'Protect quantum information from decoherence',
      unlocked: false,
      position: { x: 500, y: 480 },
      connections: ['algorithms']
    },
    {
      id: 'algorithms',
      title: 'Quantum Algorithms',
      description: 'Implement advanced quantum algorithms',
      unlocked: false,
      position: { x: 400, y: 580 },
      connections: []
    }
  ];
  
  renderSkillTree();
}

// Render skill tree
function renderSkillTree() {
  const container = document.getElementById('skill-nodes');
  const svg = document.getElementById('skill-connections');
  
  // Clear existing content
  container.innerHTML = '';
  svg.innerHTML = '';
  
  // Set SVG size
  const svgWidth = 800;
  const svgHeight = 600;
  svg.setAttribute('viewBox', `0 0 ${svgWidth} ${svgHeight}`);
  
  // Create connections first (so they appear behind nodes)
  window.skillTree.forEach(skill => {
    if (skill.connections.length > 0) {
      skill.connections.forEach(targetId => {
        const target = window.skillTree.find(s => s.id === targetId);
        
        if (target) {
          const startX = skill.position.x;
          const startY = skill.position.y;
          const endX = target.position.x;
          const endY = target.position.y;
          
          // Create SVG path
          const path = document.createElementNS('<http://www.w3.org/2000/svg>', 'path');
          path.setAttribute('d', `M ${startX} ${startY} C ${startX} ${(startY + endY) / 2}, ${endX} ${(startY + endY) / 2}, ${endX} ${endY}`);
          path.classList.add('skill-connection');
          
          if (skill.unlocked && target.unlocked) {
            path.classList.add('unlocked');
          }
          
          svg.appendChild(path);
        }
      });
    }
  });
  
  // Create nodes
  window.skillTree.forEach(skill => {
    const node = document.createElement('div');
    node.className = `skill-node ${skill.unlocked ? 'unlocked' : 'locked'}`;
    node.dataset.id = skill.id;
    
    // Position the node
    node.style.left = `${skill.position.x - 30}px`; // Center node (60px width)
    node.style.top = `${skill.position.y - 30}px`; // Center node (60px height)
    
    node.innerHTML = `
      <div class="skill-icon"></div>
      <div class="skill-tooltip">
        <h4>${skill.title}</h4>
        <p>${skill.description}</p>
        ${!skill.unlocked ? '<button class="unlock-skill">UNLOCK</button>' : ''}
      </div>
    `;
    
    container.appendChild(node);
    
    // Add click event to unlock skill
    if (!skill.unlocked) {
      const unlockButton = node.querySelector('.unlock-skill');
      if (unlockButton) {
        unlockButton.addEventListener('click', (e) => {
          e.stopPropagation();
          unlockSkill(skill.id);
        });
      }
    }
  });
}

// Unlock a skill
function unlockSkill(skillId) {
  // Check if prerequisites are met
  const skill = window.skillTree.find(s => s.id === skillId);
  
  if (skill && !skill.unlocked) {
    // Check if this skill has prerequisites that are unlocked
    const prerequisites = window.skillTree.filter(s => 
      s.connections.includes(skillId) && !s.unlocked
    );
    
    if (prerequisites.length > 0) {
      // Cannot unlock yet - prerequisites not met
      showNotification('Skill Locked', 'You must unlock prerequisite skills first!', 'error');
      return;
    }
    
    // Unlock the skill
    skill.unlocked = true;
    
    // Update the visual representation
    renderSkillTree();
    
    // Show notification
    showNotification('Skill Unlocked', `You've unlocked: ${skill.title}`, 'success');
    
    // Add the skill's functionality to the application
    addSkillFunctionality(skillId);
    
    // Check for related achievements
    if (skillId === 'entanglement') {
      unlockAchievement('quantum_entangler');
    } else if (skillId === 'algorithms') {
      unlockAchievement('algorithm_master');
    }
  }
}

// Add functionality based on unlocked skill
function addSkillFunctionality(skillId) {
  switch (skillId) {
    case 'hadamard':
      // Add Hadamard gate to toolbox if not already present
      if (!document.querySelector('.gate[data-gate="h"]')) {
        addGateToToolbox('H', 'Hadamard', 'Creates superposition');
      }
      break;
    case 'pauli':
      // Add Pauli gates to toolbox
      if (!document.querySelector('.gate[data-gate="x"]')) {
        addGateToToolbox('X', 'Pauli-X', 'Bit flip operation');
      }
      if (!document.querySelector('.gate[data-gate="y"]')) {
        addGateToToolbox('Y', 'Pauli-Y', 'Combined X and Z rotation');
      }
      if (!document.querySelector('.gate[data-gate="z"]')) {
        addGateToToolbox('Z', 'Pauli-Z', 'Phase flip operation');
      }
      break;
    case 'rotation':
      // Add rotation gates
      addGateToToolbox('Rx', 'X-Rotation', 'Rotation around X-axis');
      addGateToToolbox('Ry', 'Y-Rotation', 'Rotation around Y-axis');
      addGateToToolbox('Rz', 'Z-Rotation', 'Rotation around Z-axis');
      break;
    case 'entanglement':
      // Add entanglement gates
      addGateToToolbox('CNOT', 'Controlled-NOT', 'Creates entanglement');
      addGateToToolbox('CZ', 'Controlled-Z', 'Phase entanglement');
      break;
    // Add more cases for other skills
  }
}

// Helper function to add a gate to the toolbox
function addGateToToolbox(symbol, name, description) {
  const toolbox = document.querySelector('.quantum-gates-toolbox');
  if (!toolbox) return;
  
  const gate = document.createElement('div');
  gate.className = 'gate new';
  gate.draggable = true;
  gate.dataset.gate = symbol.toLowerCase();
  
  gate.innerHTML = `
    <div class="gate-symbol">${symbol}</div>
    <div class="gate-tooltip">
      <h4>${name}</h4>
      <p>${description}</p>
    </div>
  `;
  
  toolbox.appendChild(gate);
  
  // Add animation effect
  gate.style.animation = 'pulse 1s';
  
  // Make gate draggable
  gate.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', symbol.toLowerCase());
  });
}

// Initialize achievements system
function initAchievements() {
  // Define achievements
  window.achievements = [
    {
      id: 'first_simulation',
      title: 'Quantum Pioneer',
      description: 'Run your first quantum simulation',
      unlocked: false,
      icon: '🚀'
    },
    {
      id: 'first_recommendation',
      title: 'Strategic Planner',
      description: 'Get your first tool stack recommendation',
      unlocked: false,
      icon: '📋'
    },
    {
      id: 'quantum_entangler',
      title: 'Quantum Entangler',
      description: 'Unlock the entanglement skill',
      unlocked: false,
      icon: '🔗'
    },
    {
      id: 'algorithm_master',
      title: 'Algorithm Master',
      description: 'Unlock the quantum algorithms skill',
      unlocked: false,
      icon: '🧮'
    },
    {
      id: 'visualization_explorer',
      title: 'Visualization Explorer',
      description: 'View all visualization modes',
      unlocked: false,
      icon: '🔍'
    }
  ];
  
  renderAchievements();
}

// Render achievements list
function renderAchievements() {
  const achievementsList = document.querySelector('.achievements-list');
  achievementsList.innerHTML = '';
  
  window.achievements.forEach(achievement => {
    const achievementElement = document.createElement('div');
    achievementElement.className = `achievement ${achievement.unlocked ? 'unlocked' : 'locked'}`;
    achievementElement.dataset.id = achievement.id;
    
    achievementElement.innerHTML = `
      <div class="achievement-icon">
        <span style="font-size: 24px;">${achievement.icon}</span>
      </div>
      <div class="achievement-info">
        <h4>${achievement.title}</h4>
        <p>${achievement.description}</p>
      </div>
    `;
    
    achievementsList.appendChild(achievementElement);
  });
  
  // Update progress bar
  updateAchievementProgress();
}

// Update achievement progress
function updateAchievementProgress() {
  const unlockedCount = window.achievements.filter(a => a.unlocked).length;
  const totalCount = window.achievements.length;
  const progressBar = document.querySelector('.progress');
  const progressText = document.querySelector('.progress-text');
  
  progressBar.style.width = `${(unlockedCount / totalCount) * 100}%`;
  progressText.textContent = `${unlockedCount}/${totalCount}`;
}

// Unlock an achievement
window.unlockAchievement = function(achievementId) {
  const achievement = window.achievements.find(a => a.id === achievementId);
  if (achievement && !achievement.unlocked) {
    achievement.unlocked = true;
    
    // Update UI
    renderAchievements();
    
    // Show notification
    showAchievementNotification(achievement);
  }
};

// Show achievement notification
function showAchievementNotification(achievement) {
  const notification = document.createElement('div');
  notification.className = 'notification success';
  
  notification.innerHTML = `
    <div class="notification-icon">
      <span style="font-size: 24px;">${achievement.icon}</span>
    </div>
    <div class="notification-info">
      <h4>Achievement Unlocked!</h4>
      <h3>${achievement.title}</h3>
      <p>${achievement.description}</p>
    </div>
  `;
  
  domElements.notificationContainer.appendChild(notification);
  
  // Animate notification
  setTimeout(() => {
    notification.classList.add('show');
    
    setTimeout(() => {
      notification.classList.remove('show');
      setTimeout(() => {
        notification.remove();
      }, 500);
    }, 5000);
  }, 100);
}

// Check for visualization explorer achievement
function checkVisualizationAchievement() {
  const visualizationModes = ['bloch', 'circuit', 'matrix', 'probability', 'network'];
  const viewedModes = visualizationModes.filter(mode => 
    localStorage.getItem(`viewed_${mode}`) === 'true'
  );
  
  if (viewedModes.length === visualizationModes.length) {
    unlockAchievement('visualization_explorer');
  }
}

This integrated application creates a comprehensive Quantum Computing Studio that combines: