(function ($) {
    'use strict';

    const CONNECT_POLL_MAX_MS = 15 * 60 * 1000;

    const escapeHtml = (value) => String(value || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');

    const notice = (type, message, assetUrl) => {
        const icon = assetUrl
            ? `<img class="encypher-status-icon" src="${escapeHtml(assetUrl)}" alt="" width="16" height="16" aria-hidden="true" /> `
            : '';
        return `<div class="notice notice-${type} inline"><p>${icon}${escapeHtml(message)}</p></div>`;
    };

    const EncypherSettings = {
        init() {
            this.bindEvents();
            this.toggleBadgePosition();
            this.configureResponsiveDisclosures();
        },

        bindEvents() {
            $('#test-connection-btn').on('click', (event) => {
                event.preventDefault();
                this.testConnection();
            });

            $('#encypher-advanced-connect-btn').on('click', (event) => {
                event.preventDefault();
                this.quickConnect();
            });

            $('#encypher-tos-checkbox').on('change', function () {
                $('#encypher-activate-btn').prop('disabled', !this.checked);
            });

            $('#encypher-activate-btn').on('click', (event) => {
                event.preventDefault();
                this.activateProvenance();
            });

            $('#encypher-oauth-start-btn').on('click', (event) => {
                event.preventDefault();
                this.startOAuthConnect();
            });

            $('#encypher-oauth-cancel-btn').on('click', (event) => {
                event.preventDefault();
                this.cancelOAuthConnect();
            });

            $('#encypher-claim-btn').on('click', (event) => {
                event.preventDefault();
                this.claimWorkspace();
            });

            $('#encypher-media-scan-btn').on('click', (event) => {
                event.preventDefault();
                this.startMediaScan();
            });

            $('#encypher-process-queue-btn').on('click', (event) => {
                event.preventDefault();
                this.processQueue();
            });

            $(document).on('click', '.encypher-recent-failure-retry', (event) => {
                event.preventDefault();
                this.retryRecentFailure(event.currentTarget);
            });

            $('#encypher-retry-all-failures').on('click', (event) => {
                event.preventDefault();
                this.retryAllRecentFailures();
            });

            $(document).on('click', 'a[href="#encypher-recent-failures-title"]', () => {
                const heading = document.getElementById('encypher-recent-failures-title');
                const disclosure = heading ? heading.closest('details') : null;
                if (disclosure) {
                    disclosure.open = true;
                }
            });

            $(document).on('click', '.encypher-cdn-cta-dismiss', (event) => {
                event.preventDefault();
                const nonce = $(event.currentTarget).data('nonce');
                $('#encypher-cdn-cta').remove();
                // Fire-and-forget: dismissal is cosmetic, never block on it.
                if (typeof window.ajaxurl !== 'undefined') {
                    fetch(window.ajaxurl, {
                        method: 'POST',
                        credentials: 'same-origin',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: 'action=encypher_dismiss_cdn_cta&_wpnonce=' + encodeURIComponent(nonce || ''),
                    }).catch(() => {});
                }
            });

            $('#encypher-show-badge').on('change', () => this.toggleBadgePosition());

            this.bindBrandLogoPicker();
        },

        configureResponsiveDisclosures() {
            if (typeof window.matchMedia !== 'function' || typeof document.querySelectorAll !== 'function') {
                return;
            }
            const compact = window.matchMedia('(max-width: 782px)').matches;
            document.querySelectorAll('.encypher-responsive-disclosure, .encypher-coverage-actions-menu').forEach((details) => {
                details.open = !compact;
            });
        },

        getData() {
            return window.EncypherSettingsData || {};
        },

        setBrandedStatus($target, message, loading) {
            const data = this.getData();
            const assetUrl = loading ? data.loaderUrl : data.markUrl;
            const $icon = $('<img>', {
                class: 'encypher-status-icon',
                src: assetUrl || '',
                alt: '',
                width: 16,
                height: 16,
                'aria-hidden': 'true',
            });
            $target.empty().append($icon, document.createTextNode(' ' + message));
        },

        toggleBadgePosition() {
            const visible = $('#encypher-show-badge').is(':checked');
            $('#encypher-badge-position').prop('disabled', !visible);
            $('#encypher-badge-position-row').prop('hidden', !visible);
        },

        bindBrandLogoPicker() {
            const $field = $('.encypher-brand-logo-field');
            if (!$field.length || typeof wp === 'undefined' || !wp.media) {
                return;
            }
            const branding = window.EncypherBrandingData || {};
            let frame = null;

            $field.on('click', '.encypher-brand-logo-select', (event) => {
                event.preventDefault();
                if (frame) {
                    frame.open();
                    return;
                }
                frame = wp.media({
                    title: branding.mediaTitle || 'Select brand logo',
                    button: { text: branding.mediaButton || 'Use this logo' },
                    library: { type: 'image' },
                    multiple: false
                });
                frame.on('select', () => {
                    const attachment = frame.state().get('selection').first().toJSON();
                    const mime = attachment.mime || attachment.mime_type || '';
                    if (/svg/i.test(mime)) {
                        window.alert(branding.svgRejected || 'SVG files are not allowed. Choose a PNG, JPG, or WebP image.');
                        return;
                    }
                    const url = (attachment.sizes && attachment.sizes.medium && attachment.sizes.medium.url) || attachment.url || '';
                    $field.find('#encypher-brand-logo-id').val(attachment.id);
                    $field.find('.encypher-brand-logo-preview').attr('src', url).css('display', url ? 'block' : 'none');
                    $field.find('.encypher-brand-logo-remove').css('display', 'inline');
                });
                frame.open();
            });

            $field.on('click', '.encypher-brand-logo-remove', (event) => {
                event.preventDefault();
                $field.find('#encypher-brand-logo-id').val('');
                $field.find('.encypher-brand-logo-preview').attr('src', '').css('display', 'none');
                $field.find('.encypher-brand-logo-remove').css('display', 'none');
            });
        },

        async startOAuthConnect() {
            const $button = $('#encypher-oauth-start-btn');
            const $status = $('#encypher-oauth-status');
            $button.prop('disabled', true).text('Opening Encypher...');
            $status.html(notice('info', this.getData().strings?.connectStarted || 'Opening Encypher in a new tab.', this.getData().loaderUrl));

            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/oauth/start', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({ tos_accepted: true }),
                });
                const payload = await response.json();
                const connectUrl = payload.data?.connect_url;

                if (! response.ok || ! payload.success || ! connectUrl) {
                    throw new Error(payload.message || payload.data?.message || 'Unable to start the account connection.');
                }

                window.open(connectUrl, '_blank');
                $status.html(notice('info', 'Complete the connection in the new tab. This page will update automatically.', this.getData().loaderUrl));
                this.beginConnectPolling();
            } catch (error) {
                this.failConnect(error.message);
            } finally {
                if (! this._connectPollTimer) {
                    $button.prop('disabled', false);
                }
            }
        },

        beginConnectPolling() {
            this.stopConnectPolling();
            this._connectPollStartedAt = Date.now();
            $('#encypher-oauth-cancel-btn').prop('hidden', false);
            this._connectPollTimer = window.setInterval(() => {
                if (Date.now() - this._connectPollStartedAt > CONNECT_POLL_MAX_MS) {
                    this.failConnect(this.getData().strings?.oauthFailed);
                    return;
                }
                this.pollConnectStatus();
            }, 5000);
        },

        stopConnectPolling() {
            if (this._connectPollTimer) {
                window.clearInterval(this._connectPollTimer);
                this._connectPollTimer = null;
            }
        },

        async pollConnectStatus() {
            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/oauth/poll', {
                    method: 'GET',
                    headers: { 'X-WP-Nonce': wpApiSettings.nonce },
                });
                const payload = await response.json();
                const data = payload.data || {};
                const status = payload.status || data.status || '';

                if (['expired', 'cancelled', 'failed'].includes(status)) {
                    this.failConnect(this.getData().strings?.oauthFailed);
                    return;
                }

                if (! response.ok || ! payload.success) {
                    throw new Error(payload.message || payload.data?.message || 'Connection check failed.');
                }

                if ('completed' === status && data.api_key) {
                    this.stopConnectPolling();
                    $('#api_key').val(data.api_key);
                    $('#encypher-oauth-cancel-btn').prop('hidden', true);
                    const completed = this.getData().strings?.connectCompleted || 'WordPress connected successfully.';
                    $('#encypher-oauth-status').html(notice('success', completed, this.getData().markUrl));
                    setTimeout(() => window.location.reload(), 900);
                }
            } catch (error) {
                // A transient request failure may recover. The client deadline
                // still guarantees that polling reaches a terminal state.
            }
        },

        failConnect(message) {
            this.stopConnectPolling();
            const retry = this.getData().strings?.oauthRetry || 'Retry connection';
            const failure = message || this.getData().strings?.oauthFailed || 'We could not complete the connection.';
            $('#encypher-oauth-cancel-btn').prop('hidden', true);
            $('#encypher-oauth-start-btn').prop('disabled', false).text(retry);
            $('#encypher-oauth-status').html(notice('warning', failure, this.getData().markUrl));
        },

        async cancelOAuthConnect() {
            this.stopConnectPolling();
            try {
                await fetch(wpApiSettings.root + 'encypher-provenance/v1/oauth/cancel', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                });
            } catch (error) {
                // Local recovery is authoritative even if the cancel request fails.
            }

            const cancelled = this.getData().strings?.oauthCancelled || 'Connection cancelled.';
            const retry = this.getData().strings?.oauthRetry || 'Retry connection';
            $('#encypher-oauth-cancel-btn').prop('hidden', true);
            $('#encypher-oauth-start-btn').prop('disabled', false).text(retry);
            $('#encypher-oauth-status').html(notice('info', cancelled, this.getData().markUrl));
        },

        async activateProvenance() {
            const $button = $('#encypher-activate-btn');
            const $status = $('#encypher-activate-status');
            const $result = $('#encypher-activation-result');
            const host = this.getActivationHost();

            $result.html('').removeClass('is-success is-error');
            $status.removeClass('is-success is-error');

            if (! $('#encypher-tos-checkbox').is(':checked')) {
                $status.addClass('is-error').text('Please accept the Terms of Service and Privacy Policy to activate.');
                return;
            }

            $button.prop('disabled', true).text('Verifying control of ' + host + '...');
            $status.text('Verifying control of ' + host + '...');

            let response;
            let payload;
            const request = async (path, body) => {
                const result = await fetch(wpApiSettings.root + path, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify(body),
                });
                const raw = await result.text();
                try {
                    return { response: result, payload: JSON.parse(raw) };
                } catch (error) {
                    throw new Error('Activation service returned an unreadable response. Try again.');
                }
            };
            const readActivationStatus = async () => {
                const result = await fetch(
                    wpApiSettings.root + 'encypher-provenance/v1/site-activate/status',
                    { headers: { 'X-WP-Nonce': wpApiSettings.nonce } }
                );
                const raw = await result.text();
                try {
                    return { response: result, payload: JSON.parse(raw) };
                } catch (error) {
                    if ([502, 503, 504].includes(result.status)) {
                        return { response: result, payload: { state: 'verification_queued' } };
                    }
                    throw new Error('Activation status returned an unreadable response. Try again.');
                }
            };
            try {
                ({ response, payload } = await request(
                    'encypher-provenance/v1/site-activate',
                    { tos_accepted: true }
                ));
                if (response.ok && payload && payload.state === 'proof_pending') {
                    $button.text('Confirming control of ' + host + '...');
                    $status.text('Proof is available. Confirming control of ' + host + '...');
                    ({ response, payload } = await request(
                        'encypher-provenance/v1/site-activate/complete',
                        {}
                    ));
                    if (response.ok && payload && payload.state === 'verification_queued') {
                        for (let attempt = 0; attempt < 90; attempt++) {
                            ({ response, payload } = await readActivationStatus());
                            if (! payload || payload.state !== 'verification_queued') {
                                break;
                            }
                            await new Promise((resolve) => setTimeout(resolve, 1000));
                        }
                        if (payload && payload.state === 'verification_queued') {
                            throw new Error('Activation verification is still running. Try again shortly.');
                        }
                    }
                }
            } catch (error) {
                this.renderActivationError('', (error && error.message) || 'Activation could not be completed.');
                return;
            }

            this.renderActivationResult(response, payload);
        },

        renderActivationResult(response, payload) {
            const state = payload && payload.state;
            if (response && response.ok && state) {
                if (state === 'site_connected_unclaimed' || state === 'already_connected') {
                    this.renderActivationSuccess();
                    return;
                }
                if (state === 'existing_site_sign_in_required') {
                    this.renderExistingSitePanel();
                    return;
                }
            }

            const code = (payload && payload.code) || '';
            const message = (payload && payload.message)
                || (payload && payload.data && payload.data.message)
                || 'Activation could not be completed.';
            this.renderActivationError(code, message);
        },

        renderActivationSuccess() {
            const $status = $('#encypher-activate-status');
            const $result = $('#encypher-activation-result');

            $status.text('');
            $('#encypher-activate-btn').hide();

            const postNewUrl = escapeHtml(this.adminPostNewUrl());
            $result.addClass('is-success').html(
                '<div class="encypher-activation-panel encypher-activation-panel--success">' +
                '<p><strong>Protection is on. New and updated posts will be signed automatically.</strong></p>' +
                '<p><a href="' + postNewUrl + '">Publish and verify your first post</a></p>' +
                '</div>'
            );

            // Reload so the stored key is reflected and the connected Setup and Health view renders.
            setTimeout(() => window.location.reload(), 2500);
        },

        renderExistingSitePanel() {
            const $status = $('#encypher-activate-status');
            const $result = $('#encypher-activation-result');

            $status.text('');
            $('#encypher-activate-btn').prop('disabled', false).text('Start without an account');

            $result.addClass('is-error').html(
                '<div class="encypher-activation-panel encypher-activation-panel--info">' +
                '<p>This site is already connected to an Encypher workspace. Sign in to connect it; nothing was changed.</p>' +
                '<button type="button" id="encypher-existing-site-connect-btn" class="button button-primary">Sign in to connect this site</button>' +
                '</div>'
            );

            $result.find('#encypher-existing-site-connect-btn').on('click', (event) => {
                event.preventDefault();
                this.showOAuthConnectPanel();
                this.startOAuthConnect();
            });
        },

        renderActivationError(code, message) {
            const $status = $('#encypher-activate-status');
            const $result = $('#encypher-activation-result');
            const $button = $('#encypher-activate-btn');
            const safeMessage = escapeHtml(message || 'Activation could not be completed.');

            $status.text('');

            if (code === 'sodium_unavailable') {
                $button.hide();
                $result.addClass('is-error').html(
                    '<div class="encypher-activation-panel encypher-activation-panel--info">' +
                    '<p>' + safeMessage + '</p>' +
                    '<button type="button" id="encypher-existing-site-connect-btn" class="button button-primary">Connect existing account</button>' +
                    '</div>'
                );
                $result.find('#encypher-existing-site-connect-btn').on('click', (event) => {
                    event.preventDefault();
                    this.showOAuthConnectPanel();
                });
                return;
            }

            if (code === 'rate_limited') {
                $button.prop('disabled', true).text('Start without an account');
                $result.addClass('is-error').html(
                    '<div class="encypher-activation-panel encypher-activation-panel--error">' +
                    '<p>' + safeMessage + '</p>' +
                    '<p>Please wait a moment before trying again.</p>' +
                    '</div>'
                );
                setTimeout(() => {
                    if ($('#encypher-tos-checkbox').is(':checked')) {
                        $('#encypher-activate-btn').prop('disabled', false);
                    }
                }, 60000);
                return;
            }

            $button.prop('disabled', false).text('Start without an account');
            $result.addClass('is-error').html(
                '<div class="encypher-activation-panel encypher-activation-panel--error">' +
                '<p>' + safeMessage + '</p>' +
                '<p>Make sure this site is publicly reachable over HTTPS, then try again.</p>' +
                '<button type="button" id="encypher-activation-retry" class="button button-primary">Try again</button>' +
                '</div>'
            );
            $result.find('#encypher-activation-retry').on('click', (event) => {
                event.preventDefault();
                this.activateProvenance();
            });
        },

        showOAuthConnectPanel() {
            const $target = $('#encypher-oauth-start-btn');
            if ($target.length) {
                $('html, body').animate({ scrollTop: $target.offset().top - 100 }, 300);
            }
        },

        getActivationHost() {
            const fromDom = $('#encypher-activate-domain-display').text();
            return (fromDom && fromDom.trim()) ? fromDom.trim() : 'this site';
        },

        adminPostNewUrl() {
            const root = (typeof wpApiSettings !== 'undefined' && wpApiSettings.root) ? wpApiSettings.root : '';
            const origin = String(root).replace(/\/wp-json\/?$/, '');
            return origin + '/wp-admin/post-new.php';
        },

        async quickConnect() {
            const apiBaseUrl = ($('#api_base_url').val() || '').trim();
            const apiKey = ($('#api_key').val() || '').trim();
            const $button = $('#encypher-advanced-connect-btn');
            const $status = $('#encypher-api-key-status');

            if (! apiBaseUrl || ! apiKey) {
                $status.removeClass('is-success').addClass('is-error').text('Enter both an API key and endpoint to replace the connection.');
                return;
            }

            $button.prop('disabled', true).text('Verifying...');
            this.setBrandedStatus($status.removeClass('is-success is-error'), 'Checking connection...', true);
            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/quick-connect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({ api_base_url: apiBaseUrl, api_key: apiKey }),
                });
                const payload = await response.json();
                if (! response.ok || ! payload.success) {
                    throw new Error(payload.message || payload.data?.message || 'Connection could not be verified.');
                }

                this.setBrandedStatus($status.addClass('is-success'), 'Connection verified and saved.', false);
                setTimeout(() => window.location.reload(), 900);
            } catch (error) {
                this.setBrandedStatus($status.addClass('is-error'), error.message, false);
                $button.prop('disabled', false).text('Verify and save connection');
            }
        },

        async testConnection() {
            const $button = $('#test-connection-btn');
            const $state = $('#encypher-connection-health-state');
            const $status = $('#connection-status');
            const $result = $('#test-connection-result');
            $button.prop('disabled', true).text('Checking...');
            this.setBrandedStatus($status, 'Checking the saved connection...', true);

            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/test-connection', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({}),
                });
                const payload = await response.json();
                if (! response.ok || ! payload.success) {
                    throw new Error(payload.message || payload.data?.message || 'Connection check failed.');
                }

                $state.text('Healthy');
                this.setBrandedStatus($status.removeClass('is-error').addClass('is-success'), 'API connection check passed.', false);
                $result.text('Last API connection check: just now');
            } catch (error) {
                $state.text('Needs attention');
                this.setBrandedStatus($status.removeClass('is-success').addClass('is-error'), error.message, false);
            } finally {
                $button.prop('disabled', false).text('Check connection');
            }
        },

        async claimWorkspace() {
            const email = ($('#encypher-claim-email').val() || '').trim();
            const $button = $('#encypher-claim-btn');
            const $status = $('#encypher-claim-status');
            if (! email) {
                $status.addClass('is-error').text('Enter the account owner email.');
                return;
            }

            $button.prop('disabled', true).text('Claiming...');
            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/claim', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({ email }),
                });
                const payload = await response.json();
                if (! response.ok || ! payload.success) {
                    throw new Error(payload.message || payload.data?.message || 'Workspace claim failed.');
                }

                $status.removeClass('is-error').addClass('is-success').text('Workspace claimed.');
                setTimeout(() => window.location.reload(), 900);
            } catch (error) {
                $status.removeClass('is-success').addClass('is-error').text(error.message);
                $button.prop('disabled', false).text('Claim workspace');
            }
        },

        async startMediaScan() {
            const $button = $('#encypher-media-scan-btn');
            const $status = $('#encypher-media-scan-status');
            const originalLabel = $button.text();
            $button.prop('disabled', true).text('Starting...');
            $status.removeClass('is-error is-success').text('Starting the media library scan...');
            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/media-scan/start', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({}),
                });
                const payload = await response.json();
                if (! response.ok || ! payload.ok) {
                    throw new Error(payload.message || payload.data?.message || 'Could not start the media scan.');
                }
                const state = payload.state || {};
                const empty = state.status === 'complete' && Number(state.total || 0) === 0;
                $status.addClass('is-success').text(empty ? 'No media to scan. Reloading...' : 'Scan started. Progress updates as it runs; reloading...');
                setTimeout(() => window.location.reload(), 1200);
            } catch (error) {
                $status.addClass('is-error').text(error.message);
                $button.prop('disabled', false).text(originalLabel);
            }
        },

        async retryRecentFailure(button) {
            const $button = $(button);
            const $row = $button.closest('.encypher-recent-failure');
            const $status = $row.find('.encypher-recent-failure-status');
            const postId = Number($button.data('post-id') || 0);
            const actionUrl = String($button.data('action-url') || '');
            if (! postId || ! actionUrl) {
                $status.addClass('is-error').text('This item cannot be retried from here.');
                return false;
            }

            $button.prop('disabled', true);
            $status.removeClass('is-error is-success').text('Scheduling...');
            try {
                const response = await fetch(actionUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({ post_id: postId }),
                });
                const payload = await response.json();
                if (! response.ok || (payload && payload.code)) {
                    throw new Error(payload.message || payload.data?.message || 'Retry could not be scheduled.');
                }
                $row.attr('data-encypher-display-state', 'signing');
                $status.addClass('is-success').text('Signing scheduled. This issue remains open until signing succeeds.');
                return true;
            } catch (error) {
                $status.addClass('is-error').text(error.message || 'Retry could not be scheduled.');
                $button.prop('disabled', false);
                return false;
            }
        },

        async retryAllRecentFailures() {
            const $button = $('#encypher-retry-all-failures');
            const $status = $('#encypher-retry-all-status');
            const retryButtons = Array.from(document.querySelectorAll('.encypher-recent-failure-retry:not(:disabled)'));
            if (! retryButtons.length) {
                $status.addClass('is-error').text('No eligible failures remain to retry.');
                return;
            }

            $button.prop('disabled', true);
            $status.removeClass('is-error is-success').text('Scheduling retries...');
            let scheduled = 0;
            for (const retryButton of retryButtons) {
                if (await this.retryRecentFailure(retryButton)) {
                    scheduled += 1;
                }
            }
            const failed = retryButtons.length - scheduled;
            if (failed > 0) {
                $status.addClass('is-error').text('Scheduled ' + scheduled + ' retries; ' + failed + ' could not be scheduled.');
                $button.prop('disabled', false);
                return;
            }
            $status.addClass('is-success').text('Scheduled ' + scheduled + ' signing retries.');
        },

        async processQueue() {
            const $button = $('#encypher-process-queue-btn');
            const $status = $('#encypher-process-queue-status');
            $button.prop('disabled', true);
            $status.removeClass('is-error is-success').text('Processing queued work...');
            try {
                const response = await fetch(wpApiSettings.root + 'encypher-provenance/v1/queue/run', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce,
                    },
                    body: JSON.stringify({}),
                });
                const payload = await response.json();
                if (! response.ok || ! payload.ok) {
                    throw new Error(payload.message || payload.data?.message || 'Could not process the queue.');
                }
                const signed = payload.deferred_processed || 0;
                $status.addClass('is-success').text('Processed ' + signed + ' queued item(s). Reloading...');
                setTimeout(() => window.location.reload(), 1200);
            } catch (error) {
                $status.addClass('is-error').text(error.message);
                $button.prop('disabled', false);
            }
        },
    };

    $(document).ready(() => EncypherSettings.init());
})(jQuery);
