(function() {
    'use strict';

    /**
     * Initialize all horoscope summary blocks on the page
     */
    function initSummariesBlocks() {
        var blocks = document.querySelectorAll('.ezhp-summaries-ajax-container');
        
        blocks.forEach(function(container) {
            var blockId = container.getAttribute('data-block-id');
            
            if (!blockId || !window.ezhpSummariesData || !window.ezhpSummariesData[blockId]) {
                return;
            }
            
            var blockData = window.ezhpSummariesData[blockId];
            
            loadSummaries(container, blockData);
        });
    }

    /**
     * Render the returned HTML into the container
     */
    function renderHtml(container, blockData, html) {
        container.innerHTML = html;
        container.classList.remove('ezhp-ajax-loading');
        
        if (blockData.hasBgImages) {
            applyBackgroundImages(container);
        }
    }

    /**
     * Show error message
     */
    function showError(container, blockData) {
        container.innerHTML = '<div class="ez-horoscope-block-error">' + blockData.errorText + '</div>';
    }

    /**
     * Load via admin-ajax.php (primary path — works even if REST API is disabled)
     */
    function loadViaAdminAjax(blockData) {
        if (!blockData.ajaxUrl || !blockData.nonce) {
            return Promise.reject(new Error('admin-ajax not configured'));
        }
        
        var formData = new FormData();
        formData.append('action', 'ezhp_summaries');
        formData.append('nonce', blockData.nonce);
        formData.append('attributes', JSON.stringify(blockData.attributes));
        
        return fetch(blockData.ajaxUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('admin-ajax HTTP ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            if (data && data.success && data.data && data.data.html) {
                return data.data.html;
            }
            throw new Error('admin-ajax returned no html');
        });
    }

    /**
     * Load via WP REST API (fallback path)
     */
    function loadViaRest(blockData) {
        if (!blockData.restUrl) {
            return Promise.reject(new Error('REST not configured'));
        }
        
        return fetch(blockData.restUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(blockData.attributes),
            credentials: 'same-origin'
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('REST HTTP ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            if (data && data.html) {
                return data.html;
            }
            throw new Error('REST returned no html');
        });
    }

    /**
     * Load summaries — try admin-ajax first, fall back to REST
     */
    function loadSummaries(container, blockData) {
        loadViaAdminAjax(blockData)
            .catch(function(adminAjaxError) {
                // admin-ajax failed — fall back to REST
                return loadViaRest(blockData);
            })
            .then(function(html) {
                renderHtml(container, blockData, html);
            })
            .catch(function(error) {
                console.error('EZ Horoscope Summaries load error:', error);
                showError(container, blockData);
            });
    }

    /**
     * Apply background images from data attributes
     */
    function applyBackgroundImages(container) {
        var bgWrappers = container.querySelectorAll('.ez-hero-bg-wrapper[data-bg]');
        
        bgWrappers.forEach(function(el) {
            var url = el.getAttribute('data-bg');
            var pos = el.getAttribute('data-pos') || 'center';
            
            if (url) {
                el.style.backgroundImage = 'url(' + url + ')';
                el.style.backgroundSize = 'cover';
                el.style.backgroundPosition = pos;
                el.style.minHeight = '300px';
                el.style.position = 'relative';
            }
        });
    }

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSummariesBlocks);
    } else {
        initSummariesBlocks();
    }
})();