<?php
/**
 * voice-notes.php
 * Privacy-First Offline Voice Recorder & Speech-to-Text Transcriber
 * Stored locally inside IndexedDB database vaults. 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 Voice Notes | The Purple Fox</title>
    
    <!-- PWA support & Favicon -->
    <link rel="icon" href="voice_notes_mascot.jpg" type="image/jpeg">
    <link rel="shortcut icon" href="voice_notes_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 Notes">
    <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: #040307;
            --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, #db2777 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: 1.5rem;
            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;
        }

        /* Record Panel controls */
        .recorder-section {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 2rem;
            position: relative;
        }

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

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

        .record-btn.recording {
            background: linear-gradient(135deg, var(--error), #dc2626);
            box-shadow: 0 0 35px rgba(239, 68, 68, 0.6);
            animation: pulseRecordBtn 1.5s infinite;
        }

        @keyframes pulseRecordBtn {
            0% { transform: scale(1); }
            50% { transform: scale(1.06); }
            100% { transform: scale(1); }
        }

        .record-timer {
            font-family: 'Space Grotesk', sans-serif;
            font-size: 1.3rem;
            font-weight: 700;
            margin-top: 1rem;
            letter-spacing: 0.05em;
        }

        /* Waveform Canvas */
        .visualizer-container {
            width: 100%;
            height: 80px;
            margin: 1.5rem 0;
            border-radius: 12px;
            overflow: hidden;
            background: rgba(0,0,0,0.2);
            border: 1px solid rgba(255, 255, 255, 0.03);
            position: relative;
        }

        #visualizer {
            width: 100%;
            height: 100%;
        }

        /* Live transcription preview card */
        .live-transcript {
            background: rgba(255,255,255,0.02);
            border: 1px solid var(--card-border);
            border-radius: 12px;
            padding: 1rem;
            width: 100%;
            min-height: 70px;
            max-height: 120px;
            overflow-y: auto;
            font-size: 0.9rem;
            color: var(--text-muted);
            margin-bottom: 2rem;
            font-style: italic;
        }

        /* Saved notes lists */
        .notes-section {
            border-top: 1px solid var(--card-border);
            padding-top: 2rem;
        }

        .section-title {
            font-family: 'Space Grotesk', sans-serif;
            font-size: 1.15rem;
            font-weight: 700;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .notes-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            max-height: 350px;
            overflow-y: auto;
            padding-right: 0.2rem;
        }

        .note-card {
            background: rgba(255, 255, 255, 0.01);
            border: 1px solid var(--card-border);
            border-radius: 16px;
            padding: 1.2rem;
            transition: all 0.3s ease;
        }

        .note-card:hover {
            border-color: var(--card-hover-border);
            background: rgba(255, 255, 255, 0.03);
            transform: translateY(-2px);
        }

        .note-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }

        .note-date {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--purple-light);
        }

        .note-duration {
            font-size: 0.8rem;
            color: var(--text-muted);
            display: flex;
            align-items: center;
            gap: 0.25rem;
        }

        .note-transcript {
            font-size: 0.9rem;
            color: var(--text-main);
            margin-bottom: 1rem;
            line-height: 1.4;
            max-height: 80px;
            overflow-y: auto;
            background: rgba(0,0,0,0.1);
            padding: 0.5rem;
            border-radius: 8px;
        }

        .note-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .note-audio-player {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .play-note-btn {
            background: var(--purple-primary);
            color: #fff;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.2s ease;
        }

        .play-note-btn:hover {
            transform: scale(1.1);
        }

        .btn-action {
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: 0.4rem;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

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

        .btn-delete:hover {
            color: var(--error);
            background: rgba(239, 68, 68, 0.1);
        }

        /* Toast notification */
        .toast {
            position: fixed;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background: rgba(12, 9, 28, 0.95);
            border: 1px solid var(--purple-primary);
            box-shadow: 0 5px 25px rgba(168, 85, 247, 0.3);
            color: #fff;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            z-index: 1000;
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .toast.show {
            transform: translateX(-50%) translateY(0);
        }

        .toast-success { border-color: var(--success); }
        .toast-error { border-color: var(--error); }

        /* 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>Voice Notes</h2>
            <p class="subtitle">Private voice notes recorded and transcribed completely offline using browser AI engine. Stored locally.</p>

            <div class="recorder-section">
                <button id="btn-record" class="record-btn" title="Record Voice Note">
                    <i data-lucide="mic" id="record-icon" style="width: 28px; height: 28px;"></i>
                </button>
                <div class="record-timer" id="record-timer">00:00</div>
            </div>

            <!-- Waveform visualizer canvas -->
            <div class="visualizer-container">
                <canvas id="visualizer"></canvas>
            </div>

            <!-- Live Speech-to-text text card preview -->
            <div class="live-transcript" id="live-transcript-box">
                Live speech transcription preview will show up here as you speak...
            </div>

            <!-- Saved Notes List -->
            <div class="notes-section">
                <h3 class="section-title">
                    <i data-lucide="folder-heart" style="color: var(--purple-light);"></i>
                    <span>My Saved Voice Notes</span>
                </h3>
                
                <div class="notes-list" id="notes-container">
                    <!-- Dynamic Notes injected here -->
                </div>
            </div>
        </div>

        <!-- Toast alert -->
        <div id="toast-alert" class="toast">
            <i data-lucide="info" id="toast-icon"></i>
            <span id="toast-text">Alert</span>
        </div>

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

    <script>
        let mediaRecorder = null;
        let audioChunks = [];
        let recordInterval = null;
        let recordTime = 0;
        let audioCtx = null;
        let analyser = null;
        let dataArray = null;
        let source = null;
        let stream = null;
        let recognition = null;
        let fullTranscript = "";
        let db = null;

        // IndexedDB Configuration (Used for storing large raw audio blobs offline)
        function initDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open("purple_fox_voice_db", 1);
                request.onupgradeneeded = (e) => {
                    const database = e.target.result;
                    if (!database.objectStoreNames.contains("notes")) {
                        database.createObjectStore("notes", { keyPath: "id", autoIncrement: true });
                    }
                };
                request.onsuccess = (e) => {
                    db = e.target.result;
                    resolve(db);
                };
                request.onerror = (e) => {
                    reject("IndexedDB failed to open");
                };
            });
        }

        // Save Note to local Database
        function saveNoteToDB(blob, duration, transcript) {
            return new Promise((resolve, reject) => {
                const today = new Date();
                const dateStr = today.toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' });
                
                const note = {
                    date: dateStr,
                    duration: duration,
                    transcript: transcript,
                    audioBlob: blob
                };

                const tx = db.transaction("notes", "readwrite");
                const store = tx.objectStore("notes");
                const request = store.add(note);

                request.onsuccess = () => resolve(true);
                request.onerror = () => reject("Save Note failed");
            });
        }

        // Fetch Notes from local Database
        function fetchNotesFromDB() {
            return new Promise((resolve, reject) => {
                const tx = db.transaction("notes", "readonly");
                const store = tx.objectStore("notes");
                const request = store.getAll();

                request.onsuccess = (e) => resolve(e.target.result);
                request.onerror = () => reject("Fetch notes failed");
            });
        }

        // Delete Note from Database
        function deleteNoteFromDB(id) {
            return new Promise((resolve, reject) => {
                const tx = db.transaction("notes", "readwrite");
                const store = tx.objectStore("notes");
                const request = store.delete(id);

                request.onsuccess = () => resolve(true);
                request.onerror = () => reject("Delete failed");
            });
        }

        // Toast controller
        function showToast(text, type = "success") {
            const toast = document.getElementById('toast-alert');
            const icon = document.getElementById('toast-icon');
            const toastText = document.getElementById('toast-text');
            
            toast.className = `toast show ${type === 'success' ? 'toast-success' : 'toast-error'}`;
            toastText.textContent = text;
            icon.setAttribute('data-lucide', type === 'success' ? 'check-circle' : 'alert-octagon');
            lucide.createIcons();
            
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // Initialize Speech Recognition API
        function initSpeechRecognition() {
            const SpeechReg = window.SpeechRecognition || window.webkitSpeechRecognition;
            if (!SpeechReg) {
                console.log("Speech recognition not supported in this browser");
                return;
            }
            recognition = new SpeechReg();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.lang = 'en-US';

            recognition.onresult = (event) => {
                let interimTranscript = '';
                for (let i = event.resultIndex; i < event.results.length; ++i) {
                    if (event.results[i].isFinal) {
                        fullTranscript += event.results[i][0].transcript + ' ';
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
                const previewText = fullTranscript + interimTranscript;
                document.getElementById('live-transcript-box').textContent = previewText || "Listening...";
            };

            recognition.onerror = (e) => {
                console.error("Speech Recognition Error:", e.error);
            };
        }

        // Setup Visualizer Canvas waveform rendering
        function setupVisualizer() {
            const canvas = document.getElementById('visualizer');
            const canvasCtx = canvas.getContext('2d');
            
            // Adjust canvas dimensions
            canvas.width = canvas.parentElement.offsetWidth;
            canvas.height = canvas.parentElement.offsetHeight;

            analyser.fftSize = 256;
            const bufferLength = analyser.frequencyBinCount;
            dataArray = new Uint8Array(bufferLength);

            function draw() {
                if (!mediaRecorder || mediaRecorder.state !== 'recording') {
                    // Draw flat center line when quiet
                    canvasCtx.fillStyle = '#0f0b21';
                    canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
                    canvasCtx.lineWidth = 2;
                    canvasCtx.strokeStyle = 'var(--purple-border)';
                    canvasCtx.beginPath();
                    canvasCtx.moveTo(0, canvas.height / 2);
                    canvasCtx.lineTo(canvas.width, canvas.height / 2);
                    canvasCtx.stroke();
                    return;
                }

                requestAnimationFrame(draw);
                analyser.getByteTimeDomainData(dataArray);

                canvasCtx.fillStyle = '#080614';
                canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

                canvasCtx.lineWidth = 2;
                canvasCtx.strokeStyle = 'var(--purple-light)';
                canvasCtx.beginPath();

                const sliceWidth = canvas.width * 1.0 / bufferLength;
                let x = 0;

                for (let i = 0; i < bufferLength; i++) {
                    const v = dataArray[i] / 128.0;
                    const y = v * canvas.height / 2;

                    if (i === 0) {
                        canvasCtx.moveTo(x, y);
                    } else {
                        canvasCtx.lineTo(x, y);
                    }

                    x += sliceWidth;
                }

                canvasCtx.lineTo(canvas.width, canvas.height / 2);
                canvasCtx.stroke();
            }

            draw();
        }

        // Timer formatting helper
        const formatTime = (secs) => {
            const m = Math.floor(secs / 60);
            const s = secs % 60;
            return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
        };

        // Record Button click listener
        document.getElementById('btn-record').addEventListener('click', async () => {
            const button = document.getElementById('btn-record');
            const icon = document.getElementById('record-icon');
            const timerEl = document.getElementById('record-timer');

            if (!mediaRecorder || mediaRecorder.state === 'inactive') {
                // START RECORDING
                try {
                    stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    
                    // Web Audio API hooks for Visualizer
                    const AudioContext = window.AudioContext || window.webkitAudioContext;
                    audioCtx = new AudioContext();
                    analyser = audioCtx.createAnalyser();
                    source = audioCtx.createMediaStreamSource(stream);
                    source.connect(analyser);

                    mediaRecorder = new MediaRecorder(stream);
                    audioChunks = [];
                    fullTranscript = "";
                    document.getElementById('live-transcript-box').textContent = "Start speaking...";

                    mediaRecorder.ondataavailable = (event) => {
                        audioChunks.push(event.data);
                    };

                    mediaRecorder.onstop = async () => {
                        const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                        
                        // Save to IndexedDB
                        await saveNoteToDB(audioBlob, formatTime(recordTime), fullTranscript || "[No Transcription]");
                        showToast("Voice Note saved successfully!", "success");
                        
                        // Cleanup
                        if (stream) stream.getTracks().forEach(track => track.stop());
                        if (audioCtx) audioCtx.close();
                        
                        recordTime = 0;
                        timerEl.textContent = "00:00";
                        document.getElementById('live-transcript-box').textContent = "Live speech transcription preview will show up here as you speak...";
                        renderNotes();
                    };

                    // Speech recognition trigger
                    if (recognition) {
                        recognition.start();
                    }

                    mediaRecorder.start();
                    setupVisualizer();

                    // Start Record timer intervals
                    recordTime = 0;
                    recordInterval = setInterval(() => {
                        recordTime++;
                        timerEl.textContent = formatTime(recordTime);
                    }, 1000);

                    button.classList.add('recording');
                    icon.setAttribute('data-lucide', 'square');
                    lucide.createIcons();

                } catch (err) {
                    console.error(err);
                    showToast("Microphone permissions denied or not found.", "error");
                }
            } else {
                // STOP RECORDING
                mediaRecorder.stop();
                clearInterval(recordInterval);
                if (recognition) {
                    recognition.stop();
                }

                button.classList.remove('recording');
                icon.setAttribute('data-lucide', 'mic');
                lucide.createIcons();
            }
        });

        // Render saved notes
        async function renderNotes() {
            const container = document.getElementById('notes-container');
            container.innerHTML = "";

            let notes = [];
            try {
                notes = await fetchNotesFromDB();
            } catch (err) {
                console.error(err);
            }

            if (notes.length === 0) {
                container.innerHTML = `
                    <div style="text-align:center; padding: 2rem; color: var(--text-muted);">
                        <i data-lucide="mic-off" style="width:36px; height:36px; margin-bottom: 0.5rem; color: var(--purple-light);"></i>
                        <p>No saved voice notes.</p>
                    </div>
                `;
                lucide.createIcons();
                return;
            }

            // Render notes (newest first)
            notes.reverse().forEach((note) => {
                const card = document.createElement('div');
                card.className = 'note-card';
                
                // Read transcript text
                const safeTranscript = note.transcript || "[No Transcription]";

                card.innerHTML = `
                    <div class="note-header">
                        <div class="note-date">${note.date}</div>
                        <div class="note-duration"><i data-lucide="clock" style="width:12px; height:12px;"></i> ${note.duration}</div>
                    </div>
                    <div class="note-transcript" contenteditable="true" onblur="updateNoteTranscript(${note.id}, this.textContent)">
                        ${escapeHtml(safeTranscript)}
                    </div>
                    <div class="note-controls">
                        <div class="note-audio-player">
                            <button class="play-note-btn" onclick="playNoteAudio(${note.id}, this)" title="Play Audio">
                                <i data-lucide="play" style="width: 16px; height:16px;"></i>
                            </button>
                            <span style="font-size:0.8rem; color: var(--text-muted);" class="play-state-label">Play Recording</span>
                        </div>
                        <div style="display:flex; gap:0.5rem;">
                            <button class="btn-action" onclick="downloadNoteAudio(${note.id})" title="Download WAV Audio"><i data-lucide="download"></i></button>
                            <button class="btn-action btn-delete" onclick="deleteNote(${note.id})" title="Delete Recording"><i data-lucide="trash-2"></i></button>
                        </div>
                    </div>
                `;
                container.appendChild(card);
            });
            lucide.createIcons();
        }

        // Global note audio controller
        let activeAudio = null;
        let activePlayBtn = null;

        window.playNoteAudio = async (id, btn) => {
            const label = btn.nextElementSibling;
            
            // Toggle active playing audio
            if (activeAudio && activePlayBtn === btn) {
                if (!activeAudio.paused) {
                    activeAudio.pause();
                    btn.querySelector('i').setAttribute('data-lucide', 'play');
                    label.textContent = "Paused";
                } else {
                    await activeAudio.play();
                    btn.querySelector('i').setAttribute('data-lucide', 'pause');
                    label.textContent = "Playing...";
                }
                lucide.createIcons();
                return;
            }

            // Stop other playing audio
            if (activeAudio) {
                activeAudio.pause();
                if (activePlayBtn) {
                    activePlayBtn.querySelector('i').setAttribute('data-lucide', 'play');
                    activePlayBtn.nextElementSibling.textContent = "Play Recording";
                }
            }

            try {
                // Retrieve note blob
                const tx = db.transaction("notes", "readonly");
                const store = tx.objectStore("notes");
                const request = store.get(id);
                
                request.onsuccess = async (e) => {
                    const note = e.target.result;
                    if (note && note.audioBlob) {
                        const url = URL.createObjectURL(note.audioBlob);
                        activeAudio = new Audio(url);
                        activePlayBtn = btn;
                        
                        activeAudio.onended = () => {
                            btn.querySelector('i').setAttribute('data-lucide', 'play');
                            label.textContent = "Play Recording";
                            lucide.createIcons();
                            activeAudio = null;
                            activePlayBtn = null;
                        };
                        
                        await activeAudio.play();
                        btn.querySelector('i').setAttribute('data-lucide', 'pause');
                        label.textContent = "Playing...";
                        lucide.createIcons();
                    }
                };
            } catch (err) {
                showToast("Audio playback failed", "error");
            }
        };

        window.downloadNoteAudio = async (id) => {
            const tx = db.transaction("notes", "readonly");
            const store = tx.objectStore("notes");
            const request = store.get(id);

            request.onsuccess = (e) => {
                const note = e.target.result;
                if (note && note.audioBlob) {
                    const url = URL.createObjectURL(note.audioBlob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `voice_note_${id}.wav`;
                    document.body.appendChild(link);
                    link.click();
                    link.remove();
                    showToast("Audio file download started!", "success");
                }
            };
        };

        window.deleteNote = async (id) => {
            if (confirm("Delete this voice recording permanently?")) {
                await deleteNoteFromDB(id);
                showToast("Recording deleted", "success");
                renderNotes();
            }
        };

        window.updateNoteTranscript = (id, newText) => {
            const tx = db.transaction("notes", "readwrite");
            const store = tx.objectStore("notes");
            const request = store.get(id);

            request.onsuccess = (e) => {
                const note = e.target.result;
                if (note) {
                    note.transcript = newText.trim();
                    store.put(note);
                    showToast("Transcript updated!", "success");
                }
            };
        };

        // Escaping HTML
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Document onLoad bindings
        window.addEventListener('DOMContentLoaded', async () => {
            try {
                await initDB();
                initSpeechRecognition();
                renderNotes();
            } catch (err) {
                console.error(err);
                showToast("Failed to initialize database.", "error");
            }
            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 Notes Consent</h3>
            
            <div class="agreement-text">
                <p>Welcome to <strong>Purple Voice Notes</strong>. Before recording memo audio, please review the local privacy policies:</p>
                
                <h4>1. 🎙️ On-Device Media Vault</h4>
                <p>All recorded audio clips and transcripts remain strictly on-device inside your browser's private **IndexedDB database vault**. No voice clips or text transcripts are uploaded to remote cloud networks.</p>
                
                <h4>2. 🗣️ Speech-to-Text Transcription</h4>
                <p>Offline transcription leverages the browser's native **Speech Recognition API**. The conversion is performed client-side on supported engines.</p>
                
                <h4>3. 💾 Data Persistence</h4>
                <p>Clearing browser cookies/history will delete the IndexedDB database. Please download your recorded memos as **WAV files** regularly for offline archive preservation.</p>
            </div>
            
            <button class="btn btn-primary btn-block" id="btn-agree-continue">
                I Agree & Continue
            </button>
        </div>
    </div>

    <script>
        // Usage Agreement trigger for Voice Notes
        window.addEventListener('DOMContentLoaded', () => {
            const hasAgreed = localStorage.getItem("pf_agreement_notes_accepted");
            if (hasAgreed !== "true") {
                document.getElementById('modal-agreement').classList.add('active');
            }
        });
        document.getElementById('btn-agree-continue').addEventListener('click', () => {
            localStorage.setItem("pf_agreement_notes_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>
