// IIFE to avoid global scope pollution
(function() {
    'use strict';

    // Function to get nonce securely
    async function getNonce() {
        // Check if REST configuration exists (only for authorized users)
        if (typeof window.aipstxRest === 'undefined') {
            console.warn('REST configuration not available. User might not have required permissions.');
            return;
        }

        try {
            const response = await fetch(window.aipstxRest.url + '/get-nonce', {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': window.aipstxRest.nonce,
                    'Content-Type': 'application/json'
                },
                credentials: 'same-origin'
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const data = await response.json();
            
            // Store nonce in memory (not directly visible in source)
            window.aipstxAjax = window.aipstxAjax || {};
            Object.defineProperty(window.aipstxAjax, 'nonce', {
                value: data.nonce,
                writable: false,
                configurable: false,
                enumerable: false
            });

            // Dispatch event when nonce is ready
            const event = new CustomEvent('aipstxNonceReady');
            document.dispatchEvent(event);

        } catch (error) {
            console.error('Error fetching nonce:', error);
        }
    }

    // Initialize nonce when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof aipstxAjax !== 'undefined') {
            getNonce();
        }
    });
})(); 