document.addEventListener('DOMContentLoaded', () => {
    const switchA = document.getElementById('switchA');
    const switchB = document.getElementById('switchB');
    const switchC = document.getElementById('switchC');
    const resultValue = document.getElementById('resultValue');
    const simulateBtn = document.getElementById('simulateBtn');
    const backBtn = document.getElementById('backBtn');
    const slide1 = document.getElementById('slide1');
    const slide2 = document.getElementById('slide2');
    const splashSlide = document.getElementById('splashSlide');
    const initBtn = document.getElementById('initBtn');

    const switches = [switchA, switchB, switchC];

    function calculateOutcome() {
        const a = switchA.checked; // false: Discrete, true: Continuous
        const b = switchB.checked; // false: Finite, true: Infinite Precision
        const c = switchC.checked; // false: Point, true: Chunk

        // 0 = false, 1 = true
        // State presented as binary string ABC
        // A: Discrete(0) / Continuous(1)
        // B: Finite(0) / Infinite(1)
        // C: Point(0) / Chunk(1)

        // Logic Mapping (Default placeholder logic based on common physical intuition prompts)
        // You can edit this mapping

        // 000: Discrete, Finite, Point -> Stable (Digital Physics)
        // 001: Discrete, Finite, Chunk -> Stable (Voxel Universe)
        // 010: Discrete, Infinite, Point -> Paradoxical (Zeno's paradoxes prone?)
        // 011: Discrete, Infinite, Chunk -> Paradoxical
        // 100: Continuous, Finite, Point -> Stable (Classical Mechanics approx)
        // 101: Continuous, Finite, Chunk -> Paradoxical (Boundary issues?)
        // 110: Continuous, Infinite, Point -> Infinite (Field Theory singularities)
        // 111: Continuous, Infinite, Chunk -> Paradoxical (Measure problem?)

        // Let's implement a simplified look-up for now based on "Paradoxical, Infinite, Stable"

        let state = (a ? 4 : 0) + (b ? 2 : 0) + (c ? 1 : 0);
        let outcome = "Stable";
        let description = "";
        let visualClass = "default";

        switch (state) {
            case 0: // 000: Discrete, Finite, Point
                outcome = "Paradoxical";
                intermediate = "A point contains > 1 bit of information?";
                description = "space not really discrete ";
                visualClass = "paradox-point";
                break;
            case 1: // 001: Discrete, Finite, Chunk
                outcome = "Digital physics";
                intermediate = "Instruction programs are finite length";
                description = "Contradicts isotropy!";
                visualClass = "stable-chunk";
                break;
            case 2: // 010: Discrete, Infinite, Point
                outcome = "Memory paradox";
                intermediate = "Instruction programs are infintely long";
                description = "infinite memory in each cell";
                visualClass = "paradox-point";
                break;
            case 3: // 011: Discrete, Infinite, Chunk
                outcome = "Memory paradox";
                intermediate = "Instruction programs are infintely long";
                description = "Infinitely big particles!";
                visualClass = "paradox-chunk";
                break;
            case 4: // 100: Continuous, Finite, Point
                outcome = "Non-standard";
                intermediate = "not isotropic";
                description = "contradicts isotropy!";
                visualClass = "non-standard-particle-point";
                break;
            case 5: // 101: Continuous, Finite, Chunk
                outcome = "Non-standard";
                intermediate = "not isotropic";
                description = "but finite precision contradicts standard assumptions!";
                visualClass = "non-standard-particle-chunk";
                break;
            case 6: // 110: Continuous, Infinite, Point
                outcome = "Standard physics";
                intermediate = "isotropic";
                description = "Particles are not emergent";
                visualClass = "standard-particle-point";
                break;
            case 7: // 111: Continuous, Infinite, Chunk
                outcome = "Uncertain";
                intermediate = "isotropic";
                description = "But what is the center of a chunk?";
                visualClass = "standard-particle-chunk";
                break;
        }

        updateUI(outcome, description, visualClass, intermediate);
    }

    function updateUI(outcome, description, visualClass, intermediate) {
        const visualization = document.getElementById('visualization');
        const artCanvas = visualization.querySelector('.art-canvas');
        const descriptionText = document.getElementById('descriptionText');
        const intermediateText = document.getElementById('intermediateResult');
        const assumptionsText = document.getElementById('assumptionsText'); // New field

        // Construct Assumptions String
        const switchA = document.getElementById('switchA');
        const switchB = document.getElementById('switchB');
        const switchC = document.getElementById('switchC');

        const textA = switchA.checked ? "Continuous universe" : "Discrete universe";
        const textB = switchB.checked ? "Infinite precision" : "Finite precision";
        const textC = switchC.checked ? "Chunk particles" : "Point particles";

        const assumptionsString = `${textA} + ${textB} + ${textC}`;

        // Animate out
        resultValue.style.opacity = 0;
        descriptionText.style.opacity = 0;
        artCanvas.style.opacity = 0;
        if (assumptionsText) assumptionsText.style.opacity = 0;
        intermediateText.style.opacity = 0;

        setTimeout(() => {
            resultValue.textContent = outcome;
            descriptionText.textContent = description;
            intermediateText.textContent = intermediate || "";
            if (assumptionsText) assumptionsText.textContent = assumptionsString;

            // Remove old classes
            resultValue.classList.remove('stable', 'paradoxical', 'gnommos-paradox', 'infinite', 'unexplained', 'standard', 'non-standard');
            artCanvas.className = 'art-canvas'; // Reset base class
            artCanvas.innerHTML = ''; // Clear previous custom HTML

            // Handle Global CRT Background for Paradox
            const crtScreen = document.querySelector('.crt-screen');
            if (visualClass.includes('paradox')) {
                crtScreen.classList.add('paradox-errors');
            } else {
                crtScreen.classList.remove('paradox-errors');
            }

            // Add new classes
            const normalizedOutcome = outcome.toLowerCase().replace(' ', '-');
            if (resultValue.classList.contains(normalizedOutcome)) {
                // already added
            } else {
                resultValue.classList.add(normalizedOutcome);
            }

            artCanvas.classList.add(visualClass);

            // Inject Custom HTML for complex visuals
            if (visualClass === 'paradox-point') {
                artCanvas.innerHTML = `
                    <div class="cube-wrapper">
                        <div class="cube">
                            <div class="face front"></div>
                            <div class="face back"></div>
                            <div class="face right"></div>
                            <div class="face left"></div>
                            <div class="face top"></div>
                            <div class="face bottom"></div>
                            <div class="particle-point"></div>
                        </div>
                        <div class="info-arrow">
                            <div class="arrow-line"></div>
                            <div class="arrow-head"></div>
                            <span class="infinite-symbol">∞</span>
                        </div>
                    </div>
                `;
            } else if (visualClass === 'stable-chunk') {
                // Chakana Symbol: A cross shape. 5 cubes structure (Center + 4 arms)
                // We'll use a container and multiple cubes.
                artCanvas.innerHTML = `
                    <div class="chakana-wrapper">
                        <!-- Center -->
                        <div class="gold-cube center">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                        <!-- Top -->
                        <div class="gold-cube top-arm">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                        <!-- Bottom -->
                        <div class="gold-cube bottom-arm">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                        <!-- Left -->
                        <div class="gold-cube left-arm">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                        <!-- Right -->
                        <div class="gold-cube right-arm">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                    </div>
                `;
            } else if (visualClass === 'paradox-chunk') {
                // Memory Paradox: Unbounded Expansion
                // Create a center source and multiple debris cubes that fly out
                let debrisHTML = '';
                for (let i = 0; i < 12; i++) {
                    debrisHTML += `
                        <div class="debris-cube d-${i}">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>`;
                }

                artCanvas.innerHTML = `
                    <div class="chaos-wrapper">
                        <div class="central-source">
                            <div class="face front"></div><div class="face back"></div>
                            <div class="face right"></div><div class="face left"></div>
                            <div class="face top"></div><div class="face bottom"></div>
                        </div>
                        ${debrisHTML}
                    </div>
                `;
            } else if (visualClass === 'point-field') {
                // CSS-only implementation used before, but we need to ensure it still works
                // The CSS implementation used ::before/::after on .art-canvas.point-field
                // Since we cleared innerHTML, that's fine.
            }

            // Animate in
            resultValue.style.opacity = 1;
            descriptionText.style.opacity = 1;
            artCanvas.style.opacity = 1;
            intermediateText.style.opacity = 1;
            if (assumptionsText) assumptionsText.style.opacity = 1;
        }, 200);
    }

    switches.forEach(sw => {
        sw.addEventListener('change', () => {
            // Optional: Pre-calculate but don't show yet?
            // calculateOutcome(); // We might want to wait for button press
        });
    });

    // Transition Function
    function switchSlide(fromSlide, toSlide) {
        const wrapper = document.querySelector('.slides-wrapper');

        // 1. Collapse
        wrapper.classList.add('crt-collapse');

        // Wait for collapse animation (200ms)
        setTimeout(() => {
            // 2. Swap Content
            fromSlide.style.display = 'none';
            toSlide.style.display = 'flex';

            // 3. Expand
            wrapper.classList.remove('crt-collapse');
            wrapper.classList.add('crt-expand');

            // Cleanup after expand (200ms)
            setTimeout(() => {
                wrapper.classList.remove('crt-expand');
            }, 200);

        }, 200);
    }

    simulateBtn.addEventListener('click', () => {
        calculateOutcome();
        switchSlide(slide1, slide2);
    });

    backBtn.addEventListener('click', () => {
        switchSlide(slide2, slide1);
    });

    if (initBtn && splashSlide) {
        // Initial state: Show Splash, Hide Slide 1 (which might be default flex in CSS if not handled)
        slide1.style.display = 'none';
        slide2.style.display = 'none';
        splashSlide.style.display = 'flex';

        initBtn.addEventListener('click', () => {
            switchSlide(splashSlide, slide1);
        });
    }


    // Initial calculation
    // Initial calculation (optional to run it secretly)
    // calculateOutcome();
});
