<?php
/**
 * live.php - Gemini Live Nebula Edition
 * UI: Nebula Material You
 * Logic: Silence Detection, Smart Camera Sync, Immersive Visuals
 */
session_start();
include 'config/database.php';
if (!isset($_SESSION['user_id'])) { header("Location: auth/login_page.php"); exit; }

// Fetch Dynamic Characters
$q_chars = mysqli_query($conn, "SELECT * FROM live_characters ORDER BY id ASC");
$chars_db = [];
while ($r = mysqli_fetch_assoc($q_chars)) { $chars_db[] = $r; }
$default_char = $chars_db[1] ?? $chars_db[0]; // Prefer index 1 (remaja) as default
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Gemini Live Nebula</title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Symbols+Rounded" rel="stylesheet">
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <style>
        body {
            font-family: 'Outfit', sans-serif;
            background-color: #050505;
            color: #e3e3e3;
            overflow: hidden;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* --- AI AVATAR CORE --- */
        .avatar-container {
            position: relative;
            width: 280px;
            height: 280px;
            z-index: 10;
            transition: all 0.5s cubic-bezier(0.2, 0.8, 0.2, 1);
        }

        .avatar-img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid rgba(255,255,255,0.15);
            box-shadow: 0 0 50px rgba(66, 133, 244, 0.2);
            z-index: 20;
            position: relative;
            transition: all 0.4s ease;
        }

        /* Voice Wave Animation */
        .voice-wave {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: rgba(66, 133, 244, 0.3);
            z-index: 10;
            opacity: 0;
            pointer-events: none;
        }

        .avatar-active .voice-wave {
            animation: voice-pulse 2s infinite ease-out;
        }

        @keyframes voice-pulse {
            0% { transform: translate(-50%, -50%) scale(1); opacity: 0.6; }
            100% { transform: translate(-50%, -50%) scale(1.6); opacity: 0; }
        }

        .avatar-active .avatar-img {
            border-color: #4285f4;
            box-shadow: 0 0 80px rgba(66, 133, 244, 0.5);
            transform: scale(1.03);
        }

        /* --- USER CAMERA PILL --- */
        #user-camera {
            position: absolute;
            top: 25px;
            right: 25px;
            width: 100px;
            height: 140px;
            border-radius: 24px;
            object-fit: cover;
            z-index: 100;
            border: 1px solid rgba(255,255,255,0.1);
            background: #111;
            transform: scaleX(-1);
            display: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }

        /* --- CONTROL PANEL --- */
        .control-pill {
            background: rgba(28, 28, 30, 0.7);
            backdrop-filter: blur(25px);
            border-radius: 40px;
            padding: 12px 24px;
            display: flex;
            align-items: center;
            gap: 20px;
            border: 1px solid rgba(255,255,255,0.08);
            z-index: 200;
            margin-bottom: 40px;
        }

        .btn-action {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255,255,255,0.05);
            color: white;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .btn-action.active {
            background: #fff;
            color: #000;
        }

        .btn-end {
            background: #ff453a;
            width: 65px;
            height: 65px;
        }

        #splash {
            position: fixed;
            inset: 0;
            background: #050505;
            z-index: 999;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body class="items-center justify-between py-10 relative">

    <div id="splash">
        <div class="avatar-container avatar-active mb-10" style="opacity: 0.8; transform: scale(0.8);">
            <div class="voice-wave"></div>
            <img src="<?= htmlspecialchars($default_char['image_path']) ?>" class="avatar-img" alt="AI Avatar">
        </div>
        <h1 class="text-3xl font-light tracking-widest mb-8">AI Asisten KITA LIVE</h1>
        <button onclick="startApp()" class="px-12 py-4 bg-white text-black rounded-full font-bold hover:scale-105 transition-transform">
            MULAI SEKARANG
        </button>
    </div>

    <div class="z-50 w-full flex justify-center">
        <div class="bg-white/5 border border-white/10 px-5 py-2 rounded-full backdrop-blur-md flex items-center gap-3">
            <span class="material-symbols-rounded text-blue-400 text-sm animate-pulse">auto_awesome</span>
            <span class="text-xs font-medium tracking-widest uppercase">AI Asisten KITA Experience</span>
        </div>
    </div>

    <div class="flex-1 w-full flex items-center justify-center relative">
        <video id="user-camera" autoplay playsinline muted></video>
        <canvas id="frame-canvas" class="hidden"></canvas>
        
        <div id="avatar-core" class="avatar-container">
            <div class="voice-wave"></div>
            <div class="voice-wave" style="animation-delay: 0.6s;"></div>
            <div class="voice-wave" style="animation-delay: 1.2s;"></div>
            <img src="<?= htmlspecialchars($default_char['image_path']) ?>" id="avatar-display" class="avatar-img" alt="AI Avatar">
        </div>

        <div id="status-container" class="absolute bottom-10 w-full text-center z-50">
            <p id="status-text" class="text-xl font-light text-white/40 tracking-wide transition-all duration-500">Mempersiapkan...</p>
        </div>
    </div>

    <div class="control-pill shadow-2xl">
        <button id="char-toggle" onclick="toggleCharPicker()" class="btn-action">
            <span class="material-symbols-rounded">face</span>
        </button>

        <button id="cam-toggle" onclick="toggleCamera()" class="btn-action">
            <span class="material-symbols-rounded">videocam_off</span>
        </button>
        
        <button id="cam-flip" onclick="flipCamera()" class="btn-action" style="display: none;">
            <span class="material-symbols-rounded">cameraswitch</span>
        </button>
        
        <button id="mic-toggle" onclick="toggleMic()" class="btn-action">
            <span class="material-symbols-rounded">mic_off</span>
        </button>

        <button onclick="exitApp()" class="btn-action btn-end shadow-lg shadow-red-500/20">
            <span class="material-symbols-rounded text-3xl">call_end</span>
        </button>
    </div>

    <!-- --- CHARACTER PICKER MODAL --- -->
    <div id="char-picker" class="fixed inset-0 z-[1000] hidden flex items-center justify-center p-6 backdrop-blur-xl bg-black/60">
        <div class="bg-[#1c1c1e] w-full max-w-sm rounded-[40px] p-8 border border-white/10 shadow-2xl">
            <h2 class="text-2xl font-semibold mb-8 text-center tracking-tight text-white">Pilih Teman Bicara</h2>
            
            <div class="space-y-4">
                <?php foreach($chars_db as $c): 
                    $border_color = ($c['char_key'] == 'abg') ? 'group-hover:border-pink-400' : (($c['char_key'] == 'remaja') ? 'group-hover:border-blue-400' : 'group-hover:border-purple-400');
                ?>
                <button onclick="setChar('<?= $c['char_key'] ?>')" class="w-full flex items-center gap-5 p-4 rounded-3xl bg-white/5 hover:bg-white/10 transition-all border border-transparent hover:border-white/20 group text-white">
                    <img src="<?= htmlspecialchars($c['image_path']) ?>" class="w-16 h-16 rounded-full object-cover border-2 border-white/10 <?= $border_color ?>">
                    <div class="text-left">
                        <div class="font-bold text-lg"><?= htmlspecialchars($c['name']) ?></div>
                        <div class="text-sm text-white/40"><?= htmlspecialchars($c['description']) ?></div>
                    </div>
                </button>
                <?php endforeach; ?>
            </div>

            <button onclick="toggleCharPicker()" class="mt-8 w-full py-4 rounded-full bg-white text-black font-bold text-sm tracking-widest uppercase">Tutup</button>
        </div>
    </div>

    <script>
        // --- KONFIGURASI ---
        const CHARS = {
            <?php foreach($chars_db as $c): ?>
            '<?= $c['char_key'] ?>': { 
                img: '<?= htmlspecialchars($c['image_path']) ?>', 
                pitch: <?= $c['pitch'] ?>, 
                rate: <?= $c['rate'] ?>, 
                status: '<?= htmlspecialchars($c['status_text']) ?>' 
            },
            <?php endforeach; ?>
        };

        let currentMode = '<?= $default_char['char_key'] ?>';

        const CONFIG = {
            lang: 'id-ID',
            pitch: 1.0, 
            rate: 1.1,  
            autoRestartMic: true
        };

        let recognition;
        let isMicActive = false;
        let isCamActive = false;
        let currentFacingMode = 'user'; // 'user' (depan), 'environment' (belakang)
        let isAiSpeaking = false; // Flag penting untuk mencegah echo
        let stream = null;
        const synth = window.speechSynthesis;
        let silenceTimer;
        let availableVoices = [];

        // Load voices saat browser siap
        window.speechSynthesis.onvoiceschanged = () => {
            availableVoices = window.speechSynthesis.getVoices();
        };

        function startApp() {
            $('#splash').fadeOut(800);
            $('#avatar-display').attr('src', CHARS[currentMode].img);
            initSpeech();
            toggleMic(); 
        }

        function toggleCharPicker() {
            $('#char-picker').fadeToggle(300);
        }

        function setChar(key) {
            currentMode = key;
            const char = CHARS[key];
            
            // Update Visual
            $('#avatar-display').fadeOut(300, function() {
                $(this).attr('src', char.img).fadeIn(300);
            });

            // Update Audio Config
            CONFIG.pitch = char.pitch;
            CONFIG.rate = char.rate;

            updateStatus(char.status, "text-white/40");
            toggleCharPicker();
        }

        function initSpeech() {
            const Speech = window.webkitSpeechRecognition || window.SpeechRecognition;
            if (!Speech) {
                alert("Browser ini tidak mendukung fitur suara. Gunakan Chrome.");
                return;
            }

            recognition = new Speech();
            recognition.lang = CONFIG.lang;
            recognition.continuous = false; // False agar lebih responsif per kalimat
            recognition.interimResults = true;

            recognition.onstart = () => {
                // Hanya update status jika AI tidak sedang bicara
                if(!isAiSpeaking) updateStatus("Mendengarkan...", "text-white/80");
            };

            recognition.onresult = (e) => {
                clearTimeout(silenceTimer);
                let transcript = '';
                for (let i = e.resultIndex; i < e.results.length; i++) {
                    transcript += e.results[i][0].transcript;
                }
                
                // Tampilkan teks user sementara (opsional, bisa dihapus jika ingin super bersih)
                // updateStatus(transcript, "text-white/60");

                // Deteksi keheningan (Silence Detection)
                silenceTimer = setTimeout(() => {
                    if (transcript.trim().length > 0) {
                        recognition.stop(); // Stop mic dulu
                        sendToAI(transcript);
                    }
                }, 1500); // Tunggu 1.5 detik hening baru kirim
            };

            recognition.onend = () => {
                // Logic pintar: Restart mic HANYA jika mic tombol on DAN AI diam
                if (isMicActive && !isAiSpeaking) {
                    try { recognition.start(); } catch(e) {}
                }
            };
            
            recognition.onerror = (e) => {
                // Abaikan error 'no-speech' agar tidak spamming alert
                if(e.error !== 'no-speech') console.log("Speech Error:", e.error);
            };
        }

        function toggleMic() {
            isMicActive = !isMicActive;
            const btn = $('#mic-toggle');
            
            if (isMicActive) {
                btn.addClass('active').find('span').text('mic');
                updateStatus("Siap...", "text-white/50");
                try { recognition.start(); } catch(e) {}
            } else {
                btn.removeClass('active').find('span').text('mic_off');
                recognition.stop();
                synth.cancel(); // Matikan suara AI jika user mematikan mic
                updateStatus("Mikrofon Mati", "text-white/30");
            }
        }

        function toggleCamera() {
            isCamActive = !isCamActive;
            const btn = $('#cam-toggle');
            const flipBtn = $('#cam-flip');
            const video = document.getElementById('user-camera');

            if (isCamActive) {
                startCameraStream();
                btn.addClass('active').find('span').text('videocam');
                flipBtn.show();
            } else {
                if (stream) stream.getTracks().forEach(t => t.stop());
                $(video).fadeOut(300);
                btn.removeClass('active').find('span').text('videocam_off');
                flipBtn.hide();
                $('#nebula-core').css('transform', 'scale(1)');
            }
        }

        function startCameraStream() {
            const video = document.getElementById('user-camera');
            if (stream) stream.getTracks().forEach(t => t.stop());
            navigator.mediaDevices.getUserMedia({ video: { facingMode: currentFacingMode } })
            .then(s => {
                stream = s;
                video.srcObject = s;
                $(video).fadeIn(500);
                $('#nebula-core').css('transform', 'scale(0.8)');
                
                // Hapus mirror effect untuk kamera belakang
                if (currentFacingMode === 'environment') {
                    $(video).css('transform', 'scaleX(1)');
                } else {
                    $(video).css('transform', 'scaleX(-1)');
                }
            })
            .catch(e => {
                alert("Gagal akses kamera/Izin ditolak");
                isCamActive = false;
                $('#cam-toggle').removeClass('active').find('span').text('videocam_off');
                $('#cam-flip').hide();
            });
        }

        function flipCamera() {
            currentFacingMode = currentFacingMode === 'user' ? 'environment' : 'user';
            if (isCamActive) startCameraStream();
        }

        function sendToAI(msg) {
            updateStatus("AI Asisten KITA sedang berpikir...", "text-blue-300 animate-pulse");
            $('#avatar-core').addClass('avatar-active');

            // --- FITUR VISION: Capture Frame jika Kamera Aktif ---
            let liveImage = null;
            if (isCamActive) {
                const video = document.getElementById('user-camera');
                const canvas = document.getElementById('frame-canvas');
                const context = canvas.getContext('2d');
                
                // Set resolusi rendah agar cepat dikirim (320x240)
                canvas.width = 480; 
                canvas.height = 360;
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                
                // Ambil base64 tanpa header data:image/png;base64,
                liveImage = canvas.toDataURL('image/jpeg', 0.6).split(',')[1];
            }

            $.ajax({
                url: 'api/gemini.php',
                method: 'POST',
                data: { 
                    pesan: msg, 
                    char_key: currentMode,
                    gambar_live: liveImage 
                },
                success: function(res) {
                    // Sesuai request: Jangan tampilkan teks jawaban di layar
                    // Langsung suarakan saja
                    speakAI(res.jawaban);
                },
                error: function() {
                    updateStatus("Koneksi Error", "text-red-400");
                    $('#nebula-core').removeClass('nebula-active');
                    // Restart mic agar user bisa coba lagi
                    if(isMicActive) recognition.start(); 
                }
            });
        }

        function speakAI(text) {
            if (synth.speaking) synth.cancel();
            
            isAiSpeaking = true; // Tandai AI sedang bicara
            recognition.stop();  // Matikan mic user (PENTING!)
            
            // Pembersihan teks agar suara lebih mulus (hapus markdown)
            const cleanText = text.replace(/[*#_`]/g, ""); 
            const u = new SpeechSynthesisUtterance(cleanText);
            
            // --- LOGIC SUARA NATURAL ---
            // Mencari suara Google Indonesia jika ada (biasanya lebih bagus)
            const googleVoice = availableVoices.find(v => v.name.includes('Google') && v.lang.includes('id'));
            if (googleVoice) {
                u.voice = googleVoice;
            }
            
            u.lang = 'id-ID';
            u.pitch = CONFIG.pitch;
            u.rate = CONFIG.rate;

            u.onstart = () => {
                updateStatus("AI Asisten KITA Berbicara...", "text-purple-300");
                $('#avatar-core').addClass('avatar-active');
            };

            u.onend = () => {
                $('#avatar-core').removeClass('avatar-active');
                updateStatus("Mendengarkan...", "text-white/80");
                
                isAiSpeaking = false; // AI selesai
                
                // Nyalakan mic user lagi secara otomatis
                if (isMicActive) {
                    setTimeout(() => {
                        try { recognition.start(); } catch(e) {}
                    }, 500); // Jeda setengah detik biar natural
                }
            };

            synth.speak(u);
        }

        function updateStatus(text, classes) {
            // Fungsi helper untuk update UI status yang rapi
            const el = $('#status-text');
            el.text(text);
            el.removeClass().addClass('text-xl font-light tracking-wide transition-all duration-500 ' + classes);
        }

        function exitApp() {
            // 1. Matikan Suara AI Seketika
            if (window.speechSynthesis) {
                window.speechSynthesis.pause();
                window.speechSynthesis.cancel();
            }
            
            // 2. Matikan Mic & Recognition
            isMicActive = false;
            if (recognition) {
                recognition.onend = null; 
                recognition.stop();
            }

            // 3. Matikan Kamera
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }

            // 4. Beri jeda sangat singkat lalu pindah halaman (agar browser sempat proses cancel)
            setTimeout(() => {
                window.location.href = 'index.php';
            }, 100);
        }

        // Tambahan: Pastikan mati jika tab ditutup atau di-refresh paksa
        window.addEventListener('beforeunload', () => {
            if (window.speechSynthesis) window.speechSynthesis.cancel();
        });
    </script>
</body>
</html>