// Configuración
const API_URL = '/api/index.php';
const API_KEY = 'cler_secret_key_2024';

// Estado global
let currentPage = 'dashboard';
let charts = {};

// Inicialización
document.addEventListener('DOMContentLoaded', () => {
    initNavigation();
    initMobileMenu();
    initSidebarToggle();
    initUserModal();
    initRoleModal();
    
    const savedPage = localStorage.getItem('currentPage') || 'dashboard';
    navigateTo(savedPage);
});

// Sidebar Toggle
function initSidebarToggle() {
    const toggleBtn = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.querySelector('.main-content');
    
    if (toggleBtn) {
        toggleBtn.addEventListener('click', () => {
            sidebar.classList.toggle('collapsed');
            mainContent.classList.toggle('expanded');
        });
    }
}

// Navegación
function initNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    
    navItems.forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            const page = item.dataset.page;
            navigateTo(page);
        });
    });
}

function navigateTo(page) {
    // Verificar acceso antes de navegar
    if (!Auth.checkPageAccess(page)) {
        return;
    }
    
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
    });
    document.querySelector(`[data-page="${page}"]`).classList.add('active');
    
    // Mostrar página
    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    document.getElementById(`${page}-page`).classList.add('active');
    
    // Actualizar título
    const titles = {
        dashboard: 'Dashboard',
        users: 'Usuarios',
        feedback: 'Feedback de Usuarios',
        downloads: 'Gestión de Descargas',
        landing: 'Gestión de Landing Page',
        roles: 'Roles y Permisos'
    };
    document.getElementById('pageTitle').textContent = titles[page];
    
    // Cargar datos
    currentPage = page;
    localStorage.setItem('currentPage', page);
    loadPageData(page);
    
    // Cerrar sidebar en móvil
    if (window.innerWidth <= 768) {
        document.getElementById('sidebar').classList.remove('active');
    }
}

function loadPageData(page) {
    switch(page) {
        case 'dashboard':
            loadDashboard();
            break;
        case 'users':
            loadUsers();
            break;
        case 'feedback':
            loadFeedback();
            break;
        case 'downloads':
            loadDownloads();
            break;
        case 'landing':
            loadLandingEditor();
            break;
        case 'roles':
            loadRolesAndPermissions();
            break;
    }
}

// Menú móvil
function initMobileMenu() {
    const mobileBtn = document.getElementById('mobileMenuBtn');
    const sidebar = document.getElementById('sidebar');
    
    mobileBtn.addEventListener('click', () => {
        sidebar.classList.toggle('active');
    });
    
    // Cerrar al hacer click fuera
    document.addEventListener('click', (e) => {
        if (window.innerWidth <= 768 && 
            !sidebar.contains(e.target) && 
            !mobileBtn.contains(e.target)) {
            sidebar.classList.remove('active');
        }
    });
}

// API Calls
async function apiCall(endpoint, method = 'GET', data = null) {
    const options = {
        method,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
        }
    };
    
    if (data) {
        options.body = JSON.stringify(data);
    }
    
    try {
        const response = await fetch(`${API_URL}?endpoint=${endpoint}`, options);
        return await response.json();
    } catch (error) {
        console.error('API Error:', error);
        return { success: false, error: error.message };
    }
}

// Dashboard
async function loadDashboard() {
    applyDashboardPermissions();
    await loadDashboardStats();
    await loadInternetTraffic();
    await loadConversationsFlow();
    await loadAppUsage();
    
    setInterval(loadDashboardStats, 30000);
}

function applyDashboardPermissions() {
    const elements = document.querySelectorAll('[data-permission]');
    elements.forEach(element => {
        const permission = element.getAttribute('data-permission');
        if (!Auth.hasPermission(permission)) {
            element.style.display = 'none';
        }
    });
}

async function loadDashboardStats() {
    try {
        const response = await fetch('/api/telemetry.php?action=stats');
        const data = await response.json();
        
        if (data.success) {
            const stats = data.data;
            document.getElementById('totalUsers').textContent = stats.total_users;
            document.getElementById('activeDevices').textContent = stats.active_devices;
            document.getElementById('pendingErrors').textContent = stats.pending_errors;
            document.getElementById('totalStorage').textContent = stats.total_storage_mb + ' MB';
        }
    } catch (error) {
        console.error('Error loading dashboard stats:', error);
    }
}

async function loadInternetTraffic() {
    try {
        const response = await fetch('/api/telemetry.php?action=internet_traffic');
        const data = await response.json();
        
        if (data.success && data.data.length > 0) {
            renderInternetChart(data.data);
        } else {
            showEmptyChart('internetChart', 'No hay datos de tráfico aún');
        }
    } catch (error) {
        console.error('Error loading internet traffic:', error);
        showEmptyChart('internetChart', 'Error al cargar datos');
    }
}

function showEmptyChart(canvasId, message) {
    const canvas = document.getElementById(canvasId);
    const ctx = canvas.getContext('2d');
    canvas.height = 200;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.font = '14px Inter';
    ctx.fillStyle = '#94a3b8';
    ctx.textAlign = 'center';
    ctx.fillText(message, canvas.width / 2, canvas.height / 2);
}

function renderInternetChart(traffic) {
    const ctx = document.getElementById('internetChart');
    
    if (charts.internet) {
        charts.internet.destroy();
    }
    
    charts.internet = new Chart(ctx, {
        type: 'line',
        data: {
            labels: traffic.map(t => new Date(t.hour).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })),
            datasets: [{
                label: 'Consumo de Internet',
                data: traffic.map(t => parseFloat(t.mb_used)),
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37, 99, 235, 0.1)',
                tension: 0.4,
                fill: true,
                borderWidth: 3,
                pointRadius: 4,
                pointHoverRadius: 6,
                pointBackgroundColor: '#2563eb',
                pointBorderColor: '#fff',
                pointBorderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.9)',
                    padding: 12,
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#2563eb',
                    borderWidth: 1,
                    displayColors: false,
                    callbacks: {
                        label: function(context) {
                            return context.parsed.y.toFixed(2) + ' MB';
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return value + ' MB';
                        }
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

async function loadConversationsFlow() {
    try {
        const response = await fetch('/api/telemetry.php?action=conversations_flow');
        const data = await response.json();
        
        if (data.success && data.data.length > 0) {
            renderConversationsChart(data.data);
        } else {
            showEmptyChart('conversationsChart', 'No hay datos de conversaciones aún');
        }
    } catch (error) {
        console.error('Error loading conversations flow:', error);
        showEmptyChart('conversationsChart', 'Error al cargar datos');
    }
}

function renderConversationsChart(conversations) {
    const ctx = document.getElementById('conversationsChart');
    
    if (charts.conversations) {
        charts.conversations.destroy();
    }
    
    charts.conversations = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: conversations.map(c => new Date(c.hour).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' })),
            datasets: [{
                label: 'Conversaciones',
                data: conversations.map(c => parseInt(c.count)),
                backgroundColor: 'rgba(16, 185, 129, 0.8)',
                borderRadius: 8,
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.9)',
                    padding: 12,
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#10b981',
                    borderWidth: 1,
                    displayColors: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            }
        }
    });
}

async function loadAppUsage() {
    try {
        const response = await fetch('/api/telemetry.php?action=app_usage');
        const data = await response.json();
        
        if (data.success) {
            renderAppUsage(data.data);
        }
    } catch (error) {
        console.error('Error loading app usage:', error);
    }
}

function renderAppUsage(usage) {
    const container = document.getElementById('appUsage');
    
    if (usage.length === 0) {
        container.innerHTML = '<p class="loading">No hay datos de uso aún</p>';
        return;
    }
    
    container.innerHTML = usage.map((item, index) => {
        const hours = Math.floor(item.app_usage_minutes / 60);
        const minutes = item.app_usage_minutes % 60;
        const timeStr = hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
        
        return `
            <div class="query-item">
                <div class="query-rank">${index + 1}</div>
                <div class="query-text">Dispositivo ${item.device_id.substring(0, 8)}...</div>
                <div class="query-count">
                    <i class="fas fa-clock"></i>
                    ${timeStr}
                </div>
            </div>
        `;
    }).join('');
}

// Users - Gestión de usuarios
let allUsers = [];
let filteredUsers = [];
let currentUsersPage = 1;
let usersPerPage = 10;
let currentSortColumn = 'id';
let currentSortDirection = 'asc';

async function loadUsers() {
    console.log('Loading users...');
    const response = await fetch('/api/admins.php');
    const data = await response.json();
    
    if (data.success) {
        allUsers = data.data;
        filteredUsers = [...allUsers];
        sortUsers();
        console.log(`Loaded ${allUsers.length} users`);
        
        renderUsersTable(filteredUsers);
        
        setTimeout(() => {
            initUserSearch();
            initUsersPerPageSelector();
            initTableSort();
        }, 100);
    } else {
        console.error('Error loading users:', data.message);
    }
}

function initUserSearch() {
    const searchInput = document.getElementById('userSearch');
    if (!searchInput) {
        console.log('Search input not found');
        return;
    }
    
    // Limpiar listeners previos
    searchInput.removeEventListener('input', handleUserSearch);
    searchInput.addEventListener('input', handleUserSearch);
    
    console.log('User search initialized');
}

function handleUserSearch(e) {
    const query = e.target.value.toLowerCase().trim();
    
    if (query === '') {
        filteredUsers = [...allUsers];
    } else {
        filteredUsers = allUsers.filter(user => 
            user.username.toLowerCase().includes(query) ||
            (user.full_name && user.full_name.toLowerCase().includes(query)) ||
            user.email.toLowerCase().includes(query) ||
            user.role_name.toLowerCase().includes(query)
        );
    }
    
    sortUsers();
    currentUsersPage = 1;
    renderUsersTable(filteredUsers);
    console.log(`Search: "${query}" - Found ${filteredUsers.length} users`);
}

function initUsersPerPageSelector() {
    const selector = document.getElementById('usersPerPageSelect');
    if (!selector) {
        console.log('Users per page selector not found');
        return;
    }
    
    // Limpiar listeners previos
    selector.removeEventListener('change', handleUsersPerPageChange);
    selector.addEventListener('change', handleUsersPerPageChange);
    
    console.log('Users per page selector initialized');
}

function handleUsersPerPageChange(e) {
    usersPerPage = parseInt(e.target.value);
    currentUsersPage = 1;
    renderUsersTable(filteredUsers);
    console.log(`Changed to ${usersPerPage} users per page`);
}

function initTableSort() {
    const headers = document.querySelectorAll('#users-page th[data-sort]');
    headers.forEach(header => {
        header.style.cursor = 'pointer';
        header.addEventListener('click', () => {
            const column = header.dataset.sort;
            if (currentSortColumn === column) {
                currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortColumn = column;
                currentSortDirection = 'asc';
            }
            sortUsers();
            renderUsersTable(filteredUsers);
            updateSortIcons();
        });
    });
    updateSortIcons();
}

function sortUsers() {
    filteredUsers.sort((a, b) => {
        let valA, valB;
        
        switch(currentSortColumn) {
            case 'username':
                valA = a.username.toLowerCase();
                valB = b.username.toLowerCase();
                break;
            case 'full_name':
                valA = (a.full_name || '').toLowerCase();
                valB = (b.full_name || '').toLowerCase();
                break;
            case 'email':
                valA = a.email.toLowerCase();
                valB = b.email.toLowerCase();
                break;
            case 'role_name':
                valA = a.role_name.toLowerCase();
                valB = b.role_name.toLowerCase();
                break;
            case 'last_login':
                valA = a.last_login ? new Date(a.last_login).getTime() : 0;
                valB = b.last_login ? new Date(b.last_login).getTime() : 0;
                break;
            case 'is_active':
                valA = a.is_active ? 1 : 0;
                valB = b.is_active ? 1 : 0;
                break;
            default:
                valA = a.id;
                valB = b.id;
        }
        
        if (valA < valB) return currentSortDirection === 'asc' ? -1 : 1;
        if (valA > valB) return currentSortDirection === 'asc' ? 1 : -1;
        return 0;
    });
}

function updateSortIcons() {
    document.querySelectorAll('#users-page th[data-sort]').forEach(th => {
        const icon = th.querySelector('.sort-icon');
        if (icon) icon.remove();
        
        if (th.dataset.sort === currentSortColumn) {
            const iconEl = document.createElement('i');
            iconEl.className = `fas fa-sort-${currentSortDirection === 'asc' ? 'up' : 'down'} sort-icon`;
            iconEl.style.marginLeft = '5px';
            iconEl.style.fontSize = '0.8em';
            th.appendChild(iconEl);
        }
    });
}

function renderUsersTable(users) {
    const tbody = document.getElementById('usersTableBody');
    
    if (users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;">No se encontraron usuarios</td></tr>';
        updateTableInfo(0, 0, 0);
        const paginationContainer = document.getElementById('usersPagination');
        if (paginationContainer) paginationContainer.innerHTML = '';
        return;
    }
    
    const totalPages = Math.ceil(users.length / usersPerPage);
    const start = (currentUsersPage - 1) * usersPerPage;
    const end = start + usersPerPage;
    const paginatedUsers = users.slice(start, end);
    
    updateTableInfo(start + 1, Math.min(end, users.length), users.length);
    
    const canEdit = !Auth.user || Auth.hasPermission('edit_admin_users');
    const canDelete = !Auth.user || Auth.hasPermission('delete_admin_users');
    
    tbody.innerHTML = paginatedUsers.map(user => `
        <tr>
            <td><strong>${user.username}</strong></td>
            <td>${user.full_name || '-'}</td>
            <td>${user.email}</td>
            <td><span class="badge">${user.role_name}</span></td>
            <td>${user.last_login ? formatDate(user.last_login) : 'Nunca'}</td>
            <td><span class="badge ${user.is_active ? 'active' : 'inactive'}">${user.is_active ? 'Activo' : 'Inactivo'}</span></td>
            <td>
                ${canEdit ? `<button class="btn btn-secondary" onclick="editUser(${user.id})" style="padding: 5px 10px; font-size: 0.85rem;">
                    <i class="fas fa-edit"></i>
                </button>` : ''}
                ${canDelete && user.id !== 1 ? `<button class="btn btn-danger" onclick="deleteUser(${user.id})" style="padding: 5px 10px; font-size: 0.85rem; margin-left: 5px;">
                    <i class="fas fa-trash"></i>
                </button>` : ''}
            </td>
        </tr>
    `).join('');
    
    renderPagination(totalPages, currentUsersPage, 'usersPagination', (page) => {
        currentUsersPage = page;
        renderUsersTable(users);
    });
}

function updateTableInfo(start, end, total) {
    const startEl = document.getElementById('showingStart');
    const endEl = document.getElementById('showingEnd');
    const totalEl = document.getElementById('totalRecords');
    
    if (startEl) startEl.textContent = start;
    if (endEl) endEl.textContent = end;
    if (totalEl) totalEl.textContent = total;
}

function renderPagination(totalPages, currentPage, containerId, callback) {
    const container = document.getElementById(containerId);
    
    if (!container) return;
    
    if (totalPages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let pages = [];
    
    if (totalPages <= 7) {
        pages = Array.from({length: totalPages}, (_, i) => i + 1);
    } else {
        if (currentPage <= 3) {
            pages = [1, 2, 3, 4, '...', totalPages];
        } else if (currentPage >= totalPages - 2) {
            pages = [1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
        } else {
            pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
        }
    }
    
    let html = `
        <button ${currentPage === 1 ? 'disabled' : ''} data-page="${currentPage - 1}">
            <i class="fas fa-chevron-left"></i>
        </button>
    `;
    
    pages.forEach(page => {
        if (page === '...') {
            html += '<span class="dots">...</span>';
        } else {
            html += `<button class="${page === currentPage ? 'active' : ''}" data-page="${page}">${page}</button>`;
        }
    });
    
    html += `
        <button ${currentPage === totalPages ? 'disabled' : ''} data-page="${currentPage + 1}">
            <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    container.innerHTML = html;
    
    container.querySelectorAll('button').forEach(btn => {
        btn.addEventListener('click', () => {
            const page = parseInt(btn.dataset.page);
            if (page) callback(page);
        });
    });
}

function initUserModal() {
    document.getElementById('newUserBtn').addEventListener('click', () => {
        openUserModal();
    });
}

function openUserModal(userId = null) {
    const modal = document.getElementById('userModal');
    const title = document.getElementById('userModalTitle');
    const passwordOptional = document.getElementById('passwordOptional');
    
    // Limpiar formulario
    document.getElementById('userId').value = '';
    document.getElementById('userUsername').value = '';
    document.getElementById('userFullName').value = '';
    document.getElementById('userEmail').value = '';
    document.getElementById('userPassword').value = '';
    document.getElementById('userActive').checked = true;
    
    if (userId) {
        title.textContent = 'Editar Usuario Administrador';
        passwordOptional.style.display = 'inline';
        loadUserData(userId);
    } else {
        title.textContent = 'Nuevo Usuario Administrador';
        passwordOptional.style.display = 'none';
    }
    
    loadRolesForSelect();
    modal.classList.add('active');
}

function closeUserModal() {
    document.getElementById('userModal').classList.remove('active');
}

async function loadRolesForSelect() {
    const response = await fetch('/api/roles.php?action=list');
    const data = await response.json();
    
    if (data.success) {
        const select = document.getElementById('userRole');
        select.innerHTML = '<option value="">Seleccionar rol...</option>' + 
            data.data.map(role => `<option value="${role.id}">${role.display_name}</option>`).join('');
    }
}

async function loadUserData(userId) {
    const response = await fetch(`/api/admins.php?id=${userId}`);
    const data = await response.json();
    
    if (data.success) {
        const user = data.data;
        document.getElementById('userId').value = user.id;
        document.getElementById('userUsername').value = user.username;
        document.getElementById('userFullName').value = user.full_name;
        document.getElementById('userEmail').value = user.email;
        document.getElementById('userActive').checked = user.is_active;
        
        // Cargar roles primero, luego seleccionar el rol del usuario
        await loadRolesForSelect();
        document.getElementById('userRole').value = user.role_id;
    }
}

async function saveUser() {
    const userId = document.getElementById('userId').value;
    const userData = {
        username: document.getElementById('userUsername').value,
        full_name: document.getElementById('userFullName').value,
        email: document.getElementById('userEmail').value,
        password: document.getElementById('userPassword').value,
        role_id: document.getElementById('userRole').value,
        is_active: document.getElementById('userActive').checked
    };
    
    // Validación
    if (!userData.username || !userData.full_name || !userData.email || !userData.role_id) {
        Swal.fire('Error', 'Por favor completa todos los campos obligatorios', 'error');
        return;
    }
    
    if (!userId && !userData.password) {
        Swal.fire('Error', 'La contraseña es obligatoria para nuevos usuarios', 'error');
        return;
    }
    
    const method = userId ? 'PUT' : 'POST';
    if (userId) userData.id = userId;
    
    const response = await fetch('/api/admins.php', {
        method: method,
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(userData)
    });
    
    const data = await response.json();
    
    if (data.success) {
        Swal.fire('Éxito', userId ? 'Usuario actualizado correctamente' : 'Usuario creado correctamente', 'success');
        closeUserModal();
        loadUsers();
    } else {
        Swal.fire('Error', data.message, 'error');
    }
}

function editUser(id) {
    openUserModal(id);
}

function deleteUser(id) {
    Swal.fire({
        title: '¿Eliminar usuario?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('/api/admins.php', {
                method: 'DELETE',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id})
            }).then(r => r.json()).then(data => {
                if (data.success) {
                    Swal.fire('¡Eliminado!', 'Usuario eliminado correctamente', 'success');
                    loadUsers();
                } else {
                    Swal.fire('Error', data.message, 'error');
                }
            });
        }
    });
}

// Errors
async function loadErrors() {
    const status = document.getElementById('errorStatusFilter').value;
    const data = await apiCall(`errors&status=${status}`);
    
    if (data.success) {
        renderErrors(data.data);
    }
}

function renderErrors(errors) {
    const container = document.getElementById('errorsGrid');
    
    if (errors.length === 0) {
        container.innerHTML = '<div class="loading">No hay errores reportados</div>';
        return;
    }
    
    container.innerHTML = errors.map(error => `
        <div class="error-card ${error.priority}">
            <div class="error-header">
                <div>
                    <div class="error-title">${error.error_type}</div>
                    <div class="error-meta">
                        <span><i class="fas fa-user"></i> ${error.user_name || 'Usuario desconocido'}</span>
                        <span><i class="fas fa-mobile"></i> ${error.device_model}</span>
                        <span><i class="fas fa-clock"></i> ${formatDate(error.timestamp)}</span>
                    </div>
                </div>
                <span class="error-status ${error.status}">${translateStatus(error.status)}</span>
            </div>
            <div class="error-message">${error.error_message}</div>
            <div style="margin-top: 10px;">
                <button class="btn btn-primary" onclick="updateErrorStatus(${error.id}, 'reviewing')">
                    <i class="fas fa-eye"></i> Revisar
                </button>
                <button class="btn btn-secondary" onclick="updateErrorStatus(${error.id}, 'fixed')">
                    <i class="fas fa-check"></i> Marcar resuelto
                </button>
            </div>
        </div>
    `).join('');
}

async function updateErrorStatus(id, status) {
    const data = await apiCall('errors', 'PUT', { id, status });
    
    if (data.success) {
        loadErrors();
    }
}

// Announcements
async function loadAnnouncements() {
    const data = await apiCall('announcements');
    
    if (data.success) {
        renderAnnouncements(data.data);
    }
}

function renderAnnouncements(announcements) {
    const container = document.getElementById('announcementsList');
    
    if (announcements.length === 0) {
        container.innerHTML = '<div class="loading">No hay anuncios</div>';
        return;
    }
    
    container.innerHTML = announcements.map(ann => `
        <div class="error-card">
            <div class="error-header">
                <div>
                    <div class="error-title">${ann.title}</div>
                    <div class="error-message">${ann.message}</div>
                    <div class="error-meta">
                        <span><i class="fas fa-calendar"></i> ${formatDate(ann.created_at)}</span>
                        <span><i class="fas fa-users"></i> ${ann.target_audience}</span>
                        <span><i class="fas fa-paper-plane"></i> ${ann.total_sent || 0} enviados</span>
                    </div>
                </div>
                <span class="error-status ${ann.status}">${ann.status}</span>
            </div>
        </div>
    `).join('');
}

// Interactions
async function loadInteractions() {
    const data = await apiCall('interactions');
    
    if (data.success) {
        renderInteractionsChart(data.data);
    }
}

function renderInteractionsChart(interactions) {
    const ctx = document.getElementById('interactionsChart');
    
    if (charts.interactions) {
        charts.interactions.destroy();
    }
    
    charts.interactions = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: interactions.map(i => new Date(i.date).toLocaleDateString('es-ES', { month: 'short', day: 'numeric' })),
            datasets: [{
                label: 'Interacciones',
                data: interactions.map(i => i.total),
                backgroundColor: 'rgba(99, 102, 241, 0.8)',
                borderRadius: 8
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// Learning
async function loadLearning() {
    const data = await apiCall('learning');
    
    if (data.success) {
        renderLearning(data.data);
    }
}

function renderLearning(learning) {
    const container = document.getElementById('learningGrid');
    
    if (learning.length === 0) {
        container.innerHTML = '<div class="loading">No hay datos de aprendizaje</div>';
        return;
    }
    
    container.innerHTML = learning.map(item => `
        <div class="learning-card">
            <h3>${item.learning_type}</h3>
            <div class="learning-stat">${item.count}</div>
            <div class="learning-label">Registros</div>
            <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid var(--border);">
                <div class="learning-label">Confianza promedio</div>
                <div style="font-size: 1.5rem; font-weight: 700; color: var(--success);">
                    ${(parseFloat(item.avg_confidence) * 100).toFixed(0)}%
                </div>
            </div>
        </div>
    `).join('');
}

// Modals - Eliminado, ahora se maneja en announcements.js

// Utilidades
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES', { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function translateStatus(status) {
    const translations = {
        new: 'Nuevo',
        reviewing: 'En revisión',
        fixed: 'Resuelto',
        ignored: 'Ignorado',
        draft: 'Borrador',
        scheduled: 'Programado',
        sent: 'Enviado'
    };
    return translations[status] || status;
}




// Landing Page Editor
async function loadLandingEditor() {
    const response = await fetch('/api/landing.php');
    const data = await response.json();
    
    if (data.success && data.data) {
        const content = data.data;
        
        // Hero
        if (content.hero) {
            document.getElementById('hero_title').value = content.hero.title || '';
            document.getElementById('hero_description').value = content.hero.content.description || '';
            document.getElementById('hero_cta_text').value = content.hero.content.cta_text || '';
            document.getElementById('hero_cta_link').value = content.hero.content.cta_link || '';
        }
        
        // Features
        if (content.features) {
            renderFeaturesEditor(content.features.content);
        }
        
        // Technology
        if (content.technology) {
            renderTechnologyEditor(content.technology.content);
        }
        
        // Experience
        if (content.experience) {
            renderExperienceEditor(content.experience.content);
        }
    }
}

function renderFeaturesEditor(features) {
    const container = document.getElementById('featuresContainer');
    container.innerHTML = features.map((feature, index) => `
        <div class="feature-editor-item">
            <div class="form-group">
                <label>Título</label>
                <input type="text" id="feature_${index}_title" value="${feature.title}" class="form-input">
            </div>
            <div class="form-group">
                <label>Descripción</label>
                <textarea id="feature_${index}_description" class="form-textarea" rows="2">${feature.description}</textarea>
            </div>
            <div class="form-group">
                <label>Icono</label>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="feature_${index}_icon" value="${feature.icon}" class="form-input" readonly>
                    <button type="button" class="btn btn-secondary" onclick="openIconPicker('feature_${index}_icon')" style="white-space: nowrap;">
                        <i class="fas fa-icons"></i> Seleccionar
                    </button>
                </div>
            </div>
            <div class="form-group">
                <label>Color</label>
                <select id="feature_${index}_color" class="form-select">
                    <option value="blue" ${feature.color === 'blue' ? 'selected' : ''}>Azul</option>
                    <option value="purple" ${feature.color === 'purple' ? 'selected' : ''}>Morado</option>
                    <option value="green" ${feature.color === 'green' ? 'selected' : ''}>Verde</option>
                    <option value="orange" ${feature.color === 'orange' ? 'selected' : ''}>Naranja</option>
                    <option value="red" ${feature.color === 'red' ? 'selected' : ''}>Rojo</option>
                    <option value="teal" ${feature.color === 'teal' ? 'selected' : ''}>Teal</option>
                </select>
            </div>
        </div>
    `).join('');
}

function renderTechnologyEditor(technology) {
    const container = document.getElementById('technologyContainer');
    container.innerHTML = technology.map((tech, index) => `
        <div class="feature-editor-item">
            <div class="form-group">
                <label>Título</label>
                <input type="text" id="tech_${index}_title" value="${tech.title}" class="form-input">
            </div>
            <div class="form-group">
                <label>Descripción</label>
                <input type="text" id="tech_${index}_description" value="${tech.description}" class="form-input">
            </div>
            <div class="form-group">
                <label>Icono</label>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="tech_${index}_icon" value="${tech.icon}" class="form-input" readonly>
                    <button type="button" class="btn btn-secondary" onclick="openIconPicker('tech_${index}_icon')" style="white-space: nowrap;">
                        <i class="fas fa-icons"></i> Seleccionar
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

function renderExperienceEditor(experience) {
    const container = document.getElementById('experienceContainer');
    container.innerHTML = experience.map((exp, index) => `
        <div class="feature-editor-item">
            <div class="form-group">
                <label>Título</label>
                <input type="text" id="exp_${index}_title" value="${exp.title}" class="form-input">
            </div>
            <div class="form-group">
                <label>Descripción</label>
                <textarea id="exp_${index}_description" class="form-textarea" rows="2">${exp.description}</textarea>
            </div>
            <div class="form-group">
                <label>Icono</label>
                <div style="display: flex; gap: 10px;">
                    <input type="text" id="exp_${index}_icon" value="${exp.icon}" class="form-input" readonly>
                    <button type="button" class="btn btn-secondary" onclick="openIconPicker('exp_${index}_icon')" style="white-space: nowrap;">
                        <i class="fas fa-icons"></i> Seleccionar
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

async function saveLandingContent() {
    const btn = event.target;
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Guardando...';
    btn.disabled = true;
    
    try {
        // Guardar Hero
        await fetch('/api/landing.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                section: 'hero',
                title: document.getElementById('hero_title').value,
                subtitle: '',
                content: {
                    description: document.getElementById('hero_description').value,
                    cta_text: document.getElementById('hero_cta_text').value,
                    cta_link: document.getElementById('hero_cta_link').value
                }
            })
        });
        
        // Guardar Features
        const features = [];
        document.querySelectorAll('#featuresContainer .feature-editor-item').forEach((item, index) => {
            features.push({
                icon: document.getElementById(`feature_${index}_icon`).value,
                color: document.getElementById(`feature_${index}_color`).value,
                title: document.getElementById(`feature_${index}_title`).value,
                description: document.getElementById(`feature_${index}_description`).value
            });
        });
        
        await fetch('/api/landing.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                section: 'features',
                title: 'Características Revolucionarias',
                subtitle: 'Tecnología de vanguardia al servicio de tu día a día',
                content: features
            })
        });
        
        // Guardar Technology
        const technology = [];
        document.querySelectorAll('#technologyContainer .feature-editor-item').forEach((item, index) => {
            technology.push({
                icon: document.getElementById(`tech_${index}_icon`).value,
                title: document.getElementById(`tech_${index}_title`).value,
                description: document.getElementById(`tech_${index}_description`).value
            });
        });
        
        await fetch('/api/landing.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                section: 'technology',
                title: 'Tecnología de Vanguardia',
                subtitle: '',
                content: technology
            })
        });
        
        // Guardar Experience
        const experience = [];
        document.querySelectorAll('#experienceContainer .feature-editor-item').forEach((item, index) => {
            experience.push({
                icon: document.getElementById(`exp_${index}_icon`).value,
                title: document.getElementById(`exp_${index}_title`).value,
                description: document.getElementById(`exp_${index}_description`).value
            });
        });
        
        await fetch('/api/landing.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                section: 'experience',
                title: 'Experiencia de Chat Revolucionaria',
                subtitle: 'Todo lo que necesitas en un solo lugar',
                content: experience
            })
        });
        
        Swal.fire('¡Guardado!', 'Contenido actualizado correctamente', 'success');
        btn.innerHTML = originalText;
        btn.disabled = false;
        
    } catch (error) {
        console.error('Error:', error);
        Swal.fire('Error', 'Error al guardar el contenido', 'error');
        btn.innerHTML = originalText;
        btn.disabled = false;
    }
}

// Roles y Permisos
let currentRoleId = null;

async function loadRolesAndPermissions() {
    await loadRolesList();
    await loadAllPermissions();
}

async function loadRolesList() {
    const response = await fetch('/api/roles.php?action=list');
    const data = await response.json();
    
    if (data.success) {
        renderRolesList(data.data);
    }
}

async function loadAllPermissions() {
    const response = await fetch('/api/roles.php?action=permissions');
    const data = await response.json();
    
    if (data.success) {
        window.allPermissions = data.data;
    }
}

function renderRolesList(roles) {
    const container = document.getElementById('rolesList');
    
    container.innerHTML = roles.map(role => `
        <div class="role-card ${currentRoleId === role.id ? 'active' : ''}" onclick="selectRole(${role.id})">
            <div class="role-header">
                <h3>${role.display_name}</h3>
                <div>
                    <span class="badge">${role.user_count} usuarios</span>
                    ${role.id !== 1 ? `
                        <button class="btn btn-secondary" onclick="event.stopPropagation(); editRole(${role.id})" style="padding: 5px 10px; font-size: 0.85rem; margin-left: 5px;">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-danger" onclick="event.stopPropagation(); deleteRole(${role.id}, ${role.user_count})" style="padding: 5px 10px; font-size: 0.85rem; margin-left: 5px;">
                            <i class="fas fa-trash"></i>
                        </button>
                    ` : ''}
                </div>
            </div>
            <p class="role-description">${role.description || 'Sin descripción'}</p>
            <div class="role-stats">
                <span><i class="fas fa-shield-alt"></i> ${role.permission_count} permisos</span>
            </div>
        </div>
    `).join('');
}

async function selectRole(roleId) {
    currentRoleId = roleId;
    
    // Actualizar UI
    document.querySelectorAll('.role-card').forEach(card => {
        card.classList.remove('active');
    });
    event.target.closest('.role-card').classList.add('active');
    
    // Cargar permisos del rol
    const response = await fetch(`/api/roles.php?action=role_permissions&role_id=${roleId}`);
    const data = await response.json();
    
    if (data.success) {
        renderRolePermissions(data.data);
    }
}

function renderRolePermissions(rolePermissions) {
    const container = document.getElementById('permissionsContent');
    const rolePermIds = rolePermissions.map(p => p.id);
    
    let html = '<form id="permissionsForm">';
    
    for (const [module, permissions] of Object.entries(window.allPermissions)) {
        html += `
            <div class="permissions-module">
                <h4>${translateModule(module)}</h4>
                <div class="permissions-grid">
        `;
        
        permissions.forEach(perm => {
            const checked = rolePermIds.includes(perm.id) ? 'checked' : '';
            html += `
                <label class="permission-checkbox">
                    <input type="checkbox" name="permission" value="${perm.id}" ${checked}>
                    <span>${perm.display_name}</span>
                </label>
            `;
        });
        
        html += `
                </div>
            </div>
        `;
    }
    
    html += `
        <button type="button" class="btn btn-primary" onclick="saveRolePermissions()">
            <i class="fas fa-save"></i> Guardar Permisos
        </button>
    </form>`;
    
    container.innerHTML = html;
}

async function saveRolePermissions() {
    if (!currentRoleId) return;
    
    const form = document.getElementById('permissionsForm');
    const checkboxes = form.querySelectorAll('input[name="permission"]:checked');
    const permissions = Array.from(checkboxes).map(cb => parseInt(cb.value));
    
    const response = await fetch('/api/roles.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            action: 'update_permissions',
            role_id: currentRoleId,
            permissions: permissions
        })
    });
    
    const data = await response.json();
    
    if (data.success) {
        Swal.fire('Éxito', 'Permisos actualizados correctamente', 'success');
        loadRolesList();
    } else {
        Swal.fire('Error', data.message, 'error');
    }
}

function translateModule(module) {
    const translations = {
        dashboard: 'Dashboard',
        admin: 'Administración',
        landing: 'Landing Page'
    };
    return translations[module] || module;
}

// Gestión de Roles
function initRoleModal() {
    document.getElementById('newRoleBtn').addEventListener('click', () => {
        openRoleModal();
    });
}

function openRoleModal(roleId = null) {
    const modal = document.getElementById('roleModal');
    const title = document.getElementById('roleModalTitle');
    
    document.getElementById('roleId').value = '';
    document.getElementById('roleName').value = '';
    document.getElementById('roleDisplayName').value = '';
    document.getElementById('roleDescription').value = '';
    
    if (roleId) {
        title.textContent = 'Editar Rol';
        loadRoleData(roleId);
    } else {
        title.textContent = 'Nuevo Rol';
    }
    
    modal.classList.add('active');
}

function closeRoleModal() {
    document.getElementById('roleModal').classList.remove('active');
}

async function loadRoleData(roleId) {
    const response = await fetch(`/api/roles.php?action=get_role&id=${roleId}`);
    const data = await response.json();
    
    if (data.success) {
        const role = data.data;
        document.getElementById('roleId').value = role.id;
        document.getElementById('roleName').value = role.name;
        document.getElementById('roleDisplayName').value = role.display_name;
        document.getElementById('roleDescription').value = role.description || '';
    }
}

async function saveRole() {
    const roleId = document.getElementById('roleId').value;
    const roleData = {
        name: document.getElementById('roleName').value,
        display_name: document.getElementById('roleDisplayName').value,
        description: document.getElementById('roleDescription').value
    };
    
    if (!roleData.name || !roleData.display_name) {
        Swal.fire('Error', 'Por favor completa los campos obligatorios', 'error');
        return;
    }
    
    const method = roleId ? 'PUT' : 'POST';
    if (roleId) roleData.id = roleId;
    
    const response = await fetch('/api/roles.php', {
        method: method,
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            action: roleId ? 'update_role' : 'create_role',
            ...roleData
        })
    });
    
    const data = await response.json();
    
    if (data.success) {
        Swal.fire('Éxito', roleId ? 'Rol actualizado correctamente' : 'Rol creado correctamente', 'success');
        closeRoleModal();
        loadRolesList();
    } else {
        Swal.fire('Error', data.message, 'error');
    }
}

function editRole(id) {
    openRoleModal(id);
}

function deleteRole(id, userCount) {
    if (id === 1) {
        Swal.fire('No permitido', 'No se puede eliminar el rol de Super Administrador', 'error');
        return;
    }
    
    if (userCount > 0) {
        Swal.fire('No permitido', `No se puede eliminar este rol porque tiene ${userCount} usuario(s) asignado(s)`, 'error');
        return;
    }
    
    Swal.fire({
        title: '¿Eliminar rol?',
        text: 'Esta acción no se puede deshacer',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, eliminar',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('/api/roles.php', {
                method: 'DELETE',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    action: 'delete_role',
                    id: id
                })
            }).then(r => r.json()).then(data => {
                if (data.success) {
                    Swal.fire('¡Eliminado!', 'Rol eliminado correctamente', 'success');
                    loadRolesList();
                    document.getElementById('permissionsContent').innerHTML = '';
                    currentRoleId = null;
                } else {
                    Swal.fire('Error', data.message, 'error');
                }
            });
        }
    });
}

// Selector de Iconos Font Awesome
const fontAwesomeIcons = [
    'fa-comments', 'fa-search', 'fa-reply', 'fa-history', 'fa-brain', 'fa-heart',
    'fa-microchip', 'fa-database', 'fa-chart-line', 'fa-mobile-alt', 'fa-globe',
    'fa-lock', 'fa-shield-alt', 'fa-cog', 'fa-users', 'fa-user', 'fa-envelope',
    'fa-phone', 'fa-calendar', 'fa-clock', 'fa-star', 'fa-bookmark', 'fa-tag',
    'fa-folder', 'fa-file', 'fa-image', 'fa-video', 'fa-music', 'fa-headphones',
    'fa-camera', 'fa-map', 'fa-compass', 'fa-rocket', 'fa-lightbulb', 'fa-bell',
    'fa-wifi', 'fa-bluetooth', 'fa-battery-full', 'fa-plug', 'fa-download', 'fa-upload',
    'fa-cloud', 'fa-server', 'fa-code', 'fa-terminal', 'fa-bug', 'fa-wrench',
    'fa-hammer', 'fa-paint-brush', 'fa-palette', 'fa-magic', 'fa-wand-magic', 'fa-fire',
    'fa-bolt', 'fa-sun', 'fa-moon', 'fa-snowflake', 'fa-umbrella', 'fa-coffee',
    'fa-pizza-slice', 'fa-utensils', 'fa-shopping-cart', 'fa-credit-card', 'fa-wallet',
    'fa-gift', 'fa-trophy', 'fa-medal', 'fa-crown', 'fa-gem', 'fa-key',
    'fa-fingerprint', 'fa-eye', 'fa-eye-slash', 'fa-check', 'fa-times', 'fa-plus',
    'fa-minus', 'fa-arrow-right', 'fa-arrow-left', 'fa-arrow-up', 'fa-arrow-down'
];

let currentIconInputId = null;

function openIconPicker(inputId) {
    currentIconInputId = inputId;
    const modal = document.getElementById('iconModal');
    const grid = document.getElementById('iconGrid');
    
    grid.innerHTML = fontAwesomeIcons.map(icon => `
        <div class="icon-item" onclick="selectIcon('${icon}')" style="
            padding: 15px;
            text-align: center;
            cursor: pointer;
            border: 2px solid var(--border);
            border-radius: 8px;
            transition: all 0.2s;
        " onmouseover="this.style.borderColor='var(--primary)'; this.style.background='var(--hover)';" 
           onmouseout="this.style.borderColor='var(--border)'; this.style.background='transparent';">
            <i class="fas ${icon}" style="font-size: 24px; color: var(--text);"></i>
            <div style="font-size: 10px; margin-top: 5px; color: var(--text-secondary);">${icon.replace('fa-', '')}</div>
        </div>
    `).join('');
    
    modal.classList.add('active');
    
    // Búsqueda de iconos
    document.getElementById('iconSearch').oninput = (e) => {
        const query = e.target.value.toLowerCase();
        const filtered = fontAwesomeIcons.filter(icon => icon.includes(query));
        grid.innerHTML = filtered.map(icon => `
            <div class="icon-item" onclick="selectIcon('${icon}')" style="
                padding: 15px;
                text-align: center;
                cursor: pointer;
                border: 2px solid var(--border);
                border-radius: 8px;
                transition: all 0.2s;
            " onmouseover="this.style.borderColor='var(--primary)'; this.style.background='var(--hover)';" 
               onmouseout="this.style.borderColor='var(--border)'; this.style.background='transparent';">
                <i class="fas ${icon}" style="font-size: 24px; color: var(--text);"></i>
                <div style="font-size: 10px; margin-top: 5px; color: var(--text-secondary);">${icon.replace('fa-', '')}</div>
            </div>
        `).join('');
    };
}

function selectIcon(icon) {
    if (currentIconInputId) {
        document.getElementById(currentIconInputId).value = icon;
    }
    closeIconModal();
}

function closeIconModal() {
    document.getElementById('iconModal').classList.remove('active');
    document.getElementById('iconSearch').value = '';
    currentIconInputId = null;
}

// Feedback de Usuarios
async function loadFeedback() {
    const status = document.getElementById('feedbackStatusFilter')?.value || 'all';
    const response = await fetch(`/api/feedback.php?status=${status}`);
    const data = await response.json();
    
    if (data.success) {
        renderFeedback(data.data);
    }
}

function renderFeedback(feedback) {
    const container = document.getElementById('feedbackGrid');
    
    if (feedback.length === 0) {
        container.innerHTML = '<div class="loading">No hay feedback</div>';
        return;
    }
    
    const typeIcons = {
        error: 'fa-bug',
        sugerencia: 'fa-lightbulb',
        mejora: 'fa-star',
        otro: 'fa-comment'
    };
    
    const typeColors = {
        error: '#ef4444',
        sugerencia: '#f59e0b',
        mejora: '#10b981',
        otro: '#6366f1'
    };
    
    container.innerHTML = feedback.map(item => {
        const statusColors = {
            new: '#f59e0b',
            reviewed: '#3b82f6',
            resolved: '#10b981'
        };
        const statusLabels = {
            new: 'Nuevo',
            reviewed: 'Revisado',
            resolved: 'Resuelto'
        };
        
        const typeColor = typeColors[item.feedback_type?.toLowerCase()] || '#6366f1';
        const typeIcon = typeIcons[item.feedback_type?.toLowerCase()] || 'fa-comment';
        
        return `
            <div style="
                background: white;
                border-radius: 12px;
                padding: 20px;
                border-left: 4px solid ${typeColor};
                box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                transition: transform 0.2s, box-shadow 0.2s;
            " onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.15)';" 
               onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 1px 3px rgba(0,0,0,0.1)';">
                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
                    <div style="flex: 1;">
                        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
                            <i class="fas ${typeIcon}" style="color: ${typeColor}; font-size: 18px;"></i>
                            <span style="
                                background: ${typeColor}15;
                                color: ${typeColor};
                                padding: 4px 12px;
                                border-radius: 20px;
                                font-size: 12px;
                                font-weight: 600;
                                text-transform: uppercase;
                            ">${item.feedback_type}</span>
                        </div>
                        <h3 style="font-size: 18px; color: #1e293b; margin-bottom: 8px; font-weight: 600;">${item.subject || 'Sin asunto'}</h3>
                        <div style="display: flex; gap: 16px; font-size: 13px; color: #64748b;">
                            <span><i class="fas fa-user"></i> ${item.user_name}</span>
                            <span><i class="fas fa-clock"></i> ${formatDate(item.created_at)}</span>
                        </div>
                    </div>
                    <span style="
                        background: ${statusColors[item.status]}15;
                        color: ${statusColors[item.status]};
                        padding: 6px 14px;
                        border-radius: 20px;
                        font-size: 12px;
                        font-weight: 600;
                        white-space: nowrap;
                    ">${statusLabels[item.status] || item.status}</span>
                </div>
                
                <p style="color: #475569; line-height: 1.6; margin-bottom: 16px;">${item.message}</p>
                
                ${item.admin_response ? `
                    <div style="
                        background: #f1f5f9;
                        padding: 12px 16px;
                        border-radius: 8px;
                        margin-bottom: 16px;
                        border-left: 3px solid #3b82f6;
                    ">
                        <div style="font-size: 12px; color: #64748b; margin-bottom: 6px; font-weight: 600;">
                            <i class="fas fa-reply"></i> RESPUESTA DEL ADMINISTRADOR
                        </div>
                        <p style="color: #334155; line-height: 1.5;">${item.admin_response}</p>
                    </div>
                ` : ''}
                
                <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                    ${item.status === 'new' ? `
                        <button class="btn btn-primary" onclick="respondFeedback(${item.id})" style="padding: 8px 16px; font-size: 14px;">
                            <i class="fas fa-reply"></i> Responder
                        </button>
                    ` : ''}
                    ${item.status !== 'reviewed' ? `
                        <button class="btn btn-secondary" onclick="updateFeedbackStatus(${item.id}, 'reviewed')" style="padding: 8px 16px; font-size: 14px;">
                            <i class="fas fa-eye"></i> Marcar revisado
                        </button>
                    ` : ''}
                    ${item.status !== 'resolved' ? `
                        <button class="btn btn-secondary" onclick="updateFeedbackStatus(${item.id}, 'resolved')" style="padding: 8px 16px; font-size: 14px; background: #10b981; color: white;">
                            <i class="fas fa-check"></i> Resolver
                        </button>
                    ` : ''}
                </div>
            </div>
        `;
    }).join('');
}

function respondFeedback(id) {
    Swal.fire({
        title: 'Responder Feedback',
        input: 'textarea',
        inputLabel: 'Tu respuesta',
        inputPlaceholder: 'Escribe tu respuesta...',
        showCancelButton: true,
        confirmButtonText: 'Enviar',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            updateFeedbackWithResponse(id, result.value);
        }
    });
}

async function updateFeedbackWithResponse(id, response) {
    const data = await fetch('/api/feedback.php', {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            id: id,
            status: 'reviewed',
            admin_response: response
        })
    }).then(r => r.json());
    
    if (data.success) {
        Swal.fire('Enviado', 'Respuesta guardada', 'success');
        loadFeedback();
    }
}

async function updateFeedbackStatus(id, status) {
    const data = await fetch('/api/feedback.php', {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ id, status })
    }).then(r => r.json());
    
    if (data.success) {
        loadFeedback();
    }
}

// Inicializar filtro de feedback
document.addEventListener('DOMContentLoaded', () => {
    const filter = document.getElementById('feedbackStatusFilter');
    if (filter) {
        filter.addEventListener('change', loadFeedback);
    }
});

// Downloads Management
async function loadDownloads() {
    const response = await fetch('/api/downloads.php');
    const data = await response.json();
    
    if (data.success && data.data) {
        renderDownloadsInfo(data.data);
        await loadVersionHistory();
    } else {
        document.getElementById('downloadsContent').innerHTML = '<div class="loading">No hay versión disponible</div>';
    }
}

async function loadVersionHistory() {
    const response = await fetch('/api/downloads.php?action=history');
    const data = await response.json();
    
    if (data.success && data.data.length > 0) {
        renderVersionHistory(data.data);
    }
}

function renderVersionHistory(versions) {
    const historyHtml = `
        <div style="background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-top: 20px;">
            <h3 style="font-size: 18px; color: #1e293b; margin-bottom: 16px; display: flex; align-items: center; gap: 10px;">
                <i class="fas fa-history" style="color: #2563eb;"></i>
                Historial de Versiones
            </h3>
            <div style="max-height: 300px; overflow-y: auto;">
                ${versions.map(v => `
                    <div style="padding: 12px; border-left: 3px solid ${v.status === 'active' ? '#10b981' : '#e2e8f0'}; margin-bottom: 12px; background: ${v.status === 'active' ? '#f0fdf4' : '#f8fafc'}; border-radius: 8px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong style="color: #1e293b;">v${v.version}</strong>
                                ${v.status === 'active' ? '<span style="background: #10b981; color: white; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 8px;">ACTIVA</span>' : ''}
                                <div style="font-size: 12px; color: #64748b; margin-top: 4px;">
                                    ${new Date(v.uploaded_at).toLocaleDateString('es-ES')} • ${(v.apk_size / (1024 * 1024)).toFixed(2)} MB • ${v.download_count || 0} descargas
                                </div>
                            </div>
                            ${v.status !== 'active' ? `
                                <button class="btn btn-secondary" onclick="rollbackVersion(${v.id})" style="padding: 6px 12px; font-size: 13px;">
                                    <i class="fas fa-undo"></i> Restaurar
                                </button>
                            ` : ''}
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;
    
    document.getElementById('downloadsContent').insertAdjacentHTML('beforeend', historyHtml);
}

async function rollbackVersion(id) {
    const result = await Swal.fire({
        title: '¿Restaurar versión?',
        text: 'Esta versión se activará y la actual se archivará',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Sí, restaurar',
        cancelButtonText: 'Cancelar'
    });
    
    if (result.isConfirmed) {
        const response = await fetch('/api/downloads.php', {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({rollback_id: id})
        });
        
        const data = await response.json();
        if (data.success) {
            Swal.fire('¡Restaurada!', 'Versión activada correctamente', 'success');
            loadDownloads();
        }
    }
}

function renderDownloadsInfo(app) {
    const sizeMB = (app.apk_size / (1024 * 1024)).toFixed(2);
    const date = new Date(app.uploaded_at).toLocaleDateString('es-ES', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    document.getElementById('downloadsContent').innerHTML = `
        <div style="display: grid; gap: 20px;">
            <div style="background: white; padding: 30px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <div style="display: flex; justify-content: space-between; align-items: start; flex-wrap: wrap; gap: 20px;">
                    <div>
                        <div style="font-size: 14px; color: #64748b; margin-bottom: 8px; font-weight: 600;">VERSIÓN ACTUAL</div>
                        <div style="font-size: 48px; font-weight: 700; color: #2563eb; margin-bottom: 10px;">v${app.version}</div>
                        <div style="color: #64748b;"><i class="fas fa-calendar"></i> ${date}</div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-size: 32px; font-weight: 700; color: #10b981;">${app.download_count || 0}</div>
                        <div style="color: #64748b;">Descargas</div>
                    </div>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
                <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    <i class="fas fa-file-archive" style="font-size: 32px; color: #2563eb; margin-bottom: 12px;"></i>
                    <div style="font-size: 12px; color: #64748b; margin-bottom: 4px;">Archivo</div>
                    <div style="font-size: 14px; font-weight: 600; color: #1e293b; word-break: break-all;">${app.apk_filename}</div>
                </div>
                
                <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    <i class="fas fa-hdd" style="font-size: 32px; color: #10b981; margin-bottom: 12px;"></i>
                    <div style="font-size: 12px; color: #64748b; margin-bottom: 4px;">Tamaño</div>
                    <div style="font-size: 16px; font-weight: 600; color: #1e293b;">${sizeMB} MB</div>
                </div>
                
                <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    <i class="fas fa-link" style="font-size: 32px; color: #f59e0b; margin-bottom: 12px;"></i>
                    <div style="font-size: 12px; color: #64748b; margin-bottom: 4px;">Enlace público</div>
                    <a href="/download.html" target="_blank" style="font-size: 14px; color: #2563eb; text-decoration: none; font-weight: 600;">
                        Ver página <i class="fas fa-external-link-alt" style="font-size: 12px;"></i>
                    </a>
                </div>
            </div>
            
            ${app.release_notes ? `
                <div style="background: white; padding: 24px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    <h3 style="font-size: 18px; color: #1e293b; margin-bottom: 16px; display: flex; align-items: center; gap: 10px;">
                        <i class="fas fa-clipboard-list" style="color: #2563eb;"></i>
                        Notas de la versión
                    </h3>
                    <p style="color: #475569; line-height: 1.6; white-space: pre-line;">${app.release_notes}</p>
                </div>
            ` : ''}
        </div>
    `;
}

function openUploadModal() {
    document.getElementById('uploadModal').classList.add('active');
    document.getElementById('uploadForm').reset();
}

function closeUploadModal() {
    document.getElementById('uploadModal').classList.remove('active');
}

async function uploadAPK() {
    const version = document.getElementById('appVersion').value;
    const file = document.getElementById('apkFile').files[0];
    const notes = document.getElementById('releaseNotes').value;
    
    if (!version || !file) {
        Swal.fire('Error', 'Por favor completa todos los campos obligatorios', 'error');
        return;
    }
    
    const formData = new FormData();
    formData.append('apk', file);
    formData.append('version', version);
    formData.append('release_notes', notes);
    
    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Subiendo...';
    
    try {
        const response = await fetch('/api/downloads.php', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            Swal.fire('¡Éxito!', 'APK subido correctamente', 'success');
            closeUploadModal();
            loadDownloads();
        } else {
            Swal.fire('Error', data.message, 'error');
        }
    } catch (error) {
        Swal.fire('Error', 'Error al subir el archivo', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-upload"></i> Subir';
    }
}

// Cargar script de anuncios
const originalLoadPageData = loadPageData;
loadPageData = function(page) {
    if (page === 'announcements') {
        loadAnnouncements();
    } else {
        originalLoadPageData(page);
    }
};
