/**
 * select2 dropdownPosition
 */
var Defaults = jQuery.fn.select2.amd.require('select2/defaults');

jQuery.extend(Defaults.defaults, {
    dropdownPosition: 'auto'
});

var AttachBody = jQuery.fn.select2.amd.require('select2/dropdown/attachBody');

var _positionDropdown = AttachBody.prototype._positionDropdown;

AttachBody.prototype._positionDropdown = function () {

    var $window = jQuery(window);

    var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
    var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');

    var newDirection = null;

    var offset = this.$container.offset();

    offset.bottom = offset.top + this.$container.outerHeight(false);

    var container = {
        height: this.$container.outerHeight(false)
    };

    container.top = offset.top;
    container.bottom = offset.top + container.height;

    var dropdown = {
        height: this.$dropdown.outerHeight(false)
    };

    var viewport = {
        top: $window.scrollTop(),
        bottom: $window.scrollTop() + $window.height()
    };

    var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
    var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);

    var css = {
        left: offset.left,
        top: container.bottom
    };

    // Determine what the parent element is to use for calciulating the offset
    var $offsetParent = this.$dropdownParent;

    // For statically positoned elements, we need to get the element
    // that is determining the offset
    if ($offsetParent.css('position') === 'static') {
        $offsetParent = $offsetParent.offsetParent();
    }

    var parentOffset = $offsetParent.offset();

    css.top -= parentOffset.top
    css.left -= parentOffset.left;

    var dropdownPositionOption = this.options.get('dropdownPosition');

    if (dropdownPositionOption === 'above' || dropdownPositionOption === 'below') {

        newDirection = dropdownPositionOption;

    } else {

        if (!isCurrentlyAbove && !isCurrentlyBelow) {
            newDirection = 'below';
        }

        if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
            newDirection = 'above';
        } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
            newDirection = 'below';
        }

    }

    if (newDirection == 'above' ||
        (isCurrentlyAbove && newDirection !== 'below')) {
        css.top = container.top - parentOffset.top - dropdown.height;
    }

    if (newDirection != null) {
        this.$dropdown
            .removeClass('select2-dropdown--below select2-dropdown--above')
            .addClass('select2-dropdown--' + newDirection);
        this.$container
            .removeClass('select2-container--below select2-container--above')
            .addClass('select2-container--' + newDirection);
    }

    this.$dropdownContainer.css(css);

};

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function cookieUpdate(id, quantity) {
    var cookieName = sbuy_obj.cookie_name;
    var cookie = [];
    var obj = {};
    if (readCookie(cookieName)) {
        cookie = JSON.parse(readCookie(cookieName));
        cookie.forEach((product, i) => {
            if (id === product.id) {
                if (quantity < 1) {
                    cookie.splice(i, 1);
                } else {
                    obj["id"] = id;
                    obj["quantity"] = parseInt(quantity);
                    cookie.splice(i, 1);
                }
            } else {
                obj["id"] = id;
                obj["quantity"] = product.quantity;
            }
        });
    } else {
        obj["id"] = id;
        obj["quantity"] = quantity;
    }
    cookie.push(obj);
    createCookie(cookieName, JSON.stringify(cookie), 1);
}

function textToNumber(text) {
    var price = text.replace(/\s/g, '');
    var reversePrice = price.split('').reverse().join('');
    var decimalSeperator = '';
    // if only dot exists, set decimal_seperator to dot
    if (price.indexOf('.') > 0 && price.indexOf(',') == -1) {
        decimalSeperator = '.';
    }

    // if only comma exists, set decimal_seperator to comma
    if (price.indexOf(',') > 0 && price.indexOf('.') == -1) {
        decimalSeperator = ',';
    }

    // if comma and dot exists, calculte positions of comma and dot for determine decimal seperator
    if (price.indexOf(',') > 0 && price.indexOf('.') > 0) {
        var commaPosition = reversePrice.indexOf(',') ? reversePrice.indexOf(',') : 0;
        var dotPosition = reversePrice.indexOf('.') ? reversePrice.indexOf('.') : 0;
        decimalSeperator = commaPosition < dotPosition ? ',' : '.';
    }

    if (price.indexOf(',') == -1 && price.indexOf('.') == -1) {
        decimalSeperator = '.';
    }

    var splittedPrice = price.split(decimalSeperator),
        thousands = splittedPrice[0] ? splittedPrice[0] : 0,
        decimals = splittedPrice[1] ? splittedPrice[1] : 0;

    thousands = thousands.replace(/[,.]/g, '');
    var newPrice = thousands + '.' + decimals;

    return parseFloat(newPrice).toFixed(2);
}

function numberToText(number) {
    var text = new Intl.NumberFormat('en-DE', {minimumFractionDigits: 2, maximumFractionDigits: 2}).format(number);
    return text;
}

jQuery("#product-search")
    .select2({
        width: '100%',
        dropdownParent: jQuery('#dummy-searchbox-wrap'),
        dropdownPosition: 'below',
        ajax: {
            url: sbuy_obj.ajaxurl,
            dataType: "json",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term,
                    action: "sbuy_search",
                    nonce: sbuy_obj.nonce,
                    lang: sbuy_obj.lang || ""
                };
            },
            processResults: function (response) {
                var options = [];

                if (response.success) {
                    if (response.data) {
                        jQuery.each(response.data, function (index, text) {
                            options.push({
                                id: text[0],
                                text: text[1],
                                type: text["type"],
                            });
                        });
                    }
                } else {
                    options.push({text: response.data.message});
                }
                return {
                    results: options,
                };
            },
            cache: false,
        },
        minimumInputLength: 1,
        placeholder: sbuy_obj.searchbox_placeholder,

        templateSelection: function (data, container) {
            jQuery(data.element).attr("data-type", data.type);
            return data.text;
        },
    })
    .on("change", function (e) {
        var productId = jQuery("#product-search").find(":selected").val();
        if (productId) {
            var type = jQuery("#product-search").find(":selected").data("type");
            jQuery.ajax({
                method: "POST",
                url: sbuy_obj.ajaxurl,
                dataType: "json",
                data: {
                    action: "sbuy_selected",
                    nonce: sbuy_obj.nonce,
                    selectedId: productId,
                    type: type,
                    lang: sbuy_obj.lang || ""
                },
                success: function (response) {
                    jQuery("#product-serch-result>.product-wrap").remove();
                    if (response.data.products) {
                        var htmls = [];
                        for (var i = 0; i < response.data.products.length; i++) {
                            var id = response.data.products[i].id;
                            var title = response.data.products[i].title;
                            var content = response.data.products[i].content;
                            var price = response.data.products[i].price && textToNumber(response.data.products[i].price);

                            htmls.push(`<div class="product-wrap"><div class="title-purchase-add-area">
                <div class="product-title">${title}</div>

                  <div class="purchase-area">
                    <div class="quantity-area">
                      <span class="minus" onclick="this.parentNode.querySelector('[type=number]').stepDown();">-</span>
                      <input type="number" data-quantity="${id}" min="1" value="1" />
                      <span class="plus" onclick="this.parentNode.querySelector('[type=number]').stepUp();">+</span>
                    </div>
                    <div class="add-product-area">
                      <button class="add-product" data-id="${id}">${sbuy_obj.add_product_button}</button>
                    </div>
                  </div>
                </div>
                <div class="description">
                    <p class="product-content">${content}</p>
                    <p class="product-price"><span class="label">${sbuy_obj.product_price_label}:</span> <span class="amount">${numberToText(price)}</span> <span class="currency">${sbuy_obj.currency_symbol}</span></p>
                  </div></div>`);
                        }
                        jQuery("#product-serch-result").append(htmls);
                    }
                },
            });
        }
    });

jQuery("#product-search").one("select2:open", function (e) {
    jQuery("input.select2-search__field").prop(
        "placeholder",
        sbuy_obj.searchbox_input_placeholder
    );
});

// Pass-through: user types in the visible #dummy-searchbox; every keystroke
// drives Select2's hidden search → dropdown with results opens below.
jQuery(document).on("click", ".sbuy-search-trigger", function () {
    jQuery("#dummy-searchbox").trigger("focus");
});

function sbuyForceDummyFocus() {
    var el = document.getElementById("dummy-searchbox");
    if (el && document.activeElement !== el) {
        el.focus();
        // position caret at the end
        var v = el.value;
        el.setSelectionRange(v.length, v.length);
    }
}

jQuery(document).on("focus", "#dummy-searchbox", function () {
    if (!jQuery(".select2-container--open").length) {
        jQuery("#product-search").select2("open");
    }
    // Select2 asynchronously moves focus to its internal search field. Pull
    // focus back on the next tick so the user keeps typing in #dummy-searchbox.
    setTimeout(sbuyForceDummyFocus, 0);
    setTimeout(sbuyForceDummyFocus, 30);
});

jQuery(document).on("input", "#dummy-searchbox", function () {
    var val = jQuery(this).val();
    if (!jQuery(".select2-container--open").length) {
        jQuery("#product-search").select2("open");
    }
    var $internal = jQuery(".select2-search__field");
    if ($internal.length && $internal.val() !== val) {
        $internal.val(val).trigger("input");
    }
});

// Whenever focus lands in the hidden internal search, kick it back.
jQuery(document).on("focus", ".select2-search__field", function () {
    setTimeout(sbuyForceDummyFocus, 0);
});

// Lightweight, language-neutral "added" toast: green check + product title.
// No words → works in DE and EN without translation files.
function sbuyShowToast(title) {
    var $container = jQuery('#sbuy-toast-container');
    if (!$container.length) {
        $container = jQuery('<div id="sbuy-toast-container" aria-live="polite"></div>').appendTo('body');
    }
    var $toast = jQuery(
        '<div class="sbuy-toast">' +
        '<span class="sbuy-toast__check" aria-hidden="true">' +
        '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>' +
        '</span><span class="sbuy-toast__title"></span></div>'
    );
    $toast.find('.sbuy-toast__title').text(title); // .text() = safe against HTML injection
    $container.append($toast);
    requestAnimationFrame(function () {
        $toast.addClass('sbuy-toast--visible');
    });
    setTimeout(function () {
        $toast.removeClass('sbuy-toast--visible');
        setTimeout(function () { $toast.remove(); }, 350);
    }, 2500);
}

jQuery(document).on("click", ".add-product", function () {
    var cookieName = sbuy_obj.cookie_name;
    var newProductId = jQuery(this).data("id");
    var newProductQuantity = jQuery(this)
        .closest(".purchase-area")
        .find("input")
        .val();
    // Grab the title now — the search result (.product-wrap) gets removed below.
    var addedTitle = jQuery(this).closest('.product-wrap').find('.product-title').text();
    var cookie = [];
    var obj = {};
    if (readCookie(cookieName)) {
        cookie = JSON.parse(readCookie(cookieName));
        cookie.forEach((product, i) => {
            if (newProductId === product.id) {
                obj["id"] = newProductId;
                obj["quantity"] = product.quantity + parseInt(newProductQuantity);
                cookie.splice(i, 1);
            } else {
                obj["id"] = newProductId;
                obj["quantity"] = parseInt(newProductQuantity);
            }
        });
    } else {
        obj["id"] = newProductId;
        obj["quantity"] = parseInt(newProductQuantity);
    }
    cookie.push(obj);
    createCookie(cookieName, JSON.stringify(cookie), 30);


    var itemAlreadyInCart = jQuery(`.item[data-productid="${newProductId}"]`).length;
    if (itemAlreadyInCart) {
        var $existing = jQuery(`.item[data-productid="${newProductId}"]`);
        $existing.find('.quantity').text(obj['quantity']);
        $existing.prependTo('#product-basket'); // move to top so the change is visible
        jQuery('#product-cart-empty-message').hide();
    } else {
        var title = jQuery(this).closest('.product-wrap').find('.product-title').text(),
            price = jQuery(this).closest('.product-wrap').find('.product-price .amount').text();
        var html = `<div class="item" data-productid="${newProductId}">
                 <div class="description">
                   <p class="cart-title">${title}</p>
                   <p class="cart-amount"><span class="quantity">${newProductQuantity}</span> x <span class="price"><span class="amount">${price}</span> <span class="currency">${sbuy_obj.currency_symbol}</span></span></p>
                 </div>
                 <span class="remove-product"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span>
               </div>`;
        jQuery("#product-basket").prepend(html);
        jQuery('#product-cart-empty-message').hide();
    }

    jQuery(".product-wrap").remove();
    jQuery("#product-search").val(null).trigger("change");
    // Clear the visible search box (and Select2's internal field) so the next entry starts empty.
    jQuery("#dummy-searchbox").val("");
    jQuery(".select2-search__field").val("");

    // Ensure the shared sticky footer wrapper exists (holds subtotal + checkout button).
    if (jQuery('#sbuy-cart-footer').length === 0) {
        jQuery("#product-basket").after('<div id="sbuy-cart-footer"></div>');
    }

    if (jQuery('#cart-subtotal').length == 0) {
        var subtotalPrice = newProductQuantity * textToNumber(price);
        jQuery("#sbuy-cart-footer").append(
            `<p id="cart-subtotal"><span class="subtotal-text">${sbuy_obj.subtotal_label}:</span> <span class="subtotal-amount"><span class="amount">${numberToText(subtotalPrice)}</span> <span class="currency">${sbuy_obj.currency_symbol}</span></p>`
        );
    } else {
        var price = parseFloat(textToNumber(jQuery(`.item[data-productid="${newProductId}"] .price .amount`).text()));
        var previousSubTotal = parseFloat(textToNumber(jQuery('#cart-subtotal .subtotal-amount .amount').text()));
        var newSubtotalPrice = previousSubTotal + (newProductQuantity * price);
        jQuery("#cart-subtotal .subtotal-amount .amount").text(numberToText(newSubtotalPrice));
    }

    if (jQuery('#checkout-button').length === 0) {
        jQuery("#sbuy-cart-footer").append(
            `<button id="checkout-button" class="sb-button"><a href="${sbuy_obj.checkout_page_link}">${sbuy_obj.checkout_button_label}</a></button>`
        );
    }

    // --- Success feedback: toast + row highlight + (mobile) vibration ---
    sbuyShowToast(addedTitle);

    var $addedRow = jQuery(`.item[data-productid="${newProductId}"]`);
    if ($addedRow.length) {
        $addedRow.removeClass('sbuy-item-added');
        void $addedRow[0].offsetWidth; // force reflow so the animation restarts on repeat-add
        $addedRow.addClass('sbuy-item-added');
    }

    if (window.navigator && typeof window.navigator.vibrate === 'function') {
        window.navigator.vibrate(30);
    }
});

jQuery(document).on("click", ".remove-product", function () {
    var cookieName = sbuy_obj.cookie_name;
    var productCookie = JSON.parse(readCookie(cookieName));
    var productId = jQuery(this).parent(".item").data("productid");
    var price = 0;

    productCookie.forEach((product, i) => {
        if (product.id === productId) {
            productCookie.splice(i, 1);
        }
    });

    if (productCookie === "undefined" || productCookie.length == 0) {
        eraseCookie(cookieName);
    } else {
        createCookie(cookieName, JSON.stringify(productCookie), 30);
    }

    if (jQuery("#product-basket .item").length == 0) {
        jQuery("#checkout-button").remove();
        jQuery("#cart-subtotal").remove();
        jQuery("#sbuy-cart-footer").remove();
        jQuery('#product-cart__message').show();
    }

    var price = parseFloat(textToNumber(jQuery(this).parent(".item").find(".price .amount").text())),
        quantity = parseFloat(jQuery(this).parent(".item").find(".quantity").text()),
        previousSubTotal = parseFloat(textToNumber(jQuery("#cart-subtotal .subtotal-amount .amount").text())),
        newSubTotal = previousSubTotal - price * quantity;

    if (newSubTotal > 0) {
        jQuery("#cart-subtotal .subtotal-amount .amount").text(numberToText(newSubTotal));
    } else {
        jQuery('#cart-subtotal').remove();
        jQuery('#checkout-button').remove();
        jQuery("#sbuy-cart-footer").remove();
        jQuery('#product-cart-empty-message').show();
    }
    jQuery(`div[data-productid="${productId}"]`).remove();
});

var BasketItem = jQuery('.item').length;
if (BasketItem) {
    jQuery('#product-cart-empty-message').hide();
}
// --- 1.3.7: mobile-only — scroll search to top + cap dropdown height above keyboard ---
(function () {
    var MOBILE_MAX = 768;
    function isMobile() { return window.innerWidth <= MOBILE_MAX; }
    function adjustDropdownHeight() {
        if (!isMobile()) return;
        var dd = document.querySelector('.select2-dropdown');
        if (!dd) return;
        var ddTop = dd.getBoundingClientRect().top;
        var vv = window.visualViewport;
        var vh = vv ? vv.height : window.innerHeight;
        var maxH = Math.max(140, Math.floor(vh - ddTop - 12));
        document.documentElement.style.setProperty('--sbuy-dropdown-max-h', maxH + 'px');
    }
    function scrollSearchToTop() {
        if (!isMobile()) return;
        var wrap = document.querySelector('.searchbox-wrap');
        if (wrap && typeof wrap.scrollIntoView === 'function') {
            wrap.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }
    jQuery(document).on('focus', '#dummy-searchbox', function () {
        scrollSearchToTop();
        setTimeout(adjustDropdownHeight, 350);
    });
    jQuery(document).on('input', '#dummy-searchbox', function () {
        setTimeout(adjustDropdownHeight, 50);
    });
    if (window.visualViewport && window.visualViewport.addEventListener) {
        window.visualViewport.addEventListener('resize', adjustDropdownHeight);
    }
})();
