<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Chat - <?= htmlspecialchars($entreprise['nom']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --primary: <?= $config['couleur_primaire'] ?? '#06b6d4' ?>; 
            --primary-dark: <?= $config['couleur_primaire'] ?? '#0891b2' ?>;
        }
        
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        
        html, body { 
            height: 100%; 
            margin: 0; 
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        }
        
        .chat-wrapper {
            height: 100%;
            max-width: 100%;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            background: #ffffff;
        }
        
        @media (min-width: 480px) {
            .chat-wrapper {
                max-width: 420px;
                height: 100vh;
                max-height: 700px;
                margin: 0 auto;
                border-radius: 24px;
                box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
                position: relative;
                top: 50%;
                transform: translateY(-50%);
            }
        }
        
        .header-gradient {
            background: linear-gradient(135deg, var(--primary) 0%, #10b981 100%);
        }
        
        .message-enter {
            animation: messageSlide 0.3s ease-out;
        }
        
        @keyframes messageSlide {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-4px); }
        }
        
        .typing-dot {
            animation: typing 1.4s infinite;
        }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }
        
        .msg-bubble {
            max-width: 85%;
            word-wrap: break-word;
        }
        
        .msg-client {
            background: linear-gradient(135deg, var(--primary) 0%, #10b981 100%);
            color: white;
            border-radius: 20px 20px 4px 20px;
        }
        
        .msg-bot {
            background: #f1f5f9;
            color: #1e293b;
            border-radius: 20px 20px 20px 4px;
        }
        
        .input-area {
            background: #ffffff;
            border-top: 1px solid #e2e8f0;
            padding: env(safe-area-inset-bottom);
        }
        
        .send-btn {
            background: linear-gradient(135deg, var(--primary) 0%, #10b981 100%);
            transition: all 0.2s;
        }
        
        .send-btn:active {
            transform: scale(0.95);
        }
        
        .quick-reply {
            background: white;
            border: 1.5px solid var(--primary);
            color: var(--primary);
            transition: all 0.2s;
        }
        
        .quick-reply:hover, .quick-reply:active {
            background: var(--primary);
            color: white;
        }
        
        .online-indicator {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .messages-container {
            flex: 1;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            scroll-behavior: smooth;
        }
        
        .messages-container::-webkit-scrollbar {
            width: 4px;
        }
        
        .messages-container::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 4px;
        }
        
        .welcome-card {
            animation: fadeIn 0.5s ease-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
        
        .voice-btn {
            transition: all 0.3s ease;
        }
        
        .voice-btn.bg-red-500 {
            animation: pulse-record 1.5s infinite;
        }
        
        @keyframes pulse-record {
            0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
            50% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
        }
        
        .voice-wave {
            display: flex;
            align-items: center;
            gap: 2px;
        }
        
        .voice-wave span {
            width: 3px;
            height: 12px;
            background: #ef4444;
            border-radius: 2px;
            animation: wave 0.5s infinite ease-in-out;
        }
        
        .voice-wave span:nth-child(2) { animation-delay: 0.1s; }
        .voice-wave span:nth-child(3) { animation-delay: 0.2s; }
        .voice-wave span:nth-child(4) { animation-delay: 0.3s; }
        
        @keyframes wave {
            0%, 100% { transform: scaleY(0.5); }
            50% { transform: scaleY(1); }
        }
        
        @keyframes slide-up {
            from { transform: translateY(100%); }
            to { transform: translateY(0); }
        }
        
        .animate-slide-up {
            animation: slide-up 0.3s ease-out;
        }
    </style>
</head>
<body>
    <div class="chat-wrapper" id="chat-wrapper">
        <!-- Header -->
        <div class="header-gradient text-white px-4 py-4 flex items-center justify-between flex-shrink-0 safe-area-top">
            <div class="flex items-center">
                <div class="w-11 h-11 bg-white/20 backdrop-blur rounded-full flex items-center justify-center mr-3">
                    <i class="fas fa-robot text-lg"></i>
                </div>
                <div>
                    <p class="font-semibold text-base"><?= htmlspecialchars($entreprise['nom']) ?></p>
                    <div class="flex items-center text-xs text-white/80">
                        <span class="w-2 h-2 bg-emerald-400 rounded-full mr-1.5 online-indicator"></span>
                        <span id="status-text">Assistant IA • En ligne</span>
                    </div>
                </div>
            </div>
            <div class="relative">
                <button onclick="toggleLangMenu()" class="w-9 h-9 bg-white/20 rounded-full flex items-center justify-center" title="Changer de langue">
                    <i class="fas fa-globe text-sm"></i>
                </button>
                <div id="lang-menu" class="hidden absolute right-0 top-12 bg-white rounded-xl shadow-lg py-2 min-w-[140px] z-50">
                    <?php 
                    $allLangues = ['fr' => 'Français', 'bm' => 'Bambara'];
                    foreach ($allLangues as $code => $nom): 
                    ?>
                    <button onclick="setLangue('<?= $code ?>')" class="lang-btn w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-100 flex items-center" data-lang="<?= $code ?>">
                        <span class="lang-check w-4 mr-2 text-cyan-500 text-xs"><?= $code === 'fr' ? '✓' : '' ?></span>
                        <?= $nom ?>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <!-- Messages Container -->
        <div class="messages-container p-4" id="messages">
            <!-- Welcome message -->
            <div class="welcome-card bg-gradient-to-br from-slate-50 to-slate-100 rounded-2xl p-5 mb-4 text-center">
                <div class="w-16 h-16 bg-gradient-to-br from-cyan-500 to-emerald-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
                    <i class="fas fa-sparkles text-white text-2xl"></i>
                </div>
                <h2 class="text-lg font-bold text-slate-800 mb-1"><?= htmlspecialchars($config['message_bienvenue'] ?? 'Bonjour ! 👋') ?></h2>
                <p class="text-sm text-slate-500">Comment puis-je vous aider aujourd'hui ?</p>
            </div>
            
            <!-- Quick replies -->
            <div id="quick-replies" class="flex flex-wrap gap-2 mb-4">
                <button onclick="sendQuickReply('Quels sont vos services ?')" class="quick-reply px-4 py-2 rounded-full text-sm font-medium">
                    🛎️ Vos services
                </button>
                <button onclick="sendQuickReply('Je veux parler à un conseiller')" class="quick-reply px-4 py-2 rounded-full text-sm font-medium">
                    👤 Conseiller
                </button>
                <?php if (in_array('voice', json_decode($entreprise['canaux_actifs'] ?? '[]', true))): ?>
                <button onclick="startVoiceCall()" id="voice-call-btn" class="quick-reply px-4 py-2 rounded-full text-sm font-medium bg-green-50 text-green-600 border-green-200 hover:bg-green-100">
                    📞 Appeler
                </button>
                <?php endif; ?>
                <?php if (in_array('whatsapp', json_decode($entreprise['canaux_actifs'] ?? '[]', true))): ?>
                <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', TWILIO_WHATSAPP_NUMBER ?? '') ?>?text=<?= urlencode('Bonjour ' . htmlspecialchars($entreprise['nom']) . ', j\'ai besoin d\'aide.') ?>" 
                   target="_blank" 
                   class="quick-reply px-4 py-2 rounded-full text-sm font-medium bg-green-50 text-green-600 border-green-200 hover:bg-green-100 inline-flex items-center gap-1">
                    <i class="fab fa-whatsapp"></i> WhatsApp
                </a>
                <?php endif; ?>
                <button onclick="openDenonciationModal()" id="denonciation-btn" class="quick-reply px-4 py-2 rounded-full text-sm font-medium bg-red-50 text-red-600 border-red-200 hover:bg-red-100">
                    🚨 Signaler
                </button>
            </div>
            
            <!-- Voice Call UI -->
            <div id="voice-call-ui" class="hidden fixed inset-0 bg-black/80 z-50 flex items-center justify-center">
                <div class="bg-white rounded-3xl p-8 text-center max-w-sm mx-4 shadow-2xl">
                    <div id="call-avatar" class="w-24 h-24 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg">
                        <i class="fas fa-phone text-white text-3xl" id="call-icon"></i>
                    </div>
                    <h3 class="text-xl font-bold text-slate-800 mb-2"><?= htmlspecialchars($entreprise['nom']) ?></h3>
                    <p id="call-status" class="text-slate-500 mb-6">Connexion en cours...</p>
                    <div class="flex justify-center gap-4">
                        <button onclick="endVoiceCall()" class="w-16 h-16 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center text-white shadow-lg transition">
                            <i class="fas fa-phone-slash text-xl"></i>
                        </button>
                        <button onclick="toggleMute()" id="mute-btn" class="w-16 h-16 bg-slate-200 hover:bg-slate-300 rounded-full flex items-center justify-center text-slate-700 shadow-lg transition">
                            <i class="fas fa-microphone text-xl" id="mute-icon"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Modal Dénonciation -->
        <div id="denonciation-modal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-end justify-center">
            <div class="bg-white w-full max-w-md rounded-t-3xl max-h-[90vh] overflow-y-auto animate-slide-up">
                <div class="sticky top-0 bg-white px-4 py-4 border-b flex items-center justify-between">
                    <h3 class="font-bold text-lg text-slate-800">🚨 Faire un signalement</h3>
                    <button onclick="closeDenonciationModal()" class="w-8 h-8 rounded-full bg-slate-100 flex items-center justify-center">
                        <i class="fas fa-times text-slate-500"></i>
                    </button>
                </div>
                
                <form id="denonciation-form" class="p-4 space-y-4">
                    <!-- Type de signalement -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-2">Type de signalement</label>
                        <div class="grid grid-cols-4 gap-2">
                            <button type="button" onclick="setDenonciationType('texte')" class="denon-type-btn active flex flex-col items-center p-3 rounded-xl border-2 border-cyan-500 bg-cyan-50" data-type="texte">
                                <i class="fas fa-pen text-lg mb-1 text-cyan-600"></i>
                                <span class="text-xs text-cyan-700">Texte</span>
                            </button>
                            <button type="button" onclick="setDenonciationType('audio')" class="denon-type-btn flex flex-col items-center p-3 rounded-xl border-2 border-slate-200 hover:border-cyan-300" data-type="audio">
                                <i class="fas fa-microphone text-lg mb-1 text-slate-500"></i>
                                <span class="text-xs text-slate-600">Audio</span>
                            </button>
                            <button type="button" onclick="setDenonciationType('photo')" class="denon-type-btn flex flex-col items-center p-3 rounded-xl border-2 border-slate-200 hover:border-cyan-300" data-type="photo">
                                <i class="fas fa-camera text-lg mb-1 text-slate-500"></i>
                                <span class="text-xs text-slate-600">Photo</span>
                            </button>
                            <button type="button" onclick="setDenonciationType('video')" class="denon-type-btn flex flex-col items-center p-3 rounded-xl border-2 border-slate-200 hover:border-cyan-300" data-type="video">
                                <i class="fas fa-video text-lg mb-1 text-slate-500"></i>
                                <span class="text-xs text-slate-600">Vidéo</span>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Titre -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Titre du signalement</label>
                        <input type="text" name="titre" required placeholder="Décrivez brièvement le problème..." class="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-cyan-500 focus:ring-2 focus:ring-cyan-200 outline-none text-sm">
                    </div>
                    
                    <!-- Description (pour texte) -->
                    <div id="denon-texte-section">
                        <label class="block text-sm font-medium text-slate-700 mb-1">Description détaillée</label>
                        <textarea name="description" rows="4" placeholder="Expliquez en détail ce que vous souhaitez signaler..." class="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-cyan-500 focus:ring-2 focus:ring-cyan-200 outline-none text-sm resize-none"></textarea>
                    </div>
                    
                    <!-- Upload Audio -->
                    <div id="denon-audio-section" class="hidden">
                        <label class="block text-sm font-medium text-slate-700 mb-2">Enregistrement audio</label>
                        <div class="border-2 border-dashed border-slate-200 rounded-xl p-6 text-center">
                            <button type="button" onclick="startAudioRecording()" id="audio-record-btn" class="w-16 h-16 rounded-full bg-red-500 text-white flex items-center justify-center mx-auto mb-2 hover:bg-red-600 transition">
                                <i class="fas fa-microphone text-2xl"></i>
                            </button>
                            <p class="text-sm text-slate-500" id="audio-status">Appuyez pour enregistrer</p>
                            <audio id="audio-preview" class="hidden w-full mt-3" controls></audio>
                            <input type="file" name="fichier_audio" id="fichier-audio" accept="audio/*" class="hidden">
                        </div>
                    </div>
                    
                    <!-- Upload Photo -->
                    <div id="denon-photo-section" class="hidden">
                        <label class="block text-sm font-medium text-slate-700 mb-2">Photo</label>
                        <div class="border-2 border-dashed border-slate-200 rounded-xl p-6 text-center">
                            <input type="file" name="fichier_photo" id="fichier-photo" accept="image/*" capture="environment" class="hidden" onchange="previewFile(this, 'photo-preview')">
                            <label for="fichier-photo" class="cursor-pointer">
                                <div class="w-16 h-16 rounded-full bg-cyan-100 text-cyan-600 flex items-center justify-center mx-auto mb-2">
                                    <i class="fas fa-camera text-2xl"></i>
                                </div>
                                <p class="text-sm text-slate-500">Prendre une photo ou choisir un fichier</p>
                            </label>
                            <img id="photo-preview" class="hidden max-w-full h-32 object-cover rounded-lg mt-3 mx-auto">
                        </div>
                    </div>
                    
                    <!-- Upload Vidéo -->
                    <div id="denon-video-section" class="hidden">
                        <label class="block text-sm font-medium text-slate-700 mb-2">Vidéo</label>
                        <div class="border-2 border-dashed border-slate-200 rounded-xl p-6 text-center">
                            <input type="file" name="fichier_video" id="fichier-video" accept="video/*" capture="environment" class="hidden" onchange="previewFile(this, 'video-preview')">
                            <label for="fichier-video" class="cursor-pointer">
                                <div class="w-16 h-16 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center mx-auto mb-2">
                                    <i class="fas fa-video text-2xl"></i>
                                </div>
                                <p class="text-sm text-slate-500">Enregistrer ou choisir une vidéo</p>
                            </label>
                            <video id="video-preview" class="hidden max-w-full h-32 rounded-lg mt-3 mx-auto" controls></video>
                        </div>
                    </div>
                    
                    <!-- Catégorie -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Catégorie</label>
                        <select name="categorie" class="w-full px-4 py-3 rounded-xl border border-slate-200 focus:border-cyan-500 outline-none text-sm">
                            <option value="">Sélectionnez une catégorie</option>
                            <option value="corruption">Corruption</option>
                            <option value="fraude">Fraude</option>
                            <option value="violence">Violence</option>
                            <option value="discrimination">Discrimination</option>
                            <option value="environnement">Environnement</option>
                            <option value="securite">Sécurité</option>
                            <option value="autre">Autre</option>
                        </select>
                    </div>
                    
                    <!-- Localisation -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 mb-1">Localisation (optionnel)</label>
                        <div class="flex gap-2">
                            <input type="text" name="localisation" id="localisation-input" placeholder="Adresse ou lieu..." class="flex-1 px-4 py-3 rounded-xl border border-slate-200 focus:border-cyan-500 outline-none text-sm">
                            <button type="button" onclick="getLocation()" class="px-4 py-3 rounded-xl bg-slate-100 text-slate-600 hover:bg-slate-200">
                                <i class="fas fa-location-crosshairs"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Anonymat -->
                    <div class="flex items-center gap-3 p-3 bg-slate-50 rounded-xl">
                        <input type="checkbox" name="anonyme" id="anonyme" class="w-5 h-5 rounded text-cyan-500">
                        <label for="anonyme" class="text-sm text-slate-700">
                            <span class="font-medium">Signalement anonyme</span>
                            <p class="text-xs text-slate-500">Votre identité ne sera pas révélée</p>
                        </label>
                    </div>
                    
                    <!-- Submit -->
                    <button type="submit" id="submit-denonciation" class="w-full py-4 bg-gradient-to-r from-red-500 to-orange-500 text-white font-semibold rounded-xl hover:shadow-lg transition">
                        <i class="fas fa-paper-plane mr-2"></i>
                        Envoyer le signalement
                    </button>
                </form>
                
                <!-- Success Message -->
                <div id="denonciation-success" class="hidden p-8 text-center">
                    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-check text-3xl text-green-600"></i>
                    </div>
                    <h4 class="text-xl font-bold text-slate-800 mb-2">Signalement envoyé !</h4>
                    <p class="text-slate-500 mb-6">Votre signalement a été enregistré et sera traité dans les plus brefs délais.</p>
                    <button onclick="closeDenonciationModal()" class="px-6 py-3 bg-slate-100 rounded-xl text-slate-700 font-medium">Fermer</button>
                </div>
            </div>
        </div>
        
        <!-- Input Area -->
        <div class="input-area px-3 py-3 flex-shrink-0">
            <!-- Voice Recording Indicator -->
            <div id="voice-recording" class="hidden mb-3">
                <div class="bg-red-50 border border-red-200 rounded-2xl p-3 flex items-center justify-between">
                    <div class="flex items-center">
                        <div class="w-3 h-3 bg-red-500 rounded-full animate-pulse mr-3"></div>
                        <span class="text-sm text-red-700 font-medium">Enregistrement en cours...</span>
                        <span id="recording-time" class="text-xs text-red-500 ml-2">0:00</span>
                    </div>
                    <button onclick="cancelVoiceRecording()" class="text-red-500 hover:text-red-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <div class="flex items-end gap-2">
                <!-- Voice Button -->
                <button onclick="toggleVoiceRecording()" id="voice-btn" class="voice-btn w-11 h-11 rounded-full flex items-center justify-center text-slate-500 bg-slate-100 hover:bg-slate-200 transition">
                    <i class="fas fa-microphone text-sm"></i>
                </button>
                
                <div class="flex-1 bg-slate-100 rounded-2xl px-4 py-2 flex items-center">
                    <input type="text" id="message-input" 
                           placeholder="Écrivez ou parlez..." 
                           class="flex-1 bg-transparent border-none outline-none text-sm text-slate-800 placeholder-slate-400"
                           autocomplete="off"
                           onkeypress="handleKeyPress(event)">
                    <!-- TTS Toggle -->
                    <button onclick="toggleTTS()" id="tts-btn" class="ml-2 text-slate-400 hover:text-cyan-500 transition" title="Lecture vocale">
                        <i class="fas fa-volume-up text-sm"></i>
                    </button>
                </div>
                
                <button onclick="sendMessage()" id="send-btn" class="send-btn w-11 h-11 rounded-full flex items-center justify-center text-white shadow-lg">
                    <i class="fas fa-paper-plane text-sm"></i>
                </button>
            </div>
            
            <!-- Voice Language Selector -->
            <div id="voice-lang-selector" class="hidden mt-2 flex items-center justify-center gap-2 text-xs">
                <span class="text-slate-400">Langue:</span>
                <select id="voice-lang" onchange="setVoiceLang(this.value)" class="bg-slate-100 border-none rounded-lg px-2 py-1 text-xs text-slate-600">
                    <option value="fr-FR">🇫🇷 Français</option>
                    <option value="bm">🇲🇱 Bambara</option>
                </select>
            </div>
            
            <p class="text-center text-xs text-slate-400 mt-2">
                Propulsé par <span class="font-medium"><?= APP_NAME ?></span> • IA + 🎤 Voix
            </p>
        </div>
    </div>
    
    <script>
        const API_URL = '<?= BASE_URL ?>/api/chat';
        const TOKEN = '<?= $token ?>';
        let conversationId = null;
        let clientId = null;
        let selectedLangue = 'fr';
        let lastMessageId = 0;
        let isTyping = false;
        let chatStarted = false;
        
        // Voice settings (declared early for addMessage access)
        let ttsEnabled = true;
        let voiceLang = 'fr-FR';
        
        // Auto-start chat on first interaction
        async function ensureChatStarted() {
            if (chatStarted) return true;
            
            try {
                const res = await fetch(API_URL + '/start', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        token: TOKEN,
                        nom: 'Visiteur',
                        telephone: '',
                        langue: selectedLangue
                    })
                });
                const data = await res.json();
                
                if (data.success) {
                    conversationId = data.conversation_id;
                    clientId = data.client_id;
                    chatStarted = true;
                    startPolling();
                    return true;
                }
            } catch (e) {
                console.error('Erreur:', e);
            }
            return false;
        }
        
        function toggleLangMenu() {
            var menu = document.getElementById('lang-menu');
            menu.classList.toggle('hidden');
        }
        
        function setLangue(code) {
            selectedLangue = code;
            var langMenu = document.getElementById('lang-menu');
            if (langMenu) langMenu.classList.add('hidden');
            
            // Mettre à jour l'affichage des checkmarks
            var buttons = document.querySelectorAll('.lang-btn');
            for (var i = 0; i < buttons.length; i++) {
                var btn = buttons[i];
                var checkSpan = btn.querySelector('.lang-check');
                if (checkSpan) {
                    if (btn.getAttribute('data-lang') === code) {
                        checkSpan.textContent = '✓';
                        btn.classList.add('font-semibold');
                    } else {
                        checkSpan.textContent = '';
                        btn.classList.remove('font-semibold');
                    }
                }
            }
        }
        
        function handleKeyPress(event) {
            if (event.key === 'Enter' && !event.shiftKey) {
                event.preventDefault();
                sendMessage();
            }
        }
        
        async function sendQuickReply(text) {
            document.getElementById('quick-replies').style.display = 'none';
            document.getElementById('message-input').value = text;
            await sendMessage();
        }
        
        async function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            if (!message) return;
            
            // Ensure chat is started
            if (!await ensureChatStarted()) {
                addMessage('Désolé, une erreur est survenue. Veuillez réessayer.', 'bot');
                return;
            }
            
            input.value = '';
            document.getElementById('quick-replies').style.display = 'none';
            
            addMessage(message, 'client');
            showTypingIndicator();
            
            try {
                const res = await fetch(API_URL + '/message', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        conversation_id: conversationId,
                        message: message
                    })
                });
                const data = await res.json();
                
                hideTypingIndicator();
                
                if (data.bot_response) {
                    setTimeout(() => {
                        addMessage(data.bot_response.message, 'bot');
                        
                        // Si escalade détectée, proposer les options
                        if (data.bot_response.escalate) {
                            setTimeout(() => {
                                showEscalationOptions();
                            }, 500);
                        }
                    }, 300);
                }
            } catch (e) {
                hideTypingIndicator();
                addMessage('Désolé, une erreur est survenue. Veuillez réessayer.', 'bot');
            }
        }
        
        function addMessage(text, type, withTTS) {
            if (withTTS === undefined) withTTS = true;
            var container = document.getElementById('messages');
            var msgDiv = document.createElement('div');
            msgDiv.className = 'flex message-enter mb-3 ' + (type === 'client' ? 'justify-end' : 'justify-start');
            
            var time = new Date().toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'});
            
            if (type === 'client') {
                msgDiv.innerHTML = '<div class="msg-bubble msg-client px-4 py-3 shadow-sm"><p class="text-sm leading-relaxed">' + escapeHtml(text) + '</p><p class="text-xs text-white/60 mt-1 text-right">' + time + '</p></div>';
            } else {
                msgDiv.innerHTML = '<div class="flex items-end gap-2"><div class="w-8 h-8 bg-gradient-to-br from-cyan-500 to-emerald-500 rounded-full flex items-center justify-center flex-shrink-0"><i class="fas fa-robot text-white text-xs"></i></div><div class="msg-bubble msg-bot px-4 py-3 shadow-sm relative"><p class="text-sm leading-relaxed pr-6">' + escapeHtml(text) + '</p><p class="text-xs text-slate-400 mt-1">' + time + '</p><button onclick="speakMessage(this)" class="absolute top-2 right-2 text-slate-300 hover:text-cyan-500 transition" title="Écouter ce message"><i class="fas fa-volume-up text-xs"></i></button></div></div>';
                
                // TTS for bot messages
                if (withTTS && ttsEnabled && typeof speakText === 'function') {
                    setTimeout(function() { speakText(text); }, 100);
                }
            }
            
            container.appendChild(msgDiv);
            container.scrollTop = container.scrollHeight;
        }
        
        function showTypingIndicator() {
            if (isTyping) return;
            isTyping = true;
            
            var container = document.getElementById('messages');
            var typingDiv = document.createElement('div');
            typingDiv.id = 'typing-indicator';
            typingDiv.className = 'flex justify-start mb-3 message-enter';
            typingDiv.innerHTML = '<div class="flex items-end gap-2"><div class="w-8 h-8 bg-gradient-to-br from-cyan-500 to-emerald-500 rounded-full flex items-center justify-center flex-shrink-0"><i class="fas fa-robot text-white text-xs"></i></div><div class="msg-bubble msg-bot px-4 py-3 flex items-center gap-1"><span class="typing-dot w-2 h-2 bg-slate-400 rounded-full"></span><span class="typing-dot w-2 h-2 bg-slate-400 rounded-full"></span><span class="typing-dot w-2 h-2 bg-slate-400 rounded-full"></span></div></div>';
            container.appendChild(typingDiv);
            container.scrollTop = container.scrollHeight;
        }
        
        function hideTypingIndicator() {
            isTyping = false;
            var el = document.getElementById('typing-indicator');
            if (el) el.remove();
        }
        
        function escapeHtml(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function startPolling() {
            setInterval(async () => {
                if (!conversationId) return;
                try {
                    const res = await fetch(API_URL + '/messages/' + conversationId + '?last_id=' + lastMessageId);
                    const data = await res.json();
                    if (data.messages) {
                        data.messages.forEach(msg => {
                            if (msg.id > lastMessageId && msg.sender_type === 'agent') {
                                addMessage(msg.contenu, 'bot');
                                lastMessageId = msg.id;
                            }
                        });
                    }
                } catch (e) {}
            }, 3000);
        }
        
        // Focus input on load (desktop)
        if (window.innerWidth > 480) {
            document.getElementById('message-input').focus();
        }
        
        // Close lang menu on outside click
        document.addEventListener('click', (e) => {
            const menu = document.getElementById('lang-menu');
            const btn = e.target.closest('button[onclick="toggleLangMenu()"]');
            if (!btn && menu && !menu.contains(e.target)) {
                menu.classList.add('hidden');
            }
        });

        // ==========================================
        // VOICE FEATURES - Speech Recognition & TTS
        // ==========================================
        
        let isRecording = false;
        let recognition = null;
        let recordingTimer = null;
        let recordingSeconds = 0;
        
        // Check browser support
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const speechSynthesis = window.speechSynthesis;
        
        // Initialize Speech Recognition
        if (SpeechRecognition) {
            recognition = new SpeechRecognition();
            recognition.continuous = false;
            recognition.interimResults = true;
            recognition.lang = voiceLang;
            
            recognition.onstart = () => {
                isRecording = true;
                document.getElementById('voice-recording').classList.remove('hidden');
                document.getElementById('voice-btn').classList.add('bg-red-500', 'text-white');
                document.getElementById('voice-btn').classList.remove('bg-slate-100', 'text-slate-500');
                document.getElementById('voice-lang-selector').classList.remove('hidden');
                startRecordingTimer();
            };
            
            recognition.onresult = (event) => {
                let finalTranscript = '';
                let interimTranscript = '';
                
                for (let i = event.resultIndex; i < event.results.length; i++) {
                    const transcript = event.results[i][0].transcript;
                    if (event.results[i].isFinal) {
                        finalTranscript += transcript;
                    } else {
                        interimTranscript += transcript;
                    }
                }
                
                // Show interim results in input
                if (interimTranscript) {
                    document.getElementById('message-input').value = interimTranscript;
                }
                
                // Send final result
                if (finalTranscript) {
                    document.getElementById('message-input').value = finalTranscript;
                    stopVoiceRecording();
                    setTimeout(() => sendMessage(), 300);
                }
            };
            
            recognition.onerror = (event) => {
                console.error('Speech recognition error:', event.error);
                stopVoiceRecording();
                
                if (event.error === 'not-allowed') {
                    alert('Veuillez autoriser l\'accès au microphone pour utiliser la reconnaissance vocale.');
                }
            };
            
            recognition.onend = () => {
                if (isRecording) {
                    stopVoiceRecording();
                }
            };
        } else {
            // Hide voice button if not supported
            var voiceBtn = document.getElementById('voice-btn');
            if (voiceBtn) voiceBtn.style.display = 'none';
        }
        
        function toggleVoiceRecording() {
            if (!recognition) {
                alert('La reconnaissance vocale n\'est pas supportée par votre navigateur. Utilisez Chrome ou Safari.');
                return;
            }
            
            if (isRecording) {
                stopVoiceRecording();
            } else {
                startVoiceRecording();
            }
        }
        
        function startVoiceRecording() {
            recognition.lang = voiceLang;
            recognition.start();
        }
        
        function stopVoiceRecording() {
            isRecording = false;
            if (recognition) recognition.stop();
            clearInterval(recordingTimer);
            recordingSeconds = 0;
            document.getElementById('voice-recording').classList.add('hidden');
            document.getElementById('voice-btn').classList.remove('bg-red-500', 'text-white');
            document.getElementById('voice-btn').classList.add('bg-slate-100', 'text-slate-500');
            document.getElementById('recording-time').textContent = '0:00';
        }
        
        function cancelVoiceRecording() {
            stopVoiceRecording();
            document.getElementById('message-input').value = '';
        }
        
        function startRecordingTimer() {
            recordingSeconds = 0;
            recordingTimer = setInterval(() => {
                recordingSeconds++;
                const mins = Math.floor(recordingSeconds / 60);
                const secs = recordingSeconds % 60;
                document.getElementById('recording-time').textContent = `${mins}:${secs.toString().padStart(2, '0')}`;
                
                // Auto-stop after 30 seconds
                if (recordingSeconds >= 30) {
                    stopVoiceRecording();
                }
            }, 1000);
        }
        
        function setVoiceLang(lang) {
            voiceLang = lang;
            if (recognition) {
                recognition.lang = lang;
            }
        }
        
        // Text-to-Speech Functions
        function toggleTTS() {
            ttsEnabled = !ttsEnabled;
            const btn = document.getElementById('tts-btn');
            if (ttsEnabled) {
                btn.classList.remove('text-slate-300');
                btn.classList.add('text-cyan-500');
                btn.title = 'Lecture vocale activée';
            } else {
                btn.classList.remove('text-cyan-500');
                btn.classList.add('text-slate-300');
                btn.title = 'Lecture vocale désactivée';
                if (speechSynthesis) speechSynthesis.cancel();
            }
        }
        
        var cachedVoices = [];
        var preferredVoice = null;
        var audioPlayer = null;
        var useGoogleTTS = true; // Try Google TTS first
        
        function loadVoices() {
            if (!speechSynthesis) return;
            cachedVoices = speechSynthesis.getVoices();
            
            // Prioritize natural/premium voices
            var langCode = voiceLang.split('-')[0];
            var premiumKeywords = ['Natural', 'Premium', 'Enhanced', 'Neural', 'Wavenet', 'Google', 'Microsoft', 'Samantha', 'Thomas', 'Amelie'];
            
            // First try to find a premium voice
            for (var i = 0; i < cachedVoices.length; i++) {
                var v = cachedVoices[i];
                if (v.lang.startsWith(langCode)) {
                    for (var j = 0; j < premiumKeywords.length; j++) {
                        if (v.name.indexOf(premiumKeywords[j]) !== -1) {
                            preferredVoice = v;
                            return;
                        }
                    }
                }
            }
            
            // Fallback to any voice for the language
            for (var i = 0; i < cachedVoices.length; i++) {
                if (cachedVoices[i].lang.startsWith(langCode)) {
                    preferredVoice = cachedVoices[i];
                    return;
                }
            }
        }
        
        function speakText(text, forceSpeak) {
            if (!forceSpeak && !ttsEnabled) return;
            
            // Stop any current playback
            if (audioPlayer) {
                audioPlayer.pause();
                audioPlayer = null;
            }
            if (speechSynthesis) speechSynthesis.cancel();
            
            // Try Google Cloud TTS first for better quality
            if (useGoogleTTS) {
                speakWithGoogleTTS(text, forceSpeak);
            } else {
                speakWithBrowserTTS(text);
            }
        }
        
        function speakWithGoogleTTS(text, forceSpeak) {
            fetch(API_URL + '/tts', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    text: text,
                    lang: voiceLang
                })
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.success && data.audio) {
                    // Play the MP3 audio
                    audioPlayer = new Audio('data:audio/mp3;base64,' + data.audio);
                    audioPlayer.play().catch(function(e) {
                        console.log('Audio autoplay blocked, falling back to browser TTS');
                        speakWithBrowserTTS(text);
                    });
                } else if (data.fallback) {
                    // Google TTS not configured, use browser TTS
                    useGoogleTTS = false;
                    speakWithBrowserTTS(text);
                }
            })
            .catch(function(e) {
                console.log('Google TTS error, falling back to browser TTS');
                speakWithBrowserTTS(text);
            });
        }
        
        function speakWithBrowserTTS(text) {
            if (!speechSynthesis) return;
            
            var utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = voiceLang;
            
            // More natural speech parameters
            utterance.rate = 0.95;
            utterance.pitch = 1.05;
            utterance.volume = 1.0;
            
            // Use preferred voice if available
            if (preferredVoice) {
                utterance.voice = preferredVoice;
            } else {
                loadVoices();
                if (preferredVoice) utterance.voice = preferredVoice;
            }
            
            // Add slight pauses for more natural speech
            var processedText = text
                .replace(/\./g, '... ')
                .replace(/,/g, ', ')
                .replace(/!/g, '! ')
                .replace(/\?/g, '? ');
            
            utterance.text = processedText;
            speechSynthesis.speak(utterance);
        }
        
        // Manual speak button handler
        function speakMessage(btn) {
            var msgContainer = btn.closest('.msg-bot');
            if (msgContainer) {
                var textEl = msgContainer.querySelector('p');
                if (textEl) {
                    speakText(textEl.textContent, true);
                    btn.classList.add('text-cyan-500');
                    setTimeout(function() { btn.classList.remove('text-cyan-500'); }, 2000);
                }
            }
        }
        
        // Initialize TTS
        var ttsBtn = document.getElementById('tts-btn');
        if (ttsBtn) ttsBtn.classList.add('text-cyan-500');
        
        // Load voices (needed for some browsers)
        if (speechSynthesis) {
            loadVoices();
            speechSynthesis.onvoiceschanged = loadVoices;
        }
        
        // ==========================================
        // DENONCIATION SYSTEM
        // ==========================================
        
        var denonciationType = 'texte';
        var mediaRecorder = null;
        var audioChunks = [];
        var isRecordingDenon = false;
        var denonciationsEnabled = true;
        
        // Check if denonciation is enabled
        function checkDenonciationEnabled() {
            fetch(API_URL.replace('/chat', '/denonciation/check'), {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ token: TOKEN })
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                denonciationsEnabled = data.enabled;
                var btn = document.getElementById('denonciation-btn');
                if (btn && !denonciationsEnabled) {
                    btn.style.display = 'none';
                }
            })
            .catch(function() {});
        }
        checkDenonciationEnabled();
        
        function openDenonciationModal() {
            if (!denonciationsEnabled) {
                alert('Les signalements ne sont pas disponibles pour le moment.');
                return;
            }
            document.getElementById('denonciation-modal').classList.remove('hidden');
            document.getElementById('denonciation-form').classList.remove('hidden');
            document.getElementById('denonciation-success').classList.add('hidden');
        }
        
        function closeDenonciationModal() {
            document.getElementById('denonciation-modal').classList.add('hidden');
            document.getElementById('denonciation-form').reset();
            setDenonciationType('texte');
            // Reset previews
            document.getElementById('photo-preview').classList.add('hidden');
            document.getElementById('video-preview').classList.add('hidden');
            document.getElementById('audio-preview').classList.add('hidden');
        }
        
        function setDenonciationType(type) {
            denonciationType = type;
            
            // Update buttons
            document.querySelectorAll('.denon-type-btn').forEach(function(btn) {
                btn.classList.remove('active', 'border-cyan-500', 'bg-cyan-50');
                btn.classList.add('border-slate-200');
                btn.querySelector('i').classList.remove('text-cyan-600');
                btn.querySelector('i').classList.add('text-slate-500');
                btn.querySelector('span').classList.remove('text-cyan-700');
                btn.querySelector('span').classList.add('text-slate-600');
            });
            
            var activeBtn = document.querySelector('.denon-type-btn[data-type="' + type + '"]');
            if (activeBtn) {
                activeBtn.classList.add('active', 'border-cyan-500', 'bg-cyan-50');
                activeBtn.classList.remove('border-slate-200');
                activeBtn.querySelector('i').classList.add('text-cyan-600');
                activeBtn.querySelector('i').classList.remove('text-slate-500');
                activeBtn.querySelector('span').classList.add('text-cyan-700');
                activeBtn.querySelector('span').classList.remove('text-slate-600');
            }
            
            // Show/hide sections
            document.getElementById('denon-texte-section').classList.toggle('hidden', type !== 'texte');
            document.getElementById('denon-audio-section').classList.toggle('hidden', type !== 'audio');
            document.getElementById('denon-photo-section').classList.toggle('hidden', type !== 'photo');
            document.getElementById('denon-video-section').classList.toggle('hidden', type !== 'video');
        }
        
        function previewFile(input, previewId) {
            var preview = document.getElementById(previewId);
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.classList.remove('hidden');
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        function startAudioRecording() {
            if (isRecordingDenon) {
                stopAudioRecording();
                return;
            }
            
            navigator.mediaDevices.getUserMedia({ audio: true })
                .then(function(stream) {
                    mediaRecorder = new MediaRecorder(stream);
                    audioChunks = [];
                    
                    mediaRecorder.ondataavailable = function(e) {
                        audioChunks.push(e.data);
                    };
                    
                    mediaRecorder.onstop = function() {
                        var audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                        var audioUrl = URL.createObjectURL(audioBlob);
                        var audioPreview = document.getElementById('audio-preview');
                        audioPreview.src = audioUrl;
                        audioPreview.classList.remove('hidden');
                        
                        // Create file for upload
                        var file = new File([audioBlob], 'recording.webm', { type: 'audio/webm' });
                        var dataTransfer = new DataTransfer();
                        dataTransfer.items.add(file);
                        document.getElementById('fichier-audio').files = dataTransfer.files;
                        
                        stream.getTracks().forEach(function(track) { track.stop(); });
                    };
                    
                    mediaRecorder.start();
                    isRecordingDenon = true;
                    document.getElementById('audio-record-btn').innerHTML = '<i class="fas fa-stop text-2xl"></i>';
                    document.getElementById('audio-status').textContent = 'Enregistrement en cours...';
                })
                .catch(function(err) {
                    alert('Impossible d\'accéder au microphone');
                });
        }
        
        function stopAudioRecording() {
            if (mediaRecorder && isRecordingDenon) {
                mediaRecorder.stop();
                isRecordingDenon = false;
                document.getElementById('audio-record-btn').innerHTML = '<i class="fas fa-microphone text-2xl"></i>';
                document.getElementById('audio-status').textContent = 'Enregistrement terminé';
            }
        }
        
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var coords = position.coords.latitude + ', ' + position.coords.longitude;
                    document.getElementById('localisation-input').value = coords;
                }, function() {
                    alert('Impossible de récupérer la localisation');
                });
            }
        }
        
        // Form submission
        document.getElementById('denonciation-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            var formData = new FormData();
            formData.append('token', TOKEN);
            formData.append('type', denonciationType);
            formData.append('titre', this.querySelector('[name="titre"]').value);
            formData.append('description', this.querySelector('[name="description"]').value);
            formData.append('categorie', this.querySelector('[name="categorie"]').value);
            formData.append('localisation', this.querySelector('[name="localisation"]').value);
            formData.append('anonyme', this.querySelector('[name="anonyme"]').checked ? 'true' : 'false');
            
            if (clientId) {
                formData.append('client_id', clientId);
            }
            
            // Add file based on type
            var fileInput = null;
            if (denonciationType === 'audio') {
                fileInput = document.getElementById('fichier-audio');
            } else if (denonciationType === 'photo') {
                fileInput = document.getElementById('fichier-photo');
            } else if (denonciationType === 'video') {
                fileInput = document.getElementById('fichier-video');
            }
            
            if (fileInput && fileInput.files[0]) {
                formData.append('fichier', fileInput.files[0]);
            }
            
            var submitBtn = document.getElementById('submit-denonciation');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Envoi en cours...';
            
            fetch(API_URL.replace('/chat', '/denonciation/submit'), {
                method: 'POST',
                body: formData
            })
            .then(function(res) {
                return res.text().then(function(text) {
                    var data = null;
                    try {
                        data = JSON.parse(text);
                    } catch (e) {
                        data = { success: false, error: 'Réponse serveur non JSON', debug: text };
                    }
                    return { ok: res.ok, status: res.status, data: data };
                });
            })
            .then(function(result) {
                var data = result.data || {};

                if (result.ok && data.success) {
                    document.getElementById('denonciation-form').classList.add('hidden');
                    document.getElementById('denonciation-success').classList.remove('hidden');
                } else {
                    var debug = data.debug ? ('\n\nDétail: ' + String(data.debug).substring(0, 300)) : '';
                    alert('Erreur: ' + (data.error || ('Échec de l\'envoi (HTTP ' + result.status + ')')) + debug);
                }
            })
            .catch(function() {
                alert('Erreur de connexion');
            })
            .finally(function() {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane mr-2"></i>Envoyer le signalement';
            });
        });
        
        // ==========================================
        // WEBRTC VOICE CALL (Twilio SDK v2.x)
        // ==========================================
        var twilioDevice = null;
        var activeCall = null;
        var isMuted = false;
        var voiceCallEnabled = <?= in_array('voice', json_decode($entreprise['canaux_actifs'] ?? '[]', true)) ? 'true' : 'false' ?>;
        
        function loadTwilioSDK() {
            return new Promise(function(resolve, reject) {
                if (window.Twilio && window.Twilio.Device) {
                    resolve();
                    return;
                }
                var script = document.createElement('script');
                script.src = 'https://sdk.twilio.com/js/voice/2.10/twilio.min.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }
        
        async function startVoiceCall() {
            if (!voiceCallEnabled) {
                alert('Les appels vocaux ne sont pas activés');
                return;
            }
            
            document.getElementById('voice-call-ui').classList.remove('hidden');
            document.getElementById('call-status').textContent = 'Connexion en cours...';
            document.getElementById('call-icon').className = 'fas fa-phone text-white text-3xl';
            
            try {
                await loadTwilioSDK();
                
                var res = await fetch(API_URL.replace('/chat', '/twilio/token') + '?token=' + TOKEN);
                var data = await res.json();
                
                if (!data.success) {
                    throw new Error(data.error || 'Impossible de se connecter');
                }
                
                // Twilio SDK v2.x - nouvelle API
                twilioDevice = new Twilio.Device(data.token, {
                    codecPreferences: [Twilio.Device.Codec.Opus, Twilio.Device.Codec.PCMU],
                    logLevel: 1
                });
                
                // Enregistrer le device
                await twilioDevice.register();
                
                document.getElementById('call-status').textContent = 'Appel en cours...';
                
                // Passer l'appel
                activeCall = await twilioDevice.connect();
                
                activeCall.on('accept', function() {
                    document.getElementById('call-status').textContent = 'Connecté';
                    document.getElementById('call-icon').className = 'fas fa-phone-volume text-white text-3xl animate-pulse';
                });
                
                activeCall.on('disconnect', function() {
                    endVoiceCall();
                });
                
                activeCall.on('error', function(err) {
                    document.getElementById('call-status').textContent = 'Erreur: ' + err.message;
                    setTimeout(endVoiceCall, 2000);
                });
                
                twilioDevice.on('error', function(err) {
                    document.getElementById('call-status').textContent = 'Erreur: ' + err.message;
                    setTimeout(endVoiceCall, 2000);
                });
                
            } catch(err) {
                document.getElementById('call-status').textContent = 'Erreur: ' + (err.message || 'Connexion échouée');
                setTimeout(endVoiceCall, 2000);
            }
        }
        
        function endVoiceCall() {
            if (activeCall) {
                activeCall.disconnect();
                activeCall = null;
            }
            if (twilioDevice) {
                twilioDevice.unregister();
                twilioDevice.destroy();
                twilioDevice = null;
            }
            document.getElementById('voice-call-ui').classList.add('hidden');
            isMuted = false;
            document.getElementById('mute-icon').className = 'fas fa-microphone text-xl';
            document.getElementById('mute-btn').classList.remove('bg-red-500', 'text-white');
            document.getElementById('mute-btn').classList.add('bg-slate-200', 'text-slate-700');
        }
        
        function toggleMute() {
            if (!activeCall) return;
            
            isMuted = !isMuted;
            activeCall.mute(isMuted);
            
            if (isMuted) {
                document.getElementById('mute-icon').className = 'fas fa-microphone-slash text-xl';
                document.getElementById('mute-btn').classList.remove('bg-slate-200', 'text-slate-700');
                document.getElementById('mute-btn').classList.add('bg-red-500', 'text-white');
            } else {
                document.getElementById('mute-icon').className = 'fas fa-microphone text-xl';
                document.getElementById('mute-btn').classList.remove('bg-red-500', 'text-white');
                document.getElementById('mute-btn').classList.add('bg-slate-200', 'text-slate-700');
            }
        }

        // ==========================================
        // ESCALATION - Tickets & Live Chat
        // ==========================================
        
        let escalationShown = false;
        let escalationStatusInterval = null;

        function showEscalationOptions() {
            if (escalationShown) return;
            escalationShown = true;
            
            const container = document.getElementById('messages');
            const optionsDiv = document.createElement('div');
            optionsDiv.id = 'escalation-options';
            optionsDiv.className = 'flex justify-start mb-3 message-enter';
            optionsDiv.innerHTML = `
                <div class="flex items-start gap-2 w-full">
                    <div class="w-8 h-8 bg-gradient-to-br from-orange-500 to-red-500 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-headset text-white text-xs"></i>
                    </div>
                    <div class="flex-1">
                        <div class="msg-bubble msg-bot px-4 py-3 shadow-sm mb-2">
                            <p class="text-sm font-medium text-slate-700 mb-3">
                                <i class="fas fa-hand-point-right text-orange-500 mr-1"></i>
                                Comment souhaitez-vous continuer ?
                            </p>
                            <div class="space-y-2">
                                <button onclick="createTicket()" class="w-full flex items-center gap-3 p-3 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl hover:from-blue-600 hover:to-blue-700 transition shadow-sm">
                                    <div class="w-10 h-10 bg-white/20 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-ticket-alt text-lg"></i>
                                    </div>
                                    <div class="text-left">
                                        <div class="font-semibold text-sm">Créer un ticket</div>
                                        <div class="text-xs text-blue-100">Recevez un numéro de suivi</div>
                                    </div>
                                </button>
                                <button onclick="requestLiveChat()" class="w-full flex items-center gap-3 p-3 bg-gradient-to-r from-emerald-500 to-teal-600 text-white rounded-xl hover:from-emerald-600 hover:to-teal-700 transition shadow-sm">
                                    <div class="w-10 h-10 bg-white/20 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-comments text-lg"></i>
                                    </div>
                                    <div class="text-left">
                                        <div class="font-semibold text-sm">Chat en direct</div>
                                        <div class="text-xs text-emerald-100">Parler à un agent maintenant</div>
                                    </div>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(optionsDiv);
            container.scrollTop = container.scrollHeight;
        }

        async function createTicket() {
            // Masquer les options
            const optionsEl = document.getElementById('escalation-options');
            if (optionsEl) optionsEl.remove();
            
            showTypingIndicator();
            
            try {
                const res = await fetch(API_URL + '/escalate/ticket', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        conversation_id: conversationId,
                        token: TOKEN,
                        sujet: 'Demande d\'assistance'
                    })
                });
                const data = await res.json();
                
                hideTypingIndicator();
                
                if (data.success) {
                    showTicketConfirmation(data.ticket_number);
                } else {
                    addMessage('Désolé, une erreur est survenue lors de la création du ticket.', 'bot');
                    escalationShown = false;
                }
            } catch (e) {
                hideTypingIndicator();
                addMessage('Désolé, une erreur est survenue. Veuillez réessayer.', 'bot');
                escalationShown = false;
            }
        }

        function showTicketConfirmation(ticketNumber) {
            const container = document.getElementById('messages');
            const confirmDiv = document.createElement('div');
            confirmDiv.className = 'flex justify-start mb-3 message-enter';
            confirmDiv.innerHTML = `
                <div class="flex items-start gap-2 w-full">
                    <div class="w-8 h-8 bg-gradient-to-br from-green-500 to-emerald-500 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-check text-white text-xs"></i>
                    </div>
                    <div class="flex-1">
                        <div class="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4 shadow-sm">
                            <div class="flex items-center gap-2 mb-2">
                                <i class="fas fa-ticket-alt text-green-600"></i>
                                <span class="font-semibold text-green-800">Ticket créé avec succès!</span>
                            </div>
                            <div class="bg-white rounded-lg p-3 mb-3 border border-green-100">
                                <div class="text-xs text-slate-500 mb-1">Numéro de suivi</div>
                                <div class="text-xl font-bold text-green-700 font-mono">${ticketNumber}</div>
                            </div>
                            <p class="text-sm text-slate-600">
                                <i class="fas fa-info-circle text-blue-500 mr-1"></i>
                                Conservez ce numéro pour suivre votre demande. Un agent vous contactera prochainement.
                            </p>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(confirmDiv);
            container.scrollTop = container.scrollHeight;
        }

        async function requestLiveChat() {
            // Masquer les options
            const optionsEl = document.getElementById('escalation-options');
            if (optionsEl) optionsEl.remove();
            
            showTypingIndicator();
            
            try {
                const res = await fetch(API_URL + '/escalate/live', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        conversation_id: conversationId,
                        token: TOKEN,
                        reason: 'Demande de chat en direct'
                    })
                });
                const data = await res.json();
                
                hideTypingIndicator();
                
                if (data.success) {
                    showLiveChatWaiting(data.position);
                    startEscalationStatusPolling();
                } else {
                    addMessage('Désolé, une erreur est survenue. Veuillez réessayer.', 'bot');
                    escalationShown = false;
                }
            } catch (e) {
                hideTypingIndicator();
                addMessage('Désolé, une erreur est survenue. Veuillez réessayer.', 'bot');
                escalationShown = false;
            }
        }

        function showLiveChatWaiting(position) {
            const container = document.getElementById('messages');
            const waitDiv = document.createElement('div');
            waitDiv.id = 'live-chat-waiting';
            waitDiv.className = 'flex justify-start mb-3 message-enter';
            waitDiv.innerHTML = `
                <div class="flex items-start gap-2 w-full">
                    <div class="w-8 h-8 bg-gradient-to-br from-cyan-500 to-blue-500 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-clock text-white text-xs animate-pulse"></i>
                    </div>
                    <div class="flex-1">
                        <div class="bg-gradient-to-r from-cyan-50 to-blue-50 border border-cyan-200 rounded-xl p-4 shadow-sm">
                            <div class="flex items-center gap-2 mb-2">
                                <div class="w-3 h-3 bg-cyan-500 rounded-full animate-pulse"></div>
                                <span class="font-semibold text-cyan-800">En attente d'un agent...</span>
                            </div>
                            <div class="bg-white rounded-lg p-3 mb-3 border border-cyan-100">
                                <div class="text-xs text-slate-500 mb-1">Position dans la file</div>
                                <div class="text-2xl font-bold text-cyan-700" id="queue-position">${position}</div>
                            </div>
                            <p class="text-sm text-slate-600">
                                <i class="fas fa-bell text-yellow-500 mr-1"></i>
                                Restez connecté, un agent va prendre en charge votre conversation.
                            </p>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(waitDiv);
            container.scrollTop = container.scrollHeight;
        }

        function startEscalationStatusPolling() {
            if (escalationStatusInterval) return;
            
            escalationStatusInterval = setInterval(async () => {
                if (!conversationId) return;
                
                try {
                    const res = await fetch(API_URL + '/escalate/status?conversation_id=' + conversationId + '&token=' + TOKEN);
                    const data = await res.json();
                    
                    // Mettre à jour la position dans la file
                    if (data.live_request && data.live_request.position) {
                        const posEl = document.getElementById('queue-position');
                        if (posEl) posEl.textContent = data.live_request.position;
                    }
                    
                    // Agent connecté
                    if (data.agent_connected) {
                        clearInterval(escalationStatusInterval);
                        escalationStatusInterval = null;
                        showAgentConnected(data.agent_name);
                    }
                } catch (e) {
                    console.error('Erreur polling escalade:', e);
                }
            }, 5000);
        }

        function showAgentConnected(agentName) {
            // Supprimer le message d'attente
            const waitEl = document.getElementById('live-chat-waiting');
            if (waitEl) waitEl.remove();
            
            const container = document.getElementById('messages');
            const connectedDiv = document.createElement('div');
            connectedDiv.className = 'flex justify-start mb-3 message-enter';
            connectedDiv.innerHTML = `
                <div class="flex items-start gap-2 w-full">
                    <div class="w-8 h-8 bg-gradient-to-br from-green-500 to-emerald-500 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-user-check text-white text-xs"></i>
                    </div>
                    <div class="flex-1">
                        <div class="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4 shadow-sm">
                            <div class="flex items-center gap-2 mb-2">
                                <div class="w-3 h-3 bg-green-500 rounded-full"></div>
                                <span class="font-semibold text-green-800">Agent connecté!</span>
                            </div>
                            <p class="text-sm text-slate-700">
                                <i class="fas fa-user text-green-600 mr-1"></i>
                                <strong>${agentName || 'Un agent'}</strong> a pris en charge votre conversation.
                            </p>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(connectedDiv);
            container.scrollTop = container.scrollHeight;
        }

        // ==========================================
        // CSAT - Enquête de satisfaction
        // ==========================================
        
        let csatShown = false;

        function showCSATSurvey() {
            if (csatShown) return;
            csatShown = true;
            
            const container = document.getElementById('messages');
            const csatDiv = document.createElement('div');
            csatDiv.id = 'csat-survey';
            csatDiv.className = 'flex justify-start mb-3 message-enter';
            csatDiv.innerHTML = `
                <div class="flex items-start gap-2 w-full">
                    <div class="w-8 h-8 bg-gradient-to-br from-purple-500 to-indigo-500 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-star text-white text-xs"></i>
                    </div>
                    <div class="flex-1">
                        <div class="bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 rounded-xl p-4 shadow-sm">
                            <p class="font-semibold text-purple-800 mb-3">
                                <i class="fas fa-smile text-yellow-500 mr-1"></i>
                                Comment évaluez-vous notre service ?
                            </p>
                            <div class="flex justify-center gap-2 mb-3" id="csat-stars">
                                ${[1,2,3,4,5].map(n => `
                                    <button onclick="selectCSATScore(${n})" class="csat-star w-10 h-10 rounded-full border-2 border-purple-200 hover:border-yellow-400 hover:bg-yellow-50 transition flex items-center justify-center text-xl" data-score="${n}">
                                        <i class="far fa-star text-gray-300"></i>
                                    </button>
                                `).join('')}
                            </div>
                            <div id="csat-labels" class="flex justify-between text-xs text-purple-600 mb-3 px-1">
                                <span>Très insatisfait</span>
                                <span>Très satisfait</span>
                            </div>
                            <div id="csat-comment-box" class="hidden">
                                <textarea id="csat-comment" rows="2" class="w-full px-3 py-2 border border-purple-200 rounded-lg text-sm resize-none focus:ring-2 focus:ring-purple-500 focus:border-purple-500" placeholder="Un commentaire ? (optionnel)"></textarea>
                                <button onclick="submitCSAT()" class="mt-2 w-full py-2 bg-gradient-to-r from-purple-500 to-indigo-500 text-white rounded-lg hover:from-purple-600 hover:to-indigo-600 transition text-sm font-medium">
                                    <i class="fas fa-paper-plane mr-1"></i> Envoyer mon avis
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(csatDiv);
            container.scrollTop = container.scrollHeight;
        }

        let selectedCSATScore = 0;

        function selectCSATScore(score) {
            selectedCSATScore = score;
            
            // Mettre à jour les étoiles
            document.querySelectorAll('.csat-star').forEach((btn, idx) => {
                const star = btn.querySelector('i');
                if (idx < score) {
                    star.className = 'fas fa-star text-yellow-400';
                    btn.classList.add('border-yellow-400', 'bg-yellow-50');
                    btn.classList.remove('border-purple-200');
                } else {
                    star.className = 'far fa-star text-gray-300';
                    btn.classList.remove('border-yellow-400', 'bg-yellow-50');
                    btn.classList.add('border-purple-200');
                }
            });
            
            // Afficher le champ de commentaire
            document.getElementById('csat-comment-box').classList.remove('hidden');
        }

        async function submitCSAT() {
            if (selectedCSATScore === 0) return;
            
            const comment = document.getElementById('csat-comment').value;
            
            try {
                const res = await fetch(API_URL + '/csat/submit', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        conversation_id: conversationId,
                        token: TOKEN,
                        score: selectedCSATScore,
                        comment: comment
                    })
                });
                const data = await res.json();
                
                if (data.success) {
                    showCSATThankYou();
                }
            } catch (e) {
                console.error('Erreur CSAT:', e);
            }
        }

        function showCSATThankYou() {
            const csatEl = document.getElementById('csat-survey');
            if (csatEl) {
                csatEl.innerHTML = `
                    <div class="flex items-start gap-2 w-full">
                        <div class="w-8 h-8 bg-gradient-to-br from-green-500 to-emerald-500 rounded-full flex items-center justify-center flex-shrink-0">
                            <i class="fas fa-heart text-white text-xs"></i>
                        </div>
                        <div class="flex-1">
                            <div class="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4 shadow-sm text-center">
                                <div class="text-3xl mb-2">🎉</div>
                                <p class="font-semibold text-green-800">Merci pour votre retour !</p>
                                <p class="text-sm text-green-600 mt-1">Votre avis nous aide à nous améliorer.</p>
                            </div>
                        </div>
                    </div>
                `;
            }
        }

        // Afficher CSAT quand conversation résolue
        function checkConversationStatus() {
            if (!conversationId) return;
            
            fetch(API_URL + '/conversation/status?id=' + conversationId + '&token=' + TOKEN)
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'resolved' && !data.csat_sent) {
                        setTimeout(() => showCSATSurvey(), 1000);
                    }
                })
                .catch(() => {});
        }
    </script>
</body>
</html>
