/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * This file is part of Cast Conductor ("Software"). The Software and its source
 * code constitute proprietary, confidential, and trade secret information of
 * CastConductor.com ("Company"). Any access or use is governed strictly by the
 * Cast Conductor Proprietary License v5 ("License"). By installing, copying,
 * accessing, compiling, or otherwise using the Software you agree to be bound by
 * all terms of the License. If you do not agree, you must cease use immediately.
 * 
 * Key Terms (Summary – see full License for binding terms):
 *  1. No Redistribution: You may not publish, distribute, sublicense, rent,
 *     lease, transfer, sell, or otherwise make the Software (or any derivative)
 *     available to any third party without prior written consent of Company.
 *  2. No Modification: Modification, reverse engineering, decompilation, or
 *     disassembly is prohibited except to the limited extent expressly permitted
 *     by applicable law that cannot be contractually waived.
 *  3. Confidentiality: Treat all source code and related artifacts as Company
 *     Confidential Information. Maintain at least the same degree of care as for
 *     your own confidential materials, and not less than reasonable care.
 *  4. No Patent License: No express or implied patent rights are granted. Future
 *     patents (if any) are fully reserved.
 *  5. No Trademark License: Company names, marks, and logos may not be used
 *     without prior written permission.
 *  6. Limited Internal Use: Use is limited solely to internal evaluation and
 *     operation of licensed Cast Conductor deployments. Commercial hosting or
 *     resale as a service requires a separate written agreement.
 *  7. Telemetry & License Validation: The Software may periodically transmit a
 *     hashed installation identifier, domain (or site ID), plugin/app version,
 *     and a truncated (non-reversible) fragment of the license key solely to
 *     validate activation status and enforce licensing. This minimal "phone home"
 *     check contains no personal or content data. If optional telemetry is later
 *     introduced it will be limited to aggregate operational metrics (no PII),
 *     fully documented, and optionally disableable per published instructions.
 *  8. Third-Party Components: The Software may include open source components
 *     covered by their own licenses. See THIRD-PARTY-NOTICES.md. Those licenses
 *     govern their respective components; this License governs all remaining code.
 *  9. Export Compliance: You are responsible for compliance with all applicable
 *     export control and sanctions laws.
 * 10. Warranty Disclaimer: THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF
 *     ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY,
 *     FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 * 11. Limitation of Liability: IN NO EVENT WILL COMPANY OR AUTHORS BE LIABLE FOR
 *     ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE
 *     DAMAGES, OR LOST PROFITS, EVEN IF ADVISED OF THE POSSIBILITY.
 * 12. Acceptance: Use of the Software constitutes acceptance of the License.
 * 13. Enforcement: Unauthorized reproduction or distribution may result in civil
 *     and criminal penalties and will be prosecuted to the maximum extent allowed
 *     by law.
 * 
 * Authoritative EULA: EULA-v5.1.md (repository root – private) and https://castconductor.com/eula
 * Precedence: If this summary conflicts with the EULA, the EULA governs.
 * Revision: Current EULA revision v5.1 (subject to update; check EULA for current enterprise thresholds).
 * 
 * Full License text available from: licensing@castconductor.com
 * Security reports: security@castconductor.com
 * Commercial inquiries: licensing@castconductor.com
 * 
 * END OF HEADER
 */
class CastConductorConfigurationBackup {
    constructor() {
        this.currentPage = 1;
        this.perPage = 10;
        this.selectedBackups = new Set();
        this.settings = {};
        this.refreshInterval = null;
        
        this.init();
    }

    /**
     * Initialize the backup interface
     */
    init() {
        this.loadBackupSettings();
        this.setupEventListeners();
        this.loadBackupList();
        this.setupAutoRefresh();
    }

    /**
     * Setup event listeners
     */
    setupEventListeners() {
        // Create backup button
        const createBackupBtn = document.getElementById('create-backup-btn');
        if (createBackupBtn) {
            createBackupBtn.addEventListener('click', () => {
                this.showCreateBackupModal();
            });
        }

        // Import backup button
        const importBackupBtn = document.getElementById('import-backup-btn');
        if (importBackupBtn) {
            importBackupBtn.addEventListener('click', () => {
                this.showImportBackupModal();
            });
        }

        // Export configuration button
        const exportConfigBtn = document.getElementById('export-config-btn');
        if (exportConfigBtn) {
            exportConfigBtn.addEventListener('click', () => {
                this.showExportConfigModal();
            });
        }

        // Backup actions
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('restore-backup')) {
                const backupId = e.target.dataset.backupId;
                this.showRestoreModal(backupId);
            } else if (e.target.classList.contains('download-backup')) {
                const backupId = e.target.dataset.backupId;
                this.downloadBackup(backupId);
            } else if (e.target.classList.contains('delete-backup')) {
                const backupId = e.target.dataset.backupId;
                this.showDeleteModal(backupId);
            } else if (e.target.classList.contains('view-backup-details')) {
                const backupId = e.target.dataset.backupId;
                this.showBackupDetails(backupId);
            }
        });

        // Settings form
        const settingsForm = document.getElementById('backup-settings-form');
        if (settingsForm) {
            settingsForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveBackupSettings();
            });
        }

        // Test automated backup
        const testBackupBtn = document.getElementById('test-automated-backup');
        if (testBackupBtn) {
            testBackupBtn.addEventListener('click', () => {
                this.testAutomatedBackup();
            });
        }

        // Refresh button
        const refreshBtn = document.getElementById('refresh-backups-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.refreshBackupList();
            });
        }

        // Auto-refresh toggle
        const autoRefreshToggle = document.getElementById('auto-refresh-backups');
        if (autoRefreshToggle) {
            autoRefreshToggle.addEventListener('change', (e) => {
                if (e.target.checked) {
                    this.setupAutoRefresh();
                } else {
                    this.clearAutoRefresh();
                }
            });
        }

        // File upload handlers
        const backupFileInput = document.getElementById('backup-file-input');
        if (backupFileInput) {
            backupFileInput.addEventListener('change', (e) => {
                this.handleBackupFileUpload(e);
            });
        }

        const configFileInput = document.getElementById('config-file-input');
        if (configFileInput) {
            configFileInput.addEventListener('change', (e) => {
                this.handleConfigFileUpload(e);
            });
        }
    }

    /**
     * Load backup list
     */
    async loadBackupList() {
        try {
            this.showLoader('Loading backups...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/list`,
                {
                    method: 'GET',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    }
                }
            );

            const data = await response.json();
            if (data.success) {
                this.renderBackupList(data.backups);
                this.updateBackupStats(data.backups);
            } else {
                this.showNotification('Failed to load backups', 'error');
            }
        } catch (error) {
            console.error('Failed to load backups:', error);
            this.showNotification('Failed to load backups', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Render backup list
     */
    renderBackupList(backups) {
        const container = document.getElementById('backup-list');
        if (!container) return;

        if (backups.length === 0) {
            container.innerHTML = `
                <div class="no-backups">
                    <div class="dashicons dashicons-backup"></div>
                    <h3>No backups found</h3>
                    <p>Create your first backup to protect your CastConductor configuration.</p>
                    <button type="button" class="button button-primary" onclick="castconductorConfigBackup.showCreateBackupModal()">
                        Create First Backup
                    </button>
                </div>
            `;
            return;
        }

        container.innerHTML = backups.map(backup => `
            <div class="backup-item" data-backup-id="${backup.id}">
                <div class="backup-header">
                    <div class="backup-info">
                        <h4 class="backup-name">${this.escapeHtml(backup.name)}</h4>
                        <div class="backup-meta">
                            <span class="backup-id">#${backup.id}</span>
                            <span class="backup-date">${this.formatDate(backup.created_at)}</span>
                            <span class="backup-size">${backup.size_formatted}</span>
                            ${backup.includes.imported ? '<span class="backup-imported">Imported</span>' : ''}
                        </div>
                    </div>
                    <div class="backup-status">
                        <span class="status-badge status-${backup.status}">${backup.status}</span>
                    </div>
                </div>

                <div class="backup-includes">
                    ${this.renderBackupIncludes(backup.includes)}
                </div>

                <div class="backup-actions">
                    <button type="button" class="button button-secondary view-backup-details" data-backup-id="${backup.id}">
                        <span class="dashicons dashicons-visibility"></span> Details
                    </button>
                    <button type="button" class="button button-primary restore-backup" data-backup-id="${backup.id}">
                        <span class="dashicons dashicons-update"></span> Restore
                    </button>
                    <button type="button" class="button button-secondary download-backup" data-backup-id="${backup.id}">
                        <span class="dashicons dashicons-download"></span> Download
                    </button>
                    <button type="button" class="button button-link-delete delete-backup" data-backup-id="${backup.id}">
                        <span class="dashicons dashicons-trash"></span> Delete
                    </button>
                </div>
            </div>
        `).join('');
    }

    /**
     * Render backup includes
     */
    renderBackupIncludes(includes) {
        const items = [];
        
        if (includes.content) items.push('<span class="include-item">Content Blocks</span>');
        if (includes.settings) items.push('<span class="include-item">Settings</span>');
        if (includes.containers) items.push('<span class="include-item">Containers</span>');

        return `<div class="backup-includes-list">${items.join('')}</div>`;
    }

    /**
     * Update backup statistics
     */
    updateBackupStats(backups) {
        const totalBackups = backups.length;
        const totalSize = backups.reduce((sum, backup) => sum + backup.size, 0);
        const latestBackup = backups[0];

        // Update stats display
        const statsContainer = document.getElementById('backup-stats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <span class="stat-number">${totalBackups}</span>
                    <span class="stat-label">Total Backups</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${this.formatBytes(totalSize)}</span>
                    <span class="stat-label">Total Size</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number">${latestBackup ? this.formatDate(latestBackup.created_at) : 'None'}</span>
                    <span class="stat-label">Latest Backup</span>
                </div>
            `;
        }
    }

    /**
     * Show create backup modal
     */
    showCreateBackupModal() {
        const modal = document.getElementById('create-backup-modal');
        if (modal) {
            // Reset form
            const form = modal.querySelector('#create-backup-form');
            if (form) form.reset();

            modal.style.display = 'block';
        }
    }

    /**
     * Create backup
     */
    async createBackup() {
        try {
            const form = document.getElementById('create-backup-form');
            const formData = new FormData(form);

            const backupData = {
                name: formData.get('backup_name') || 'Manual Backup',
                include_content: formData.get('include_content') === 'on',
                include_settings: formData.get('include_settings') === 'on',
                include_containers: formData.get('include_containers') === 'on'
            };

            this.showLoader('Creating backup...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/create`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: JSON.stringify(backupData)
                }
            );

            const data = await response.json();
            if (data.success) {
                this.showNotification(`Backup "${data.backup_name}" created successfully`, 'success');
                this.hideModal('create-backup-modal');
                this.loadBackupList();
            } else {
                this.showNotification('Failed to create backup', 'error');
            }
        } catch (error) {
            console.error('Failed to create backup:', error);
            this.showNotification('Failed to create backup', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Show restore modal
     */
    async showRestoreModal(backupId) {
        try {
            // Get backup details first
            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/${backupId}`,
                {
                    method: 'GET',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    }
                }
            );

            const data = await response.json();
            if (!data.success) {
                this.showNotification('Failed to load backup details', 'error');
                return;
            }

            const modal = document.getElementById('restore-backup-modal');
            if (modal) {
                // Update modal content with backup details
                const backupName = modal.querySelector('#restore-backup-name');
                const backupDate = modal.querySelector('#restore-backup-date');
                const backupStats = modal.querySelector('#restore-backup-stats');
                const confirmBtn = modal.querySelector('#confirm-restore-backup');

                if (backupName) backupName.textContent = data.backup.meta.name;
                if (backupDate) backupDate.textContent = this.formatDate(data.backup.meta.created_at);
                if (backupStats) {
                    backupStats.innerHTML = `
                        <div class="restore-stat">Content Blocks: ${data.backup.stats.content_blocks}</div>
                        <div class="restore-stat">Settings: ${data.backup.stats.settings}</div>
                        <div class="restore-stat">Containers: ${data.backup.stats.containers}</div>
                    `;
                }

                if (confirmBtn) {
                    confirmBtn.onclick = () => this.restoreBackup(backupId);
                }

                modal.style.display = 'block';
            }
        } catch (error) {
            console.error('Failed to show restore modal:', error);
            this.showNotification('Failed to load backup details', 'error');
        }
    }

    /**
     * Restore backup
     */
    async restoreBackup(backupId) {
        try {
            const form = document.getElementById('restore-backup-form');
            const formData = new FormData(form);

            const restoreData = {
                restore_content: formData.get('restore_content') === 'on',
                restore_settings: formData.get('restore_settings') === 'on',
                restore_containers: formData.get('restore_containers') === 'on',
                create_restore_point: formData.get('create_restore_point') === 'on'
            };

            this.showLoader('Restoring backup...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/${backupId}/restore`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: JSON.stringify(restoreData)
                }
            );

            const data = await response.json();
            if (data.success) {
                let message = 'Backup restored successfully';
                if (data.restore_point) {
                    message += `. Restore point created: ${data.restore_point}`;
                }
                this.showNotification(message, 'success');
                this.hideModal('restore-backup-modal');
                this.loadBackupList();
            } else {
                this.showNotification('Failed to restore backup', 'error');
            }
        } catch (error) {
            console.error('Failed to restore backup:', error);
            this.showNotification('Failed to restore backup', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Download backup
     */
    async downloadBackup(backupId) {
        try {
            const url = `${castconductorBackupAjax.rest_url}castconductor/v5/backup/${backupId}/download`;
            
            // Create temporary link for download
            const link = document.createElement('a');
            link.href = url;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            this.showNotification('Download started', 'success');
        } catch (error) {
            console.error('Failed to download backup:', error);
            this.showNotification('Failed to download backup', 'error');
        }
    }

    /**
     * Show delete modal
     */
    showDeleteModal(backupId) {
        const modal = document.getElementById('delete-backup-modal');
        if (modal) {
            const confirmBtn = modal.querySelector('#confirm-delete-backup');
            if (confirmBtn) {
                confirmBtn.onclick = () => this.deleteBackup(backupId);
            }
            modal.style.display = 'block';
        }
    }

    /**
     * Delete backup
     */
    async deleteBackup(backupId) {
        try {
            this.showLoader('Deleting backup...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/${backupId}`,
                {
                    method: 'DELETE',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    }
                }
            );

            const data = await response.json();
            if (data.success) {
                this.showNotification('Backup deleted successfully', 'success');
                this.hideModal('delete-backup-modal');
                this.loadBackupList();
            } else {
                this.showNotification('Failed to delete backup', 'error');
            }
        } catch (error) {
            console.error('Failed to delete backup:', error);
            this.showNotification('Failed to delete backup', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Show backup details
     */
    async showBackupDetails(backupId) {
        try {
            this.showLoader('Loading backup details...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/${backupId}`,
                {
                    method: 'GET',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    }
                }
            );

            const data = await response.json();
            if (data.success) {
                this.renderBackupDetailsModal(data.backup);
            } else {
                this.showNotification('Failed to load backup details', 'error');
            }
        } catch (error) {
            console.error('Failed to load backup details:', error);
            this.showNotification('Failed to load backup details', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Render backup details modal
     */
    renderBackupDetailsModal(backup) {
        const modal = document.getElementById('backup-details-modal');
        if (!modal) return;

        const content = modal.querySelector('.backup-details-content');
        if (content) {
            content.innerHTML = `
                <div class="backup-detail-section">
                    <h4>General Information</h4>
                    <table class="backup-details-table">
                        <tr><td><strong>Name:</strong></td><td>${this.escapeHtml(backup.meta.name)}</td></tr>
                        <tr><td><strong>ID:</strong></td><td>${backup.meta.id}</td></tr>
                        <tr><td><strong>Created:</strong></td><td>${this.formatDate(backup.meta.created_at)}</td></tr>
                        <tr><td><strong>Size:</strong></td><td>${backup.size_formatted}</td></tr>
                        <tr><td><strong>Version:</strong></td><td>${backup.meta.version}</td></tr>
                        <tr><td><strong>WordPress:</strong></td><td>${backup.meta.wp_version}</td></tr>
                        <tr><td><strong>PHP:</strong></td><td>${backup.meta.php_version}</td></tr>
                        <tr><td><strong>Site URL:</strong></td><td>${backup.meta.site_url}</td></tr>
                    </table>
                </div>

                <div class="backup-detail-section">
                    <h4>Content Statistics</h4>
                    <table class="backup-details-table">
                        <tr><td><strong>Content Blocks:</strong></td><td>${backup.stats.content_blocks}</td></tr>
                        <tr><td><strong>Containers:</strong></td><td>${backup.stats.containers}</td></tr>
                        <tr><td><strong>Settings:</strong></td><td>${backup.stats.settings}</td></tr>
                    </table>
                </div>

                <div class="backup-detail-section">
                    <h4>Included Components</h4>
                    <div class="included-components">
                        ${backup.meta.includes.content ? '<span class="component-included">✓ Content Blocks</span>' : '<span class="component-excluded">✗ Content Blocks</span>'}
                        ${backup.meta.includes.settings ? '<span class="component-included">✓ Settings</span>' : '<span class="component-excluded">✗ Settings</span>'}
                        ${backup.meta.includes.containers ? '<span class="component-included">✓ Containers</span>' : '<span class="component-excluded">✗ Containers</span>'}
                    </div>
                </div>
            `;
        }

        modal.style.display = 'block';
    }

    /**
     * Load backup settings
     */
    async loadBackupSettings() {
        try {
            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/settings`,
                {
                    method: 'GET',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    }
                }
            );

            const data = await response.json();
            if (data.success) {
                this.settings = data.settings;
                this.populateSettingsForm(data.settings);
            }
        } catch (error) {
            console.error('Failed to load backup settings:', error);
        }
    }

    /**
     * Populate settings form
     */
    populateSettingsForm(settings) {
        const form = document.getElementById('backup-settings-form');
        if (!form) return;

        // Set checkbox values
        const checkboxes = {
            'automated-enabled': settings.automated_enabled,
            'include-content': settings.include_content,
            'include-settings': settings.include_settings,
            'include-containers': settings.include_containers,
            'email-notifications': settings.email_notifications
        };

        Object.entries(checkboxes).forEach(([id, value]) => {
            const checkbox = document.getElementById(id);
            if (checkbox) {
                checkbox.checked = value;
            }
        });

        // Set select values
        const frequency = document.getElementById('automated-frequency');
        if (frequency) {
            frequency.value = settings.automated_frequency || 'weekly';
        }

        // Set text/number values
        const fields = {
            'automated-time': settings.automated_time,
            'retention-days': settings.retention_days,
            'max-backups': settings.max_backups,
            'notification-email': settings.notification_email
        };

        Object.entries(fields).forEach(([id, value]) => {
            const field = document.getElementById(id);
            if (field && value !== undefined) {
                field.value = value;
            }
        });
    }

    /**
     * Save backup settings
     */
    async saveBackupSettings() {
        try {
            const form = document.getElementById('backup-settings-form');
            const formData = new FormData(form);

            const settings = {
                automated_enabled: formData.get('automated_enabled') === 'on',
                automated_frequency: formData.get('automated_frequency'),
                automated_time: formData.get('automated_time'),
                retention_days: parseInt(formData.get('retention_days')),
                max_backups: parseInt(formData.get('max_backups')),
                include_content: formData.get('include_content') === 'on',
                include_settings: formData.get('include_settings') === 'on',
                include_containers: formData.get('include_containers') === 'on',
                email_notifications: formData.get('email_notifications') === 'on',
                notification_email: formData.get('notification_email')
            };

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/settings`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: JSON.stringify(settings)
                }
            );

            const data = await response.json();
            if (data.success) {
                this.showNotification('Backup settings saved successfully', 'success');
                this.settings = settings;
            } else {
                this.showNotification('Failed to save backup settings', 'error');
            }
        } catch (error) {
            console.error('Failed to save backup settings:', error);
            this.showNotification('Failed to save backup settings', 'error');
        }
    }

    /**
     * Handle backup file upload
     */
    async handleBackupFileUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        try {
            this.showLoader('Importing backup...');

            const formData = new FormData();
            formData.append('backup_file', file);

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/upload`,
                {
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: formData
                }
            );

            const data = await response.json();
            if (data.success) {
                this.showNotification(`Backup imported successfully: ${data.backup_name}`, 'success');
                this.hideModal('import-backup-modal');
                this.loadBackupList();
            } else {
                this.showNotification('Failed to import backup', 'error');
            }
        } catch (error) {
            console.error('Failed to import backup:', error);
            this.showNotification('Failed to import backup', 'error');
        } finally {
            this.hideLoader();
            event.target.value = ''; // Reset file input
        }
    }

    /**
     * Handle config file upload
     */
    async handleConfigFileUpload(event) {
        const file = event.target.files[0];
        if (!file) return;

        try {
            this.showLoader('Importing configuration...');

            const formData = new FormData();
            formData.append('config_file', file);

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/import`,
                {
                    method: 'POST',
                    headers: {
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: formData
                }
            );

            const data = await response.json();
            if (data.success) {
                const items = Object.entries(data.imported_items).map(([key, count]) => `${count} ${key}`).join(', ');
                this.showNotification(`Configuration imported successfully: ${items}`, 'success');
                this.hideModal('import-config-modal');
                this.loadBackupList();
            } else {
                this.showNotification('Failed to import configuration', 'error');
            }
        } catch (error) {
            console.error('Failed to import configuration:', error);
            this.showNotification('Failed to import configuration', 'error');
        } finally {
            this.hideLoader();
            event.target.value = ''; // Reset file input
        }
    }

    /**
     * Show export config modal
     */
    showExportConfigModal() {
        const modal = document.getElementById('export-config-modal');
        if (modal) {
            modal.style.display = 'block';
        }
    }

    /**
     * Export configuration
     */
    async exportConfiguration() {
        try {
            const form = document.getElementById('export-config-form');
            const formData = new FormData(form);

            const exportData = {
                export_type: formData.get('export_type') || 'complete'
            };

            this.showLoader('Generating export...');

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/export`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: JSON.stringify(exportData)
                }
            );

            const data = await response.json();
            if (data.success) {
                // Trigger download
                const blob = new Blob([JSON.stringify(data.export_data, null, 2)], {
                    type: 'application/json'
                });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = data.filename;
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);

                this.showNotification('Configuration exported successfully', 'success');
                this.hideModal('export-config-modal');
            } else {
                this.showNotification('Failed to export configuration', 'error');
            }
        } catch (error) {
            console.error('Failed to export configuration:', error);
            this.showNotification('Failed to export configuration', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Test automated backup
     */
    async testAutomatedBackup() {
        try {
            this.showLoader('Testing automated backup...');

            // Create a test backup
            const backupData = {
                name: 'Test Automated Backup - ' + new Date().toLocaleString(),
                include_content: true,
                include_settings: true,
                include_containers: true
            };

            const response = await fetch(
                `${castconductorBackupAjax.rest_url}castconductor/v5/backup/create`,
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': castconductorBackupAjax.nonce
                    },
                    body: JSON.stringify(backupData)
                }
            );

            const data = await response.json();
            if (data.success) {
                this.showNotification('Automated backup test completed successfully', 'success');
                this.loadBackupList();
            } else {
                this.showNotification('Automated backup test failed', 'error');
            }
        } catch (error) {
            console.error('Automated backup test failed:', error);
            this.showNotification('Automated backup test failed', 'error');
        } finally {
            this.hideLoader();
        }
    }

    /**
     * Helper methods
     */

    formatDate(dateString) {
        return new Date(dateString).toLocaleString();
    }

    formatBytes(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    hideModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.style.display = 'none';
        }
    }

    setupAutoRefresh() {
        this.clearAutoRefresh();
        this.refreshInterval = setInterval(() => {
            this.loadBackupList();
        }, 60000); // Refresh every minute
    }

    clearAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
        }
    }

    refreshBackupList() {
        this.loadBackupList();
    }

    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `backup-notification backup-notification-${type}`;
        notification.textContent = message;
        
        // Add to container
        const container = document.getElementById('backup-notifications') || document.body;
        container.appendChild(notification);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 5000);
    }

    showLoader(message = 'Loading...') {
        const loader = document.getElementById('backup-loader');
        if (loader) {
            loader.style.display = 'flex';
            const loaderText = loader.querySelector('.loader-text');
            if (loaderText) {
                loaderText.textContent = message;
            }
        }
    }

    hideLoader() {
        const loader = document.getElementById('backup-loader');
        if (loader) {
            loader.style.display = 'none';
        }
    }

    showImportBackupModal() {
        const modal = document.getElementById('import-backup-modal');
        if (modal) {
            modal.style.display = 'block';
        }
    }
}

// Initialize backup interface when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('configuration-backup-container')) {
        window.castconductorConfigBackup = new CastConductorConfigurationBackup();
    }
});

// Form submit handlers
document.addEventListener('DOMContentLoaded', function() {
    // Create backup form
    const createBackupForm = document.getElementById('create-backup-form');
    if (createBackupForm) {
        createBackupForm.addEventListener('submit', function(e) {
            e.preventDefault();
            window.castconductorConfigBackup.createBackup();
        });
    }

    // Restore backup form
    const restoreBackupForm = document.getElementById('restore-backup-form');
    if (restoreBackupForm) {
        restoreBackupForm.addEventListener('submit', function(e) {
            e.preventDefault();
            // Handle restore - this will be called by the restore button click
        });
    }

    // Export config form
    const exportConfigForm = document.getElementById('export-config-form');
    if (exportConfigForm) {
        exportConfigForm.addEventListener('submit', function(e) {
            e.preventDefault();
            window.castconductorConfigBackup.exportConfiguration();
        });
    }
});
