(function() {
    'use strict';

    /**
     * RTL language codes
     */
    var rtlLanguages = ['ar', 'he', 'ur', 'fa'];

    /**
     * Check if a language is RTL
     */
    function isRtlLanguage(lang) {
        return rtlLanguages.indexOf(lang) !== -1;
    }

    /**
     * Initialize moon phase widgets
     * Works on both frontend and in the block editor
     */
    function initMoonPhaseWidgets() {
        var widgets = document.querySelectorAll('.ez-moon-phase-widget:not([data-ezhp-initialized])');

        widgets.forEach(function(widget) {
            widget.setAttribute('data-ezhp-initialized', 'true');
            
            var dropdown = widget.querySelector('.ez-moon-zodiac-dropdown');
            var resultEl = widget.querySelector('.ez-moon-content-result');
            var language = widget.dataset.language || 'en';
            var isRtl = isRtlLanguage(language) || widget.getAttribute('dir') === 'rtl';

            // CTA settings from data attributes
            var ctaEnabled = widget.dataset.ctaEnabled === 'true';
            var ctaText = widget.dataset.ctaText || '';
            var ctaImageUrl = widget.dataset.ctaImageUrl || '';
            var ctaImageAlt = widget.dataset.ctaImageAlt || '';
            var ctaUrl = widget.dataset.ctaUrl || '';
            var ctaLinkType = widget.dataset.ctaLinkType || 'button';
            var ctaLinkText = widget.dataset.ctaLinkText || '';
            var ctaImageClickable = widget.dataset.ctaImageClickable === 'true';
            var ctaElementId = widget.dataset.ctaElementId || '';

            if (!dropdown || !resultEl) return;

            dropdown.addEventListener('change', function() {
                var zodiacSign = this.value;

                // Clear result if no sign selected
                if (!zodiacSign) {
                    resultEl.innerHTML = '';
                    return;
                }

                // Show progress bar
                resultEl.innerHTML = '<div class="ezhp-progress-container"><div class="ezhp-progress-bar"></div></div>';

                // Build WordPress REST API URL (works in both frontend and editor)
                var apiUrl = '/wp-json/ezhp/v1/moon-content' +
                    '?zodiacSign=' + encodeURIComponent(zodiacSign) +
                    '&language=' + encodeURIComponent(language);

                // Fetch moon content
                fetch(apiUrl, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .then(function(response) {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(function(data) {
                    if (data && data.moonContentHtml) {
                        var html = data.moonContentHtml;

                        // Replace CTA placeholder if enabled
                        if (ctaEnabled && ctaUrl) {
                            html = replaceCTA(html, {
                                ctaText: ctaText,
                                ctaImageUrl: ctaImageUrl,
                                ctaImageAlt: ctaImageAlt,
                                ctaUrl: ctaUrl,
                                ctaLinkType: ctaLinkType,
                                ctaLinkText: ctaLinkText,
                                ctaImageClickable: ctaImageClickable,
                                ctaElementId: ctaElementId,
                                isRtl: isRtl
                            });
                        }

                        resultEl.innerHTML = html;
                    } else {
                        resultEl.innerHTML = '<p>No moon content available for this sign.</p>';
                    }
                })
                .catch(function(error) {
                    resultEl.innerHTML = '<p>Unable to load moon content. Please try again.</p>';
                    console.error('EZ Moon Phase Widget Error:', error);
                });
            });
        });
    }

    /**
     * Replace the cb-moon-reading placeholder with custom CTA
     */
    function replaceCTA(html, settings) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
        
        // Find the placeholder element
        var placeholder = doc.querySelector('[data-elementid="cb-moon-reading"]');
        
        if (!placeholder) {
            return html; // No placeholder found, return original
        }

        // Build CTA HTML
        var ctaDiv = doc.createElement('div');
        ctaDiv.className = 'ez-moon-cta';
        if (settings.ctaElementId) {
            ctaDiv.id = settings.ctaElementId;
        }

        // Add intro text
        if (settings.ctaText) {
            var textP = doc.createElement('p');
            textP.className = 'ez-moon-cta-text';
            textP.textContent = settings.ctaText;
            ctaDiv.appendChild(textP);
        }

        // Handle image
        if (settings.ctaImageUrl) {
            var img = doc.createElement('img');
            img.src = settings.ctaImageUrl;
            img.alt = settings.ctaImageAlt || '';
            img.className = 'ez-moon-cta-image';

            // If link type is 'image' OR (has image AND imageClickable is true)
            if (settings.ctaLinkType === 'image' || settings.ctaImageClickable) {
                var imgLink = doc.createElement('a');
                imgLink.href = settings.ctaUrl;
                imgLink.target = '_blank';
                imgLink.rel = 'noopener noreferrer';
                imgLink.className = 'ez-moon-cta-image-link';
                imgLink.appendChild(img);
                ctaDiv.appendChild(imgLink);
            } else {
                ctaDiv.appendChild(img);
            }
        }

        // Handle text link or button (only if not 'image' link type)
        if (settings.ctaLinkType !== 'image' && settings.ctaLinkText) {
            var link = doc.createElement('a');
            link.href = settings.ctaUrl;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            link.textContent = settings.ctaLinkText;

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

            ctaDiv.appendChild(link);
        }

        // Replace placeholder with CTA
        placeholder.parentNode.replaceChild(ctaDiv, placeholder);

        return doc.body.innerHTML;
    }

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

    // Watch for dynamically added content (for block editor)
    var observer = new MutationObserver(function(mutations) {
        var shouldInit = false;
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes.length) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) {
                        if (node.classList && node.classList.contains('ez-moon-phase-widget')) {
                            shouldInit = true;
                        } else if (node.querySelector && node.querySelector('.ez-moon-phase-widget')) {
                            shouldInit = true;
                        }
                    }
                });
            }
        });
        if (shouldInit) {
            initMoonPhaseWidgets();
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

})();