jQuery(document).ready(function($) {
    // Function to initialize all PollBolt iframes
    function initPollBoltIframes() {
        // Find all PollBolt iframes
        $('.pollbolt-iframe').each(function() {
            var iframe = $(this);
            var iframeId = iframe.attr('id');
            
            // Skip if already initialized
            if (iframe.data('pollbolt-initialized')) {
                return;
            }
            
            // Mark as initialized
            iframe.data('pollbolt-initialized', true);
            
            // Add CSS to hide scrollbars
            iframe.css({
                'scrollbar-width': 'none',
                '-ms-overflow-style': 'none',
                'overflow': 'hidden'
            });
            
            // Add parameters to URL for better embedding
            var src = iframe.attr('src');
            if (src.indexOf('?') === -1) {
                src += '?';
            } else {
                src += '&';
            }
            src += 'embedded=true&hideScroll=true&autoresize=true';
            iframe.attr('src', src);
            
            // Function to adjust iframe height
            function adjustIframeHeight(height) {
                // Add padding to height
                height = parseInt(height) + 50;
                iframe.css('height', height + 'px');
                console.log('Adjusted height for', iframeId, 'to', height, 'px');
            }
            
            // Listen for messages from iframe
            window.addEventListener('message', function(event) {
                try {
                    // Check if it's a string (legacy format) or object
                    if (typeof event.data === 'string') {
                        // Try to parse as JSON
                        try {
                            var data = JSON.parse(event.data);
                            if (data.frameId === iframeId && data.height) {
                                adjustIframeHeight(data.height);
                            }
                        } catch (e) {
                            // Not JSON, ignore
                        }
                    } else if (typeof event.data === 'object') {
                        // Modern format with pollbolt-height type
                        if (event.data.type === 'pollbolt-height') {
                            adjustIframeHeight(event.data.height);
                        }
                    }
                } catch (e) {
                    console.error('Error processing message:', e);
                }
            }, false);
            
            // Request height periodically
            var heightInterval = setInterval(function() {
                if (iframe[0].contentWindow) {
                    // Try both message formats
                    iframe[0].contentWindow.postMessage('requestHeight', '*');
                    iframe[0].contentWindow.postMessage({
                        type: 'pollbolt-get-height'
                    }, '*');
                }
            }, 2000);
            
            // Start checking after load
            iframe.on('load', function() {
                // Immediate request
                if (iframe[0].contentWindow) {
                    iframe[0].contentWindow.postMessage('requestHeight', '*');
                    iframe[0].contentWindow.postMessage({
                        type: 'pollbolt-get-height'
                    }, '*');
                }
                
                // Try to apply styles to hide scrollbars
                try {
                    var iframeDoc = iframe[0].contentWindow.document;
                    var style = iframeDoc.createElement('style');
                    style.textContent = `
                        html, body { 
                            overflow: hidden !important; 
                            scrollbar-width: none !important;
                            -ms-overflow-style: none !important;
                        }
                        ::-webkit-scrollbar { 
                            display: none !important; 
                            width: 0 !important; 
                            height: 0 !important; 
                        }
                    `;
                    iframeDoc.head.appendChild(style);
                } catch(e) {
                    // Expected cross-origin errors, ignore
                }
            });
        });
    }
    
    // Initialize on page load
    initPollBoltIframes();
    
    // Re-initialize when content changes (helpful for AJAX loaded content)
    $(document).on('DOMNodeInserted', function(e) {
        if ($(e.target).find('.pollbolt-iframe').length > 0 || $(e.target).hasClass('pollbolt-iframe')) {
            initPollBoltIframes();
        }
    });
    
    // For WordPress admin - initialize when editor changes occur
    if (typeof wp !== 'undefined' && wp.data && wp.data.subscribe) {
        wp.data.subscribe(function() {
            setTimeout(initPollBoltIframes, 500);
        });
    }
}); 