/**
 * Cloudflare Media Offload - Admin Scripts
 * 
 * @package suspended-cloud/cloudflare-media-offload
 * @since 2.0.0
 */

(function($) {
    'use strict';

    // Keep the AJAX nonce fresh via the WordPress Heartbeat API. The PHP
    // side (SQMedia_Admin::refresh_nonce_via_heartbeat) injects a new value
    // into every heartbeat response on StaticQ admin screens; we copy it
    // into the cached `sqmediaAdmin.nonce` so subsequent AJAX calls use it.
    // Default heartbeat interval is 60s in the WP admin, so a long-lived
    // tab never reaches the 24h nonce-expiry wall.
    $(document).on('heartbeat-tick', function(event, data) {
        if (data && data.sqmedia_nonce) {
            sqmediaAdmin.nonce = data.sqmedia_nonce;
        }
    });

    // Safety net: if a StaticQ AJAX call fails with a nonce-rejection 403
    // (because the heartbeat couldn't fire — tab throttled by the browser,
    // user actually logged out, etc.), surface a clear "reload" message
    // instead of the silent failure the inline .fail() handlers produce.
    $(document).ajaxError(function(event, jqxhr, settings) {
        if (!settings || !settings.data || String(settings.data).indexOf('action=sqmedia') === -1) {
            return;
        }
        var isAuthFail = jqxhr.status === 403
            || jqxhr.responseText === '-1'
            || (jqxhr.responseText && jqxhr.responseText.indexOf('rest_cookie_invalid_nonce') !== -1);
        if (isAuthFail && !window.sqmediaSessionExpiredShown) {
            window.sqmediaSessionExpiredShown = true;
            var msg = (sqmediaAdmin && sqmediaAdmin.strings && sqmediaAdmin.strings.session_expired)
                || 'Your StaticQ session has expired. Please reload the page to continue.';
            window.alert(msg);
        }
    });

    // Test Cloudflare Connection
    $('#sqmedia-test-cloudflare').on('click', function() {
        var $btn = $(this);
        var $result = $('#sqmedia-cloudflare-result');

        $btn.prop('disabled', true);
        $result.html('<span class="spinner is-active" style="float:none;margin:0 5px;"></span>');

        $.post(sqmediaAdmin.ajaxurl, {
            action: 'sqmedia_test_cloudflare_connection',
            nonce: sqmediaAdmin.nonce
        }, function(response) {
            $btn.prop('disabled', false);

            if (response.success) {
                $result.html('<span class="sqmedia-status-ok">✓ ' + response.data.message + '</span>');
            } else {
                $result.html('<span class="sqmedia-status-error">✗ ' + (response.data || sqmediaAdmin.strings.connection_failed) + '</span>');
            }
        }).fail(function() {
            $btn.prop('disabled', false);
            $result.html('<span class="sqmedia-status-error">✗ ' + sqmediaAdmin.strings.request_failed + '</span>');
        });
    });

    // Format numbers with locale
    window.sqFormatNumber = function(num) {
        return num.toLocaleString();
    };

    // Format bytes
    window.sqFormatBytes = function(bytes, decimals) {
        if (bytes === 0) return '0 Bytes';
        
        decimals = decimals || 2;
        var k = 1024;
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
    };

})(jQuery);
