// Announcements Management
let allDevices = [];

async function loadAnnouncements() {
    const response = await fetch('/api/announcements.php');
    const data = await response.json();
    
    if (data.success) {
        renderAnnouncements(data.data);
    }
    
    // Cargar dispositivos
    await loadDevices();
}

async function loadDevices() {
    const response = await fetch('/api/announcements.php?action=devices');
    const data = await response.json();
    
    if (data.success) {
        allDevices = data.data;
    }
}

function renderAnnouncements(announcements) {
    const container = document.getElementById('announcementsContent');
    
    if (announcements.length === 0) {
        container.innerHTML = '<div class="loading">No hay anuncios</div>';
        return;
    }
    
    const typeColors = {
        info: '#3b82f6',
        warning: '#f59e0b',
        update: '#10b981',
        critical: '#ef4444'
    };
    
    const actionLabels = {
        none: 'Solo mostrar',
        force_update: '⚠️ Forzar Actualización',
        block_app: '🔒 Bloquear App'
    };
    
    container.innerHTML = `
        <div style="display: grid; gap: 16px;">
            ${announcements.map(ann => {
                const isIndefinite = ann.block_duration == -1;
                const blockText = isIndefinite ? 'INDEFINIDO' : `${ann.block_duration} min`;
                
                return `
                <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-left: 4px solid ${typeColors[ann.type] || '#3b82f6'};">
                    <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
                        <div style="flex: 1;">
                            <h3 style="font-size: 18px; color: #1e293b; margin-bottom: 8px;">${ann.title}</h3>
                            <div style="display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 8px;">
                                <span style="background: ${typeColors[ann.type]}15; color: ${typeColors[ann.type]}; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600;">${ann.type.toUpperCase()}</span>
                                ${ann.action !== 'none' ? `<span style="background: ${ann.action === 'block_app' ? '#dc262615' : '#f59e0b15'}; color: ${ann.action === 'block_app' ? '#dc2626' : '#f59e0b'}; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600;">${actionLabels[ann.action]}</span>` : ''}
                                ${ann.action === 'block_app' && ann.block_duration > 0 ? `<span style="background: ${isIndefinite ? '#dc262615' : '#64748b15'}; color: ${isIndefinite ? '#dc2626' : '#64748b'}; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600;">${blockText}</span>` : ''}
                                <span style="background: ${ann.status === 'active' ? '#10b98115' : '#64748b15'}; color: ${ann.status === 'active' ? '#10b981' : '#64748b'}; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600;">${ann.status === 'active' ? 'ACTIVO' : 'INACTIVO'}</span>
                            </div>
                            <p style="color: #475569; margin-bottom: 12px;">${ann.message}</p>
                            <div style="font-size: 13px; color: #64748b;">
                                <i class="fas fa-eye"></i> ${ann.views_count || 0} vistas
                                ${ann.target_devices !== 'all' ? ` • <i class="fas fa-mobile-alt"></i> Dispositivos específicos` : ' • <i class="fas fa-globe"></i> Todos'}
                                ${ann.expires_at ? ` • <i class="fas fa-calendar"></i> Expira: ${new Date(ann.expires_at).toLocaleDateString('es-ES')}` : ''}
                            </div>
                        </div>
                        ${ann.image_url ? `<img src="${ann.image_url}" style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px; margin-left: 16px;">` : ''}
                    </div>
                    <div style="display: flex; gap: 8px;">
                        ${ann.status === 'active' ? `
                            <button class="btn btn-secondary" onclick="toggleAnnouncementStatus(${ann.id}, 'inactive')" style="padding: 6px 12px; font-size: 13px;">
                                <i class="fas fa-pause"></i> Desactivar
                            </button>
                        ` : `
                            <button class="btn btn-secondary" onclick="toggleAnnouncementStatus(${ann.id}, 'active')" style="padding: 6px 12px; font-size: 13px;">
                                <i class="fas fa-play"></i> Activar
                            </button>
                        `}
                        <button class="btn btn-danger" onclick="deleteAnnouncement(${ann.id})" style="padding: 6px 12px; font-size: 13px;">
                            <i class="fas fa-trash"></i> ${isIndefinite && ann.status === 'active' ? 'Eliminar y Desbloquear' : 'Eliminar'}
                        </button>
                    </div>
                </div>
            `}).join('')}
        </div>
    `;
}

function openAnnouncementModal() {
    document.getElementById('announcementModal').classList.add('active');
    
    // Cargar selector de dispositivos
    renderDeviceSelector();
    
    // Listener para cambiar según acción
    const actionSelect = document.getElementById('annAction');
    const blockDurationGroup = document.getElementById('blockDurationGroup');
    const deviceSelectorGroup = document.getElementById('deviceSelectorGroup');
    const targetTypeSelect = document.getElementById('annTargetType');
    
    actionSelect.addEventListener('change', function() {
        if (this.value === 'block_app') {
            blockDurationGroup.style.display = 'block';
        } else {
            blockDurationGroup.style.display = 'none';
        }
    });
    
    targetTypeSelect.addEventListener('change', function() {
        if (this.value === 'specific') {
            deviceSelectorGroup.style.display = 'block';
            renderDeviceSelector();
        } else {
            deviceSelectorGroup.style.display = 'none';
        }
    });
}

function renderDeviceSelector() {
    const container = document.getElementById('deviceSelector');
    if (!container || allDevices.length === 0) return;
    
    const now = new Date();
    
    container.innerHTML = `
        <div style="max-height: 200px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px;">
            ${allDevices.map(device => {
                const lastActivity = new Date(device.last_activity);
                const minutesAgo = Math.floor((now - lastActivity) / 60000);
                const isActive = minutesAgo < 5;
                const deviceShort = device.device_id.substring(0, 12);
                
                return `
                    <label style="display: flex; align-items: center; padding: 8px; border-bottom: 1px solid #f1f5f9; cursor: pointer;" 
                           onmouseover="this.style.background='#f8fafc'" 
                           onmouseout="this.style.background='transparent'">
                        <input type="checkbox" name="device_check" value="${device.device_id}" style="margin-right: 10px;">
                        <div style="flex: 1;">
                            <div style="font-weight: 600; color: #1e293b;">${deviceShort}...</div>
                            <div style="font-size: 12px; color: #64748b;">
                                ${isActive ? 
                                    '<span style="color: #10b981;">● Activo</span>' : 
                                    `<span style="color: #64748b;">○ Inactivo (${minutesAgo}m)</span>`
                                }
                                • ${device.app_usage_minutes || 0}m uso
                            </div>
                        </div>
                    </label>
                `;
            }).join('')}
        </div>
        <div style="margin-top: 10px; display: flex; gap: 10px;">
            <button type="button" class="btn btn-secondary" onclick="selectAllDevices()" style="padding: 6px 12px; font-size: 13px;">
                Seleccionar todos
            </button>
            <button type="button" class="btn btn-secondary" onclick="selectActiveDevices()" style="padding: 6px 12px; font-size: 13px;">
                Solo activos
            </button>
            <button type="button" class="btn btn-secondary" onclick="deselectAllDevices()" style="padding: 6px 12px; font-size: 13px;">
                Deseleccionar todos
            </button>
        </div>
    `;
}

function selectAllDevices() {
    document.querySelectorAll('input[name="device_check"]').forEach(cb => cb.checked = true);
}

function selectActiveDevices() {
    const now = new Date();
    document.querySelectorAll('input[name="device_check"]').forEach(cb => {
        const device = allDevices.find(d => d.device_id === cb.value);
        if (device) {
            const minutesAgo = Math.floor((now - new Date(device.last_activity)) / 60000);
            cb.checked = minutesAgo < 5;
        }
    });
}

function deselectAllDevices() {
    document.querySelectorAll('input[name="device_check"]').forEach(cb => cb.checked = false);
}

function closeAnnouncementModal() {
    document.getElementById('announcementModal').classList.remove('active');
    // Resetear formulario
    document.getElementById('annTitle').value = '';
    document.getElementById('annMessage').value = '';
    document.getElementById('annType').value = 'info';
    document.getElementById('annAction').value = 'none';
    document.getElementById('annBlockDuration').value = '5';
    document.getElementById('annPriority').value = '0';
    document.getElementById('annExpires').value = '';
    document.getElementById('annTargetType').value = 'all';
    document.getElementById('blockDurationGroup').style.display = 'none';
    document.getElementById('deviceSelectorGroup').style.display = 'none';
}

async function createAnnouncement() {
    const title = document.getElementById('annTitle').value;
    const message = document.getElementById('annMessage').value;
    const type = document.getElementById('annType').value;
    const action = document.getElementById('annAction').value;
    const blockDuration = document.getElementById('annBlockDuration').value;
    const priority = document.getElementById('annPriority').value;
    const expires = document.getElementById('annExpires').value;
    const targetType = document.getElementById('annTargetType').value;
    
    if (!title || !message) {
        Swal.fire('Error', 'Completa título y mensaje', 'error');
        return;
    }
    
    // Obtener dispositivos seleccionados
    let selectedDevices = [];
    if (targetType === 'specific') {
        const checkboxes = document.querySelectorAll('input[name="device_check"]:checked');
        selectedDevices = Array.from(checkboxes).map(cb => cb.value);
        
        if (selectedDevices.length === 0) {
            Swal.fire('Error', 'Selecciona al menos un dispositivo', 'error');
            return;
        }
    }
    
    const data = {
        title,
        message,
        type,
        action,
        block_duration: action === 'block_app' ? parseInt(blockDuration) : 0,
        priority: parseInt(priority),
        expires_at: expires || null,
        created_by: 1,
        selected_devices: targetType === 'specific' ? selectedDevices : []
    };
    
    const response = await fetch('/api/announcements.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    
    const result = await response.json();
    
    if (result.success) {
        const deviceCount = targetType === 'specific' ? selectedDevices.length : 'todos los';
        Swal.fire('¡Enviado!', `Anuncio enviado a ${deviceCount} dispositivos`, 'success');
        closeAnnouncementModal();
        loadAnnouncements();
    } else {
        Swal.fire('Error', result.message, 'error');
    }
}

async function toggleAnnouncementStatus(id, status) {
    try {
        const response = await fetch('/api/announcements.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({id, status})
        });
        
        if (!response.ok) {
            throw new Error('Error al actualizar estado');
        }
        
        const data = await response.json();
        if (data.success) {
            loadAnnouncements();
        } else {
            Swal.fire('Error', data.message || 'Error al actualizar', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        Swal.fire('Error', 'No se pudo actualizar el estado', 'error');
    }
}

async function deleteAnnouncement(id) {
    const result = await Swal.fire({
        title: '¿Eliminar anuncio?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
    });
    
    if (result.isConfirmed) {
        const response = await fetch('/api/announcements.php', {
            method: 'DELETE',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({id})
        });
        
        const data = await response.json();
        if (data.success) {
            Swal.fire('¡Eliminado!', 'Anuncio eliminado', 'success');
            loadAnnouncements();
        }
    }
}
