<?php
// --- Backend Selection Logic ---
// 1. Define a whitelist of valid backend modes.
$valid_modes = ['wasm',  'webgpu', 'webgl'];

// 2. Get the mode from the URL, or default to 'wasm' if it's invalid or not set.
$mode = isset($_GET['mode']) && in_array($_GET['mode'], $valid_modes) ? $_GET['mode'] : 'wasm';

// 3. Construct the correct CDN URL for the selected backend's script.
$onnx_script_url = "https://cdnjs.cloudflare.com/ajax/libs/onnxruntime-web/1.22.0/ort.{$mode}.min.js";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>openWakeWord Web Demo (Backend: <?php echo strtoupper($mode); ?>)</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>openWakeWord Web Demo</h1>
        <h2>Click on Start Listening and Say "Hey Jarvis; Hey Mycroft; Alexa"</h2>
        <p>Real-time wake word detection in your browser using ONNX Runtime.</p>
        
        <div class="backend-links">
            <strong>Switch Backend:</strong>
            <a href="?mode=wasm" class="<?php if ($mode === 'wasm') echo 'active'; ?>">WASM</a> |
            <a href="?mode=webgpu" class="<?php if ($mode === 'webgpu') echo 'active'; ?>">WebGPU</a> |
            <a href="?mode=webgl" class="<?php if ($mode === 'webgl') echo 'active'; ?>">WebGL (not working)</a> 
        </div>

        <div class="controls">
            <select id="mic-select"></select>
            <button id="start-button" disabled>Loading Models...</button>
            <button id="test-button" disabled>Test from WAV</button>
        </div>

        <div class="control-group">
            <label for="gain-slider">Input Gain:</label>
            <input type="range" id="gain-slider" min="0" max="5" value="1" step="0.1">
            <span id="gain-value">100%</span>
        </div>

        <p>Status: <span id="vad-status">●</span> <span id="status-text">...</span></p>

        <div id="detection-result">
            <p id="detection-text"></p>
        </div>

        <div class="chart-container">
            <canvas id="score-chart"></canvas>
        </div>

        <div id="debug-audio-container">
            <h3>Debug Audio Clips</h3>
        </div>
    </div>

    <!-- This script tag is now dynamically generated by PHP -->
    <?php echo "<script src=\"{$onnx_script_url}\"></script>"; ?>
    
    <!-- Pass the selected mode to our main JavaScript file -->
    <script>
        const backend_mode = '<?php echo $mode; ?>';
    </script>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="main.js"></script>
</body>
</html>