(function () {
    'use strict';

    /**
     * Build CTA HTML from settings
     */
    function buildCTA(settings, slotNumber) {
        var ctaDiv = document.createElement('div');
        var alignClass = 'ez-daily-cta-' + (settings.alignment || 'center');
        ctaDiv.className = 'ez-daily-cta ez-daily-cta-' + slotNumber + ' ' + alignClass;

        if (settings.elementId) {
            ctaDiv.id = settings.elementId;
        }

        if (settings.headerText) {
            var validLevels = ['h2', 'h3', 'h4'];
            var level = validLevels.includes(settings.headerLevel) ? settings.headerLevel : 'h3';
            var header = document.createElement(level);
            header.className = 'ez-daily-cta-header';
            header.textContent = settings.headerText;
            ctaDiv.appendChild(header);
        }

        if (settings.text) {
            var textP = document.createElement('p');
            textP.className = 'ez-daily-cta-text';
            textP.textContent = settings.text;
            ctaDiv.appendChild(textP);
        }

        if (settings.imageUrl) {
            var img = document.createElement('img');
            img.src = settings.imageUrl;
            img.alt = settings.imageAlt || '';
            img.className = 'ez-daily-cta-image';

            if (settings.linkType === 'image' || settings.imageClickable) {
                var imgLink = document.createElement('a');
                imgLink.href = settings.url;
                imgLink.target = '_blank';
                imgLink.rel = 'noopener noreferrer';
                imgLink.className = 'ez-daily-cta-image-link';
                imgLink.appendChild(img);
                ctaDiv.appendChild(imgLink);
            } else {
                ctaDiv.appendChild(img);
            }
        }

        if (settings.linkType !== 'image' && settings.linkText) {
            var link = document.createElement('a');
            link.href = settings.url;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            link.textContent = settings.linkText;

            if (settings.linkType === 'button') {
                link.className = 'wp-element-button ez-daily-cta-button';
            } else {
                link.className = 'ez-daily-cta-link';
            }

            ctaDiv.appendChild(link);
        }

        return ctaDiv;
    }

    /**
     * Get CTA settings from data attributes
     */
    function getCTASettings(block, num) {
        var enabled = block.getAttribute('data-cta' + num + '-enabled');

        if (enabled !== '1') {
            return null;
        }

        return {
            headerText: block.getAttribute('data-cta' + num + '-header-text') || '',
            headerLevel: block.getAttribute('data-cta' + num + '-header-level') || 'h3',
            text: block.getAttribute('data-cta' + num + '-text') || '',
            imageUrl: block.getAttribute('data-cta' + num + '-image-url') || '',
            imageAlt: block.getAttribute('data-cta' + num + '-image-alt') || '',
            url: block.getAttribute('data-cta' + num + '-url') || '',
            linkType: block.getAttribute('data-cta' + num + '-link-type') || 'button',
            linkText: block.getAttribute('data-cta' + num + '-link-text') || '',
            imageClickable: block.getAttribute('data-cta' + num + '-image-clickable') === '1',
            elementId: block.getAttribute('data-cta' + num + '-element-id') || '',
            alignment: block.getAttribute('data-cta' + num + '-alignment') || 'center'
        };
    }

    /**
     * Replace a placeholder with CTA content
     */
    function replacePlaceholder(block, slotNumber) {
        var settings = getCTASettings(block, slotNumber);

        if (!settings) {
            return;
        }

        var placeholder = block.querySelector('[data-elementid="cta-slot-' + slotNumber + '"]');

        if (!placeholder) {
            return;
        }

        var ctaElement = buildCTA(settings, slotNumber);
        placeholder.parentNode.replaceChild(ctaElement, placeholder);
    }

    /**
     * Process all CTA placeholders in a block
     */
    function processBlock(block) {
        // Skip if already processed
        if (block.getAttribute('data-cta-processed') === '1') {
            return;
        }

        replacePlaceholder(block, 1);
        replacePlaceholder(block, 2);
        replacePlaceholder(block, 3);

        // Mark as processed
        block.setAttribute('data-cta-processed', '1');
    }

    /**
     * Process all blocks on the page
     */
    function processAllBlocks() {
        var blocks = document.querySelectorAll('.ez-horoscope-block');
        blocks.forEach(function (block) {
            processBlock(block);
        });
    }

    /**
     * Initialize - run immediately and set up observer for editor
     */
    function init() {
        // Process any existing blocks
        processAllBlocks();

        // Set up MutationObserver to catch dynamically loaded content (editor)
        var observer = new MutationObserver(function (mutations) {
            var shouldProcess = false;

            mutations.forEach(function (mutation) {
                // Check if nodes were added
                if (mutation.addedNodes.length > 0) {
                    mutation.addedNodes.forEach(function (node) {
                        if (node.nodeType === 1) {
                            // Check if it's a horoscope block or contains one
                            if (node.classList && node.classList.contains('ez-horoscope-block')) {
                                shouldProcess = true;
                            } else if (node.querySelector && node.querySelector('.ez-horoscope-block')) {
                                shouldProcess = true;
                            }
                        }
                    });
                }
            });

            if (shouldProcess) {
                // Small delay to ensure content is fully loaded
                setTimeout(processAllBlocks, 100);
            }
        });

        // Observe the entire document for changes
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // Run on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();