jQuery(document).ready(function ($) {
    const $modal = $('.adminlgb-telemetry-modal');
    if (!$modal.length) return;

    // Show modal if it exists
    setTimeout(() => {
        $modal.addClass('active');
    }, 500);

    // Handle Allow button
    $('.adminlgb-js-telemetry-allow').on('click', function (e) {
        e.preventDefault();
        sendOptInData('yes', $(this));
    });

    // Handle Deny button
    $('.adminlgb-js-telemetry-deny').on('click', function (e) {
        e.preventDefault();
        sendOptInData('no', $(this));
    });

    function sendOptInData(status, $btn) {
        if ($btn.hasClass('loading')) return;

        $btn.addClass('loading');

        $.ajax({
            url: admilogu_telemetry_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'admilogu_tracking_optin',
                status: status,
                nonce: admilogu_telemetry_vars.nonce
            },
            success: function (response) {
                if (response.success) {
                    $modal.removeClass('active');
                    setTimeout(() => {
                        location.reload();
                    }, 400);
                }
            },
            error: function () {
                // If it fails, close anyway to avoid bothering the user
                $modal.removeClass('active');
            },
            complete: function () {
                $btn.removeClass('loading');
            }
        });
    }
});
