jQuery(function($) {
    function mysterxToggleGeneral() {

        var $type = $('#product-type');
        if (!$type.length) return;
        var type = $type.val();
        var $virtual_field = $('#_virtual').closest('label');
        var $downloadable_field = $('#_downloadable').closest('label');
        var $shipping_tab = $('li.shipping_options');
        var $linked_tab = $('li.linked_product_options');
        var $all_tabs_li = $('#woocommerce-product-data').find('ul.wc-tabs li');
        var $all_panels = $('#woocommerce-product-data').find('.panel');
        var $general_tab_li = $('li.general_options');
        var $general_panel = $('#general_product_data');


        if (type === 'mysterx') {
            jQuery('.show_if_simple').show();
			console.log('Showing simple product options for MysterX');
            jQuery('.inventory_options').show();
            jQuery('.general_options').show();
            jQuery('#inventory_product_data ._manage_stock_field').addClass('hide_if_mysterx').hide();
            jQuery('#inventory_product_data ._sold_individually_field').parent().addClass('hide_if_mysterx').hide();
            jQuery('#inventory_product_data ._sold_individually_field').addClass('hide_if_mysterx').hide();
            jQuery('#inventory_product_data ._stock_field ').addClass('hide_if_mysterx').hide();
            jQuery('#inventory_product_data ._backorders_field ').parent().addClass('hide_if_mysterx').hide();
            jQuery('#inventory_product_data ._stock_status_field ').addClass('hide_if_mysterx').hide();
            jQuery('#general_product_data .show_if_downloadable').addClass('hide_if_mysterx').hide();

            $virtual_field.hide();
            $downloadable_field.hide();

            $shipping_tab.hide();
            $linked_tab.hide();
            $('#_virtual').prop('checked', true);
            $('#_downloadable').prop('checked', true);
            $all_tabs_li.removeClass('current');
            $general_tab_li.addClass('current');
            $all_panels.hide();
            $general_panel.show();

        }
    }

    jQuery(document).ready(function($) {
        const urlParams = new URLSearchParams(window.location.search);
        if ($('body').hasClass('post-new-php')) {
            if (urlParams.get('mysterxmenu') === '1' && urlParams.get('product_type') === 'mysterx') {
                $('#product-type').val('mysterx');
                $('#product-type').trigger('change');
            }
        }

        if (urlParams.get('mysterxmenu') === '1') {
            $('#menu-posts-product').removeClass('wp-has-current-submenu wp-menu-open').addClass('wp-not-current-submenu');

            var mysterxMenu = $(
                '#toplevel_page_edit-php-post_type-product-product_type-mysterx, ' +
                'li[class*="mysterx"], ' +
                'a[href*="product_type=mysterx"]'
            ).closest('li');

            mysterxMenu.removeClass('wp-not-current-submenu')
                        .addClass('wp-has-current-submenu wp-menu-open current');
            mysterxMenu.find('> a').addClass('wp-has-current-submenu');
            
            if (window.location.pathname.indexOf('edit.php') > -1) {
                $('#toplevel_page_mysterx .wp-first-item').addClass('current');
            }
        }

        mysterxToggleGeneral();
        $('#product-type').on('change', mysterxToggleGeneral);

    // Repeater logic
    var container = $('#wc-crates-repeater-body');

    function bindRowEvents($row){
        $row.find('.remove').on('click', function(e){
            e.preventDefault();
            $row.remove();
        });
    }

    if (container.length) {
        $('#wc-crates-add-row').on('click', function(e){
            e.preventDefault();
            var index = container.find('.row').length;

            var localizedSearchText = typeof MYSTERX_ADMIN !== 'undefined' ? MYSTERX_ADMIN.search_product : 'Search for a product...';

            // Generate HTML using localized variables and options
            var rowHtml = '<div class="row" data-index="'+index+'">' +
                '<div class="col-handle"><span class="dashicons dashicons-menu"></span></div>' +
                '<div class="col-product">' +
                    '<select class="wc-product-search" name="mysterx_items['+index+'][product_id]" style="width: 100%;" data-placeholder="'+ localizedSearchText +'"></select>' +
                '</div>' +
                '<div class="col-qty"><input type="number" name="mysterx_items['+index+'][quantity]" value="0" min="0" /></div>' +
                '<div class="col-stock"><span>—</span></div>' +
                '<div class="col-action"><button type="button" class="remove">×</button></div>' +
            '</div>';

            var $row = $(rowHtml);
            container.append($row);
            bindRowEvents($row);

            // Allow premium add-ons to hook in
            $(document).trigger('mysterx_row_added', [$row, index]);

            // Re-init selectWoo/select2
            if (typeof wc_enhanced_select_params !== 'undefined') {
                $row.find('.wc-product-search').filter(':not(.select2-hidden-accessible)').selectWoo({
                    allowClear: true,
                    minimumInputLength: 3,
                    ajax: {
                        url: wc_enhanced_select_params.ajax_url,
                        dataType: 'json',
                        delay: 250,
                        data: function(params) {
                            return {
                                term: params.term,
                                action: 'woocommerce_json_search_products_and_variations',
                                security: wc_enhanced_select_params.search_products_nonce
                            };
                        },
                        processResults: function(data) {
                            var results = [];
                            $.each(data, function(id, text) {
                                results.push({ id: id, text: text });
                            });
                            return { results: results };
                        },
                        cache: true
                    }
                });
            }
        });

        // Enable sorting
        if (typeof $.fn.sortable === 'function') {
            container.sortable({
                handle: '.col-handle',
                axis: 'y'
            });
        }

        container.find('.row').each(function(){
            bindRowEvents($(this));
        });

        $('#post').on('submit', function(){
            var items = [];
            container.find('.row').each(function(){
                var $r = $(this);
                var pid = $r.find('select[name$="[product_id]"]').val() || 0;
                
                var $weightInput = $r.find('input[name$="[weight]"]');
                var weight = $weightInput.length ? parseInt($weightInput.val() || 0, 10) : 1;
                if (isNaN(weight)) weight = 1;
                
                var qty = parseInt($r.find('input[name$="[quantity]"]').val() || 0, 10);
                if (isNaN(qty)) qty = 0;

                if(pid > 0) {
                    items.push({ product_id: parseInt(pid, 10), weight: weight, quantity: qty });
                }
            });
            $('#mysterx_items_json').val(JSON.stringify(items));
            return true;
        });
    }
    });

    var observerTarget = document.getElementById('product_data');
    if (observerTarget) {
        var obs = new MutationObserver(function() {
            mysterxToggleGeneral();
        });
        obs.observe(observerTarget, { childList: true, subtree: true });
    }

});
