jQuery(document).ready(function($) {

    /** -----------------------------
     * ADD MEGA MENU BUTTON TO ITEMS (PARENT ONLY)
     ------------------------------*/
    $('#menu-to-edit .menu-item').each(function () {

        var $li = $(this);

        // Extract menu item ID
        var id = $li.attr('id').replace('menu-item-', '');

        // Extract depth
        var depth = 0;
        $li.attr('class').split(/\s+/).forEach(function(cls){
            if (cls.startsWith('menu-item-depth-')) {
                depth = parseInt(cls.replace('menu-item-depth-', ''));
            }
        });

        // Only add button to parent menu items (depth 0)
        if (depth === 0 && !$li.find('.softech-mm-settings-btn').length) {
            $li.append(
                '<div class="softech-mm-settings-btn" data-id="'+ id +'" data-depth="'+ depth +'">' +
                    '<span>S</span> Mega Menu' +
                    '<p class="softech-mm-enabled-badge" style="display:none;margin:0px; padding-left:5px;">✓</p>' +
                '</div>'
            );
        }
    });

    /** -----------------------------
     * LOAD INITIAL ENABLED STATUS FOR PARENT MENU ITEMS ONLY
     ------------------------------*/
    $('#menu-to-edit .menu-item').each(function () {
        var $li = $(this);
        var id = $li.attr('id').replace('menu-item-', '');
        
        // Extract depth
        var depth = 0;
        $li.attr('class').split(/\s+/).forEach(function(cls){
            if (cls.startsWith('menu-item-depth-')) {
                depth = parseInt(cls.replace('menu-item-depth-', ''));
            }
        });
        
        // Only check status for parent menu items (depth 0)
        if (depth === 0) {
            $.ajax({
                type: 'POST',
                url: softech_mm.ajaxurl || ajaxurl,
                data: {
                    action: 'softech_get_mega_menu_template',
                    item_id: id,
                    nonce: softech_mm.nonce
                },
                success: function(res) {
                    if (res.success && res.data && res.data.mm_enable) {
                        updateMegaMenuBadge(id, true);
                    }
                }
            });
        }
    });

    /** -----------------------------
     * UPDATE MEGA MENU ENABLED BADGE
     ------------------------------*/
    function updateMegaMenuBadge(menuId, isEnabled) {
        var $button = $('.softech-mm-settings-btn[data-id="' + menuId + '"]');
        var $badge = $button.find('.softech-mm-enabled-badge');
        
        if (isEnabled) {
            $badge.show();
            $button.addClass('has-mega-menu');
        } else {
            $badge.hide();
            $button.removeClass('has-mega-menu');
        }
    }

    /** -----------------------------
     * OPEN SETTINGS POPUP
     ------------------------------*/
    $(document).on('click', '.softech-mm-settings-btn', function(){

        var menu_id   = $(this).data('id');
        var menu_depth = $(this).data('depth');

        console.log("Settings Clicked → ID=" + menu_id + " Depth=" + menu_depth);

        // Store values for later use
        $('#softech_mm_current_id').val(menu_id);
        $('#softech_mm_current_depth').val(menu_depth);

        // Update popup title
        $('.softech-mm-popup-title span').text(menu_id);

        // RESET/CLEAR all form fields FIRST
        $('#softech_mm_current_template_id').val('');
        $('#softech_mm_template_status').text('');
        $('#softech_mm_enable').prop('checked', false);
        $('#softech_mm_template_select').val('0');

        // Fetch existing template data via AJAX
        $.ajax({
            type: 'POST',
            url: softech_mm.ajaxurl || ajaxurl,
            data: {
                action: 'softech_get_mega_menu_template',
                item_id: menu_id,
                nonce: softech_mm.nonce
            },
            success: function(res) {
                if (res.success && res.data && res.data.template_id) {
                    var templateId = res.data.template_id;
                    var isEnabled = !!res.data.mm_enable;
                    
                    $('#softech_mm_current_template_id').val(templateId);
                    $('#softech_mm_enable').prop('checked', isEnabled);
                    
                    // Update button badge based on enabled status
                    updateMegaMenuBadge(menu_id, isEnabled);
                    
                    // Check if this template exists in dropdown
                    var templateExists = $('#softech_mm_template_select option[value="' + templateId + '"]').length > 0;
                    
                    if (templateExists) {
                        // Set dropdown to existing template
                        $('#softech_mm_template_select').val(templateId);
                        $('#softech_mm_template_status').text('Current Template ID: ' + templateId);
                    } else {
                        // Custom created template (not in list)
                        $('#softech_mm_template_select').val('0');
                        $('#softech_mm_template_status').text('Custom Template ID: ' + templateId + ' (Not in list)');
                    }
                } else {
                    // No template assigned
                    $('#softech_mm_current_template_id').val('');
                    $('#softech_mm_template_status').text('No template assigned');
                    $('#softech_mm_enable').prop('checked', false);
                    $('#softech_mm_template_select').val('0');
                    
                    // Remove enabled badge
                    updateMegaMenuBadge(menu_id, false);
                }

                // Show popup AFTER data is loaded
                $('.softech-mm-settings-popup-wrap').fadeIn(200);
            },
            error: function(err) {
                console.error('AJAX ERROR', err);
                $('#softech_mm_template_status').text('Error loading template data');
                $('.softech-mm-settings-popup-wrap').fadeIn(200);
            }
        });
    });

    /** -----------------------------
     * CLOSE SETTINGS POPUP
     ------------------------------*/
    $(document).on('click', '.softech-mm-settings-close-popup-btn', function(){
        $('.softech-mm-settings-popup-wrap').fadeOut(200);
    });

    $(document).on('click', '.softech-mm-settings-popup-wrap', function(e){
        if ($(e.target).hasClass('softech-mm-settings-popup-wrap')) {
            $(this).fadeOut(200);
        }
    });

    /** -----------------------------
     * OPEN ELEMENTOR TEMPLATE EDITOR
     ------------------------------*/
    $(document).on('click', '.softech-edit-mega-menu-btn', function(){

        var menu_id   = $('#softech_mm_current_id').val();
        var menu_depth = $('#softech_mm_current_depth').val();
        var selected_template = $('#softech_mm_template_select').val();

        // If user selected an existing template from dropdown
        if (selected_template && selected_template !== '0') {
            console.log("Opening existing template:", selected_template);
            
            // Update current template ID
            $('#softech_mm_current_template_id').val(selected_template);
            $('#softech_mm_template_status').text('Current Template ID: ' + selected_template);
            $('#softech_mm_enable').prop('checked', true);
            
            // Open existing template in Elementor
            var editLink = (softech_mm.admin_url || '/wp-admin/') + 'post.php?post=' + selected_template + '&action=elementor';
            openTemplateEditorPopup(editLink);
        } 
        // If dropdown is set to "Create New Template" (value = 0)
        else {
            console.log("Creating new template for menu item:", menu_id);
            
            // Create a brand new template
            createNewMenuTemplate(menu_id, menu_depth);
        }
    });

    function createNewMenuTemplate(id, depth) {

        $.ajax({
            type: 'POST',
            url: softech_mm.ajaxurl || ajaxurl,
            data: {
                action: 'softech_create_new_mega_menu_template',
                item_id: id,
                item_depth: depth,
                nonce: softech_mm.nonce,
                force_new: true
            },
            success: function(response) {

                if (!response.success) {
                    console.error("Error: invalid response", response);
                    return;
                }

                console.log("New Template Created! Edit link:", response.data.edit_link);

                // Store the NEW template ID
                if (response.data && response.data.template_id) {
                    $('#softech_mm_current_template_id').val(response.data.template_id);
                    $('#softech_mm_template_status').text('New Template ID: ' + response.data.template_id + ' (Created)');
                    $('#softech_mm_enable').prop('checked', true);
                }

                openTemplateEditorPopup(response.data.edit_link);
            },
            error: function(err) {
                console.error("AJAX ERROR", err);
            }
        });
    }

    /** -----------------------------
     * OPEN EDITOR POPUP WITH IFRAME
     ------------------------------*/
    function openTemplateEditorPopup(editorLink) {

        $('.softech-mm-editor-popup-wrap').fadeIn(200);

        var iframeWrapper = $('.softech-mm-editor-popup-iframe');

        // Replace iframe fully (ensures fresh editor load)
        iframeWrapper.html('<iframe src="'+ editorLink +'" frameborder="0" width="100%" height="100%"></iframe>');
    }

    /** -----------------------------
     * CLOSE EDITOR POPUP
     ------------------------------*/
    $(document).on('click', '.softech-mm-editor-close-popup-btn', function(){
        $('.softech-mm-editor-popup-wrap').fadeOut(200);

        // Remove iframe to prevent Elementor from lingering
        $('.softech-mm-editor-popup-iframe').empty();
    });

    // Listen for messages from iframe (elementor editor) and handle save events
    window.addEventListener('message', function(e) {
        try {
            var data = (typeof e.data === 'string') ? JSON.parse(e.data) : e.data;

            if (data && data.action === 'sitsel_mega_menu_saved') {
                // Close the editor popup and wipe iframe
                $('.softech-mm-editor-popup-wrap').fadeOut(200);
                $('.softech-mm-editor-popup-iframe').empty();

                // Optionally show a status that template was saved
                $('#softech_mm_template_status').text(function(i, v) {
                    var existing = $(this).text();
                    if (existing) {
                        return existing + ' (Saved)';
                    }
                    return 'Saved';
                });
            }
        } catch (err) {
            // ignore
        }
    }, false);

    /** -----------------------------
     * SAVE SETTINGS VIA AJAX
     ------------------------------*/
    $(document).on('click', '.softech-save-mega-menu-btn', function(){
        var menu_id = $('#softech_mm_current_id').val();
        var selected_template = $('#softech_mm_template_select').val();
        var current_template = $('#softech_mm_current_template_id').val();
        var template_id = 0;
        
        // Determine which template ID to save
        if (selected_template && selected_template !== '0') {
            // User selected existing template
            template_id = selected_template;
        } else if (current_template && current_template !== '0') {
            // User created new template (stored in hidden field)
            template_id = current_template;
        }
        
        var enable = $('#softech_mm_enable').is(':checked');
        const badgeColor = $('#softech_mm_badge_bg_color').val();

        if (!template_id || template_id === '0') {
            alert('Please create a new template or select an existing one before saving.');
            return;
        }

        $.ajax({
            type: 'POST',
            url: softech_mm.ajaxurl || ajaxurl,
            data: {
                action: 'softech_save_mega_menu_settings',
                item_id: menu_id,
                template_id: template_id,
                enable: enable,
                nonce: softech_mm.nonce,
                badge_bg_color: badgeColor,
            },
            success: function(res) {
                if (res.success) {
                    alert(res.data.message || 'Saved successfully!');
                    
                    // Update status display
                    $('#softech_mm_current_template_id').val(template_id);
                    $('#softech_mm_template_status').text('Current Template ID: ' + template_id + ' (Saved)');
                    
                    // Update the enabled badge on the button
                    updateMegaMenuBadge(menu_id, enable);
                    
                    // Update dropdown if template exists in list
                    var templateExists = $('#softech_mm_template_select option[value="' + template_id + '"]').length > 0;
                    if (templateExists) {
                        $('#softech_mm_template_select').val(template_id);
                    }
                } else {
                    alert(res.data.message || 'Failed to save');
                }
            },
            error: function(err) {
                console.error('AJAX ERROR', err);
                alert('Error saving settings');
            }
        });
    });

    /** -----------------------------
     * TOGGLE ENABLED BADGE ON CHECKBOX CHANGE
     ------------------------------*/
    $(document).on('change', '#softech_mm_enable', function(){
        var menu_id = $('#softech_mm_current_id').val();
        var isEnabled = $(this).is(':checked');
        
        // Immediately update the badge when checkbox changes
        updateMegaMenuBadge(menu_id, isEnabled);
    });

});