(function (window, document) {
    'use strict';

    function getQrOption(element, name, fallback) {
        var value = element.getAttribute('data-noesia-cs-qr-' + name);
        if (value === null || value === '') {
            return fallback;
        }
        return value;
    }


    function copyText(value) {
        if (!value) {
            return Promise.reject();
        }
        if (window.navigator && window.navigator.clipboard && window.navigator.clipboard.writeText) {
            return window.navigator.clipboard.writeText(value);
        }
        return new Promise(function (resolve, reject) {
            var textarea = document.createElement('textarea');
            textarea.value = value;
            textarea.setAttribute('readonly', 'readonly');
            textarea.style.position = 'fixed';
            textarea.style.left = '-9999px';
            document.body.appendChild(textarea);
            textarea.select();
            try {
                if (document.execCommand('copy')) {
                    resolve();
                } else {
                    reject();
                }
            } catch (error) {
                reject(error);
            }
            document.body.removeChild(textarea);
        });
    }

    function bindPromoCodeCopy() {
        document.querySelectorAll('[data-noesia-cs-copy-code]').forEach(function (element) {
            var resetTimer = null;
            var copy = function () {
                var value = element.getAttribute('data-noesia-cs-copy-code') || element.textContent;
                var original = element.getAttribute('data-noesia-cs-copy-original') || value;
                var done = element.getAttribute('data-noesia-cs-copy-done') || 'Copied!';
                copyText(value).then(function () {
                    element.textContent = done;
                    element.setAttribute('aria-live', 'polite');
                    window.clearTimeout(resetTimer);
                    resetTimer = window.setTimeout(function () {
                        element.textContent = original;
                    }, 1400);
                }).catch(function () {});
            };
            element.addEventListener('click', copy);
            element.addEventListener('keydown', function (event) {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    copy();
                }
            });
        });
    }

    function getCheckoutForm() {
        return document.querySelector('form.checkout, form.woocommerce-checkout, form[name="checkout"]');
    }

    function setCheckoutCookie(name, value) {
        if (!name) {
            return;
        }
        var secure = window.location.protocol === 'https:' ? '; Secure' : '';
        document.cookie = name + '=' + encodeURIComponent(value || '') + '; Max-Age=86400; Path=/; SameSite=Lax' + secure;
    }

    function clearCheckoutCookie(name) {
        if (!name) {
            return;
        }
        var secure = window.location.protocol === 'https:' ? '; Secure' : '';
        document.cookie = name + '=; Max-Age=0; Path=/; SameSite=Lax' + secure;
    }

    function findSelectedCheckoutReorderBox() {
        var selectedBox = null;
        document.querySelectorAll('[data-noesia-cs-checkout-reorder]').forEach(function (box) {
            var toggle = box.querySelector('[data-noesia-cs-checkout-reorder-toggle]');
            if (toggle && toggle.checked) {
                selectedBox = box;
            }
        });
        return selectedBox;
    }

    function setHiddenCheckoutValue(form, name, value) {
        if (!form || !name) {
            return;
        }

        var field = form.querySelector('input[type="hidden"][data-noesia-cs-checkout-reorder-proxy="' + name + '"]');
        if (!field) {
            field = document.createElement('input');
            field.type = 'hidden';
            field.name = name;
            field.setAttribute('data-noesia-cs-checkout-reorder-proxy', name);
            form.appendChild(field);
        }
        field.value = value || '';
    }

    function removeHiddenCheckoutValue(form, name) {
        if (!form || !name) {
            return;
        }

        var field = form.querySelector('input[type="hidden"][data-noesia-cs-checkout-reorder-proxy="' + name + '"]');
        if (field && field.parentNode) {
            field.parentNode.removeChild(field);
        }
    }

    function syncCheckoutReorderSubmission() {
        var form = getCheckoutForm();
        var selectedBox = findSelectedCheckoutReorderBox();

        if (!selectedBox) {
            if (form) {
                removeHiddenCheckoutValue(form, 'noesia_cs_reorder_request');
                removeHiddenCheckoutValue(form, 'noesia_cs_reorder_date');
            }
            clearCheckoutCookie('noesia_cs_reorder_request');
            clearCheckoutCookie('noesia_cs_reorder_date');
            return;
        }

        var dateInput = selectedBox.querySelector('[data-noesia-cs-checkout-reorder-date] input[type="date"]');
        var dateValue = dateInput ? dateInput.value : '';

        if (form) {
            setHiddenCheckoutValue(form, 'noesia_cs_reorder_request', 'yes');
            setHiddenCheckoutValue(form, 'noesia_cs_reorder_date', dateValue);
        }

        setCheckoutCookie('noesia_cs_reorder_request', 'yes');
        setCheckoutCookie('noesia_cs_reorder_date', dateValue);
    }

    function bindCheckoutReorderRequest() {
        document.querySelectorAll('[data-noesia-cs-checkout-reorder]').forEach(function (box) {
            var toggle = box.querySelector('[data-noesia-cs-checkout-reorder-toggle]');
            var dateBox = box.querySelector('[data-noesia-cs-checkout-reorder-date]');
            var dateInput = dateBox ? dateBox.querySelector('input[type="date"]') : null;
            if (!toggle || !dateBox) {
                return;
            }
            var sync = function () {
                if (toggle.checked) {
                    dateBox.hidden = false;
                    if (dateInput) {
                        dateInput.setAttribute('required', 'required');
                    }
                } else {
                    dateBox.hidden = true;
                    if (dateInput) {
                        dateInput.removeAttribute('required');
                        dateInput.value = '';
                    }
                }
                syncCheckoutReorderSubmission();
            };
            toggle.addEventListener('change', sync);
            if (dateInput) {
                dateInput.addEventListener('change', syncCheckoutReorderSubmission);
                dateInput.addEventListener('input', syncCheckoutReorderSubmission);
            }
            sync();
        });

        var checkoutForm = getCheckoutForm();
        if (checkoutForm) {
            checkoutForm.addEventListener('submit', syncCheckoutReorderSubmission, true);
            checkoutForm.addEventListener('change', syncCheckoutReorderSubmission, true);
        }

        document.addEventListener('click', function (event) {
            var target = event.target;
            if (target && target.closest && target.closest('#place_order')) {
                syncCheckoutReorderSubmission();
            }
        }, true);

        document.addEventListener('mousedown', function (event) {
            var target = event.target;
            if (target && target.closest && target.closest('#place_order')) {
                syncCheckoutReorderSubmission();
            }
        }, true);

        document.addEventListener('touchstart', function (event) {
            var target = event.target;
            if (target && target.closest && target.closest('#place_order')) {
                syncCheckoutReorderSubmission();
            }
        }, true);

        if (window.jQuery) {
            window.jQuery(function ($) {
                $('form.checkout, form.woocommerce-checkout').on('checkout_place_order', function () {
                    syncCheckoutReorderSubmission();
                    return true;
                });
                $(document.body).on('updated_checkout init_checkout payment_method_selected', syncCheckoutReorderSubmission);
            });
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        bindPromoCodeCopy();
        bindCheckoutReorderRequest();

        if (!window.noesiaCommerceSuiteQr) {
            return;
        }
        var config = (window.noesiaCommerceSuitePublic && window.noesiaCommerceSuitePublic.qr) || {};
        document.querySelectorAll('[data-noesia-cs-qr]').forEach(function (element) {
            var size = parseInt(getQrOption(element, 'size', config.size || 160), 10);
            if (!size || size < 40) {
                size = 160;
            }
            window.noesiaCommerceSuiteQr.render(element, element.getAttribute('data-noesia-cs-qr'), {
                size: size,
                color: getQrOption(element, 'foreground', config.foreground || '#111827'),
                background: getQrOption(element, 'background', config.background || '#ffffff')
            });
        });
    });
}(window, document));
