/**
 * FoodOrd Toppings Interactive Functionality
 *
 * Handles the interactive behavior of toppings selections in product modal
 *
 * @package FoodOrd
 */

(function ($) {
    'use strict';

    class FoodOrdToppings {
        constructor() {

            this.init();
        }

        init() {
            this.bindEvents();
            this.initializeCollapsibleGroups();
            this.updateSelectedStates();
        }

        bindEvents() {
            // Handle radio/checkbox changes
            $(document).on('change', '.foodord-product-toppings__input', (e) => {
                this.handleInputChange($(e.target));
            });



            // Handle select changes
            $(document).on('change', '.foodord-product-toppings__select', (e) => {
                this.handleSelectChange($(e.target));
            });

            $(document).on('click', '.foodord-product-toppings__dropdown .foodord-ttd__trigger', (e) => {
                e.preventDefault();

                const $trigger = $(e.currentTarget);
                if ($trigger.prop('disabled')) {
                    return;
                }

                const $dropdown = $trigger.closest('.foodord-product-toppings__dropdown');
                const isOpen = $dropdown.hasClass('is-open');

                this.closeCustomDropdowns($dropdown.get(0));
                $dropdown.toggleClass('is-open', !isOpen);
                $trigger.attr('aria-expanded', String(!isOpen));

                if (!isOpen) {
                    this.positionCustomDropdown($dropdown);
                } else {
                    $dropdown.removeClass('foodord-ttd__dropdown--upward');
                }
            });

            $(document).on('click', '.foodord-product-toppings__dropdown .foodord-ttd__option', (e) => {
                const $option = $(e.currentTarget);
                const $dropdown = $option.closest('.foodord-product-toppings__dropdown');
                const $select = $dropdown.siblings('.foodord-product-toppings__select');

                if (!$select.length || $option.prop('disabled')) {
                    return;
                }

                e.preventDefault();

                $select.val(String($option.data('value'))).trigger('change');
                this.closeCustomDropdowns();
            });

            $(document).on('keydown', '.foodord-product-toppings__dropdown .foodord-ttd__trigger', (e) => {
                if (e.key === 'Escape') {
                    this.closeCustomDropdowns();
                    e.currentTarget.blur();
                    return;
                }

                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    $(e.currentTarget).trigger('click');
                }
            });

            $(document).on('click', (e) => {
                if (!$(e.target).closest('.foodord-product-toppings__dropdown').length) {
                    this.closeCustomDropdowns();
                }
            });

            $(window).on('resize.foodordToppingsDropdown', () => {
                $('.foodord-product-toppings__dropdown.is-open').each((index, dropdown) => {
                    this.positionCustomDropdown($(dropdown));
                });
            });

            // Handle show more/less toggles
            $(document).on('click', '.foodord-product-toppings__toggle', (e) => {
                e.preventDefault();
                this.toggleCollapsibleGroup($(e.currentTarget));
            });
        }



        handleInputChange($input) {
            const $option = $input.closest('.foodord-product-toppings__option');
            const inputType = $input.attr('type');
            const isChecked = $input.is(':checked');

            if (inputType === 'radio') {
                // Remove checked class from all radio options in the same group
                const groupName = $input.attr('name');
                $(`input[name="${groupName}"]`).closest('.foodord-product-toppings__option')
                    .removeClass('is-checked');

                // Add checked class to selected option
                if (isChecked) {
                    $option.addClass('is-checked');
                }
            } else if (inputType === 'checkbox') {
                // Enforce only the MAX limit live; do not block unchecking (customers may want to change selection).
                // Minimum requirements are validated on add-to-cart.
                const $set = $input.closest('.foodord-product-toppings__set');

                // Only validate if trying to check (not uncheck)
                if (isChecked && !this.validateCheckboxLimits($input, $set, isChecked)) {
                    // If validation fails, prevent the change and return early
                    $input.prop('checked', false);
                    return;
                }

                // Toggle checked class for checkbox
                $option.toggleClass('is-checked', isChecked);

                // Update visual feedback for the entire checkbox group
                this.updateCheckboxGroupFeedback($set);
            }

            // Update pricing and header status
            this.updatePricing();
            this.updateHeaderStatus($input.closest('.foodord-product-toppings__set'));
        }

        handleSelectChange($select) {
            const selectedValue = $select.val();

            // Add visual feedback for select
            $select.toggleClass('has-selection', selectedValue !== '');
            this.syncCustomSelectDropdown($select);

            // Update pricing and header status
            this.updatePricing();
            this.updateHeaderStatus($select.closest('.foodord-product-toppings__set'));
        }

        updateSelectedStates() {
            // Update checked states on page load
            $('.foodord-product-toppings__input:checked').each((index, input) => {
                this.handleInputChange($(input));
            });

            // Update select states
            $('.foodord-product-toppings__select').each((index, select) => {
                this.handleSelectChange($(select));
            });

            // Update header states
            $('.foodord-product-toppings__set, .foodord-attr-wrapper').each((index, set) => {
                this.updateHeaderStatus($(set));
            });
        }

        closeCustomDropdowns(exceptDropdown = null) {
            $('.foodord-product-toppings__dropdown.is-open').each((index, dropdown) => {
                if (exceptDropdown && dropdown === exceptDropdown) {
                    return;
                }

                const $dropdown = $(dropdown);
                $dropdown.removeClass('is-open');
                $dropdown.removeClass('foodord-ttd__dropdown--upward');
                $dropdown.find('.foodord-ttd__trigger').attr('aria-expanded', 'false');
            });
        }

        positionCustomDropdown($dropdown) {
            if (!$dropdown || !$dropdown.length) {
                return;
            }

            const dropdownEl = $dropdown.get(0);
            const triggerEl = $dropdown.find('.foodord-ttd__trigger').get(0);
            const menuEl = $dropdown.find('.foodord-ttd__menu').get(0);

            if (!dropdownEl || !triggerEl || !menuEl) {
                return;
            }

            const triggerRect = triggerEl.getBoundingClientRect();
            const modalBody = dropdownEl.closest('.foodord-modal-body');
            const spacing = 10;
            const viewportTop = 8;
            const viewportBottom = window.innerHeight - 8;
            let visibleTop = viewportTop;
            let visibleBottom = viewportBottom;

            if (modalBody) {
                const modalBodyRect = modalBody.getBoundingClientRect();
                visibleTop = Math.max(visibleTop, modalBodyRect.top + 8);
                visibleBottom = Math.min(visibleBottom, modalBodyRect.bottom - 8);
            }

            const desiredHeight = Math.min(menuEl.scrollHeight || 0, 260);
            const spaceBelow = Math.max(0, visibleBottom - triggerRect.bottom - spacing);
            const spaceAbove = Math.max(0, triggerRect.top - visibleTop - spacing);
            const shouldOpenUpward = spaceBelow < desiredHeight && spaceAbove > spaceBelow;
            $dropdown.toggleClass('foodord-ttd__dropdown--upward', shouldOpenUpward);
        }

        syncCustomSelectDropdown($select) {
            if (!$select || !$select.length) {
                return;
            }

            let $dropdown = $select.siblings('.foodord-product-toppings__dropdown');

            if (!$dropdown.length) {
                $dropdown = $(`
                    <div class="foodord-product-toppings__dropdown foodord-ttd__dropdown">
                        <button type="button" class="foodord-ttd__trigger" aria-expanded="false">
                            <span class="foodord-ttd__trigger-label"></span>
                            <span class="foodord-ttd__trigger-icon" aria-hidden="true">
                                <svg viewBox="0 0 20 20" fill="none" focusable="false">
                                    <path d="M6 8L10 12L14 8" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"></path>
                                </svg>
                            </span>
                        </button>
                        <div class="foodord-ttd__menu" role="listbox"></div>
                    </div>
                `);

                $select.addClass('foodord-ttd__native-select').after($dropdown);
            }

            const $trigger = $dropdown.find('.foodord-ttd__trigger');
            const $triggerLabel = $dropdown.find('.foodord-ttd__trigger-label');
            const $menu = $dropdown.find('.foodord-ttd__menu');
            const selectedValue = String($select.val() || '');
            const isDisabled = $select.prop('disabled');
            const selectedText = $.trim($select.find('option:selected').text()) || $.trim($select.find('option').first().text());

            $triggerLabel.text(selectedText);
            $trigger.prop('disabled', isDisabled);
            $trigger.attr('aria-expanded', $dropdown.hasClass('is-open') ? 'true' : 'false');
            $menu.empty();

            $select.find('option').each((index, option) => {
                const $option = $(option);
                const optionValue = String($option.val() || '');
                const optionText = $.trim($option.text());
                const isSelected = optionValue === selectedValue;
                const optionDisabled = $option.prop('disabled');
                const $menuOption = $('<button type="button" class="foodord-ttd__option"></button>');

                $menuOption.text(optionText);
                $menuOption.attr('role', 'option');
                $menuOption.attr('aria-selected', isSelected ? 'true' : 'false');
                $menuOption.data('value', optionValue);
                $menuOption.toggleClass('is-selected', isSelected);

                if (optionDisabled) {
                    $menuOption.prop('disabled', true);
                }

                $menu.append($menuOption);
            });

            if (isDisabled) {
                this.closeCustomDropdowns($dropdown.get(0));
            }
        }

        updatePricing() {
            // Get all selected toppings and calculate total
            let totalToppingsPrice = 0;
            // Scope to the visible modal to avoid double-counting from other parts of the page
            const $modal = $('.foodord-modal:visible').length ? $('.foodord-modal:visible') : $('.foodord-modal');

            // Calculate radio/checkbox selections using data-price attributes when available
            $modal.find('.foodord-product-toppings__input:checked').each((index, input) => {
                const $input = $(input);
                const attrPrice = parseFloat($input.data('price'));
                if (!isNaN(attrPrice)) {
                    totalToppingsPrice += attrPrice;
                    return;
                }
                // Fallback to parsing visible price text if attribute is missing
                const $priceSpan = $input.closest('.foodord-product-toppings__option')
                    .find('.foodord-product-toppings__option-price');
                if ($priceSpan.length) {
                    const priceText = $priceSpan.text().replace(/[^\d.,]/g, '');
                    const price = parseFloat(priceText.replace(',', '.')) || 0;
                    totalToppingsPrice += price;
                }
            });

            // Calculate select selections (prefer data-price attribute on option)
            $modal.find('.foodord-product-toppings__select').each((index, select) => {
                const $select = $(select);
                const $selectedOption = $select.find('option:selected');
                const attrPrice = parseFloat($selectedOption.data('price'));
                if (!isNaN(attrPrice)) {
                    totalToppingsPrice += attrPrice;
                    return;
                }
                // Fallback: extract from text "Label (€5.00)"
                const optionText = $selectedOption.text();
                const priceMatch = optionText.match(/\(([^)]+)\)$/);
                if (priceMatch) {
                    const priceText = priceMatch[1].replace(/[^\d.,]/g, '');
                    const price = parseFloat(priceText.replace(',', '.')) || 0;
                    totalToppingsPrice += price;
                }
            });

            // Update the add to cart button total
            this.updateAddToCartTotal(totalToppingsPrice);
        }

        updateAddToCartTotal(toppingsPrice) {
            // Scope to visible FoodOrd modal to avoid touching non-modal buttons
            const $modal = $('.foodord-modal:visible').length ? $('.foodord-modal:visible') : $('.foodord-modal');
            if (!$modal.length) { return; }
            const $addToCartBtn = $modal.find('.foodord-modal-footer .foodord-add-to-cart-btn');
            if (!$addToCartBtn.length) { return; }

            // Always treat data-unit-price as BASE price (may change with variation)
            const baseFromBtn = parseFloat($addToCartBtn.data('unit-price'));
            const baseFallback = parseFloat($addToCartBtn.data('unit-price-initial'));
            const basePrice = !isNaN(baseFromBtn) ? baseFromBtn : (!isNaN(baseFallback) ? baseFallback : 0);
            const quantity = parseInt(($modal.find('#foodord-quantity-input').val() || 1), 10);

            // Calculate new unit price including toppings
            const newUnitPrice = basePrice + (toppingsPrice || 0);
            const newTotal = newUnitPrice * quantity;

            // Store toppings extra for footer logic (do not mutate base unit price)
            $addToCartBtn.data('toppings-extra', Number(toppingsPrice || 0));

            // Notify listeners for topping price updates
            $(document).trigger('foodord_toppings_price_updated', {
                basePrice: basePrice,
                toppingsPrice: toppingsPrice,
                unitPrice: newUnitPrice,
                quantity: quantity,
                total: newTotal
            });

            // Get modal footer instance and force update (primary method)
            const footerInstance = $modal.data('footerInstance');
            if (footerInstance && typeof footerInstance.updateAddToCartCta === 'function') {
                footerInstance.updateAddToCartCta();
            } else {
                // Fallback: Manual update if footer instance not available
                const $totalSpan = $addToCartBtn.find('.foodord-add-to-cart-total');
                const $countSpan = $addToCartBtn.find('.foodord-add-to-cart-count');

                if ($totalSpan.length) {
                    $totalSpan.html(this.formatPrice(newTotal));
                }
                if ($countSpan.length) {
                    $countSpan.text(String(quantity));
                }
            }
        }

        formatPrice(price) {
            // Use WooCommerce formatting if available
            if (typeof foodord_modal_vars !== 'undefined') {
                const cfg = foodord_modal_vars;
                const symbol = cfg.currency_symbol || '€';
                const pos = cfg.currency_pos || 'left';
                const decimals = (typeof cfg.price_decimals === 'number') ? cfg.price_decimals : 2;
                const decSep = cfg.price_decimal_sep || '.';
                const thouSep = cfg.price_thousand_sep || ',';

                const negative = price < 0;
                const n = Math.abs(price);
                const fixed = n.toFixed(decimals);
                const [intPartRaw, decPart] = fixed.split('.');
                let intPart = intPartRaw;
                intPart = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, thouSep);
                let number = intPart;
                if (decimals > 0) {
                    number += decSep + (decPart || '').padEnd(decimals, '0');
                }
                let out = '';
                switch (pos) {
                    case 'left':
                        out = symbol + number; break;
                    case 'right':
                        out = number + symbol; break;
                    case 'left_space':
                        out = symbol + ' ' + number; break;
                    case 'right_space':
                        out = number + ' ' + symbol; break;
                    default:
                        out = symbol + number; break;
                }
                return negative ? '-' + out : out;
            }

            // Fallback formatting
            return '€' + price.toFixed(2).replace('.', ',');
        }

        // Validate checkbox min/max limits
        validateCheckboxLimits($input, $set, willBeChecked) {
            const groupType = $set.data('group-type');
            if (groupType !== 'checkbox') {
                return true; // Only validate checkbox groups
            }

            const checkboxMax = parseInt($set.data('checkbox-max'), 10);

            // Never block unchecking; min requirements are enforced during add-to-cart validation.
            if (!willBeChecked) {
                return true;
            }

            // Get current number of checked items (excluding the current input)
            const $allInputs = $set.find('.foodord-product-toppings__input[type="checkbox"]');
            const currentChecked = $allInputs.not($input).filter(':checked').length;
            const finalChecked = currentChecked + (willBeChecked ? 1 : 0);

            // Check maximum limit (only when checking)
            if (willBeChecked && !isNaN(checkboxMax) && checkboxMax > 0 && finalChecked > checkboxMax) {
                return false;
            }

            return true;
        }

        // Update visual feedback for checkbox groups
        updateCheckboxGroupFeedback($set) {
            const groupType = $set.data('group-type');
            if (groupType !== 'checkbox') {
                return;
            }

            const checkboxMin = parseInt($set.data('checkbox-min'), 10);
            const checkboxMax = parseInt($set.data('checkbox-max'), 10);
            const $allInputs = $set.find('.foodord-product-toppings__input[type="checkbox"]');
            const checkedCount = $allInputs.filter(':checked').length;

            $allInputs.each((index, input) => {
                const $input = $(input);
                $input.closest('.foodord-product-toppings__option').toggleClass('is-checked', $input.prop('checked'));
            });

            // Remove previous limit classes
            $set.removeClass('checkbox-at-min checkbox-at-max checkbox-near-max');

            // Check min/max states
            if (!isNaN(checkboxMin) && checkboxMin > 0 && checkedCount <= checkboxMin) {
                $set.addClass('checkbox-at-min');
            }

            if (!isNaN(checkboxMax) && checkboxMax > 0) {
                if (checkedCount >= checkboxMax) {
                    $set.addClass('checkbox-at-max');
                    $allInputs.prop('disabled', false);
                    // Disable unchecked inputs when at maximum
                    $allInputs.not(':checked').prop('disabled', true);
                } else {
                    // Re-enable all inputs when below maximum
                    $allInputs.prop('disabled', false);

                    if (checkedCount >= checkboxMax - 1) {
                        $set.addClass('checkbox-near-max');
                    }
                }
            }

        }

        /**
         * Update the visual status of the set header (badge)
         * @param {jQuery} $set 
         */
        updateHeaderStatus($set) {
            if (!$set.length) return;

            // Detect selection (handles both standard toppings and variation attributes)
            const hasCheckedInput = $set.find('input:checked').length > 0;
            const hasSelectValue = $set.find('select').filter(function () {
                const val = $(this).val();
                return val && val !== '';
            }).length > 0;

            const hasValue = hasCheckedInput || hasSelectValue;

            // Find associated header
            // 1. Check sibling immediately before (standard for both toppings and variations)
            let $header = $set.prev('.foodord-product-toppings__set-header, .foodord-attr-legend');

            // 2. Fallback: Search inside if the structure is nested (defensive)
            if (!$header.length) {
                $header = $set.find('.foodord-attr-legend, .foodord-product-toppings__set-header');
            }

            if (!$header.length) return;

            // Determine min required and current selection count for dynamic required badges.
            const groupType = String($set.data('group-type') || '');
            const isRequired = String($set.data('is-required') || '') === '1';
            const $requiredBadge = $header.find('.foodord-product-toppings__badge--required').first();
            const supportsDynamicCounts = groupType === 'checkbox' && $requiredBadge.is('[data-required-min]');

            let minRequired = 0;
            if ($requiredBadge.length) {
                const minFromBadge = parseInt($requiredBadge.data('required-min'), 10);
                if (!isNaN(minFromBadge) && minFromBadge > 0) {
                    minRequired = minFromBadge;
                }
            }
            if (isRequired && minRequired <= 0) {
                minRequired = 1;
                if ('checkbox' === groupType) {
                    const checkboxMinRaw = parseInt($set.data('checkbox-min'), 10);
                    if (!isNaN(checkboxMinRaw) && checkboxMinRaw > 0) {
                        minRequired = checkboxMinRaw;
                    }
                }
            }

            let selectionCount = 0;
            if ('checkbox' === groupType) {
                selectionCount = $set.find('input[type="checkbox"]:checked').length;
            } else {
                selectionCount = hasValue ? 1 : 0;
            }

            if ($requiredBadge.length) {
                if (supportsDynamicCounts && minRequired > 0) {
                    const remaining = Math.max(minRequired - selectionCount, 0);
                    if (remaining > 0) {
                        const template = String($requiredBadge.data('required-template-number') || '%d Required');
                        $requiredBadge.text(template.replace('%d', String(remaining)));
                    } else {
                        const requiredText = String($requiredBadge.data('required-text') || 'Required');
                        $requiredBadge.text(requiredText);
                    }
                } else {
                    const requiredText = String($requiredBadge.data('required-text') || 'Required');
                    $requiredBadge.text(requiredText);
                }
            }

            const isSatisfied = isRequired ? (selectionCount >= minRequired) : hasValue;

            if (isSatisfied) {
                // Determine if we should re-trigger animation (always for radios to show "new selection" feedback)
                // For checkboxes, we typically only animate on the first selection (0 -> 1)
                const isRadio = $header.hasClass('foodord-attr-legend') || $set.data('group-type') === 'radio';
                const shouldAnimate = !$header.hasClass('has-selection') || isRadio;

                $header.addClass('has-selection');

                if (shouldAnimate) {
                    $header.removeClass('just-selected');
                    // Force reflow to restart animation
                    void $header[0].offsetWidth;
                    $header.addClass('just-selected');
                    setTimeout(() => $header.removeClass('just-selected'), 600);
                }
            } else {
                $header.removeClass('has-selection just-selected');
            }
        }


        // Validation method for required toppings and checkbox limits
        validateRequiredToppings() {
            let isValid = true;
            const errors = [];

            $('.foodord-product-toppings__set').each((index, set) => {
                const $set = $(set);
                const setName = $set.find('.foodord-product-toppings__set-title').text() || $set.data('set-label') || 'Topping Group';
                const groupType = $set.data('group-type');
                const isRequired = $set.data('is-required') === '1' || $set.data('is-required') === 1;

                let hasSelection = false;
                let checkedCount = 0;

                if (groupType === 'dropdown') {
                    const $select = $set.find('.foodord-product-toppings__select');
                    hasSelection = $select.val() !== '';
                } else {
                    checkedCount = $set.find('.foodord-product-toppings__input:checked').length;
                    hasSelection = checkedCount > 0;
                }

                // Check required validation (no visual inline error or class mutations)
                if (isRequired && !hasSelection) {
                    isValid = false;
                    errors.push(`${setName} selection is required.`);
                    // no visual inline error UI (no .has-error class)
                } else {
                    // no visual inline error UI (no .has-error class)
                }

                // Check checkbox min/max limits for checkbox groups
                if (groupType === 'checkbox') {
                    const checkboxMin = parseInt($set.data('checkbox-min'), 10);
                    const checkboxMax = parseInt($set.data('checkbox-max'), 10);

                    if (!isNaN(checkboxMin) && checkboxMin > 0 && checkedCount < checkboxMin) {
                        isValid = false;
                        errors.push(`You must select at least ${checkboxMin} options for ${setName}.`);
                        // no visual inline error UI (no .has-error class)
                    }

                    if (!isNaN(checkboxMax) && checkboxMax > 0 && checkedCount > checkboxMax) {
                        isValid = false;
                        errors.push(`You can select maximum ${checkboxMax} options for ${setName}.`);
                        // no visual inline error UI (no .has-error class)
                    }
                }
            });

            return { isValid, errors };
        }

        // Method to get all selected toppings data
        getSelectedToppings() {
            const toppings = {};

            $('.foodord-product-toppings__set').each((index, set) => {
                const $set = $(set);
                const setId = $set.data('set-id');
                const groupType = $set.data('group-type');

                if (groupType === 'dropdown') {
                    const $select = $set.find('.foodord-product-toppings__select');
                    const selectedValue = $select.val();
                    if (selectedValue) {
                        toppings[setId] = selectedValue;
                    }
                } else {
                    const selectedValues = [];
                    $set.find('.foodord-product-toppings__input:checked').each((i, input) => {
                        selectedValues.push($(input).val());
                    });
                    if (selectedValues.length > 0) {
                        toppings[setId] = groupType === 'radio' ? selectedValues[0] : selectedValues;
                    }
                }
            });

            return toppings;
        }

        initializeCollapsibleGroups(context) {
            const $context = context ? $(context) : $(document);
            const $groups = $context.find('.foodord-product-toppings__options--collapsible');

            if (!$groups.length) {
                return;
            }

            $groups.each((index, element) => {
                const $options = $(element);
                const $button = this.findToggleButton($options);
                if (!$button.length) {
                    return;
                }

                const collapsedText = $button.data('collapsed-text');
                if (collapsedText) {
                    this.updateToggleText($button, collapsedText);
                }

                $button.attr('aria-expanded', 'false').removeClass('is-expanded');
                this.applyCollapsedState($options, true);
            });
        }

        toggleCollapsibleGroup($button) {
            if (!$button || !$button.length) {
                return;
            }

            const controlsId = $button.attr('aria-controls');
            let $options = null;

            if (controlsId) {
                $options = $('#' + controlsId);
            }

            if (!$options || !$options.length) {
                $options = $button.prev('.foodord-product-toppings__options');
            }

            if (!$options || !$options.length) {
                return;
            }

            const isExpanded = $button.attr('aria-expanded') === 'true';
            const collapsedText = $button.data('collapsed-text');
            const expandedText = $button.data('expanded-text');

            if (isExpanded) {
                this.applyCollapsedState($options, true);
                $button.attr('aria-expanded', 'false').removeClass('is-expanded');
                if (collapsedText) {
                    this.updateToggleText($button, collapsedText);
                }
            } else {
                this.applyCollapsedState($options, false);
                $button.attr('aria-expanded', 'true').addClass('is-expanded');
                if (expandedText) {
                    this.updateToggleText($button, expandedText);
                }
            }
        }

        applyCollapsedState($options, collapsed) {
            const $items = $options.find('.foodord-product-toppings__option');
            const limit = 3;

            if (collapsed) {
                $options.addClass('is-collapsed').removeClass('is-expanded');
                $items.each((index, element) => {
                    const $item = $(element);
                    const isChecked = $item.find('.foodord-product-toppings__input').is(':checked');
                    $item.toggleClass('is-hidden-by-toggle', index >= limit && !isChecked);
                });
            } else {
                $options.removeClass('is-collapsed').addClass('is-expanded');
                $items.removeClass('is-hidden-by-toggle');
            }
        }

        findToggleButton($options) {
            if (!$options || !$options.length) {
                return $();
            }

            const $nextButton = $options.next('.foodord-product-toppings__toggle');
            if ($nextButton.length) {
                return $nextButton;
            }

            return $options.closest('.foodord-product-toppings__set').find('.foodord-product-toppings__toggle').first();
        }

        updateToggleText($button, text) {
            const $textSpan = $button.find('.foodord-product-toppings__toggle-text');
            if ($textSpan.length) {
                $textSpan.text(text);
            } else {
                $button.text(text);
            }
        }
    }

    // Initialize when DOM is ready
    $(document).ready(() => {
        // Initialize toppings functionality
        window.foodordToppings = new FoodOrdToppings();

        // Listen to quantity changes to update pricing
        $(document).on('change input', '#foodord-quantity-input', () => {
            window.foodordToppings.updatePricing();
        });

        // Listen to variation changes (if applicable) to recalculate base price
        $(document).on('change', '.variations_form select', () => {
            // Wait a bit for WooCommerce to process the variation change
            setTimeout(() => {
                window.foodordToppings.updatePricing();
            }, 100);
        });

        // Global fix for mobile scroll hover issues
        let scrollTimer;
        window.addEventListener('scroll', () => {
            document.body.classList.add('foodord-is-scrolling');
            clearTimeout(scrollTimer);
            scrollTimer = setTimeout(() => {
                document.body.classList.remove('foodord-is-scrolling');
            }, 150);
        }, { passive: true, capture: true });
    });

})(jQuery);
