// Settings Page JavaScript

$(document).ready(function() {
    loadSettings();
    loadSystemInfo();
    bindEvents();
});

function bindEvents() {
    // Save settings
    $('#settingsForm').submit(function(e) {
        e.preventDefault();
        saveSettings();
    });

    // Validate configuration
    $('#validateBtn').click(function() {
        validateConfiguration();
    });

    // Reset to defaults
    $('#resetBtn').click(function() {
        if (confirm('Reset all settings to default values?')) {
            resetToDefaults();
        }
    });

    // Browse button (note: file input for local path selection)
    $('#browseBtn').click(function() {
        alert('Please enter the path manually or copy it from your file explorer.');
    });
}

function loadSettings() {
    $.ajax({
        url: '/api/settings/get',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const settings = response.settings;
                $('#executablePath').val(settings.executable_path || '');
                $('#workingDirectory').val(settings.working_directory || '');
                $('#timeout').val(settings.timeout || 300);
                $('#keepTempFiles').prop('checked', settings.keep_temp_files || false);
                $('#verbosity').val(settings.verbose || 1);
            }
        },
        error: function(xhr) {
            console.error('Failed to load settings:', xhr);
        }
    });
}

function saveSettings() {
    const settings = {
        executable_path: $('#executablePath').val(),
        working_directory: $('#workingDirectory').val(),
        timeout: parseInt($('#timeout').val()),
        keep_temp_files: $('#keepTempFiles').is(':checked'),
        verbose: parseInt($('#verbosity').val())
    };

    $.ajax({
        url: '/api/settings/save',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(settings),
        success: function(response) {
            if (response.success) {
                showToast('Settings saved successfully!', 'success');
            } else {
                showAlert('danger', 'Error saving settings: ' + response.error);
            }
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.error || 'Unknown error';
            showAlert('danger', 'Error saving settings: ' + error);
        }
    });
}

function validateConfiguration() {
    const $btn = $('#validateBtn');
    $btn.prop('disabled', true);
    $btn.html('<span class="spinner-border spinner-border-sm me-2"></span>Testing...');

    $.ajax({
        url: '/api/settings/validate',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            executable_path: $('#executablePath').val()
        }),
        success: function(response) {
            if (response.valid) {
                $('#pathStatus').html('<div class="alert alert-success"><i class="bi bi-check-circle"></i> Configuration is valid!</div>');
            } else {
                $('#pathStatus').html(`<div class="alert alert-danger"><i class="bi bi-x-circle"></i> ${response.message}</div>`);
            }
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.error || 'Unknown error';
            $('#pathStatus').html(`<div class="alert alert-danger"><i class="bi bi-x-circle"></i> ${error}</div>`);
        },
        complete: function() {
            $btn.prop('disabled', false);
            $btn.html('<i class="bi bi-check-circle"></i> Test Configuration');
        }
    });
}

function resetToDefaults() {
    $.ajax({
        url: '/api/settings/defaults',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const settings = response.settings;
                $('#executablePath').val(settings.executable_path || '');
                $('#workingDirectory').val(settings.working_directory || '');
                $('#timeout').val(settings.timeout || 300);
                $('#keepTempFiles').prop('checked', settings.keep_temp_files || false);
                $('#verbosity').val(settings.verbose || 1);
                showToast('Settings reset to defaults', 'info');
            }
        },
        error: function(xhr) {
            showAlert('danger', 'Error resetting settings');
        }
    });
}

function loadSystemInfo() {
    $.ajax({
        url: '/api/settings/system_info',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const info = response.info;
                let html = '<table class="table table-sm">';
                html += `<tr><th>Platform:</th><td>${info.system}</td></tr>`;
                html += `<tr><th>Python Version:</th><td>${info.python_version}</td></tr>`;
                html += `<tr><th>Default Executable Path:</th><td><code>${info.default_executable}</code></td></tr>`;
                html += `<tr><th>Default Working Directory:</th><td><code>${info.default_working_dir}</code></td></tr>`;
                html += '</table>';
                $('#systemInfo').html(html);
            }
        },
        error: function(xhr) {
            $('#systemInfo').html('<div class="alert alert-warning">Failed to load system information</div>');
        }
    });
}

function showAlert(type, message) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show mt-3" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('.card-body').first().prepend(alertHtml);

    setTimeout(function() {
        $('.alert').fadeOut('slow', function() {
            $(this).remove();
        });
    }, 3000);
}

// =============================================================================
// License Management
// =============================================================================

function loadLicenseInfo() {
    fetch('/api/license/status')
        .then(r => r.json())
        .then(data => {
            const container = document.getElementById('licenseInfo');
            if (!container) return;

            if (!data.activated && data.mode === 'none') {
                container.innerHTML = `
                    <div class="alert alert-warning mb-0">
                        <i class="bi bi-exclamation-triangle"></i> No license activated.
                        <a href="/license" class="alert-link">Activate now</a>
                    </div>`;
                return;
            }

            let statusClass = 'success';
            let statusIcon = 'shield-check';
            let statusText = 'Active';

            if (data.mode === 'offline_cached') {
                statusClass = 'warning';
                statusIcon = 'wifi-off';
                statusText = 'Offline (cached)';
            } else if (!data.activated) {
                statusClass = 'danger';
                statusIcon = 'shield-x';
                statusText = 'Inactive';
            }

            container.innerHTML = `
                <table class="table table-sm mb-0">
                    <tr>
                        <td class="text-muted">Status</td>
                        <td><span class="badge bg-${statusClass}"><i class="bi bi-${statusIcon}"></i> ${statusText}</span></td>
                    </tr>
                    <tr>
                        <td class="text-muted">License Key</td>
                        <td><code>${data.license_key_masked || 'N/A'}</code></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Type</td>
                        <td>${data.license_type || 'N/A'}</td>
                    </tr>
                    <tr>
                        <td class="text-muted">Last Online Check</td>
                        <td>${data.last_online_check || 'Never'}</td>
                    </tr>
                    <tr>
                        <td class="text-muted">Offline Grace Remaining</td>
                        <td>${data.grace_remaining_days !== undefined ? data.grace_remaining_days + ' days' : 'N/A'}</td>
                    </tr>
                    ${data.expires_at ? `<tr><td class="text-muted">Expires</td><td>${data.expires_at}</td></tr>` : ''}
                </table>`;
        })
        .catch(err => {
            const container = document.getElementById('licenseInfo');
            if (container) {
                container.innerHTML = '<span class="text-danger">Could not load license info.</span>';
            }
        });
}

// Re-validate license online
document.getElementById('revalidateLicenseBtn')?.addEventListener('click', function () {
    this.disabled = true;
    this.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Checking...';

    // The simplest approach: redirect to /license which triggers a fresh check
    window.location.href = '/license';
});

// Deactivate license
document.getElementById('deactivateLicenseBtn')?.addEventListener('click', function () {
    if (!confirm('Are you sure you want to deactivate your license? You will need to re-enter your license key.')) {
        return;
    }

    fetch('/api/license/deactivate', { method: 'POST' })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                window.location.href = '/license';
            }
        })
        .catch(err => alert('Error deactivating license: ' + err));
});

// Load license info on page load
document.addEventListener('DOMContentLoaded', loadLicenseInfo);
