

jQuery(document).ready(function ($) {
    var pollingInterval;

    function pollScheduler() {
        $.post(sbpai_obj.ajax_url, {
            action: 'sbpai_get_polling_status',
            nonce: sbpai_obj.nonce
        }, function (res) {
            if (res.success) {
                var count = res.data.pending;
                if (count > 0) {
                    $('#sbpai-polling-area').slideDown(200);
                    $('#sbpai-pending-count').text(count);
                } else {
                    $('#sbpai-polling-area').slideUp(200);
                }
            }
        });
    }

    pollingInterval = setInterval(pollScheduler, 3000);
    pollScheduler();


    $('.sbpai-generate-btn').on('click', function (e) {
        e.preventDefault();

        var btn = $(this);
        var type = btn.data('type');
        var inputId = btn.data('input');
        var amount = parseInt($('#' + inputId).val());

        var payload = {
            action: 'sbpai_queue_generation',
            nonce: sbpai_obj.nonce,
            type: type,
            amount: amount,
            args: {}
        };

        if (type === 'posts') {
            payload.args = {
                post_type: $('#sbpai-post-type').val() || 'post',
                builder: $('#sbpai-post-builder').val() || 'gutenberg',
                source: $('#sbpai-post-source').val() || 'hybrid',
                length: $('#sbpai-post-length').val() || 'medium',
                status: $('#sbpai-post-status').val() || 'publish',
                author: $('#sbpai-post-author').val() || 'random',
                date_from: $('#sbpai-date-from').val() || '',
                date_to: $('#sbpai-date-to').val() || '',
                image: $('#sbpai-post-image').is(':checked') ? 1 : 0,
                terms: $('#sbpai-post-terms').is(':checked') ? 1 : 0,
                comments: $('#sbpai-post-comments').is(':checked') ? 1 : 0
            };
        } else if (type === 'woocommerce') {
            var types = ['simple', 'variable', 'grouped', 'virtual'];
            var totalQueued = 0;
            var requests = [];

            btn.prop('disabled', true).text('Queueing...');
            var progressDiv = $('#progress-' + type);
            progressDiv.text('Adding to Action Scheduler...');

            types.forEach(function (t) {
                var amt = parseInt($('#sbpai-wc-count-' + t).val());
                if (!amt || amt <= 0) return;

                var wcPayload = {
                    action: 'sbpai_queue_generation',
                    nonce: sbpai_obj.nonce,
                    type: 'products',
                    amount: amt,
                    args: {
                        wc_type: t,
                        source: $('#sbpai-wc-source').val() || 'hybrid',
                        price_min: $('#sbpai-wc-price-min').val() || '10',
                        price_max: $('#sbpai-wc-price-max').val() || '500',
                        stock: $('#sbpai-wc-stock').val() || 'random',
                        image: $('#sbpai-wc-image').is(':checked') ? 1 : 0,
                        terms: $('#sbpai-wc-terms').is(':checked') ? 1 : 0,
                        orders: $('#sbpai-wc-orders').is(':checked') ? 1 : 0,
                        coupons: $('#sbpai-wc-coupons').is(':checked') ? 1 : 0,
                        reviews: $('#sbpai-wc-reviews').is(':checked') ? 1 : 0,
                        acf: $('#sbpai-wc-acf').is(':checked') ? 1 : 0
                    }
                };
                totalQueued += amt;
                requests.push($.post(sbpai_obj.ajax_url, wcPayload));
            });

            var ordersAmt = parseInt($('#sbpai-wc-count-orders-standalone').val());
            if (ordersAmt > 0) {
                totalQueued += ordersAmt;
                requests.push($.post(sbpai_obj.ajax_url, {
                    action: 'sbpai_queue_generation',
                    nonce: sbpai_obj.nonce,
                    type: 'orders',
                    amount: ordersAmt,
                    args: {}
                }));
            }

            if (requests.length === 0) {
                alert('Please enter at least one value > 0.');
                btn.prop('disabled', false).text('Generate eCommerce Simulation');
                progressDiv.text('');
                return;
            }

            Promise.all(requests).then(function () {
                progressDiv.text('✅ ' + totalQueued + ' tasks queued.');
                pollScheduler();
                setTimeout(() => {
                    btn.prop('disabled', false).text('Generate eCommerce Simulation');
                    progressDiv.text('');
                }, 3000);
            }).catch(function () {
                alert('AJAX Error');
                btn.prop('disabled', false).text('Generate eCommerce Simulation');
            });

            return; // bypass standard click handler bottom
        }

        if (!amount || amount <= 0) {
            alert('Please enter a valid number.');
            return;
        }

        btn.prop('disabled', true).text('Queueing...');
        var progressDiv = $('#progress-' + type);
        progressDiv.text('Adding to Action Scheduler...');

        $.ajax({
            url: sbpai_obj.ajax_url,
            type: 'POST',
            data: payload,
            success: function (response) {
                if (response.success) {
                    progressDiv.text('✅ ' + amount + ' tasks queued.');
                    pollScheduler();
                } else {
                    alert('Error: ' + response.data);
                }
                setTimeout(() => {
                    btn.prop('disabled', false).text('Generate posts');
                    progressDiv.text('');
                }, 3000);
            },
            error: function () {
                alert('AJAX Error');
                btn.prop('disabled', false).text('Generate posts');
            }
        });
    });

    // ── Users per-role generation ──────────────────────────
    $(document).on('click', '#sbpai-generate-users-btn', function (e) {
        e.preventDefault();
        var btn = $(this);
        var password = $('#sbpai-user-password').val() || '';
        var avatar = $('#sbpai-user-avatar').is(':checked') ? 1 : 0;
        var billing = $('#sbpai-user-wc-billing').is(':checked') ? 1 : 0;
        var bio = $('#sbpai-user-bio').is(':checked') ? 1 : 0;

        var requests = [];
        var totalQueued = 0;

        $('.sbpai-role-checkbox:checked').each(function () {
            var role = $(this).data('role');
            var count = parseInt($('#sbpai-role-count-' + role).val()) || 0;
            if (count <= 0) return;
            totalQueued += count;

            requests.push($.post(sbpai_obj.ajax_url, {
                action: 'sbpai_queue_generation',
                nonce: sbpai_obj.nonce,
                type: 'users',
                amount: count,
                args: {
                    role: role,
                    password: password,
                    avatar: avatar,
                    billing: billing,
                    bio: bio
                }
            }));
        });

        if (requests.length === 0) {
            alert('Please enable at least one role and set a count > 0.');
            return;
        }

        btn.prop('disabled', true).text('Queueing...');
        $('#progress-users').text('Scheduling ' + totalQueued + ' users...');

        $.when.apply($, requests).then(function () {
            $('#progress-users').text('✅ ' + totalQueued + ' user tasks queued!');
            pollScheduler();
            setTimeout(function () {
                btn.prop('disabled', false).text('⚡ Generate Users');
                $('#progress-users').text('');
            }, 4000);
        });
    });

    $(document).on('click', '#sbpai-run-store-setup', function (e) {
        e.preventDefault();
        var btn = $(this);
        if (!confirm('This will explicitly override your connected WooCommerce settings globally. Proceed?')) return;

        btn.prop('disabled', true).text('Applying Configurations...');

        var payloadArgs = {
            address: $('#sbpai-setup-address').val(),
            city: $('#sbpai-setup-city').val(),
            country: $('#sbpai-setup-country').val(),
            postcode: $('#sbpai-setup-postcode').val(),
            currency: $('#sbpai-setup-currency').val(),
            tax: $('#sbpai-setup-tax').is(':checked') ? 1 : 0,
            shipping: $('#sbpai-setup-shipping').is(':checked') ? 1 : 0,
            gateways: {
                cod: $('#sbpai-setup-cod').is(':checked') ? 1 : 0,
                bacs: $('#sbpai-setup-bacs').is(':checked') ? 1 : 0,
                cheque: $('#sbpai-setup-cheque').is(':checked') ? 1 : 0
            }
        };

        $.post(sbpai_obj.ajax_url, {
            action: 'sbpai_quick_config_wc',
            nonce: sbpai_obj.nonce,
            args: payloadArgs
        }, function (res) {
            if (res.success) {
                btn.text('✅ Settings Successfully Applied!');
            } else {
                alert('Error applying settings: ' + res.data);
                btn.text('Configure Store Options');
            }
            setTimeout(() => {
                btn.prop('disabled', false).text('Configure Store Options');
            }, 4000);
        });
    });

    $(document).on('click', '#sbpai-reset-store-setup', function (e) {
        e.preventDefault();
        var btn = $(this);
        if (!confirm('WARNING: This will completely WIPE your global WooCommerce Store Address, Currency, Taxes, and Payment Gateways. Are you sure you want to clear these settings?')) return;

        btn.prop('disabled', true).text('Clearing Settings...');

        $.post(sbpai_obj.ajax_url, {
            action: 'sbpai_reset_config_wc',
            nonce: sbpai_obj.nonce
        }, function (res) {
            if (res.success) {
                btn.text('✅ Settings Cleared!');
                // Auto-refresh the page so the fresh defaults load into the UI inputs correctly if needed,
                // Or just clear the UI inputs manually.
                $('#sbpai-setup-address, #sbpai-setup-city, #sbpai-setup-postcode').val('');
                $('#sbpai-setup-country').val('US');
                $('#sbpai-setup-currency').val('USD');
                $('#sbpai-setup-tax, #sbpai-setup-shipping, #sbpai-setup-cod, #sbpai-setup-bacs, #sbpai-setup-cheque').prop('checked', false);
            } else {
                alert('Error clearing settings: ' + res.data);
                btn.text('Clear All Settings');
            }
            setTimeout(() => {
                btn.prop('disabled', false).text('Clear All Settings');
            }, 4000);
        });
    });

    // ── Danger Zone Creative Confirmation & Loader ──────────────────
    $('#sbpai-trigger-delete').on('click', function (e) {
        e.preventDefault();
        $('#sbpai-delete-overlay').css('display', 'flex').hide().fadeIn(300);
        $('#sbpai-delete-prompt').show();
        $('#sbpai-delete-loader').hide();
    });

    $('#sbpai-cancel-delete').on('click', function () {
        $('#sbpai-delete-overlay').fadeOut(300);
    });

    $('#sbpai-confirm-delete').on('click', function () {
        // Transition to Creative Loader
        $('#sbpai-delete-prompt').hide();
        $('#sbpai-delete-loader').css('display', 'flex').hide().fadeIn(300);

        $.post(sbpai_obj.ajax_url, {
            action: 'sbpai_ajax_delete_all',
            nonce: sbpai_obj.nonce
        }, function (res) {
            $('#sbpai-delete-overlay').fadeOut(400);
            if (res.success) {
                $('#sbpai-delete-success-msg').text('✅ ' + res.data).fadeIn();
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            } else {
                alert('Deletion failed: ' + (res.data || 'Unauthorized'));
            }
        }).fail(function () {
            $('#sbpai-delete-overlay').fadeOut(400);
            alert('A server error occurred during deletion.');
        });
    });

    // ── Table Select All Checkboxes ──────────────────────────
    $(document).on('change', '#cb-select-all-prods', function () {
        $(this).closest('table').find('input[name="bulk_ids[]"]').prop('checked', $(this).prop('checked'));
    });

    $(document).on('change', '#cb-select-all-orders', function () {
        $(this).closest('table').find('input[name="bulk_ids[]"]').prop('checked', $(this).prop('checked'));
    });

    $(document).on('change', '#cb-select-all', function () {
        $(this).closest('table').find('input[name="bulk_ids[]"]').prop('checked', $(this).prop('checked'));
    });

    $(document).on('change', '#cb-select-all-users', function () {
        $(this).closest('table').find('input[name="bulk_ids[]"]').prop('checked', $(this).prop('checked'));
    });

    // ── General settings save ──────────────────────────
    $(document).on('click', '#sbpai-save-general-settings', function () {
        var btn = $(this);
        btn.prop('disabled', true).text('Saving...');
        $.post(sbpai_obj.ajax_url, {
            action: 'sbpai_save_settings',
            nonce: sbpai_obj.nonce,
            niche: $('#sbpai-niche').val(),
            ai: $('#sbpai-use-ai-provider').is(':checked') ? 1 : 0
        }, function () {
            $('#sbpai-settings-saved').fadeIn().delay(2000).fadeOut();
            btn.prop('disabled', false).text('💾 Save Settings');
        });
    });

    // ── Password Visibility Toggles ──────────────────────────
    $(document).on('click', '#sbpai-toggle-primary-key', function () {
        var f = document.getElementById('sbpai-primary-api-key');
        if (f) f.type = f.type === 'password' ? 'text' : 'password';
    });

    $(document).on('click', '#sbpai-toggle-fallback-key', function () {
        var f = document.getElementById('sbpai-fallback-api-key');
        if (f) f.type = f.type === 'password' ? 'text' : 'password';
    });

    // ── Primary Provider Actions ──────────────────────────
    $(document).on('click', '#sbpai-save-primary', function () {
        var prov = $('#sbpai-primary-provider').val();
        var key = $('#sbpai-primary-api-key').val();
        var $res = $('#sbpai-primary-result');
        if (!prov) { $res.html('<span style="color:#dc2626;">Please select a provider first.</span>'); return; }
        var btn = $(this).prop('disabled', true).text('Saving...');
        $.post(sbpai_obj.ajax_url, { action: 'sbpai_save_primary_provider', nonce: sbpai_obj.nonce, provider: prov, api_key: key }, function (r) {
            $res.html(r.success ? '<span style="color:#16a34a;">✅ Primary saved and activated!</span>' : '<span style="color:#dc2626;">❌ ' + r.data + '</span>');
            btn.prop('disabled', false).text('💾 Save & Activate');
            if (r.success) setTimeout(() => location.reload(), 1500);
        });
    });

    $(document).on('click', '#sbpai-test-primary', function () {
        var prov = $('#sbpai-primary-provider').val();
        var key = $('#sbpai-primary-api-key').val();
        var $res = $('#sbpai-primary-result');
        if (!prov || !key) { $res.html('<span style="color:#dc2626;">Select a provider and enter a key first.</span>'); return; }
        var btn = $(this).prop('disabled', true).text('Testing...');
        $res.html('<span style="color:#f59e0b;">⏳ Connecting...</span>');
        $.post(sbpai_obj.ajax_url, { action: 'sbpai_test_ai_connection', nonce: sbpai_obj.nonce, provider: prov, api_key: key }, function (r) {
            $res.html(r.success ? '<span style="color:#16a34a;">✅ ' + r.data + '</span>' : '<span style="color:#dc2626;">❌ ' + r.data + '</span>');
            btn.prop('disabled', false).text('🔌 Test Connection');
        });
    });

    // ── Fallback Provider Actions ──────────────────────────
    $(document).on('click', '#sbpai-save-fallback', function () {
        var prov = $('#sbpai-fallback-provider').val();
        var key = $('#sbpai-fallback-api-key').val();
        var $res = $('#sbpai-fallback-result');
        if (!prov) { $res.html('<span style="color:#dc2626;">Please select a fallback provider.</span>'); return; }
        var btn = $(this).prop('disabled', true).text('Saving...');
        $.post(sbpai_obj.ajax_url, { action: 'sbpai_save_fallback_provider', nonce: sbpai_obj.nonce, provider: prov, api_key: key }, function (r) {
            $res.html(r.success ? '<span style="color:#2563eb;">✅ Fallback saved!</span>' : '<span style="color:#dc2626;">❌ ' + r.data + '</span>');
            btn.prop('disabled', false).text('💾 Save Fallback');
            if (r.success) setTimeout(() => location.reload(), 1500);
        });
    });

    $(document).on('click', '#sbpai-test-fallback', function () {
        var prov = $('#sbpai-fallback-provider').val();
        var key = $('#sbpai-fallback-api-key').val();
        var $res = $('#sbpai-fallback-result');
        if (!prov || !key) { $res.html('<span style="color:#dc2626;">Select a provider and enter a key first.</span>'); return; }
        var btn = $(this).prop('disabled', true).text('Testing...');
        $res.html('<span style="color:#f59e0b;">⏳ Connecting...</span>');
        $.post(sbpai_obj.ajax_url, { action: 'sbpai_test_ai_connection', nonce: sbpai_obj.nonce, provider: prov, api_key: key }, function (r) {
            $res.html(r.success ? '<span style="color:#16a34a;">✅ ' + r.data + '</span>' : '<span style="color:#dc2626;">❌ ' + r.data + '</span>');
            btn.prop('disabled', false).text('🔌 Test Connection');
        });
    });

});

