jQuery(document).ready(function($) {
    var confirmTrashMsg = iotc_admin_vars.confirmTrashMsg;
    var confirmDeleteMsg = iotc_admin_vars.confirmDeleteMsg;
    var ajaxTrashNonce = iotc_admin_vars.ajaxTrashNonce;
    var ajaxRestoreNonce = iotc_admin_vars.ajaxRestoreNonce;
    var ajaxForceNonce = iotc_admin_vars.ajaxForceNonce;
    var ajaxOptimizeNonce = iotc_admin_vars.ajaxOptimizeNonce;
    var ajaxSaveCronNonce = iotc_admin_vars.ajaxSaveCronNonce;
    var recoveryUrl = iotc_admin_vars.recoveryUrl;
    var alertSelectMsg = iotc_admin_vars.alertSelectMsg;
    var optimizingMsg = iotc_admin_vars.optimizingMsg;
    var optimizeDbMsg = iotc_admin_vars.optimizeDbMsg;
    var suspendedMsg = iotc_admin_vars.suspendedMsg;
    var restoredMsg = iotc_admin_vars.restoredMsg;
    var deletedMsg = iotc_admin_vars.deletedMsg;

    // Tabs logic
    $(document).on('click', '.wpdd-nav-tabs .nav-tab', function(e) {
        e.preventDefault();
        var tabLink = $(this).closest('.nav-tab');
        var targetId = tabLink.attr('href');
        if (!targetId) return;
        $('.wpdd-nav-tabs .nav-tab').removeClass('nav-tab-active');
        tabLink.addClass('nav-tab-active');
        $('.wpdd-tab-content').hide();
        $(targetId).show();
    });

    // Slim PRO reminder strip — jumps to the Settings tab by reusing the nav-tab click logic above
    $(document).on('click', '.wpdd-pro-strip__link', function(e) {
        e.preventDefault();
        var target = $(this).attr('href');
        $('.wpdd-nav-tabs .nav-tab[href="' + target + '"]').trigger('click');
    });

    // Select All toggle
    $('.wpdd-select-all').on('click', function() {
        $(this).closest('table').find('.wpdd-table-checkbox').prop('checked', $(this).prop('checked'));
    });

    // Help card expand/collapse (replaces inline onclick)
    $(document).on('click', '.wpdd-help-toggle', function() {
        $('#wpdd-help-content').slideToggle();
    });

    // Select recovery link text on click (replaces inline onclick)
    $(document).on('click', '.wpdd-select-on-click', function() {
        this.select();
    });

    // Trash (Suspend) Table
    $('.ajax-trash-table-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var tableName = btn.data('tablename');
        var row = btn.closest('tr');
        var sizeMb = parseFloat(row.find('.table-size').data('size'));

        if ( ! confirm( confirmTrashMsg ) ) { return; }

        // Open recovery link in new tab before suspending
        window.open(recoveryUrl, '_blank');

        btn.prop('disabled', true);
        
        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: 'iotc_trash_orphan_table', nonce: ajaxTrashNonce, table_name: tableName },
            success: function(response) {
                if (response.success) {
                    row.find('.delete-feedback').text(suspendedMsg).fadeIn(200);
                    btn.hide();

                    var totalTablesEl = $('#stat-total-tables');
                    var totalMbEl = $('#stat-total-mb');
                    if (totalTablesEl.length && totalMbEl.length) {
                        var currentTables = parseInt(totalTablesEl.text()) - 1;
                        var currentMb = parseFloat(totalMbEl.text()) - sizeMb;
                        totalTablesEl.text(currentTables);
                        totalMbEl.text(currentMb.toFixed(2));
                    }

                    setTimeout(function() {
                        row.fadeOut(400, function() {
                            location.reload(); // Reload to show it in the Trash table
                        });
                    }, 1000);
                } else {
                    alert(response.data.message || 'Error suspending table.');
                    btn.prop('disabled', false);
                }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    // Restore Table
    $('.ajax-restore-table-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var tableName = btn.data('tablename');
        var row = btn.closest('tr');

        btn.prop('disabled', true);
        row.find('.ajax-force-delete-table-btn').prop('disabled', true);
        
        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: 'iotc_restore_orphan_table', nonce: ajaxRestoreNonce, table_name: tableName },
            success: function(response) {
                if (response.success) {
                    var feedback = row.find('.action-feedback');
                    feedback.css('color', '#46b450').text(restoredMsg).fadeIn();
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    alert(response.data.message || 'Error restoring table.');
                    btn.prop('disabled', false);
                    row.find('.ajax-force-delete-table-btn').prop('disabled', false);
                }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    // Force Delete Table
    $('.ajax-force-delete-table-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var tableName = btn.data('tablename');
        var row = btn.closest('tr');

        if ( ! confirm( confirmDeleteMsg ) ) { return; }

        btn.prop('disabled', true);
        row.find('.ajax-restore-table-btn').prop('disabled', true);
        
        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: 'iotc_force_delete_orphan_table', nonce: ajaxForceNonce, table_name: tableName },
            success: function(response) {
                if (response.success) {
                    var feedback = row.find('.action-feedback');
                    feedback.css('color', '#d63638').text(deletedMsg).fadeIn();
                    setTimeout(function() {
                        row.fadeOut(400, function() {
                            $(this).remove();
                            if ( $('#trashed-tables-list tbody tr').length === 0 ) {
                                location.reload();
                            }
                        });
                    }, 1000);
                } else {
                    alert(response.data.message || 'Error deleting table.');
                    btn.prop('disabled', false);
                    row.find('.ajax-restore-table-btn').prop('disabled', false);
                }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    var isPro = iotc_admin_vars.isPro;

    // Bulk Trash (Suspend)
    $('.bulk-trash-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var checked = $('#orphan-tables-list .wpdd-table-checkbox:checked');
        if (checked.length === 0) { alert(alertSelectMsg); return; }
        
        var tables = [];
        checked.each(function() { tables.push($(this).val()); });

        if ( ! confirm( confirmTrashMsg ) ) { return; }
        window.open(recoveryUrl, '_blank');
        btn.prop('disabled', true);

        var actionName = isPro ? 'iotc_bulk_trash_orphan_tables__premium_only' : 'iotc_bulk_trash_orphan_tables';

        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: actionName, nonce: ajaxTrashNonce, table_names: tables },
            success: function(response) {
                if (response.success) { location.reload(); }
                else { alert(response.data.message || 'Error'); btn.prop('disabled', false); }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    // Bulk Restore
    $('.bulk-restore-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var checked = $('#trashed-tables-list .wpdd-table-checkbox:checked');
        if (checked.length === 0) { alert(alertSelectMsg); return; }
        
        var tables = [];
        checked.each(function() { tables.push($(this).val()); });

        btn.prop('disabled', true);

        var actionName = isPro ? 'iotc_bulk_restore_orphan_tables__premium_only' : 'iotc_bulk_restore_orphan_tables';

        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: actionName, nonce: ajaxRestoreNonce, table_names: tables },
            success: function(response) {
                if (response.success) { location.reload(); }
                else { alert(response.data.message || 'Error'); btn.prop('disabled', false); }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    // Bulk Force Delete
    $('.bulk-force-delete-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var checked = $('#trashed-tables-list .wpdd-table-checkbox:checked');
        if (checked.length === 0) { alert(alertSelectMsg); return; }
        
        if ( ! confirm( confirmDeleteMsg ) ) { return; }

        var tables = [];
        checked.each(function() { tables.push($(this).val()); });

        btn.prop('disabled', true);

        var actionName = isPro ? 'iotc_bulk_force_delete_orphan_tables__premium_only' : 'iotc_bulk_force_delete_orphan_tables';

        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: actionName, nonce: ajaxForceNonce, table_names: tables },
            success: function(response) {
                if (response.success) { location.reload(); }
                else { alert(response.data.message || 'Error'); btn.prop('disabled', false); }
            },
            error: function() { alert('Network error.'); btn.prop('disabled', false); }
        });
    });

    // Optimize Database
    $('#btn-optimize-db').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var feedback = $('#optimize-feedback');
        var btnText = btn.find('.btn-text');
        var dashicon = btn.find('.dashicons');

        btn.prop('disabled', true);
        dashicon.addClass('update-spin'); // Uses native WP class if available, else we fake it via CSS but it's fine
        btnText.text(optimizingMsg);
        feedback.hide();

        $.ajax({
            url: ajaxurl, type: 'POST',
            data: { action: 'iotc_optimize_database', nonce: ajaxOptimizeNonce },
            success: function(response) {
                dashicon.removeClass('update-spin');
                if (response.success) {
                    btnText.text(optimizeDbMsg);
                    feedback.css('color', '#46b450').text(response.data.message).fadeIn();
                    $('#stat-overhead-mb').css('color', '#46b450').text('0 MB');
                } else {
                    btnText.text(optimizeDbMsg);
                    alert(response.data.message || 'Error optimizing database.');
                    btn.prop('disabled', false);
                }
            },
            error: function() { 
                dashicon.removeClass('update-spin');
                btnText.text(optimizeDbMsg);
                alert('Network error.'); 
                btn.prop('disabled', false); 
            }
        });
    });

    // Cron Settings UI
    $('#wpdd-cron-frequency').on('change', function() {
        if ( $(this).val() === 'custom' ) {
            $('#wpdd-cron-custom-days-row').show();
        } else {
            $('#wpdd-cron-custom-days-row').hide();
        }
    });

    $('#wpdd-report-enabled').on('change', function() {
        if ( $(this).is(':checked') ) {
            $('#wpdd-report-email-row').show();
            $('#wpdd-report-frequency-row').show();
            if ( $('#wpdd-report-frequency').val() === 'custom' ) {
                $('#wpdd-report-custom-days-row').show();
            }
        } else {
            $('#wpdd-report-email-row').hide();
            $('#wpdd-report-frequency-row').hide();
            $('#wpdd-report-custom-days-row').hide();
        }
    });

    $('#wpdd-report-frequency').on('change', function() {
        if ( $(this).val() === 'custom' ) {
            $('#wpdd-report-custom-days-row').show();
        } else {
            $('#wpdd-report-custom-days-row').hide();
        }
    });

    // Save Cron Settings
    $('#btn-save-cron-settings').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var feedback = $('#save-cron-feedback');
        var enabled = $('#wpdd-cron-enabled').is(':checked') ? 'yes' : 'no';
        var frequency = $('#wpdd-cron-frequency').val();
        var days = $('#wpdd-cron-days').val();
        var report_enabled = $('#wpdd-report-enabled').is(':checked') ? 'yes' : 'no';
        var report_email = $('#wpdd-report-email').val();
        var report_frequency = $('#wpdd-report-frequency').val();
        var report_days = $('#wpdd-report-days').val();

        btn.prop('disabled', true);
        feedback.hide();

        $.ajax({
            url: ajaxurl, type: 'POST',
            data: {
                action: 'iotc_save_cron_settings',
                nonce: ajaxSaveCronNonce,
                enabled: enabled,
                frequency: frequency,
                days: days,
                report_enabled: report_enabled,
                report_email: report_email,
                report_frequency: report_frequency,
                report_days: report_days
            },
            success: function(response) {
                if (response.success) {
                    feedback.css('color', '#46b450').text(response.data.message).fadeIn();
                } else {
                    alert(response.data.message || 'Error saving settings.');
                }
                btn.prop('disabled', false);
            },
            error: function() {
                alert('Network error.');
                btn.prop('disabled', false);
            }
        });
    });

});
