// Navigation
document.querySelectorAll('.nav-item').forEach(item => {
    item.addEventListener('click', () => {
        const page = item.dataset.page;
        document.querySelectorAll('.nav-item').forEach(nav => nav.classList.remove('active'));
        item.classList.add('active');
        document.querySelectorAll('.page').forEach(p => p.style.display = 'none');
        const pageElement = document.getElementById(page + '-page');
        if (pageElement) pageElement.style.display = 'block';
        const titles = {'dashboard': 'Dashboard Overview', 'restore': 'Restore Actions', 'backups': 'Backup Management', 'settings': 'Platform Settings'};
        const titleElement = document.getElementById('page-title');
        if (titleElement) titleElement.textContent = titles[page];
    });
});

function checkServerStatus() {
    fetch('/server/status')
        .then(res => res.json())
        .then(data => {
            const statusText = document.getElementById('server-status-text');
            const statusDot = document.getElementById('server-status-dot');
            if (statusText && statusDot) {
                if (data.status === 'online') {
                    statusText.innerHTML = data.info;
                    statusDot.className = 'status-dot online';
                } else {
                    statusText.innerHTML = 'Offline';
                    statusDot.className = 'status-dot offline';
                }
            }
        })
        .catch(() => {
            const statusText = document.getElementById('server-status-text');
            const statusDot = document.getElementById('server-status-dot');
            if (statusText) statusText.innerHTML = 'Connection Failed';
            if (statusDot) statusDot.className = 'status-dot offline';
        });
}

// Backup functionality
let backupEventSource = null;

window.runBackupNow = function() {
    if(confirm('⚠️ Run backup now? This will take a few minutes.')) {
        const progressDiv = document.getElementById('backup-progress');
        const progressBar = document.getElementById('backup-progress-bar');
        const logDiv = document.getElementById('backup-log');
        const runBtn = document.getElementById('runBackupBtn');
        
        if (progressDiv) progressDiv.style.display = 'block';
        if (runBtn) {
            runBtn.disabled = true;
            runBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Running Backup...';
        }
        if (logDiv) logDiv.innerHTML = '';
        
        fetch('/backup/run')
            .then(res => res.json())
            .then(data => {
                if (data.error) throw new Error(data.error);
                
                if (backupEventSource) backupEventSource.close();
                backupEventSource = new EventSource('/backup/stream');
                
                backupEventSource.onmessage = function(event) {
                    const data = JSON.parse(event.data);
                    if (logDiv) {
                        const line = document.createElement('div');
                        line.textContent = data.line;
                        logDiv.appendChild(line);
                        logDiv.scrollTop = logDiv.scrollHeight;
                    }
                    
                    if (data.complete) {
                        backupEventSource.close();
                        if (progressBar) progressBar.style.width = '100%';
                        setTimeout(() => {
                            if (progressDiv) progressDiv.style.display = 'none';
                            if (runBtn) {
                                runBtn.disabled = false;
                                runBtn.innerHTML = '<i class="fas fa-play"></i> Run Backup Now';
                            }
                            refreshStatus();
                        }, 2000);
                    }
                };
            })
            .catch(err => {
                if (logDiv) logDiv.innerHTML = `<div style="color: red;">❌ Error: ${err.message}</div>`;
                if (runBtn) {
                    runBtn.disabled = false;
                    runBtn.innerHTML = '<i class="fas fa-play"></i> Run Backup Now';
                }
            });
    }
};

window.restoreLocal = function() {
    const backup = document.getElementById('local-backup');
    if (!backup) return;
    const backupValue = backup.value;
    if(confirm('⚠️ Restore from ' + backupValue.split('/').pop() + '?\n\nThis will overwrite current data on this server!')) {
        const statusDiv = document.getElementById('restore-status');
        if (statusDiv) {
            statusDiv.style.display = 'block';
            statusDiv.className = 'restore-status warning';
            statusDiv.innerHTML = '<p>🔄 Starting restore from local backup...</p>';
        }
        
        fetch('/restore/local?backup=' + encodeURIComponent(backupValue))
            .then(res => res.json())
            .then(data => {
                if (statusDiv) {
                    if (data.error) {
                        statusDiv.className = 'restore-status error';
                        statusDiv.innerHTML = '<p>❌ ' + data.error + '</p>';
                    } else {
                        statusDiv.className = 'restore-status success';
                        statusDiv.innerHTML = '<p>✅ ' + data.status + '</p>';
                    }
                }
            })
            .catch(err => {
                if (statusDiv) {
                    statusDiv.className = 'restore-status error';
                    statusDiv.innerHTML = '<p>❌ Restore failed: ' + err + '</p>';
                }
            });
    }
};

window.disasterRestore = function() {
    const backupFile = document.getElementById('vm-backup-select').value;
    const targetIp = document.getElementById('target-ip').value;
    const targetUser = document.getElementById('target-user').value || 'root';
    const targetPassword = document.getElementById('target-password').value;
    
    if (!targetIp) {
        alert('Please enter target server IP');
        return;
    }
    
    if(confirm(`⚠️ DISASTER RESTORE to ${targetIp}\n\nBackup: ${backupFile.split('/').pop()}\n\nThis will OVERWRITE containers on the target server! Continue?`)) {
        const statusDiv = document.getElementById('disaster-status');
        if (statusDiv) {
            statusDiv.style.display = 'block';
            statusDiv.className = 'restore-status warning';
            statusDiv.innerHTML = '<p>🔄 Starting disaster restore to ' + targetIp + '...</p>';
        }
        
        fetch('/disaster/restore', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                backup_file: backupFile,
                target_ip: targetIp,
                target_user: targetUser,
                target_password: targetPassword
            })
        })
        .then(res => res.json())
        .then(data => {
            if (statusDiv) {
                if (data.error) {
                    statusDiv.className = 'restore-status error';
                    statusDiv.innerHTML = '<p>❌ ' + data.error + '</p>';
                } else {
                    statusDiv.className = 'restore-status success';
                    statusDiv.innerHTML = '<p>✅ ' + data.status + '<br>Target: ' + data.target + '</p>';
                }
            }
        })
        .catch(err => {
            if (statusDiv) {
                statusDiv.className = 'restore-status error';
                statusDiv.innerHTML = '<p>❌ Restore failed: ' + err + '</p>';
            }
        });
    }
};

window.refreshStatus = function() { location.reload(); };
window.refreshAll = function() { fetch('/server/status').then(() => location.reload()); };

// Add backup panel to Backups page
document.addEventListener('DOMContentLoaded', () => {
    checkServerStatus();
    
    const backupsNav = document.querySelector('.nav-item[data-page="backups"]');
    if (backupsNav) {
        backupsNav.addEventListener('click', () => {
            setTimeout(() => {
                if (document.getElementById('backup-panel')) return;
                const backupsPage = document.getElementById('backups-page');
                if (backupsPage) {
                    const backupPanel = document.createElement('div');
                    backupPanel.id = 'backup-panel';
                    backupPanel.className = 'card';
                    backupPanel.innerHTML = `
                        <div class="card-header"><div class="card-title"><span>📦</span><span>Manual Backup</span></div></div>
                        <div style="padding: 20px; background: var(--primary-soft); border-radius: 12px;">
                            <h3 style="margin-bottom: 10px;">Run Backup Now</h3>
                            <p style="color: var(--gray); margin-bottom: 15px;">Manually trigger a backup of all containers</p>
                            <button id="runBackupBtn" class="btn btn-primary" onclick="runBackupNow()"><i class="fas fa-play"></i> Run Backup Now</button>
                            <div id="backup-progress" style="display: none; margin-top: 15px;">
                                <div style="background: var(--gray-light); border-radius: 10px; overflow: hidden;"><div id="backup-progress-bar" style="width: 0%; height: 20px; background: var(--success); transition: width 0.3s;"></div></div>
                                <div id="backup-log" style="margin-top: 10px; max-height: 200px; overflow-y: auto; background: #1e1e1e; color: #d4d4d4; padding: 10px; border-radius: 8px; font-family: monospace; font-size: 11px;"></div>
                            </div>
                        </div>
                    `;
                    backupsPage.insertBefore(backupPanel, backupsPage.firstChild);
                }
            }, 100);
        });
    }
});
