/**
 * Handles interactive elements within the Event Monster meta box.
 * @param {object} jQuery - jQuery
 */
jQuery(function(jQuery) {
    // --- Media Type Switcher ---
    function toggleMediaOptions() {
        var selectedType = jQuery('#logo_upd').val();
        
        // Hide all option containers
        jQuery('.em-media-type-option').hide();
        
        // Show the container that matches the selected type
        jQuery('#em-media-type-' + selectedType).show();
    }

    // Run on page load to show the correct section initially
    toggleMediaOptions();

    // Run whenever the dropdown is changed
    jQuery('#logo_upd').on('change', function() {
        toggleMediaOptions();
    });

    // --- Image Uploader ---
    var frame;
    jQuery('#upload_image_button').on('click', function(e) {
        e.preventDefault();
        if (frame) { frame.open(); return; }
        frame = wp.media({
            title: 'Select or Upload Media',
            button: { text: 'Use this media' },
            multiple: false
        });
        frame.on('select', function() {
            var attachment = frame.state().get('selection').first().toJSON();
            jQuery('#em_upload_image').val(attachment.url);
            jQuery('#upload_single_image_preview').attr('src', attachment.url);
        });
        frame.open();
    });

    // --- Remove Image ---
    jQuery('#remove-single-img').on('click', function(e) {
        e.preventDefault();
        jQuery('#em_upload_image').val('');
        // Get the placeholder image URL from the data attribute or use a default
        var placeholderUrl = jQuery('#upload_single_image_preview').data('placeholder') || '';
        if (placeholderUrl) {
            jQuery('#upload_single_image_preview').attr('src', placeholderUrl);
        }
    });

    // --- Icon Picker ---
    // Initialize Bootstrap Icon Picker for the "Choose Icon" button
    jQuery(document).ready(function() {
        console.log('Checking icon picker availability...');
        console.log('jQuery.fn.iconpicker:', typeof jQuery.fn.iconpicker);
        console.log('jQuery.fn.popover:', typeof jQuery.fn.popover);

        // Wait a bit for all scripts to load
        setTimeout(function() {
            if (jQuery.fn.iconpicker && jQuery('#em_icon_picker_btn').length) {
                console.log('Initializing icon picker...');
                try {
                    // Initialize icon picker directly on the button
                    jQuery('#em_icon_picker_btn').iconpicker({
                        iconset: 'fontawesome',
                        icon: jQuery('#em_upload_icon').val() || 'fa-calendar',
                        placement: 'bottom',
                        animation: true
                    }).on('change', function(e) {
                        console.log('Icon changed:', e.icon);
                        // Update the button icon when a new icon is selected
                        var selectedIcon = e.icon;
                        jQuery('#em_selected_icon_display').attr('class', 'fa ' + selectedIcon + ' em-mr-2');
                        jQuery('#em_upload_icon').val(selectedIcon);
                    });

                    console.log('Icon picker initialized successfully!');
                } catch (error) {
                    console.error('Error initializing icon picker:', error);
                }
            } else {
                console.error('Icon picker not available or element not found');
                console.log('Button exists:', jQuery('#em_icon_picker_btn').length);
                console.log('iconpicker function:', typeof jQuery.fn.iconpicker);
            }
        }, 500);
    });

    // --- YouTube/Vimeo Video Provider Switch ---
    // Handle visual state changes for video provider radio buttons
    jQuery('input[name="em_video_option"]').on('change', function() {
        var selectedProvider = jQuery(this).val();

        // Update visual state of all labels
        jQuery('input[name="em_video_option"]').each(function() {
            var label = jQuery(this).parent();
            if (jQuery(this).val() === selectedProvider) {
                // Active state
                label.addClass('em-bg-white em-shadow em-text-red-800').removeClass('em-text-red-600');
            } else {
                // Inactive state
                label.removeClass('em-bg-white em-shadow em-text-red-800').addClass('em-text-red-600');
            }
        });
    });

    // --- Layout Builder Integration ---
    // Initialize layout builder when the layout tab is shown
    jQuery(document).on('click', 'button[onclick*="em-tab-layout"]', function() {
        console.log('Layout tab clicked, initializing layout builder...');

        // Small delay to ensure tab content is visible
        setTimeout(function() {
            const builderWrapper = jQuery('.em-layout-builder-wrapper');
            console.log('Layout builder wrapper found:', builderWrapper.length);

            if (builderWrapper.length && typeof window.initLayoutBuilder === 'function') {
                console.log('Initializing layout builder...');
                window.initLayoutBuilder();
            } else {
                console.log('Layout builder not available:', {
                    wrapperExists: builderWrapper.length > 0,
                    functionExists: typeof window.initLayoutBuilder === 'function'
                });
            }
        }, 200);
    });

    // Also try to initialize on page load if layout tab is already active
    setTimeout(function() {
        const layoutTab = jQuery('#em-tab-layout');
        if (layoutTab.length && !layoutTab.hasClass('em-hidden')) {
            console.log('Layout tab is active on page load, initializing...');
            if (typeof window.initLayoutBuilder === 'function') {
                window.initLayoutBuilder();
            }
        }
    }, 500);

});