let editor;
let timeRemaining = INITIAL_TIME_REMAINING;
let timerInterval;
let messageInterval;
let firstMessageTimeout;

// Audio Files
const audios = {
    siren: new Audio('audio/siren.mp3'),
    fatal: new Audio('audio/msg_fatal_error.mp3'),
    stability: new Audio('audio/msg_stability_low.mp3'),
    core: new Audio('audio/msg_core_temp.mp3'),
    failure: new Audio('audio/msg_grid_failure.mp3'),
    unauthorized: new Audio('audio/msg_unauthorized.mp3'),
    success: new Audio('audio/msg_success.mp3')
};

// Initialize Monaco Editor
require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs' } });
require(['vs/editor/editor.main'], function () {
    editor = monaco.editor.create(document.getElementById('monaco-editor'), {
        value: INITIAL_CODE,
        language: 'php',
        theme: 'vs-dark',
        automaticLayout: true,
        fontFamily: "'Fira Code', monospace",
        fontSize: 14,
        minimap: { enabled: false },
        lineNumbers: 'on',
        renderLineHighlight: 'all',
        scrollbar: {
            vertical: 'visible',
            horizontal: 'visible',
            useShadows: false,
            verticalHasArrows: false,
            horizontalHasArrows: false,
            verticalScrollbarSize: 10,
            horizontalScrollbarSize: 10
        }
    });

    // Custom theme for cyber look
    monaco.editor.defineTheme('cyber-terminal', {
        base: 'vs-dark',
        inherit: true,
        rules: [
            { token: 'comment', foreground: '003b00', fontStyle: 'italic' },
            { token: 'keyword', foreground: '00ff41', fontStyle: 'bold' },
            { token: 'string', foreground: '00aa2b' },
            { token: 'variable', foreground: '00ff41' }
        ],
        colors: {
            'editor.background': '#050505',
            'editor.foreground': '#00ff41',
            'editorCursor.foreground': '#00ff41',
            'editorLineNumber.foreground': '#003b00',
            'editor.lineHighlightBackground': '#001a00',
            'editorSelection.background': '#003b00'
        }
    });
    monaco.editor.setTheme('cyber-terminal');
});

// Timer Logic
function updateTimer() {
    if (timeRemaining <= 0) {
        clearInterval(timerInterval);
        triggerShutdown();
        return;
    }

    const minutes = Math.floor(timeRemaining / 60);
    const seconds = timeRemaining % 60;
    document.getElementById('timer').textContent =
        `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

    timeRemaining--;
}

function triggerShutdown() {
    log("CRITICAL ERROR: TIME EXPIRED. INITIATING SHUTDOWN.");
    playSound('failure');
    fetch('shutdown.php', { method: 'POST' })
        .then(res => res.json())
        .then(data => {
            document.body.innerHTML = `<div style="background:#000;color:red;height:100vh;display:flex;align-items:center;justify-content:center;font-size:3rem;text-align:center;">SYSTEM HALTED<br>GRID FAILURE</div>`;
        });
}

// Audio System
function setupAudio() {
    audios.siren.loop = true;
    audios.siren.volume = 0.2;

    // The boot button will trigger this
    document.getElementById('boot-btn').addEventListener('click', () => {
        document.getElementById('boot-screen').style.display = 'none';

        console.log("SYSTEM: Boot sequence initiated. Unlocking audio...");
        audios.siren.play()
            .then(() => {
                log("SYSTEM: Audio systems active. Siren engaged.");
                startRandomMessages();
            })
            .catch(err => {
                console.error("Audio Playback Error:", err);
                log("CRITICAL: Audio playback blocked or files missing.");
            });

        // Start the timer only AFTER boot
        timerInterval = setInterval(updateTimer, 1000);
        updateTimer();
        log("SYSTEM READY. WAITING FOR CODE FIX...");
    });
}

function playSound(name) {
    if (audios[name]) {
        console.log(`SYSTEM: Playing audio resource [${name}]`);
        audios[name].currentTime = 0;
        audios[name].play().catch(err => {
            console.error(`Playback error for ${name}:`, err);
        });
    }
}

function stopAllSounds() {
    console.log("SYSTEM: Halting all audio modules...");
    Object.values(audios).forEach(audio => {
        audio.pause();
        audio.currentTime = 0;
    });
}

function startRandomMessages() {
    const messages = ['fatal', 'stability', 'core', 'unauthorized'];

    // First message after 10 seconds (Announcement to Partymakers)
    firstMessageTimeout = setTimeout(() => {
        playSound('fatal');
        log(`SYSTEM BROADCAST: FATAL WARNING EMITTED. ATTENTION PARTYMAKERS!`);
    }, 10000);

    // Subsequent random messages every 30 seconds
    messageInterval = setInterval(() => {
        const otherMessages = ['stability', 'core', 'unauthorized'];
        const msg = otherMessages[Math.floor(Math.random() * otherMessages.length)];
        playSound(msg);
        log(`SYSTEM BROADCAST: ${msg.toUpperCase()} WARNING EMITTED.`);
    }, 30000);
}

// Diagnostics (AJAX)
document.getElementById('run-tests-btn').addEventListener('click', runDiagnostics);

function runDiagnostics() {
    const code = editor.getValue();
    log("RUNNING DIAGNOSTICS...");

    fetch('test_engine.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'code=' + encodeURIComponent(code)
    })
        .then(res => res.json())
        .then(data => {
            if (data.error) {
                log(`PHP FATAL: ${data.error}`);
                return;
            }

            updateTestDashboard(data.tests);

            if (data.debug) {
                log(`DEBUG OUTPUT:<br>${data.debug.replace(/\n/g, '<br>')}`);
            }

            if (data.all_passed) {
                log("SUCCESS: ALL TESTS PASSED. GRID STABILIZED.");

                // Final state cleanup
                clearInterval(timerInterval);
                clearInterval(messageInterval);
                clearTimeout(firstMessageTimeout);

                stopAllSounds();
                setTimeout(() => {
                    playSound('success');
                    document.getElementById('success-screen').style.display = 'flex';
                }, 500);
            } else {
                log("DIAGNOSTIC FAILURE: UNRESOLVED INCIDENTS:");
                data.tests.forEach(test => {
                    if (!test.passed) {
                        log(`&nbsp;&nbsp;- ${test.name}: ${test.message}`);
                    }
                });
            }
        })
        .catch(err => log(`COMMUNICATION ERROR: ${err.message}`));
}

function updateTestDashboard(tests) {
    const items = document.querySelectorAll('.test-item');
    tests.forEach((test, index) => {
        const item = items[index];
        if (test.passed) {
            item.classList.remove('pending', 'failed');
            item.classList.add('passed');
        } else {
            item.classList.remove('pending', 'passed');
            item.classList.add('failed');
        }
    });
}

function log(msg) {
    const logContainer = document.getElementById('system-log');
    const time = new Date().toLocaleTimeString();
    logContainer.innerHTML += `[${time}] ${msg}<br>`;
    logContainer.scrollTop = logContainer.scrollHeight;
}

// Initial Setup
setupAudio();
// timerInterval moved inside setupAudio listener to wait for user interaction

