<?php
/**
 * sound-mixer.php
 * Privacy-First Offline Ambient Sound Mixer & Sleep Machine
 * Synthesizes audio loops dynamically in code using Web Audio API. Built by The Purple Fox.
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Purple Sound Mixer | The Purple Fox</title>
    
    <!-- PWA support & Favicon -->
    <link rel="icon" href="sound_mixer_mascot.jpg" type="image/jpeg">
    <link rel="shortcut icon" href="sound_mixer_mascot.jpg" type="image/jpeg">
    <link rel="manifest" href="manifest.json">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Purple Mixer">
    <link rel="apple-touch-icon" href="logo.jpg">
    
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Space+Grotesk:wght@400;700&display=swap" rel="stylesheet">
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>
    
    <style>
        :root {
            --bg-color: #040308;
            --card-bg: rgba(22, 16, 48, 0.4);
            --card-border: rgba(168, 85, 247, 0.15);
            --card-hover-border: rgba(168, 85, 247, 0.5);
            --text-main: #f3f4f6;
            --text-muted: #a1a1aa;
            --purple-primary: #a855f7;
            --purple-light: #c084fc;
            --purple-glow: rgba(168, 85, 247, 0.4);
            --glass-header: rgba(12, 9, 28, 0.85);
            --success: #22c55e;
            --error: #ef4444;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-main);
            font-family: 'Outfit', sans-serif;
            min-height: 100vh;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
        }

        .bg-blobs {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            overflow: hidden;
            pointer-events: none;
        }

        .blob {
            position: absolute;
            border-radius: 50%;
            filter: blur(120px);
            opacity: 0.3;
        }

        .blob-1 {
            top: -10%;
            left: -10%;
            width: 50vw;
            height: 50vw;
            background: radial-gradient(circle, var(--purple-primary) 0%, rgba(0,0,0,0) 70%);
        }

        .blob-2 {
            bottom: -10%;
            right: -10%;
            width: 50vw;
            height: 50vw;
            background: radial-gradient(circle, #6366f1 0%, rgba(0,0,0,0) 70%);
        }

        /* Container */
        .container {
            max-width: 650px;
            width: 100%;
            margin: 0 auto;
            padding: 1.5rem;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        header {
            text-align: center;
            margin-bottom: 2rem;
            position: relative;
        }

        .header-logo {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            color: #fff;
            margin-bottom: 0.5rem;
        }

        .header-logo img {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: 2px solid var(--purple-primary);
        }

        .header-logo span {
            font-family: 'Space Grotesk', sans-serif;
            font-weight: 700;
            font-size: 1.2rem;
        }

        .header-logo span span {
            color: var(--purple-light);
        }

        .main-panel {
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 24px;
            padding: 2.5rem 2rem;
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        h2 {
            font-family: 'Space Grotesk', sans-serif;
            font-size: 1.8rem;
            margin-bottom: 0.5rem;
            text-align: center;
            font-weight: 700;
        }

        p.subtitle {
            color: var(--text-muted);
            text-align: center;
            margin-bottom: 2rem;
            font-size: 0.95rem;
        }

        /* Master Play Button */
        .master-controls {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 2.5rem;
        }

        .play-btn {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--purple-primary), #6366f1);
            border: none;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 0 30px var(--purple-glow);
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .play-btn:hover {
            transform: scale(1.08);
            box-shadow: 0 0 45px rgba(168, 85, 247, 0.6);
        }

        .play-btn.playing {
            background: linear-gradient(135deg, var(--error), #db2777);
            box-shadow: 0 0 30px rgba(239, 68, 68, 0.4);
        }

        .play-btn i {
            width: 32px;
            height: 32px;
        }

        /* Sound Channels Grid */
        .channels-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 1.2rem;
            margin-bottom: 2rem;
        }

        .channel-card {
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid var(--card-border);
            border-radius: 16px;
            padding: 1.2rem 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 1.5rem;
            transition: all 0.3s ease;
        }

        .channel-card.active {
            border-color: var(--card-hover-border);
            background: rgba(168, 85, 247, 0.05);
            box-shadow: 0 4px 20px rgba(168, 85, 247, 0.1);
        }

        .channel-info {
            display: flex;
            align-items: center;
            gap: 1rem;
            width: 150px;
            flex-shrink: 0;
        }

        .channel-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            background: rgba(255,255,255,0.03);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--purple-light);
            transition: all 0.3s ease;
        }

        .channel-card.active .channel-icon {
            background: var(--purple-primary);
            color: #fff;
            box-shadow: 0 0 15px var(--purple-glow);
        }

        .channel-title {
            font-weight: 600;
            font-size: 0.95rem;
        }

        /* Custom Slider styling */
        .slider-container {
            flex-grow: 1;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .slider-container i {
            color: var(--text-muted);
            font-size: 0.9rem;
        }

        .vol-slider {
            -webkit-appearance: none;
            width: 100%;
            height: 6px;
            border-radius: 3px;
            background: rgba(255, 255, 255, 0.1);
            outline: none;
            transition: background 0.3s ease;
        }

        .vol-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: var(--purple-light);
            cursor: pointer;
            box-shadow: 0 0 8px var(--purple-glow);
            transition: transform 0.2s ease;
        }

        .vol-slider::-webkit-slider-thumb:hover {
            transform: scale(1.2);
            background: #fff;
        }

        .channel-toggle {
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 8px;
            transition: all 0.2s ease;
        }

        .channel-toggle:hover {
            color: #fff;
            background: rgba(255,255,255,0.05);
        }

        .channel-card.active .channel-toggle {
            color: var(--purple-light);
        }

        /* Sleep Timer selector */
        .timer-section {
            border-top: 1px solid var(--card-border);
            padding-top: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .timer-title {
            font-weight: 600;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--purple-light);
        }

        .timer-options {
            display: flex;
            gap: 0.5rem;
        }

        .timer-btn {
            background: rgba(255,255,255,0.03);
            border: 1px solid var(--card-border);
            color: var(--text-muted);
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
            font-size: 0.8rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .timer-btn:hover {
            background: rgba(255,255,255,0.08);
            color: #fff;
        }

        .timer-btn.active {
            background: var(--purple-primary);
            border-color: var(--purple-primary);
            color: #fff;
            box-shadow: 0 0 10px var(--purple-glow);
        }

        .timer-countdown {
            font-family: 'Space Grotesk', sans-serif;
            font-weight: 700;
            font-size: 1.1rem;
            color: #fff;
            display: none;
        }

        footer {
            text-align: center;
            padding: 2rem 0;
            color: var(--text-muted);
            font-size: 0.8rem;
        }

        footer a {
            color: var(--purple-light);
            text-decoration: none;
        }

        /* Usage Agreement Modal Overlay */
        .agreement-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(4, 3, 10, 0.95);
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
            padding: 1.5rem;
            backdrop-filter: blur(15px);
            -webkit-backdrop-filter: blur(15px);
        }
        
        .agreement-modal.active {
            display: flex;
        }
        
        .agreement-content {
            background: #0f0b21;
            border: 2px solid var(--purple-primary);
            border-radius: 24px;
            padding: 2.5rem 2rem;
            max-width: 500px;
            width: 100%;
            box-shadow: 0 0 35px var(--purple-glow);
            text-align: center;
            animation: zoomIn 0.3s ease;
        }
        
        @keyframes zoomIn {
            from { transform: scale(0.95); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        
        .agreement-text {
            text-align: left;
            max-height: 250px;
            overflow-y: auto;
            background: rgba(0,0,0,0.25);
            padding: 1.2rem;
            border-radius: 12px;
            border: 1px solid var(--card-border);
            margin: 1.5rem 0;
            font-size: 0.85rem;
            line-height: 1.5;
            color: var(--text-muted);
        }
        
        .agreement-text h4 {
            color: #fff;
            margin-bottom: 0.4rem;
            margin-top: 0.8rem;
            font-size: 0.9rem;
        }
        
        .agreement-text p {
            margin-bottom: 0.6rem;
        }
        
        .agreement-text::-webkit-scrollbar {
            width: 6px;
        }
        .agreement-text::-webkit-scrollbar-track {
            background: rgba(0,0,0,0.1);
        }
        .agreement-text::-webkit-scrollbar-thumb {
            background: var(--card-border);
            border-radius: 3px;
        }
    </style>
</head>
<body>

    <div class="bg-blobs">
        <div class="blob blob-1"></div>
        <div class="blob blob-2"></div>
    </div>

    <div class="container">

        <header>
            <a href="index.php" class="header-logo">
                <img src="logo.jpg" alt="Purple Fox Logo">
                <span>The <span>Purple Fox</span> Hub</span>
            </a>
        </header>

        <div class="main-panel">
            <h2>Ambient Mixer</h2>
            <p class="subtitle">Synthesize relaxing ambient noise loops locally in code. 100% tracker-free sleep sounds.</p>
            
            <div class="master-controls">
                <button id="btn-master-play" class="play-btn" title="Master Play/Pause">
                    <i data-lucide="play" id="master-play-icon"></i>
                </button>
                <div style="font-size: 0.85rem; color: var(--text-muted); margin-top: 0.75rem; font-weight: 600;" id="master-status-text">SYSTEM STANDBY</div>
            </div>

            <div class="channels-grid">
                <!-- Brown Noise Card -->
                <div class="channel-card" id="card-brown">
                    <div class="channel-info">
                        <div class="channel-icon"><i data-lucide="waves"></i></div>
                        <div class="channel-title">Deep Brown Noise</div>
                    </div>
                    <div class="slider-container">
                        <i data-lucide="volume-x"></i>
                        <input type="range" class="vol-slider" id="vol-brown" min="0" max="1" step="0.05" value="0.5">
                        <i data-lucide="volume-2"></i>
                    </div>
                    <button class="channel-toggle" id="toggle-brown"><i data-lucide="power"></i></button>
                </div>

                <!-- Rain Card -->
                <div class="channel-card" id="card-rain">
                    <div class="channel-info">
                        <div class="channel-icon"><i data-lucide="cloud-rain"></i></div>
                        <div class="channel-title">Synthesized Rain</div>
                    </div>
                    <div class="slider-container">
                        <i data-lucide="volume-x"></i>
                        <input type="range" class="vol-slider" id="vol-rain" min="0" max="1" step="0.05" value="0.5">
                        <i data-lucide="volume-2"></i>
                    </div>
                    <button class="channel-toggle" id="toggle-rain"><i data-lucide="power"></i></button>
                </div>

                <!-- Wind Card -->
                <div class="channel-card" id="card-wind">
                    <div class="channel-info">
                        <div class="channel-icon"><i data-lucide="wind"></i></div>
                        <div class="channel-title">Howling Wind</div>
                    </div>
                    <div class="slider-container">
                        <i data-lucide="volume-x"></i>
                        <input type="range" class="vol-slider" id="vol-wind" min="0" max="1" step="0.05" value="0.4">
                        <i data-lucide="volume-2"></i>
                    </div>
                    <button class="channel-toggle" id="toggle-wind"><i data-lucide="power"></i></button>
                </div>

                <!-- Ocean Waves Card -->
                <div class="channel-card" id="card-ocean">
                    <div class="channel-info">
                        <div class="channel-icon"><i data-lucide="droplets"></i></div>
                        <div class="channel-title">Ocean Waves</div>
                    </div>
                    <div class="slider-container">
                        <i data-lucide="volume-x"></i>
                        <input type="range" class="vol-slider" id="vol-ocean" min="0" max="1" step="0.05" value="0.4">
                        <i data-lucide="volume-2"></i>
                    </div>
                    <button class="channel-toggle" id="toggle-ocean"><i data-lucide="power"></i></button>
                </div>
            </div>

            <!-- Sleep Timer Section -->
            <div class="timer-section">
                <div class="timer-title">
                    <i data-lucide="timer"></i>
                    <span>Sleep Timer</span>
                </div>
                <div class="timer-countdown" id="timer-display">00:00</div>
                <div class="timer-options" id="timer-ops">
                    <button class="timer-btn active" data-time="0">Off</button>
                    <button class="timer-btn" data-time="15">15m</button>
                    <button class="timer-btn" data-time="30">30m</button>
                    <button class="timer-btn" data-time="60">1h</button>
                    <button class="timer-btn" data-time="120">2h</button>
                </div>
            </div>
        </div>

        <footer>
            Built by <a href="index.php">The Purple Fox</a> Hub &copy; <?php echo date('Y'); ?>
        </footer>
    </div>

    <script>
        let audioCtx = null;
        let masterGain = null;
        let isPlaying = false;
        
        // Timer variables
        let timerDuration = 0; // seconds
        let timerInterval = null;

        // Sound configuration object
        const sounds = {
            brown: { active: true, gainNode: null, sourceNode: null, vol: 0.5 },
            rain: { active: true, gainNode: null, sourceNode: null, vol: 0.5, filterNode: null },
            wind: { active: true, gainNode: null, sourceNode: null, vol: 0.4, filterNode: null, lfoNode: null },
            ocean: { active: true, gainNode: null, sourceNode: null, vol: 0.4, filterNode: null, lfoNode: null, lfoGain: null }
        };

        // Initialize Audio context on first click
        function initAudio() {
            if (audioCtx) return;

            // Support both standard and Safari prefixes
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            audioCtx = new AudioContext();
            
            // Master gain node
            masterGain = audioCtx.createGain();
            masterGain.gain.setValueAtTime(0.001, audioCtx.currentTime); // start quiet
            masterGain.connect(audioCtx.destination);
            
            setupSynthesizers();
        }

        // --- DSP Audio synthesis algorithm loops ---

        // Generates 10 seconds of high quality Deep Brownian Noise
        function createBrownNoiseBuffer() {
            const bufferSize = 10 * audioCtx.sampleRate;
            const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
            const data = buffer.getChannelData(0);
            let lastOut = 0.0;
            
            for (let i = 0; i < bufferSize; i++) {
                const white = Math.random() * 2 - 1;
                // Accumulate and decay path
                data[i] = (lastOut + (0.02 * white)) / 1.02;
                lastOut = data[i];
                data[i] *= 3.5; // Compensate amplitude drop
            }
            return buffer;
        }

        // Generates 2 seconds of White Noise
        function createWhiteNoiseBuffer() {
            const bufferSize = 2 * audioCtx.sampleRate;
            const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
            const data = buffer.getChannelData(0);
            for (let i = 0; i < bufferSize; i++) {
                data[i] = Math.random() * 2 - 1;
            }
            return buffer;
        }

        function setupSynthesizers() {
            // Pre-create buffers
            const brownBuffer = createBrownNoiseBuffer();
            const whiteBuffer = createWhiteNoiseBuffer();

            // 1. Setup Deep Brown Noise
            sounds.brown.sourceNode = audioCtx.createBufferSource();
            sounds.brown.sourceNode.buffer = brownBuffer;
            sounds.brown.sourceNode.loop = true;
            sounds.brown.gainNode = audioCtx.createGain();
            sounds.brown.gainNode.gain.setValueAtTime(sounds.brown.active ? sounds.brown.vol : 0, audioCtx.currentTime);
            
            sounds.brown.sourceNode.connect(sounds.brown.gainNode);
            sounds.brown.gainNode.connect(masterGain);
            sounds.brown.sourceNode.start(0);

            // 2. Setup Rain (Filtered white noise + subtle low frequency)
            sounds.rain.sourceNode = audioCtx.createBufferSource();
            sounds.rain.sourceNode.buffer = whiteBuffer;
            sounds.rain.sourceNode.loop = true;
            
            sounds.rain.filterNode = audioCtx.createBiquadFilter();
            sounds.rain.filterNode.type = 'lowpass';
            sounds.rain.filterNode.frequency.setValueAtTime(800, audioCtx.currentTime); // Rain frequency spectrum
            
            sounds.rain.gainNode = audioCtx.createGain();
            sounds.rain.gainNode.gain.setValueAtTime(sounds.rain.active ? sounds.rain.vol * 0.7 : 0, audioCtx.currentTime);

            sounds.rain.sourceNode.connect(sounds.rain.filterNode);
            sounds.rain.filterNode.connect(sounds.rain.gainNode);
            sounds.rain.gainNode.connect(masterGain);
            sounds.rain.sourceNode.start(0);

            // 3. Setup Howling Wind (Bandpass filtered brown noise modulated by slow LFO)
            sounds.wind.sourceNode = audioCtx.createBufferSource();
            sounds.wind.sourceNode.buffer = brownBuffer;
            sounds.wind.sourceNode.loop = true;

            sounds.wind.filterNode = audioCtx.createBiquadFilter();
            sounds.wind.filterNode.type = 'bandpass';
            sounds.wind.filterNode.frequency.setValueAtTime(350, audioCtx.currentTime);
            sounds.wind.filterNode.Q.setValueAtTime(2.0, audioCtx.currentTime); // tight sweep

            sounds.wind.gainNode = audioCtx.createGain();
            sounds.wind.gainNode.gain.setValueAtTime(sounds.wind.active ? sounds.wind.vol : 0, audioCtx.currentTime);

            // Modulating LFO to sweep wind frequency (howling effect)
            sounds.wind.lfoNode = audioCtx.createOscillator();
            sounds.wind.lfoNode.type = 'sine';
            sounds.wind.lfoNode.frequency.setValueAtTime(0.08, audioCtx.currentTime); // very slow (12 seconds period)
            
            const lfoGain = audioCtx.createGain();
            lfoGain.gain.setValueAtTime(150, audioCtx.currentTime); // sweep bounds: 350 +/- 150Hz

            sounds.wind.lfoNode.connect(lfoGain);
            lfoGain.connect(sounds.wind.filterNode.frequency);
            
            sounds.wind.sourceNode.connect(sounds.wind.filterNode);
            sounds.wind.filterNode.connect(sounds.wind.gainNode);
            sounds.wind.gainNode.connect(masterGain);
            
            sounds.wind.lfoNode.start(0);
            sounds.wind.sourceNode.start(0);

            // 4. Setup Ocean Waves (Filtered white noise modulated in volume by a slow 6-second sine)
            sounds.ocean.sourceNode = audioCtx.createBufferSource();
            sounds.ocean.sourceNode.buffer = whiteBuffer;
            sounds.ocean.sourceNode.loop = true;

            sounds.ocean.filterNode = audioCtx.createBiquadFilter();
            sounds.ocean.filterNode.type = 'lowpass';
            sounds.ocean.filterNode.frequency.setValueAtTime(300, audioCtx.currentTime);

            sounds.ocean.gainNode = audioCtx.createGain();
            sounds.ocean.gainNode.gain.setValueAtTime(0, audioCtx.currentTime); // modulated gain

            // Wave LFO: frequency 0.16Hz (6 seconds cycle)
            sounds.ocean.lfoNode = audioCtx.createOscillator();
            sounds.ocean.lfoNode.type = 'sine';
            sounds.ocean.lfoNode.frequency.setValueAtTime(0.16, audioCtx.currentTime);

            sounds.ocean.lfoGain = audioCtx.createGain();
            sounds.ocean.lfoGain.gain.setValueAtTime(sounds.ocean.vol * 0.5, audioCtx.currentTime); 

            // Connect LFO through gain node offset directly to modulate ocean volume
            sounds.ocean.lfoNode.connect(sounds.ocean.lfoGain);
            sounds.ocean.lfoGain.connect(sounds.ocean.gainNode.gain);

            sounds.ocean.sourceNode.connect(sounds.ocean.filterNode);
            sounds.ocean.filterNode.connect(sounds.ocean.gainNode);
            sounds.ocean.gainNode.connect(masterGain);

            sounds.ocean.lfoNode.start(0);
            sounds.ocean.sourceNode.start(0);
        }

        // Master play toggle
        document.getElementById('btn-master-play').addEventListener('click', async () => {
            initAudio();
            
            if (audioCtx.state === 'suspended') {
                await audioCtx.resume();
            }

            const icon = document.getElementById('master-play-icon');
            const status = document.getElementById('master-status-text');
            const playBtn = document.getElementById('btn-master-play');

            if (!isPlaying) {
                // Fade-in volume smoothly
                masterGain.gain.cancelScheduledValues(audioCtx.currentTime);
                masterGain.gain.setValueAtTime(masterGain.gain.value, audioCtx.currentTime);
                masterGain.gain.linearRampToValueAtTime(1.0, audioCtx.currentTime + 1.5);
                
                isPlaying = true;
                playBtn.classList.add('playing');
                icon.setAttribute('data-lucide', 'pause');
                status.textContent = "SYNTHESIZERS ACTIVE";
            } else {
                // Fade-out volume smoothly
                masterGain.gain.cancelScheduledValues(audioCtx.currentTime);
                masterGain.gain.setValueAtTime(masterGain.gain.value, audioCtx.currentTime);
                masterGain.gain.linearRampToValueAtTime(0.001, audioCtx.currentTime + 1.2);
                
                setTimeout(() => {
                    if (!isPlaying && audioCtx) {
                        audioCtx.suspend();
                    }
                }, 1300);

                isPlaying = false;
                playBtn.classList.remove('playing');
                icon.setAttribute('data-lucide', 'play');
                status.textContent = "SYSTEM STANDBY";
            }
            lucide.createIcons();
        });

        // Setup individual channel control listeners
        function setupChannelListeners(id) {
            const toggle = document.getElementById(`toggle-${id}`);
            const slider = document.getElementById(`vol-${id}`);
            const card = document.getElementById(`card-${id}`);

            // Toggle power for specific sound
            toggle.addEventListener('click', () => {
                sounds[id].active = !sounds[id].active;
                card.classList.toggle('active', sounds[id].active);
                
                if (audioCtx && sounds[id].gainNode) {
                    const targetVal = sounds[id].active ? sounds[id].vol : 0;
                    sounds[id].gainNode.gain.cancelScheduledValues(audioCtx.currentTime);
                    sounds[id].gainNode.gain.setValueAtTime(sounds[id].gainNode.gain.value, audioCtx.currentTime);
                    sounds[id].gainNode.gain.linearRampToValueAtTime(targetVal, audioCtx.currentTime + 0.8);
                }
            });

            // Adjust volume slider
            slider.addEventListener('input', (e) => {
                const val = parseFloat(e.target.value);
                sounds[id].vol = val;
                
                if (sounds[id].active && audioCtx && sounds[id].gainNode) {
                    if (id === 'ocean' && sounds[id].lfoGain) {
                        sounds[id].lfoGain.gain.setValueAtTime(val * 0.5, audioCtx.currentTime);
                    } else {
                        sounds[id].gainNode.gain.setValueAtTime(val, audioCtx.currentTime);
                    }
                }
            });

            // Set default active color
            card.classList.toggle('active', sounds[id].active);
        }

        setupChannelListeners('brown');
        setupChannelListeners('rain');
        setupChannelListeners('wind');
        setupChannelListeners('ocean');

        // Sleep Timer Actions
        document.querySelectorAll('.timer-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.timer-btn').forEach(b => b.classList.remove('active'));
                e.currentTarget.classList.add('active');
                
                const mins = parseInt(e.currentTarget.getAttribute('data-time'));
                setSleepTimer(mins);
            });
        });

        function setSleepTimer(mins) {
            clearInterval(timerInterval);
            
            const countdownEl = document.getElementById('timer-display');
            const opsEl = document.getElementById('timer-ops');

            if (mins === 0) {
                countdownEl.style.display = 'none';
                opsEl.style.display = 'flex';
                timerDuration = 0;
                return;
            }

            countdownEl.style.display = 'block';
            opsEl.style.display = 'none';
            
            timerDuration = mins * 60;
            updateTimerDisplay();

            timerInterval = setInterval(() => {
                timerDuration--;
                updateTimerDisplay();
                
                if (timerDuration <= 0) {
                    clearInterval(timerInterval);
                    triggerAutoStop();
                }
            }, 1000);
        }

        function updateTimerDisplay() {
            const h = Math.floor(timerDuration / 3600);
            const m = Math.floor((timerDuration % 3600) / 60);
            const s = timerDuration % 60;
            
            const pad = (num) => String(num).padStart(2, '0');
            
            const display = document.getElementById('timer-display');
            if (h > 0) {
                display.textContent = `${pad(h)}:${pad(m)}:${pad(s)}`;
            } else {
                display.textContent = `${pad(m)}:${pad(s)}`;
            }
        }

        function triggerAutoStop() {
            if (isPlaying) {
                document.getElementById('btn-master-play').click();
            }
            // Reset timer UI options
            document.querySelectorAll('.timer-btn').forEach(b => b.classList.remove('active'));
            document.querySelector('.timer-btn[data-time="0"]').classList.add('active');
            document.getElementById('timer-display').style.display = 'none';
            document.getElementById('timer-ops').style.display = 'flex';
        }

        // Cancel timer on click countdown to return options
        document.getElementById('timer-display').addEventListener('click', () => {
            setSleepTimer(0);
        });

        // Initialize lucide icons at load
        window.addEventListener('load', () => {
            lucide.createIcons();
        });
    </script>

    <!-- Usage Agreement Modal Overlay -->
    <div class="agreement-modal" id="modal-agreement">
        <div class="agreement-content">
            <h3 style="font-family:'Space Grotesk'; font-size: 1.3rem;"><i data-lucide="shield-check" style="vertical-align:middle; color:var(--purple-light); margin-right:0.4rem;"></i> Purple Mixer Consent</h3>
            
            <div class="agreement-text">
                <p>Welcome to the <strong>Purple Sound Mixer</strong>. Before synthesizing ambient sounds, please review the local privacy policies:</p>
                
                <h4>1. 🌧️ Offline Audio Generation</h4>
                <p>This application does not download pre-recorded sound files or track your listening activity. All ambient tracks (Brownian waves, white noise, modulated howling wind) are synthesized in real-time entirely within your browser via the **Web Audio API**.</p>
                
                <h4>2. 🔋 Zero Tracking & Analytics</h4>
                <p>We do not collect statistics, device configurations, or user analytics. The application functions 100% offline without any server communication.</p>
            </div>
            
            <button class="btn btn-primary btn-block" id="btn-agree-continue">
                I Agree & Continue
            </button>
        </div>
    </div>

    <script>
        // Usage Agreement trigger for Sound Mixer
        window.addEventListener('DOMContentLoaded', () => {
            const hasAgreed = localStorage.getItem("pf_agreement_mixer_accepted");
            if (hasAgreed !== "true") {
                document.getElementById('modal-agreement').classList.add('active');
            }
        });
        document.getElementById('btn-agree-continue').addEventListener('click', () => {
            localStorage.setItem("pf_agreement_mixer_accepted", "true");
            document.getElementById('modal-agreement').classList.remove('active');
        });

        // Register Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('sw.js')
                    .then(reg => console.log('Service Worker Registered'))
                    .catch(err => console.log('Service Worker Failed', err));
            });
        }
    </script>
</body>
</html>
