File size: 26,258 Bytes
4b16238
2e947b2
 
 
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
 
 
 
 
 
 
 
 
 
4b16238
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
2e947b2
 
 
 
4b16238
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
2e947b2
4b16238
2e947b2
4b16238
 
 
 
 
2e947b2
4b16238
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
 
4b16238
 
 
 
 
 
2e947b2
 
 
 
4b16238
2e947b2
 
4b16238
 
2e947b2
 
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
2e947b2
 
 
4b16238
 
2e947b2
4b16238
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
2e947b2
4b16238
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
2e947b2
4b16238
2e947b2
4b16238
 
2e947b2
 
 
4b16238
 
 
2e947b2
4b16238
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
2e947b2
4b16238
 
 
 
2e947b2
4b16238
 
 
 
 
 
2e947b2
4b16238
2e947b2
4b16238
 
2e947b2
 
 
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
 
4b16238
 
 
 
 
 
 
 
 
 
2e947b2
 
4b16238
 
2e947b2
4b16238
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
2e947b2
 
 
4b16238
 
2e947b2
 
 
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
2e947b2
 
4b16238
 
 
 
 
2e947b2
 
4b16238
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
2e947b2
4b16238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
// Variables globales
let recognition = null;
let isProcessingSpeech = false;
let isPlayingAudio = false;
let currentMode = 'soporte';
let currentModel = 'gemini';
let currentTTS = 'EDGE';
let isListening = false;
let sessionId = null;
let shouldRestartRecognition = true;

// Variables globales para audio
let currentAudio = null;
let isPlaying = false;
let audioQueue = [];
let isProcessingQueue = false;

// Variables para control de interrupción
let lastInterruptTime = 0;
const INTERRUPT_COOLDOWN = 1000; // 1 segundo entre interrupciones
const ENERGY_THRESHOLD = 1.5; // Umbral de energía para detectar interrupción
let audioContext = null;
let analyser = null;
let microphoneStream = null;

const STOP_WORDS = ['alto', 'detente', 'permiteme', 'callate', 'silencio', 'calla', 'para', 'espera'];
const GREETING_WORDS = ['hola', 'buenas', 'buenos días', 'buenas tardes', 'buenas noches'];
const INTEREST_WORDS = ['acepto', 'me interesa', 'dime más', 'cuéntame más', 'quiero saber más'];

// Elementos del DOM
const chatBox = document.getElementById('chatBox');
const textInput = document.getElementById('textInput');
const sendTextButton = document.getElementById('sendText');
const modoSelect = document.getElementById('modoSelect');
const modeloSelect = document.getElementById('modeloSelect');
const vozSelect = document.getElementById('vozSelect');
const configForm = document.getElementById('configForm');
const statusLabel = document.getElementById('statusLabel');
const startRecordingButton = document.getElementById('startRecording');

// Comandos de voz
const VOICE_COMMANDS = {
    stop: ['para', 'detente', 'silencio', 'cállate', 'espera', 'stop', 'alto', 'basta', 'suficiente', 'ya', 'shh', 'sh'],
    greet: ['hola', 'buenas', 'buenos días', 'buenas tardes', 'buenas noches'],
    interest: ['acepto', 'me interesa', 'dime más', 'cuéntame más', 'quiero saber más']
};

// Funciones de utilidad
const Utils = {
    checkCommand(text, type) {
        return VOICE_COMMANDS[type].some(cmd => text.toLowerCase().includes(cmd));
    },
    
    updateStatus(text, type = 'info') {
        if (statusLabel) {
            statusLabel.textContent = text;
            statusLabel.classList.remove('error', 'success');
            if (type === 'error' || type === 'success') {
                statusLabel.classList.add(type);
            }
        }
    }
};

// Funciones de chat
const ChatManager = {
    addMessage(text, sender) {
        if (!text || !sender || !chatBox) return;
        
        try {
            console.log('Agregando mensaje al chat:', { text, sender });
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            
            const iconSpan = document.createElement('span');
            iconSpan.className = 'message-icon';
            iconSpan.textContent = sender === 'user' ? '👤' : '🤖';
            
            const textSpan = document.createElement('span');
            textSpan.className = 'message-text';
            textSpan.textContent = text;
            
            messageDiv.appendChild(iconSpan);
            messageDiv.appendChild(textSpan);
            chatBox.appendChild(messageDiv);
            
            // Hacer scroll al último mensaje
            chatBox.scrollTop = chatBox.scrollHeight;
            
            console.log('Mensaje agregado exitosamente');
        } catch (error) {
            console.error('Error al agregar mensaje:', error);
        }
    },
    
    async sendMessage(text) {
        if (!text) return;
        
        try {
            Utils.updateStatus('Procesando...');
            this.addMessage(text, 'user');
            textInput.value = '';
            
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    mensaje: text,
                    mode: currentMode,
                    model: currentModel,
                    tts: currentTTS
                })
            });
            
            if (!response.ok) {
                throw new Error(`Error HTTP: ${response.status}`);
            }
            
            const data = await response.json();
            if (data.success && data.texto) {
                this.addMessage(data.texto, 'bot');
                
                if (data.audio) {
                    try {
                        const audioType = data.audio_type || 'mp3';
                        await AudioManager.playAudio(data.audio, audioType);
                    } catch (audioError) {
                        console.error('Error reproduciendo audio:', audioError);
                        handleAudioError();
                    }
                }
            } else {
                throw new Error(data.error || 'Error desconocido');
            }
            
        } catch (error) {
            console.error('Error:', error);
            Utils.updateStatus('Error de conexión', 'error');
            this.addMessage('Lo siento, hubo un error al procesar tu mensaje.', 'bot');
        } finally {
            Utils.updateStatus('Escuchando...');
        }
    }
};

// Gestión de audio
const AudioManager = {
    async playAudio(base64Audio, audioType = 'wav') {
        if (!base64Audio) return;
        
        try {
            if (isPlayingAudio) {
                audioQueue.push({ base64Audio, audioType });
                return;
            }
            
            isPlayingAudio = true;
            Utils.updateStatus('Reproduciendo audio...');
            
            const audioBlob = await fetch(`data:audio/${audioType};base64,${base64Audio}`)
                .then(res => res.blob());
            
            currentAudio = new Audio(URL.createObjectURL(audioBlob));
            
            currentAudio.onended = () => {
                isPlayingAudio = false;
                URL.revokeObjectURL(currentAudio.src);
                currentAudio = null;
                Utils.updateStatus('Escuchando...');
                this.processQueue();
            };
            
            await currentAudio.play();
            
        } catch (error) {
            console.error('Error reproduciendo audio:', error);
            this.handleError();
        }
    },
    
    async processQueue() {
        if (isProcessingQueue || audioQueue.length === 0) return;
        
        isProcessingQueue = true;
        const nextAudio = audioQueue.shift();
        await this.playAudio(nextAudio.base64Audio, nextAudio.audioType);
        isProcessingQueue = false;
    },
    
    handleError() {
        isPlayingAudio = false;
        if (currentAudio) {
            URL.revokeObjectURL(currentAudio.src);
            currentAudio = null;
        }
        Utils.updateStatus('Error de audio', 'error');
    },
    
    stop() {
        if (currentAudio) {
            currentAudio.pause();
            URL.revokeObjectURL(currentAudio.src);
            currentAudio = null;
        }
        isPlayingAudio = false;
        audioQueue = [];
        Utils.updateStatus('Audio detenido');
    }
};

// Gestión de voz
const VoiceManager = {
    async processCommand(text) {
        if (!text) return false;
        
        const currentTime = Date.now();
        
        if (Utils.checkCommand(text, 'stop')) {
            if (currentTime - lastInterruptTime > INTERRUPT_COOLDOWN) {
                lastInterruptTime = currentTime;
                AudioManager.stop();
                Utils.updateStatus('Audio detenido por comando de voz');
                return true;
            }
        }
        
        if (Utils.checkCommand(text, 'greet') || Utils.checkCommand(text, 'interest')) {
            if (currentTime - lastInterruptTime > INTERRUPT_COOLDOWN) {
                lastInterruptTime = currentTime;
                
                if (isPlayingAudio) {
                    AudioManager.stop();
                    await new Promise(resolve => setTimeout(resolve, 300));
                }
                
                ChatManager.addMessage(text, 'user');
                await this.processVoiceResponse(text);
                return true;
            }
        }
        
        return false;
    },
    
    async processVoiceResponse(text) {
        try {
            shouldRestartRecognition = false;
            if (recognition && isListening) {
                recognition.stop();
            }
            
            const response = await fetch('/procesar_voz', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    texto: text,
                    mode: currentMode,
                    model: currentModel,
                    tts: currentTTS
                })
            });
            
            if (!response.ok) throw new Error(`Error HTTP: ${response.status}`);
            
            const data = await response.json();
            if (data.success && data.texto) {
                ChatManager.addMessage(data.texto, 'bot');
                if (data.audio) {
                    await AudioManager.playAudio(data.audio, data.audio_type || 'wav');
                }
            }
        } catch (error) {
            console.error('Error procesando voz:', error);
            Utils.updateStatus('Error procesando voz', 'error');
        } finally {
            shouldRestartRecognition = true;
            if (!isListening) {
                await this.startRecognition();
            }
        }
    },
    
    async startRecognition() {
        if (!recognition || !isListening) {
            try {
                await this.initializeSpeechRecognition();
                isListening = true;
                startRecordingButton.classList.add('active');
                Utils.updateStatus('Escuchando...');
            } catch (error) {
                console.error('Error iniciando reconocimiento:', error);
                Utils.updateStatus('Error de micrófono', 'error');
            }
        }
    },
    
    async pauseRecognition() {
        if (recognition && isListening) {
            recognition.stop();
            isListening = false;
            startRecordingButton.classList.remove('active');
            Utils.updateStatus('Reconocimiento pausado');
        }
    },
    
    async initializeSpeechRecognition() {
        if (!('webkitSpeechRecognition' in window)) {
            throw new Error('Reconocimiento de voz no soportado');
        }
        
        recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = true;
        recognition.lang = 'es-ES';
        
        recognition.onstart = () => {
            isListening = true;
            Utils.updateStatus('Escuchando...');
        };
        
        recognition.onend = () => {
            isListening = false;
            if (shouldRestartRecognition) {
                recognition.start();
            }
        };
        
        recognition.onresult = async (event) => {
            if (isProcessingSpeech) return;
            
            const results = Array.from(event.results);
            const lastResult = results[results.length - 1];
            
            if (lastResult.isFinal) {
                const text = lastResult[0].transcript.trim();
                if (text) {
                    isProcessingSpeech = true;
                    await this.processCommand(text);
                    isProcessingSpeech = false;
                }
            }
        };
        
        recognition.onerror = (event) => {
            console.error('Error de reconocimiento:', event.error);
            Utils.updateStatus('Error de reconocimiento', 'error');
        };
        
        recognition.start();
    }
};

// Funciones de modo y modelo
function changeMode(mode) {
    currentMode = mode;
    fetch('/cambiar_modo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ mode })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            ChatManager.addMessage(`Modo cambiado a: ${mode}`, 'bot');
        } else {
            console.error('Error cambiando modo:', data.error);
        }
    })
    .catch(error => console.error('Error:', error));
}

function changeModel(model) {
    currentModel = model;
    fetch('/cambiar_modelo', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ model })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            ChatManager.addMessage(`Modelo cambiado a: ${model}`, 'bot');
        } else {
            console.error('Error cambiando modelo:', data.error);
        }
    })
    .catch(error => console.error('Error:', error));
}

async function changeTTS(model) {
    console.log("Cambiando modelo TTS a:", model);
    Utils.updateStatus("Cambiando voz...");
    
    try {
        const response = await fetch('/cambiar_tts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ model: model })
        });

        if (!response.ok) {
            throw new Error('Error en la respuesta del servidor');
        }

        const data = await response.json();
        
        let voiceName;
        switch(model) {
            case 'EDGE':
                voiceName = "Jorge (MX)";
                break;
            case 'EDGE_ES':
                voiceName = "Álvaro (ES)";
                break;
            case 'VITS':
                voiceName = "VITS (ES)";
                break;
            default:
                voiceName = model;
        }
        
        Utils.updateStatus(`Voz cambiada a ${voiceName}`);
        console.log("Modelo TTS cambiado exitosamente");
    } catch (error) {
        console.error("Error al cambiar el modelo de voz:", error);
        Utils.updateStatus("Error al cambiar la voz");
    }
}

// Reconocimiento de voz
async function checkMicrophonePermissions() {
    try {
        // Verificar si ya tenemos permisos
        const permissionStatus = await navigator.permissions.query({ name: 'microphone' });
        
        if (permissionStatus.state === 'granted') {
            return true;
        } else if (permissionStatus.state === 'prompt') {
            // Solicitar permisos explícitamente
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            stream.getTracks().forEach(track => track.stop());
            return true;
        } else if (permissionStatus.state === 'denied') {
            Utils.updateStatus('Permisos de micrófono denegados. Por favor, habilítalos en la configuración del navegador.', 'error');
            ChatManager.addMessage('❌ El micrófono está bloqueado. Para habilitarlo:\n1. Haz clic en el icono 🔒 o 🎤 en la barra de direcciones\n2. Selecciona "Permitir" para el micrófono\n3. Recarga la página', 'bot');
            return false;
        }
    } catch (error) {
        console.error('Error verificando permisos:', error);
        return false;
    }
}

// Función para inicializar el análisis de audio
async function setupAudioAnalysis() {
    try {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioContext.createAnalyser();
        analyser.fftSize = 256;
        
        // Configurar filtros para reducir eco
        const lowpass = audioContext.createBiquadFilter();
        lowpass.type = 'lowpass';
        lowpass.frequency.value = 2000;
        
        const highpass = audioContext.createBiquadFilter();
        highpass.type = 'highpass';
        highpass.frequency.value = 85;
        
        // Obtener stream del micrófono
        microphoneStream = await navigator.mediaDevices.getUserMedia({ 
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: false
            }
        });
        
        const source = audioContext.createMediaStreamSource(microphoneStream);
        source.connect(highpass);
        highpass.connect(lowpass);
        lowpass.connect(analyser);
        
        return true;
    } catch (error) {
        console.error('Error configurando análisis de audio:', error);
        return false;
    }
}

// Función para detectar interrupción basada en energía de audio
function detectInterruption() {
    if (!analyser) return false;
    
    const dataArray = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(dataArray);
    
    // Calcular energía promedio
    const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
    const normalizedEnergy = average / 128; // Normalizar a un rango de 0-1
    
    return normalizedEnergy > ENERGY_THRESHOLD;
}

// Funciones de sesión
async function initSession() {
    try {
        const response = await fetch('/get_session_data');
        const data = await response.json();
        sessionId = data.id;
        currentMode = data.mode;
        currentModel = data.model;
        currentTTS = data.tts;
        
        // Actualizar selectores con valores de la sesión
        if (modoSelect) modoSelect.value = currentMode;
        if (modeloSelect) modeloSelect.value = currentModel;
        if (vozSelect) vozSelect.value = currentTTS;
        
        // Cargar historial de chat
        if (data.chat_history && data.chat_history.length > 0) {
            data.chat_history.forEach(msg => {
                ChatManager.addMessage(msg.text, msg.sender);
            });
        }
        
        return sessionId;
    } catch (error) {
        console.error('Error inicializando sesión:', error);
        return null;
    }
}

async function updateAudioState(isPlaying, currentAudio = null) {
    try {
        await fetch('/update_audio_state', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                is_playing: isPlaying,
                current_audio: currentAudio
            })
        });
    } catch (error) {
        console.error('Error actualizando estado del audio:', error);
    }
}

// Función para obtener el mensaje de presentación según el modo
function getMensajePresentacion(modo) {
    const presentaciones = {
        'soporte': '¡Hola! Soy tu asistente de soporte técnico. Estoy aquí para ayudarte con cualquier problema de PC o Android. ¿En qué puedo ayudarte?',
        'seguros': '¡Hola! Soy tu asesor de seguros personal. Te ayudaré a encontrar la mejor protección para ti y tu familia. ¿Qué tipo de seguro te interesa?',
        'creditos': '¡Hola! Soy tu asesor financiero. Estoy aquí para ayudarte a obtener el crédito que necesitas con las mejores condiciones. ¿Cuánto necesitas?',
        'cobranza': '¡Hola! Soy tu gestor de cobranza. Estoy aquí para ayudarte a regularizar tu situación y encontrar la mejor solución para ti. ¿Cómo puedo ayudarte?',
        'encuestas': '¡Hola! Soy tu encuestador profesional. Me gustaría conocer tu opinión sobre temas importantes. ¿Estás listo para comenzar?'
    };
    return presentaciones[modo] || '¡Hola! ¿En qué puedo ayudarte?';
}

// Función para iniciar el modo con presentación
async function iniciarModoConPresentacion(modo) {
    try {
        Utils.updateStatus('Iniciando modo...');
        const mensajePresentacion = getMensajePresentacion(modo);
        
        const response = await fetch('/cambiar_modo', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ mode: modo })
        });

        const data = await response.json();
        if (data.success) {
            currentMode = modo;
            ChatManager.addMessage(mensajePresentacion, 'bot');
            
            if (data.audio) {
                try {
                    const audioType = data.audio_type || 'wav';
                    await AudioManager.playAudio(data.audio, audioType);
                } catch (error) {
                    console.error('Error reproduciendo audio:', error);
                    handleAudioError();
                }
            }
        }
    } catch (error) {
        console.error('Error iniciando modo:', error);
        Utils.updateStatus('Error al iniciar modo');
    }
}

// Event Listeners
document.addEventListener('DOMContentLoaded', async () => {
    console.log('Página cargada, inicializando...');
    
    // Inicializar sesión
    await initSession();
    
    // Inicializar reconocimiento de voz
    await VoiceManager.startRecognition();
    
    // Iniciar modo inicial con presentación
    await iniciarModoConPresentacion(currentMode);
    
    // Iniciar reconocimiento automáticamente
    setTimeout(() => {
        if (startRecordingButton && !isListening && !isPlayingAudio) {
            console.log('Iniciando reconocimiento automático...');
            VoiceManager.startRecognition();
            Utils.updateStatus('Escuchando...');
        }
    }, 1000);
    
    // Botón de envío de texto
    if (sendTextButton) {
        sendTextButton.addEventListener('click', () => {
            const text = textInput.value.trim();
            if (text) {
                ChatManager.sendMessage(text);
            }
        });
    }
    
    // Input de texto (Enter)
    if (textInput) {
        textInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const text = textInput.value.trim();
                if (text) {
                    ChatManager.sendMessage(text);
                }
            }
        });
    }
    
    // Selectores
    if (modoSelect) {
        modoSelect.addEventListener('change', async function() {
            try {
                Utils.updateStatus('Cambiando modo...');
                
                // Detener cualquier audio actual
                if (currentAudio && isPlaying) {
                    currentAudio.pause();
                    currentAudio.currentTime = 0;
                    currentAudio = null;
                    isPlaying = false;
                }
                
                // Iniciar nuevo modo con presentación
                await iniciarModoConPresentacion(this.value);
                
            } catch (error) {
                console.error('Error en cambio de modo:', error);
                Utils.updateStatus('Error al cambiar modo');
                this.value = currentMode; // Revertir al modo anterior
            } finally {
                setTimeout(() => Utils.updateStatus('Escuchando...'), 2000);
            }
        });
    }

    if (modeloSelect) {
        modeloSelect.addEventListener('change', async (e) => {
            currentModel = e.target.value;
            changeModel(currentModel);
        });
    }

    if (vozSelect) {
        vozSelect.addEventListener('change', async (e) => {
            const newVoice = e.target.value;
            console.log('Seleccionada nueva voz:', newVoice);
            Utils.updateStatus('Cambiando voz...');
            currentTTS = newVoice;
            changeTTS(newVoice);
        });
    }

    // Botón de grabación
    if (startRecordingButton) {
        startRecordingButton.addEventListener('click', async () => {
            if (!isListening) {
                await VoiceManager.startRecognition();
                Utils.updateStatus('Escuchando...');
            } else {
                await VoiceManager.pauseRecognition();
                Utils.updateStatus('Reconocimiento pausado');
            }
        });
    }

    // Manejar visibilidad de la página
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            if (isListening) {
                VoiceManager.pauseRecognition();
            }
        } else {
            if (!isListening && !isPlayingAudio) {
                setTimeout(VoiceManager.startRecognition, 500);
            }
        }
    });
});

// Agregar al inicio del archivo, después de las variables globales
const permissionModal = `
<div class="permission-modal" id="permissionModal">
    <div class="permission-content">
        <h4>Permisos de Micrófono</h4>
        <p>Para usar el chat por voz, necesitamos acceso a tu micrófono.</p>
        <div class="alert alert-warning">
            <small>⚠️ Si el sitio no es seguro (HTTPS), el navegador puede bloquear el acceso al micrófono.</small>
        </div>
        <div class="permission-buttons">
            <button class="btn btn-primary" onclick="requestMicrophonePermission()">Permitir Micrófono</button>
            <button class="btn btn-secondary" onclick="closePermissionModal()">Cancelar</button>
        </div>
    </div>
</div>`;

// Agregar después de document.addEventListener('DOMContentLoaded'...
document.body.insertAdjacentHTML('beforeend', permissionModal);

// Funciones para el modal de permisos
function showPermissionModal() {
    document.getElementById('permissionModal').classList.add('show');
}

function closePermissionModal() {
    document.getElementById('permissionModal').classList.remove('show');
}

async function requestMicrophonePermission() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        stream.getTracks().forEach(track => track.stop());
        closePermissionModal();
        await VoiceManager.initializeSpeechRecognition();
    } catch (error) {
        console.error('Error al solicitar permisos:', error);
        Utils.updateStatus('Error: No se pudo acceder al micrófono', 'error');
        ChatManager.addMessage('❌ No se pudo acceder al micrófono. Por favor, verifica los permisos en tu navegador.', 'bot');
    }
}