(function($) {
    'use strict';

    const WCMMQCustom = {
        decimalSeparator: WCMMQ_DATA.decimal_separator || '.',
        decimalCount: parseInt(WCMMQ_DATA.decimal_count || 2),

        init: function() {
            this.bindEvents();
            this.addCustomInputBox();
        },

        // =========================
        // Event Bindings
        // =========================
        bindEvents: function() {
            const self = this;

            // Ajax complete trigger
            $(document).ajaxComplete(function() {
                setTimeout(() => self.addCustomInputBox(), 150);
            });

            // Variation change (WPT compatibility)
            $(document.body).on('wpt_changed_variations', function(e, targetAttributeObject) {
                if (!targetAttributeObject.status) return;
                const productId = targetAttributeObject.product_id;
                const variationId = targetAttributeObject.variation_id;
                const variationData = $('#wcmmq_variation_data_' + productId).data('variation_data');
                const qtyBoxWPT = $('.product_id_' + productId + ' input.input-text.qty.text');
                self.distributeMinMax(variationId, variationData, qtyBoxWPT);
            });

            // Validation message customization
            $(document).on('keyup invalid change', 'input.input-text.qty.text.wcmmq-qty-custom-validation', function() {
                self.validateCustomMessage(this);
            });

            // Variation stock/limits
            $(document.body).on('change', 'form.variations_form.cart input.variation_id', function() {
                self.handleVariationChange($(this));
            });

            // Comma separator input handling
            $(document.body).on('keyup', '.wcmmq-second-input-box', function(e) {
                self.handleSecondInputKeyup(e, $(this));
            });

            // Sync quantity box on change
            const qtySelector = '.qib-button-wrapper .quantity input.input-text.qty.text, .single-product div.product form.cart .quantity input[type=number]';
            $(document.body).on('change', qtySelector, function() {
                self.syncSecondInput($(this));
            });
        },

        // =========================
        // Core Functions
        // =========================
        addCustomInputBox: function() {
            const self = this;
            if (self.decimalSeparator !== '.') {
                $('input.input-text.qty.text').not('.wcmmq-second-input-box,.wcmmq-main-input-box').each(function() {
                    $(this).addClass('wcmmq-main-input-box');
                    const inputVal = $(this).val();
                    const valWithComma = inputVal.replace(/\./g, self.decimalSeparator);
                    const parentQuantity = $(this).parents('.quantity');
                    parentQuantity.addClass('wcmmq-coma-separator-activated');
                    $(this).after('<input type="text" value="' + valWithComma + '" class="wcmmq-second-input-box input-text qty text">');
                });
            }
        },

        validateCustomMessage: function(inputEl) {
            const $el = $(inputEl);
            const DataObject = $('.wcmmq-json-options-data');
            const stepValidationMsg = DataObject.data('step_error_valiation') || '';
            let fullMessage = "";
            const msgMinLimit = (DataObject.data('msg_min_limit') || '') + " ";
            const msgMaxLimit = (DataObject.data('msg_max_limit') || '') + " ";
            const productName = "🎁 Product";

            let inputValue = parseFloat($el.val());
            const min = parseFloat($el.attr('min'));
            const max = parseFloat($el.attr('max'));
            const step = parseFloat($el.attr('step'));

            let lowerNearest = Math.floor((inputValue - min) / step) * step + min;
            let upperNearest = lowerNearest + step;

            if (inputValue < min) {
                fullMessage += msgMinLimit.replace("[min_quantity]", min);
                lowerNearest = min;
                upperNearest = lowerNearest + step;
            } else if (inputValue > max && max > min) {
                fullMessage += msgMaxLimit.replace("[max_quantity]", max);
                lowerNearest = max - step;
                upperNearest = max;
            }

            let msg = stepValidationMsg.replace("[should_min]", lowerNearest).replace("[should_next]", upperNearest);
            fullMessage += msg;

            let finalMessage = fullMessage.replace('"[product_name]"', productName).replace("[product_name]", productName);

            if (inputValue < min || inputValue > max || (inputValue - min) % step !== 0) {
                inputEl.setCustomValidity(finalMessage);
                this.showNotification(finalMessage, 'error');
            } else {
                inputEl.setCustomValidity('');
            }
        },

        handleVariationChange: function($input) {
            const form = $input.closest('form.variations_form.cart');
            form.find('.wcmmq-custom-stock-msg').remove();

            const qtyBox = form.find('input.input-text.qty.text');
            let variationId = parseInt($input.val());

            if (!(variationId > 0)) return;

            let productVariations = form.data('product_variations');
            if (!productVariations) {
                productVariations = form.find('.wcmmq-available-variaions').data('product_variations');
            }

            $.each(productVariations, function(index, eachVariation) {
                if (eachVariation.variation_id == variationId) {

                    let { is_in_stock, availability_html, min_value, max_value, step } = eachVariation;

                    if (!is_in_stock) {
                        form.find('.single_variation_wrap').prepend('<div class="wcmmq-custom-stock-msg">' + availability_html + '</div>');
                        min_value = max_value = step = 0;
                    }

                    const updater = setInterval(() => {
                        qtyBox.attr({ min: min_value, max: max_value, step: step, value: min_value });
                        qtyBox.val(min_value).trigger('change');
                        clearInterval(updater);
                    }, 200);


                    if (!is_in_stock) {
                        WCMMQCustom.showNotification('This variation is out of stock.', 'error', 8000);
                    }
                }
            });
        },

        distributeMinMax: function(variationId, variationData, qtyBox) {
            if (!variationId || !variationData[variationId]) return;

            const min = variationData[variationId]['min_quantity'];
            const max = variationData[variationId]['max_quantity'];
            const step = variationData[variationId]['step_quantity'];


            setTimeout(() => {
                qtyBox.attr({ min: min, max: max, step: step, value: min });
                qtyBox.val(min).trigger('change');
            }, 500);

            this.showNotification(`Quantity set between ${min} - ${max}`, 'info');
        },

        handleSecondInputKeyup: function(Event, $input) {
            let arrowPress = false;

            if (Event.originalEvent) {
                if (Event.originalEvent.keyCode === 38 || Event.originalEvent.code === 'ArrowUp') {
                    arrowPress = 'ArrowUp';
                } else if (Event.originalEvent.keyCode === 40 || Event.originalEvent.code === 'ArrowDown') {
                    arrowPress = 'ArrowDown';
                }
            }

            if (!arrowPress) {
                const parentQuantity = $input.parents('.quantity');
                const secondValWithDot = $input.val().replace(/,/g, '.');
                parentQuantity.find('.wcmmq-main-input-box').val(secondValWithDot);
            } else {
                Event.preventDefault();
                this.plusMinusOnArrowCalculate(arrowPress, $input);
            }
        },

        plusMinusOnArrowCalculate: function(type, $secondInput) {
            const qty = $secondInput.closest('.wcmmq-coma-separator-activated').find('.wcmmq-main-input-box');
            let val = parseFloat(qty.val());
            const max = parseFloat(qty.attr("max"));
            const min = parseFloat(qty.attr("min"));
            const step = parseFloat(qty.attr("step"));

            if (type === 'ArrowUp') {
                if (val === max) return false;
                if (isNaN(val)) { qty.val(step).trigger('change'); return false; }
                qty.val(val + step);
            } else if (type === 'ArrowDown') {
                if (val === min) return false;
                if (isNaN(val)) { qty.val(min).trigger('change'); return false; }
                qty.val(val - step < min ? min : val - step);
            }

            qty.val(Math.round(qty.val() * 100000) / 100000);
            qty.trigger("change");
        },

        syncSecondInput: function($mainInput) {
            let val = $mainInput.val();
            if (this.decimalSeparator !== '.') {
                val = val.replace(/\./g, this.decimalSeparator);
            }
            $mainInput.parents('.quantity').find('.wcmmq-second-input-box').val(val);
        },

        // =========================
        // Notification System
        // =========================

        showNotification: function (message, type = 'info', timeout = 3000) {
            const $notification = $(`<div class="wcmmq-notification wcmmq-notification-${type}">${message}</div>`);

            // style for notification
            $notification.css({
                background: type === 'success' ? '#46b450' : (type === 'error' ? '#dc3232' : '#0073aa'),
                color: 'white',
                padding: '10px 18px',
                borderRadius: '4px',
                fontSize: '13px',
                fontWeight: '500',
                boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
                transform: 'translateX(120%)',
                transition: 'transform 0.3s ease',
                cursor: 'pointer'
            });

            // container for stacking
            let $container = $('.wcmmq-notification-container');
            if (!$container.length) {
                $container = $('<div class="wcmmq-notification-container"></div>').css({
                    position: 'fixed',
                    top: '52px',
                    right: '30px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'flex-end',
                    gap: '10px',
                    zIndex: 1000000
                });
                $('body').append($container);
            }

            // add to container
            $container.append($notification);

            // animate in
            setTimeout(() => $notification.css('transform', 'translateX(0)'), 30);

            // auto remove after 3s
            setTimeout(() => {
                $notification.css('transform', 'translateX(120%)');
                setTimeout(() => $notification.remove(), 300);
            }, timeout);
            $notification.on('click', function() {
                $(this).css('transform', 'translateX(100%)');
                setTimeout(() => $(this).remove(), 300);
            });
        }
    };

    $(document).ready(function() {
        WCMMQCustom.init();
    });

    window.WCMMQCustom = WCMMQCustom;

})(jQuery);
