(function($) {
    'use strict';

    $(document).ready(function() {
        // Session Timeout Validation
        const sessionTimeoutInput = $('#session_timeout_minutes');
        if (sessionTimeoutInput.length) {
            sessionTimeoutInput.on('change', function() {
                const value = parseInt($(this).val(), 10);
                if (isNaN(value) || value < 5) {
                    $(this).val(5);
                } else if (value > 120) {
                    $(this).val(120);
                }
            });
        }
        
        // Geo Database Update
        const updateBtn = $('#pagevico-update-geo-db');
        const messageDiv = $('#pagevico-geo-update-message');
        const lastUpdatedSpan = $('#pagevico-geo-last-updated');

        updateBtn.on('click', function() {
            // Disable button and show loading state
            updateBtn.prop('disabled', true)
                .html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Updating...');
            messageDiv.hide();

            // Make AJAX request
            fetch(pagevicoSettings.geo_db_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': pagevicoSettings.geo_db_nonce
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageDiv.removeClass('alert-danger').addClass('alert alert-success').html(data.message).show();
                    lastUpdatedSpan.text(data.last_updated);
                } else {
                    messageDiv.removeClass('alert-success').addClass('alert alert-danger').html(data.message).show();
                }
            })
            .catch(error => {
                messageDiv.removeClass('alert-success').addClass('alert alert-danger')
                    .html('An error occurred while updating the database.').show();
                console.error('Error:', error);
            })
            .finally(() => {
                // Reset button state
                updateBtn.prop('disabled', false)
                    .html('<span class="dashicons dashicons-download"></span> Update Geo Database Now');
            });
        });

        // Settings Reset
        const resetBtn = $('#pagevico-reset-settings');
        const resetMessageDiv = $('#pagevico-reset-message');

        resetBtn.on('click', function() {
            if (!confirm(pagevicoSettings.confirm_reset)) {
                return;
            }

            alert('Resetting settings...');

            resetBtn.prop('disabled', true)
                .html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Resetting...');
            resetMessageDiv.hide();

            $.ajax({
                url: pagevicoSettings.ajax_url,
                type: 'POST',
                data: {
                    action: 'pagevico_reset_settings',
                    nonce: pagevicoSettings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        resetMessageDiv.removeClass('alert-danger')
                            .addClass('alert alert-success')
                            .html(response.data.message)
                            .show();
                        // Reload page after 1.5 seconds to show updated values
                        setTimeout(() => window.location.reload(), 1500);
                    } else {
                        resetMessageDiv.removeClass('alert-success')
                            .addClass('alert alert-danger')
                            .html(response.data.message || 'Failed to reset settings')
                            .show();
                    }
                },
                error: function(xhr, status, error) {
                    resetMessageDiv.removeClass('alert-success')
                        .addClass('alert alert-danger')
                        .html('An error occurred while resetting settings: ' + error)
                        .show();
                },
                complete: function() {
                    resetBtn.prop('disabled', false)
                        .html('Reset All Settings');
                }
            });
        });



        // [fs_premium_only]
        // Handle manage partitions button
        $('#manage-partitions-btn').on('click', function(e) {
            e.preventDefault();
            if (confirm(pagevicoSettings.confirm_partitions)) {
                // Show spinner
                $('#partition-result').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                
                $.ajax({
                    url: pagevicoSettings.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'pagevico_manage_partitions',
                        nonce: pagevicoSettings.partition_nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $('#partition-result').html('<span class="text-success">' + response.data.message + '</span>');
                        } else {
                            $('#partition-result').html('<span class="text-danger">Error: ' + response.data.message + '</span>');
                        }
                    },
                    error: function() {
                        $('#partition-result').html('<span class="text-danger">An unknown error occurred.</span>');
                    }
                });
            }
        });
        // [/fs_premium_only]

    });
})(jQuery); 