<div id="tab-timers-audio" class="tab-content">
    <div class="card">
        <h2>🔊 Timers de Audio (Juegos)</h2>
        <p style="color: #888;">Configura las alertas de voz para eventos dentro del juego.</p>
        
        <form action="/config/discord" method="POST">
            <input type="hidden" name="form_type" value="timers">
            <!-- Este input se llena con JS al seleccionar el guild en la otra pestaña -->
            <input type="hidden" name="guild_id" id="timer-guild-id" value="<%= discordConfig.guild_id || '' %>">

            <div style="margin-top: 1.5rem;">
                <h3 style="color: #D4AF37;">🌀 Rifts (Horarios Personalizados)</h3>
                <p style="color: #888; font-size: 0.9rem;">Configura hora, mensaje y voz para cada alerta.</p>
                
                <div id="rifts-container">
                    <% 
                        // Lógica de Migración Visual:
                        // 1. Intentamos mostrar los datos de la nueva tabla (rift_alerts).
                        let riftsToShow = (locals.riftAlerts || []).filter(r => r.guild_id === discordConfig.guild_id);
                        
                        // 2. Si no hay datos nuevos, mostramos los antiguos (rift_times) para que el usuario pueda editarlos y guardarlos en el nuevo formato.
                        if (riftsToShow.length === 0 && discordConfig.rift_times && Array.isArray(discordConfig.rift_times)) {
                            riftsToShow = discordConfig.rift_times.map(time => ({
                                time: time,
                                message: '¡Atención! Se han abierto los Rifts.',
                                voice_id: discordConfig.selected_voice || 'es-MX'
                            }));
                        }
                    %>
                    <% riftsToShow.forEach(function(rift) { %>
                        <div class="rift-row" style="display: flex; gap: 10px; margin-bottom: 10px; align-items: center;">
                            <!-- Hora (24h para el value, visualmente el usuario usa el picker) -->
                            <input type="time" name="rift_time" value="<%= rift.time %>" required style="background: #222; color: #fff; border: 1px solid #444; padding: 5px;">
                            
                            <!-- Mensaje -->
                            <input type="text" name="rift_message" value="<%= rift.message %>" placeholder="Mensaje de alerta..." style="flex-grow: 1; background: #222; color: #fff; border: 1px solid #444; padding: 5px;">
                            
                            <!-- Selector de Voz -->
                            <select name="rift_voice" style="background: #222; color: #fff; border: 1px solid #444; padding: 5px; width: 150px;">
                                <option value="es-MX" <%= rift.voice_id === 'es-MX' ? 'selected' : '' %>>🇲🇽 Mujer A</option>
                                <option value="es-MX-Male" <%= rift.voice_id === 'es-MX-Male' ? 'selected' : '' %>>🇲🇽 Hombre A</option>
                                <option value="es-MX-Male-B" <%= rift.voice_id === 'es-MX-Male-B' ? 'selected' : '' %>>🇲🇽 Hombre B</option>
                                <option value="es-US-Male-B" <%= rift.voice_id === 'es-US-Male-B' ? 'selected' : '' %>>🇺🇸 Latino B</option>
                                <option value="es-US-Male-C" <%= rift.voice_id === 'es-US-Male-C' ? 'selected' : '' %>>🇺🇸 Latino C</option>
                                <option value="es-ES" <%= rift.voice_id === 'es-ES' ? 'selected' : '' %>>🇪🇸 Mujer A</option>
                                <option value="es-ES-Male" <%= rift.voice_id === 'es-ES-Male' ? 'selected' : '' %>>🇪🇸 Hombre A</option>
                                <option value="en-US" <%= rift.voice_id === 'en-US' ? 'selected' : '' %>>🇺🇸 Inglés Mujer</option>
                                <option value="en-US-Male" <%= rift.voice_id === 'en-US-Male' ? 'selected' : '' %>>🇺🇸 Inglés Hombre</option>
                            </select>

                            <button type="button" onclick="this.parentElement.remove()" style="background: #ff4444; border: none; color: white; cursor: pointer; padding: 5px 10px;">X</button>
                        </div>
                    <% }); %>
                </div>
                <button type="button" onclick="addRiftRow()" class="btn-add" style="margin-top: 10px; background: #28a745; border: none; padding: 8px 15px; color: white; cursor: pointer;">+ Agregar Horario</button>
                <!-- Botón de guardado rápido para Rifts -->
                <button type="submit" class="btn-save" style="margin-top: 10px; margin-left: 10px; padding: 8px 15px; width: auto; font-size: 0.9rem;">💾 Guardar Rifts</button>
            </div>

            <div style="margin-top: 2rem; padding: 15px; background: #1a1a1a; border: 1px solid #333; border-radius: 8px; display: flex; align-items: center; gap: 15px;">
                <input type="checkbox" name="shugo_enabled" id="shugo-toggle" <%= discordConfig.shugo_enabled ? 'checked' : '' %> style="width: 20px; height: 20px; margin: 0; cursor: pointer; accent-color: #D4AF37;">
                <div>
                    <label for="shugo-toggle" style="margin: 0; cursor: pointer; font-weight: bold; color: #D4AF37; display: block;">🐹 Alertas Shugo (Cada Hora)</label>
                    <small style="color: #666;">Avisa a los minutos 50, 55 y 00.</small>
                </div>
            </div>
            
            <!-- Textos Personalizados Shugo -->
            <div style="margin-top: 1rem; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <!-- Rotación A -->
                <div style="padding: 10px; background: #222; border-radius: 5px;">
                    <h4 style="color: #D4AF37; margin-top: 0;">🅰️ Rotación 1 (Minuto 15 - Shugo Chido)</h4>
                    <label>Voz:</label>
                    <div style="display: flex; gap: 5px; margin-bottom: 10px;">
                        <select id="shugo_voice_a" name="shugo_voice_a" style="flex-grow: 1; background: #333; color: #fff; border: 1px solid #555; padding: 5px;">
                            <option value="es-MX" <%= discordConfig.shugo_voice_a === 'es-MX' ? 'selected' : '' %>>🇲🇽 Mujer A</option>
                            <option value="es-MX-Male" <%= discordConfig.shugo_voice_a === 'es-MX-Male' ? 'selected' : '' %>>🇲🇽 Hombre A</option>
                            <option value="es-MX-Male-B" <%= discordConfig.shugo_voice_a === 'es-MX-Male-B' ? 'selected' : '' %>>🇲🇽 Hombre B</option>
                            <option value="es-US-Male-B" <%= discordConfig.shugo_voice_a === 'es-US-Male-B' ? 'selected' : '' %>>🇺🇸 Latino B</option>
                            <option value="es-US-Male-C" <%= discordConfig.shugo_voice_a === 'es-US-Male-C' ? 'selected' : '' %>>🇺🇸 Latino C</option>
                            <option value="es-ES" <%= discordConfig.shugo_voice_a === 'es-ES' ? 'selected' : '' %>>🇪🇸 Mujer A</option>
                            <option value="es-ES-Male" <%= discordConfig.shugo_voice_a === 'es-ES-Male' ? 'selected' : '' %>>🇪🇸 Hombre A</option>
                            <option value="en-US" <%= discordConfig.shugo_voice_a === 'en-US' ? 'selected' : '' %>>🇺🇸 Inglés Mujer</option>
                            <option value="en-US-Male" <%= discordConfig.shugo_voice_a === 'en-US-Male' ? 'selected' : '' %>>🇺🇸 Inglés Hombre</option>
                        </select>
                        <button type="button" onclick="testShugoVoice('a')" title="Probar Voz" style="background: #444; border: 1px solid #555; color: #fff; cursor: pointer; padding: 0 10px;">🔊</button>
                    </div>
                    <label>10 min antes:</label>
                    <input type="text" name="shugo_10m_text" value="<%= discordConfig.shugo_10m_text || 'Atención Daevas. el Chugo abre en 10 minutos.' %>" style="width: 100%; margin-bottom: 5px;">
                    <label>5 min antes:</label>
                    <input type="text" name="shugo_5m_text" value="<%= discordConfig.shugo_5m_text || 'Atención. El Chugo abre en 5 minutos. Prepárense.' %>" style="width: 100%; margin-bottom: 5px;">
                    <label>Inicio:</label>
                    <input type="text" name="shugo_start_text" value="<%= discordConfig.shugo_start_text || 'Chugo ha abierto. ¡Al ataque!' %>" style="width: 100%;">
                </div>

                <!-- Rotación B -->
                <div style="padding: 10px; background: #222; border-radius: 5px;">
                    <h4 style="color: #28a745; margin-top: 0;">🅱️ Rotación 2 (Minuto 45 - Up Up)</h4>
                    <label>Voz:</label>
                    <div style="display: flex; gap: 5px; margin-bottom: 10px;">
                        <select id="shugo_voice_b" name="shugo_voice_b" style="flex-grow: 1; background: #333; color: #fff; border: 1px solid #555; padding: 5px;">
                            <option value="es-MX" <%= discordConfig.shugo_voice_b === 'es-MX' ? 'selected' : '' %>>🇲🇽 Mujer A</option>
                            <option value="es-MX-Male" <%= discordConfig.shugo_voice_b === 'es-MX-Male' ? 'selected' : '' %>>🇲🇽 Hombre A</option>
                            <option value="es-MX-Male-B" <%= discordConfig.shugo_voice_b === 'es-MX-Male-B' ? 'selected' : '' %>>🇲🇽 Hombre B</option>
                            <option value="es-US-Male-B" <%= discordConfig.shugo_voice_b === 'es-US-Male-B' ? 'selected' : '' %>>🇺🇸 Latino B</option>
                            <option value="es-US-Male-C" <%= discordConfig.shugo_voice_b === 'es-US-Male-C' ? 'selected' : '' %>>🇺🇸 Latino C</option>
                            <option value="es-ES" <%= discordConfig.shugo_voice_b === 'es-ES' ? 'selected' : '' %>>🇪🇸 Mujer A</option>
                            <option value="es-ES-Male" <%= discordConfig.shugo_voice_b === 'es-ES-Male' ? 'selected' : '' %>>🇪🇸 Hombre A</option>
                            <option value="en-US" <%= discordConfig.shugo_voice_b === 'en-US' ? 'selected' : '' %>>🇺🇸 Inglés Mujer</option>
                            <option value="en-US-Male" <%= discordConfig.shugo_voice_b === 'en-US-Male' ? 'selected' : '' %>>🇺🇸 Inglés Hombre</option>
                        </select>
                        <button type="button" onclick="testShugoVoice('b')" title="Probar Voz" style="background: #444; border: 1px solid #555; color: #fff; cursor: pointer; padding: 0 10px;">🔊</button>
                    </div>
                    <label>10 min antes:</label>
                    <input type="text" name="shugo_10m_text_alt" value="<%= discordConfig.shugo_10m_text_alt || 'Atención. El evento Up Up comienza en 10 minutos.' %>" style="width: 100%; margin-bottom: 5px;">
                    <label>5 min antes:</label>
                    <input type="text" name="shugo_5m_text_alt" value="<%= discordConfig.shugo_5m_text_alt || 'Atención. Up Up comienza en 5 minutos.' %>" style="width: 100%; margin-bottom: 5px;">
                    <label>Inicio:</label>
                    <input type="text" name="shugo_start_text_alt" value="<%= discordConfig.shugo_start_text_alt || '¡El evento Up Up ha comenzado!' %>" style="width: 100%;">
                </div>
            </div>
            
            <!-- Botón de guardado específico para Shugo -->
            <button type="button" onclick="saveShugoConfig()" class="btn-save" style="margin-top: 15px; background: #28a745; width: auto; padding: 8px 15px; font-size: 0.9rem;">💾 Guardar Configuración Shugo</button>

            <button type="submit" class="btn-save" style="margin-top: 2rem;">💾 Guardar Timers de Audio</button>
        </form>
    </div>

    <script>
    function addRiftRow() {
        const div = document.createElement('div');
        div.className = 'rift-row';
        div.style = 'display: flex; gap: 10px; margin-bottom: 10px; align-items: center;';
        div.innerHTML = `
            <input type="time" name="rift_time" required style="background: #222; color: #fff; border: 1px solid #444; padding: 5px;">
            <input type="text" name="rift_message" value="¡Atención! Se han abierto los Rifts." placeholder="Mensaje..." style="flex-grow: 1; background: #222; color: #fff; border: 1px solid #444; padding: 5px;">
            <select name="rift_voice" style="background: #222; color: #fff; border: 1px solid #444; padding: 5px; width: 150px;">
                <option value="es-MX">🇲🇽 Mujer A</option>
                <option value="es-MX-Male">🇲🇽 Hombre A</option>
                <option value="es-MX-Male-B">🇲🇽 Hombre B</option>
                <option value="es-US-Male-B">🇺🇸 Latino B</option>
                <option value="es-US-Male-C">🇺🇸 Latino C</option>
                <option value="es-ES">🇪🇸 Mujer A</option>
                <option value="es-ES-Male">🇪🇸 Hombre A</option>
                <option value="en-US">🇺🇸 Inglés Mujer</option>
                <option value="en-US-Male">🇺🇸 Inglés Hombre</option>
            </select>
            <button type="button" onclick="this.parentElement.remove()" style="background: #ff4444; border: none; color: white; cursor: pointer; padding: 5px 10px;">X</button>
        `;
        document.getElementById('rifts-container').appendChild(div);
    }

    async function testShugoVoice(rotation) {
        const guildId = document.getElementById('timer-guild-id').value;
        const channelId = '<%= discordConfig.voice_channel_id || "" %>';
        
        if (!guildId || !channelId) {
            alert('❌ Error: Configura y guarda primero el servidor y canal de voz en la pestaña "Conexión".');
            return;
        }

        const voiceSelect = document.getElementById(rotation === 'a' ? 'shugo_voice_a' : 'shugo_voice_b');
        const voiceId = voiceSelect.value;
        
        // Usamos el texto de "Inicio" como prueba
        let textInput = document.getElementsByName(rotation === 'a' ? 'shugo_start_text' : 'shugo_start_text_alt')[0];
        const text = textInput ? textInput.value : 'Prueba de voz Shugo';

        try {
            const res = await fetch('/api/proxy/discord/tts-test', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ guildId, channelId, text: `Prueba de voz: ${text}`, voiceId })
            });
            const data = await res.json();
            if (data.success) alert('✅ Prueba enviada al canal de voz.');
            else alert('❌ Error: ' + (data.error || 'Desconocido'));
        } catch (e) { alert('❌ Error de red: ' + e.message); }
    }

    async function saveShugoConfig() {
        const guildId = document.getElementById('timer-guild-id').value;
        const enabled = document.getElementById('shugo-toggle').checked;
        
        // Gather A
        const voiceA = document.getElementById('shugo_voice_a').value;
        const text10A = document.getElementsByName('shugo_10m_text')[0].value;
        const text5A = document.getElementsByName('shugo_5m_text')[0].value;
        const textStartA = document.getElementsByName('shugo_start_text')[0].value;

        // Gather B
        const voiceB = document.getElementById('shugo_voice_b').value;
        const text10B = document.getElementsByName('shugo_10m_text_alt')[0].value;
        const text5B = document.getElementsByName('shugo_5m_text_alt')[0].value;
        const textStartB = document.getElementsByName('shugo_start_text_alt')[0].value;

        try {
            const res = await fetch('/config/discord', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    form_type: 'shugo_settings',
                    guild_id: guildId,
                    shugo_enabled: enabled,
                    shugo_voice_a: voiceA,
                    shugo_10m_text: text10A,
                    shugo_5m_text: text5A,
                    shugo_start_text: textStartA,
                    shugo_voice_b: voiceB,
                    shugo_10m_text_alt: text10B,
                    shugo_5m_text_alt: text5B,
                    shugo_start_text_alt: textStartB
                })
            });
            const data = await res.json();
            if (data.success) alert('✅ ' + data.message);
            else alert('❌ Error: ' + data.error);
        } catch (e) {
            alert('❌ Error de red: ' + e.message);
        }
    }
    </script>
</div>