/*!
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 * Copy of the Licence is available at: https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * @author    Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */
$(function () {
    window.SimplyIn = {
        ajax: '',
        phones: false,
        email_field: false,
        email_login_field: false,
        customer_email: null,
        is_login: false,
        last_code: false,
        is_login_page: false,

        on_close_refresh_page: false,
        counting_interval: false,
        counting_message_interval: false,
        push_notification_interval: false,
        autocomplete_interval: false,

        validate_code_timeout: false,
        validate_code_sended: false,

        last_popup: '',
        delivery_popup: '',
        delivery_popup_scroll: 0,
        popup: null,

        counting_value: 0,
        counting_value_message: 0,

        select_customer_privacy: false,
        select_psgdpr: false,
        submit_guest_form: false,

        login_request_send: false,
        last_email: '',
        send_sms_code_run: false,
        send_email_code_run: false,
        hideIconCheckout: false,
        showIconCheckout: false,
        new_account_listeners_inited: false,
        force_login: false,
        submit_email_in_progress: false,

        init: async function (config = {}) {
            this.ajax = simplyin.controllers.ajax;
            this.is_login = simplyin.customer_email != '' ? true : false;
            this.select_customer_privacy = simplyin.select_customer_privacy;
            this.select_psgdpr = simplyin.select_psgdpr;
            this.submit_guest_form = simplyin.submit_guest_form;
            if (simplyin.display && simplyin.display.bar_color === false) {
                $('body').addClass('simplyin-bar-mono');
            }
            if (simplyin.display && simplyin.display.badge_color === false) {
                $('body').addClass('simplyin-badge-mono');
            }
            if (simplyin.display && simplyin.display.accent_color) {
                document.documentElement.style.setProperty('--simplyin-accent-color', simplyin.display.accent_color);
            }
            if (simplyin.display && simplyin.display.font_color) {
                document.documentElement.style.setProperty('--simplyin-font-color', simplyin.display.font_color);
            }
            if (simplyin.order_sended) {
                return;
            }
            else if (typeof (simplyin.order) != 'undefined') {
                this.placeOrder();
            } else {
                await this.preloadImages().then(() => {
                    this.initCheckout();
                    this.initEventListeners();
                    this.initEventListenersPin();
                    this.initEventListenersDelivery();
                    this.initEventListenersEditAddress();
                    this.initEventListenersAddParcelLocker();
                    this.initEventListenersNewAccount();
                    this.initDhlAssistantDisplay();
                    this.dpdshippingmodule();
                    this.furgonetkamodule();
                    this.authController();
                    this.initAddressForm();
                });
            }
            this.customer_email = simplyin.customer_email;
        },
        initCheckout: function () {
            this.initOpcStandard();
            if (simplyin.customer.need_login && simplyin.controller == 'order' && $('#checkout-personal-information-step.-current').length > 0) {
                simplyin.customer.need_login = false;
                this.force_login = true;
                this.submitEmail(false);
            }
        },
        preloadImages() {
            const base = simplyin.files_url + '/views/img/';
            const images = [
                'logo_smalln.svg',
                'logo_medium.svg',
                'edit_icon.svg',
                'trash_icon.svg',
                'close_icon.svg',
                'point.svg',
                'expand_icon.svg',
                'dots_icon.svg',
                'add_icon.svg'
            ];

            return Promise.all(
                images.map(src =>
                    new Promise((resolve) => {
                        const img = new Image();
                        img.onload = resolve;
                        img.onerror = resolve;
                        img.src = base + src;
                    })
                )
            );
        },
        initAddressForm: function () {
            const self = this;
            if (simplyin.customer.logged && simplyin.customer.logged == true && simplyin.customer.has_selected_address == false && simplyin.customer.has_token) {
                if (window.location.search.indexOf('action') == -1) {
                    self.showPopupByType('delivery', {
                        email: simplyin.customer_email,
                    });
                }
            }

            if (simplyin.customer.point.label == 'dpd') {
                self.waitForElement('.dpdshipping-pudo-new-point', function () {
                    let modal = {
                        modal: function (toogle) { }
                    }
                    dpdshippingSavePudoCode(simplyin.customer.point.locker_id, modal);
                    let span = $('span.dpdshipping-selected-point');
                    dpdshippingGetPudoAddress(simplyin.customer.point.locker_id, span);
                }, 20000);
            }

        },

        
        waitForElement: function (selector, onFound, timeoutMs) {
            if ($(selector).length) {
                onFound();
                return;
            }
            var observer = new MutationObserver(function () {
                if ($(selector).length) {
                    observer.disconnect();
                    onFound();
                }
            });
            observer.observe(document.body, { childList: true, subtree: true });
            if (timeoutMs) {
                setTimeout(function () {
                    observer.disconnect();
                }, timeoutMs);
            }
        },

        barEnabled: function () {
            return simplyin.display ? !!simplyin.display.bar : true;
        },
        badgeEnabled: function () {

            return true;
        },
        barHtml: function () {

            
            return `
                <div class="simplyin-logo-container">
                  <div class="simplyin-logo-inner">
                    <div class="simplyin-logo-svg-wrap">
                      <span class="simplyin-logo-line"></span>
                      <span class="simplyin-logo-caption">${simplyin.labels.bar_caption}</span>
                      <img class="simplyin-logo-brand" src="${simplyin.files_url}/views/img/logo_medium.svg" alt="simply.in"/>
                      <span class="simplyin-logo-line"></span>
                    </div>
                  </div>
                </div>
            `;
        },
        fieldBadgeHtml: function () {
            return `
                <div class="simplyin-field-badge">
                  <img class="simplyin-field-badge-logo" src="${simplyin.files_url}/views/img/logo_medium.svg" alt="simply.in"/>
                </div>
            `;
        },

        
        injectFieldBadge: function (emailField) {
            var $field = $(emailField);
            if (!$field.length || $('.simplyin-field-badge').length) {
                return;
            }
            if (!$field.parent().hasClass('simplyin-field-wrap')) {
                $field.wrap('<div class="simplyin-field-wrap"></div>');
            }
            $field.after(this.fieldBadgeHtml());
            if ($('.simplyin-show-popup').is(':visible')) {
                $('.simplyin-field-badge').hide();
            }
        },
        initOpcStandard: function () {
            this.email_field = '#customer-form input[name="email"]';
            if ($(this.email_field).length) {
                var email_field = $(this.email_field);
                var form_group = email_field.closest('.form-group');
                var customer_form = $('#customer-form');
                if (form_group.length && customer_form.length) {
                    customer_form.prepend(form_group);
                    this.customer_email = simplyin.customer_email;
                    if (simplyin.customer_email != '') {
                        email_field.parent().append(`
                            <div class="simplyin-show-popup">
                                <div class="simplyin-show-popup-icon">
                                    <img width="30" height="30" src="${simplyin.files_url}/views/img/logo_smalln.svg"/>
                                    <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>
                                      <path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>
                                    </svg>
                                </div>
                                <div class="simplyin-show-popup-edit">
                                    <span>${simplyin.labels.data_completed}</span>
                                    <div class="simplyin-show-popup-edit-bottom">
                                      <span>${simplyin.labels.change}</span>
                                      <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path>
                                      </svg>
                                    </div>
                                </div>
                            </div>
                        `);
                        $(email_field).val(simplyin.customer_email);
                        if (!simplyin.customer.has_token) {
                            this.hideIcon();
                        }
                    } else {
                        email_field.parent().append(` <br/>
                            <div class="simplyin-show-popup" style="margin-left: 0">
                                <div class="simplyin-show-popup-icon">
                                    <img width="30" height="30" src="${simplyin.files_url}/views/img/logo_smalln.svg"/>
                                    <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>
                                      <path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>
                                    </svg>
                                </div>
                                <div class="simplyin-show-popup-edit">
                                    <span>${simplyin.labels.data_completed}</span>
                                    <div class="simplyin-show-popup-edit-bottom">
                                      <span>${simplyin.labels.change}</span>
                                      <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path>
                                      </svg>
                                    </div>
                                </div>
                            </div>
                        `);
                        this.hideIcon();
                    }

                }
            } else {
                let identity = $('.identity');
                identity.parent().prepend(`
                    <div class="simplyin-identity-right">
                        <div class="simplyin-show-popup">
                            <div class="simplyin-show-popup-icon">
                                <img width="30" height="30" src="${simplyin.files_url}/views/img/logo_smalln.svg"/>
                                <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                                  <rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>
                                  <path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>
                                </svg>
                            </div>
                            <div class="simplyin-show-popup-edit">
                                <span>${simplyin.labels.data_completed}</span>
                                <div class="simplyin-show-popup-edit-bottom">
                                  <span>${simplyin.labels.change}</span>
                                  <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path>
                                  </svg>
                                </div>
                            </div>
                        </div>
                    </div>
                `);
            }
            if (this.barEnabled()) {
                $('#checkout-personal-information-step').prepend(this.barHtml());
            }
            if (this.badgeEnabled()) {
                this.injectFieldBadge(this.email_field);
            }
            this.dockBadge();
        },
        initEventListeners: function () {
            const self = this;

            $(document).on('click', '.simplyin-popup-close-button, .simplyin-popup-overlay', function () {
                // The shop-login challenge popup must not be dismissed by an accidental
                // outside/overlay click — dismissing it is a dead-end (no SMS fallback until the
                // email is retyped). The explicit close button stays a deliberate exit.
                if ($(this).hasClass('simplyin-popup-overlay')
                    && $('#simplyin-input-code').attr('data-shop-login-challenge') === '1') {
                    return;
                }
                self.hidePopup();
            });

            $(document).on('click', '.simplyin-show-popup', function () {
                self.showLastPopup();
            });
            $(document).on('input', this.email_field, function () {
                self.force_login = false;
                let logout = false;
                if (self.is_login && self.customer_email != $(this).val()) {
                    logout = true;
                }
                if (self.customer_email != $.trim($(this).val())) {
                    self.login_request_send = false;
                    if (!self.isValidEmailAddress(self.customer_email)) {
                        self.hideIcon();
                    }
                    self.customer_email = $.trim($(this).val());
                    self.stopPushNotifications();
                    self.submitEmail(logout);
                }
            });
            $(document).on('click', '#simplyin-button-send-sms', function () {
                self.sendSmsCode();
                self.stopPushNotifications();
            });
            $(document).on('click', '#simplyin-button-send-email', function () {
                self.sendEmailCode();
                self.stopPushNotifications();
            });
            $(document).on('click', '#simplyin-button-resend-shop-login', function () {
                self.startShopLoginEmailChallenge(true);
            });
        },
        toggleElement: function (selector, target, show) {
            let element = $('#' + target + ' ' + selector);
            if (show) {
                $(element).slideDown({ duration: 150 });
            } else {
                $(element).slideUp({ duration: 150 });
            }
        },
        positionMenu: function (button, menu) {
            let offset = button.offset();
            let buttonHeight = button.outerHeight();
            let buttonWidth = button.outerWidth();
            if (window.innerWidth < 685) {
                menu.css({
                    top: offset.top + buttonHeight + "px",
                    right: buttonWidth + "px",
                    zIndex: 20000001
                });
            } else {
                menu.css({
                    top: offset.top + buttonHeight + "px",
                    left: offset.left + "px",
                    zIndex: 20000001
                });
            }
        },
        toggleDeliveryAddress: function (btn) {
            const self = this;
            let target = $(btn).data('target');
            let expanded = $(btn).is('.expanded');
            let checked = $('.popup-address-select-label-group input[type="checkbox"]').is(':checked');
            self.toggleElement('.popup-address-select-group', target, expanded);
        },
        initEventListenersPin: function () {
            const self = this;
            var selector = '#simplyin-input-code input[type="text"]';
            $(document).on('keypress', selector, function (e) {
                if (!/[0-9]/.test(e.key)) e.preventDefault();
            });
            $(document).on('input', selector, function () {
                var $all = $(selector),
                    idx = $all.index(this),
                    val = this.value;

                val = val.replace(/\D/g, '');

                if (val.length > 1) {
                    for (let i = 0; i < val.length && (idx + i) < $all.length; i++) {
                        $all.eq(idx + i).val(val[i]);
                    }
                    let nextFocus = idx + val.length < $all.length ? idx + val.length : $all.length - 1;
                    $all.eq(nextFocus).focus().select();
                } else {
                    this.value = val;

                    if (val.length === 1 && idx < $all.length - 1) {
                        $all.eq(idx + 1).focus().select();
                    }
                }
                self.validatePinCode();
            });

            $(document).on('keydown', selector, function (e) {
                var $all = $(selector),
                    idx = $all.index(this);

                switch (e.key) {
                    case 'Backspace':
                        e.preventDefault();

                        this.value = '';
                        if (idx > 0) {
                            var $prev = $all.eq(idx - 1);
                            $prev.focus().select();
                        }
                        break;

                    case 'ArrowLeft':
                        if (idx > 0) {
                            e.preventDefault();
                            var $prev = $all.eq(idx - 1);
                            $prev.focus().select();
                        }
                        break;

                    case 'ArrowRight':
                        if (idx < $all.length - 1) {
                            e.preventDefault();
                            var $next = $all.eq(idx + 1);
                            $next.focus().select();
                        }
                        break;
                }
            });

            $(document).on('paste', selector, function (e) {
                e.preventDefault();

                const clip = (e.originalEvent || e).clipboardData || window.clipboardData;
                if (!clip) return;

                const digits = (clip.getData('text') || '').replace(/\D/g, '');
                if (!digits) return;

                const $all = $(selector);
                let idx = $all.index(this);

                for (let i = 0; i < digits.length && idx < $all.length; i++, idx++) {
                    $all.eq(idx).val(digits[i]);
                }

                const $empties = $all.filter((_, el) => el.value === '');

                self.validatePinCode();
            });

            $(document).on('keyup', selector, self.validatePinCode);
        },
        removeContextMenu: function () {
            $(".dropdown-actions-menu").remove();
            $(".simplyin-popup-overlay-context").remove();
        },
        deleteAddress: function (id, address_type) {
            const self = this;
            self.removeContextMenu();
            const callback = function () {
                let params = {
                    action: 'deleteAddress',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    id: id,
                    address_type: address_type,
                };
                $.ajax({
                    url: self.ajax,
                    method: 'POST',
                    data: params,
                    dataType: 'json',
                }).done(data => {
                    if (data.success) {
                        if (address_type == 'billingAddresses') {
                            $(`.popup-address-select[data-id="${id}"]`).parent().remove();
                        } else {
                            $(`.popup-address-select[data-id="${id}"]`).remove();
                        }
                        self.removeContextMenu();
                        self.checkSelectedAddress();
                        self.last_popup = '';
                    }
                });
            }
            self.confirmationPopup(simplyin.labels.delete_header, simplyin.labels.confirm_delete, callback);
        },
        initEventListenersDelivery: function () {
            const self = this;

            $(document).on('change', '#simplyin-parcel-lockers input[name="simplyin-parcel-locker-selected"],#simplyin-delivery-points input[name="simplyin-delivery-point-selected"]', function () {
                $('#popup-delivery-parcel-locker-address .popup-selected-address .popup-address-label-line-1').html($(this).data('address-1'));
                if ($(this).attr('name') == 'simplyin-delivery-point-selected') {
                    $('input[name="simplyin-parcel-locker-selected"]').prop('checked', false);
                } else {
                    $('input[name="simplyin-delivery-point-selected"]').prop('checked', false);
                }
            });

            $(document).on('change', 'input[name="simplyin-invoice-address"]', function () {
                $('#popup-invoice-address .popup-selected-address .popup-selected-address-line-1').html($(this).data('address-1'));
                $('#popup-invoice-address .popup-selected-address .popup-selected-address-line-2').html($(this).data('address-2'));
            });

            $(document).on('change', 'input[name="simplyin-delivery-address"]', function () {
                $('#popup-delivery-address .popup-selected-address .popup-selected-address-line-1').html($(this).data('address-1'));
                $('#popup-delivery-address .popup-selected-address .popup-selected-address-line-2').html($(this).data('address-2'));

            });

            $(document).on("click", function () {
                self.removeContextMenu();
            });

            $(document).on('click', '.simplyin-button-edit', function (e) {
                e.stopPropagation();
                self.removeContextMenu();
                self.editAddress($(this).data('id'), $(this).data('address-type'));
            });

            $(document).on('click', '.simplyin-button-delete', function (e) {
                e.stopPropagation();
                let id = $(this).data('id');
                let address_type = $(this).data('address-type');
                self.deleteAddress(id, address_type);
            });

            $(document).on('click', '.popup-address-actions', function (e) {
                e.stopPropagation();
                self.removeContextMenu();
                let items_count = $(this).parents('.popup-address-selector').find('.popup-address-select').length;
                let action_edit = parseInt($(this).parents('.popup-address-selector').data('edit'));
                let action_delete = parseInt($(this).parents('.popup-address-selector').data('delete'));
                let force_delete = parseInt($(this).parents('.popup-address-selector').data('force-delete'));
                let edit_label = simplyin.labels.edit;
                let delete_label = simplyin.labels.delete;
                let menu = $(`<div class="dropdown-actions-menu"><ul></ul></div>`);
                let item_id = $(this).parents('.popup-address-select').data('id');
                if (!action_edit && !action_delete) {
                    return;
                }
                let address_type = '';
                if ($(this).parents('#popup-invoice-address').length) {
                    address_type = 'billingAddresses';
                } else if ($(this).parents('#popup-delivery-address').length) {
                    address_type = 'shippingAddresses'
                } else {
                    address_type = 'parcelLockers';
                }

                if (action_edit) {
                    $(menu).find('ul').append(`
                        <li class="simplyin-button-edit edit-action" data-id="${item_id}" data-address-type="${address_type}">
                            <svg class="simplyin-action-icon" width="23" height="24" viewBox="0 0 23 24" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="${edit_label}">
                              <path d="M20.3103 7.2539L16.1216 3.06422C15.9823 2.92489 15.8169 2.81437 15.6349 2.73897C15.4529 2.66357 15.2578 2.62476 15.0608 2.62476C14.8638 2.62476 14.6687 2.66357 14.4867 2.73897C14.3047 2.81437 14.1393 2.92489 14 3.06422L2.43969 14.6255C2.2998 14.7642 2.18889 14.9295 2.11341 15.1115C2.03792 15.2935 1.99938 15.4887 2.00001 15.6858V19.8755C2.00001 20.2733 2.15804 20.6548 2.43935 20.9361C2.72065 21.2174 3.10218 21.3755 3.50001 21.3755H7.6897C7.88675 21.3761 8.08197 21.3375 8.26399 21.2621C8.44602 21.1866 8.61122 21.0757 8.75001 20.9358L20.3103 9.37547C20.4496 9.23617 20.5602 9.0708 20.6356 8.88879C20.711 8.70678 20.7498 8.5117 20.7498 8.31468C20.7498 8.11767 20.711 7.92259 20.6356 7.74058C20.5602 7.55857 20.4496 7.3932 20.3103 7.2539ZM7.6897 19.8755H3.50001V15.6858L11.75 7.43578L15.9397 11.6255L7.6897 19.8755ZM17 10.5642L12.8103 6.37547L15.0603 4.12547L19.25 8.31422L17 10.5642Z"/>
                            </svg>
                            ${edit_label}
                        </li>
                    `);
                }
                if (items_count > 1 && action_delete || force_delete) {
                    $(menu).find('ul').append(`
                        <li class="simplyin-button-delete delete-action" data-id="${item_id}" data-address-type="${address_type}">
                            <svg class="simplyin-action-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Usuń">
                              <path d="M20.25 5.25H16.5V4.5C16.5 3.90326 16.2629 3.33097 15.841 2.90901C15.419 2.48705 14.8467 2.25 14.25 2.25H9.75C9.15326 2.25 8.58097 2.48705 8.15901 2.90901C7.73705 3.33097 7.5 3.90326 7.5 4.5V5.25H3.75C3.55109 5.25 3.36032 5.32902 3.21967 5.46967C3.07902 5.61032 3 5.80109 3 6C3 6.19891 3.07902 6.38968 3.21967 6.53033C3.36032 6.67098 3.55109 6.75 3.75 6.75H4.5V20.25C4.5 20.6478 4.65804 21.0294 4.93934 21.3107C5.22064 21.592 5.60218 21.75 6 21.75H18C18.3978 21.75 18.7794 21.592 19.0607 21.3107C19.342 21.0294 19.5 20.6478 19.5 20.25V6.75H20.25C20.4489 6.75 20.6397 6.67098 20.7803 6.53033C20.921 6.38968 21 6.19891 21 6C21 5.80109 20.921 5.61032 20.7803 5.46967C20.6397 5.32902 20.4489 5.25 20.25 5.25ZM9 4.5C9 4.30109 9.07902 4.11032 9.21967 3.96967C9.36032 3.82902 9.55109 3.75 9.75 3.75H14.25C14.4489 3.75 14.6397 3.82902 14.7803 3.96967C14.921 4.11032 15 4.30109 15 4.5V5.25H9V4.5ZM18 20.25H6V6.75H18V20.25ZM10.5 10.5V16.5C10.5 16.6989 10.421 16.8897 10.2803 17.0303C10.1397 17.171 9.94891 17.25 9.75 17.25C9.55109 17.25 9.36032 17.171 9.21967 17.0303C9.07902 16.8897 9 16.6989 9 16.5V10.5C9 10.3011 9.07902 10.1103 9.21967 9.96967C9.36032 9.82902 9.55109 9.75 9.75 9.75C9.94891 9.75 10.1397 9.82902 10.2803 9.96967C10.421 10.1103 10.5 10.3011 10.5 10.5Z"/>
                            </svg>
                            Usuń
                        </li>
                    `);
                }
                if (items_count >= 1 && (action_edit || action_delete)) {
                    if ($(menu).find('li').length > 0) {
                        $(".simplyin-popup").parent().append(menu);
                        SimplyIn.positionMenu($(this), menu);
                    }
                }
            });

            $(document).on('change', '.popup-address-select-label-group input[type="checkbox"]', function (e) {
                e.preventDefault();
                const btn = $('.popup-button-expand[data-target="popup-delivery-address"]')[0];
                let checked = $(this).parents('.popup-address-select-label-group').find('input[type="checkbox"]').is(':checked');
                let button_label = $('.popup-button-expand[data-target="popup-delivery-address"]');
                if (!checked && !button_label.is('.expanded')) {
                    button_label.addClass('expanded');
                } else {
                    button_label.removeClass('expanded');
                }
                if (!checked) {
                    $('#popup-delivery-address').find('input[type="radio"]:first').prop('checked', true);
                } else {
                    $('#popup-delivery-address').find('input[type="radio"]').prop('checked', false);
                }
                self.toggleDeliveryAddress(btn);
                return false;
            });

            $(window).on("resize", function () {
                self.removeContextMenu();
            });

            $(document).on('change', '.simplyin-delivery-type', function (e) {
                e.preventDefault();
                if ($(this).val() == 'address') {
                    $('.popup-delivery-address-box').show();
                    $('.popup-delivery-parcel-locker-box').hide();
                } else {
                    $('.popup-delivery-parcel-locker-box .popup-button-expand').addClass('expanded');
                    $('.popup-delivery-address-box').hide();
                    $('.popup-delivery-parcel-locker-box').show();
                }
            });

            $(document).on('click', '.popup-button-expand[data-target="popup-invoice-address"]', function (e) {
                e.preventDefault();
                let target = $(this).data('target');
                let expanded = $(this).is('.expanded');

                $(this).toggleClass('expanded');
                self.toggleElement('.popup-address-select-group', target, !expanded);
            });

            $(document).on('click', '.popup-button-expand[data-target="popup-delivery-parcel-locker-address"]', function (e) {
                e.preventDefault();
                let target = $(this).data('target');
                let fields_to_show = $('.popup-address-selector-header button.active').data('target');
                let fields_to_hide = $('.popup-address-selector-header button:not(.active)').data('target');
                $(this).toggleClass('expanded');
                let expanded = $(this).is('.expanded');
                self.toggleElement('.popup-address-select-group', target, expanded);
                $('#' + fields_to_show).show();
                $('#' + fields_to_hide).hide();
            });

            $(document).on('click', '.popup-button-expand[data-target="popup-delivery-address"]', function (e) {
                e.preventDefault();
                $(this).toggleClass('expanded');
                self.toggleDeliveryAddress(this);
            });

            $(document).on('change', '#popup-delivery-address input[type="radio"]', function (e) {
                e.preventDefault();
                $('.popup-address-select-label-group input[type="checkbox"]').prop('checked', false);
            });

            $(document).on('click', '.popup-address-selector-header button', function (e) {
                e.preventDefault();
                $('.popup-delivery-parcel-locker-box .popup-button-expand').addClass('expanded');
                let target = $(this).data('target');
                $(this).addClass('active').siblings().removeClass('active');
                $('#' + target).show().siblings().hide();
            });

            $(document).on('click', '.popup-address-actions-add', function (e) {
                e.preventDefault();
                let target = $(this).data('type');
                self.storeDeliveryPopup();
                var params = {
                    action: 'addAddress',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    address_type: target,
                };

                $.ajax({
                    url: self.ajax,
                    method: 'POST',
                    data: params,
                    dataType: 'json'
                }).done(data => {
                    if (data.success) {
                        self.showPopupByContent(data.html);
                        self.initAutocomplete();
                        $('#pickup-search').focus();
                    }
                });
            });

            $(document).on('click', '.popup-select-address', function () {
                self.selectAddress();
            });
        },
        initAutocomplete: function () {
            const self = this;
            const input = document.querySelector('.simplyin-autocomplete #pickup-search');

            if (!input) return;

            const dropdown = document.createElement('div');
            dropdown.className = 'autocomplete-dropdown';
            dropdown.style.position = 'absolute';
            dropdown.style.zIndex = '999999999';
            dropdown.style.display = 'none';
            dropdown.style.backgroundColor = '#fff';
            dropdown.style.border = '1px solid #ccc';
            dropdown.style.maxHeight = '200px';
            dropdown.style.overflowY = 'auto';
            document.body.appendChild(dropdown);

            function positionDropdown() {
                const rect = input.getBoundingClientRect();
                dropdown.style.width = rect.width + 'px';
                dropdown.style.left = rect.left + window.scrollX + 'px';
                dropdown.style.top = rect.bottom + window.scrollY + 'px';
            }

            input.addEventListener('input', function (e) {
                const value = input.value;
                if (value.length < 3) {
                    dropdown.style.display = 'none';
                    return;
                }

                self.fetchAddressSuggestions({ term: value }, function (suggestions) {
                    dropdown.innerHTML = '';
                    if (!suggestions || !suggestions.length) {
                        dropdown.style.display = 'none';
                        return;
                    }

                    suggestions.forEach(item => {
                        const div = document.createElement('div');
                        div.textContent = item.label || item.value || item;
                        div.style.padding = '5px 10px';
                        div.style.cursor = 'pointer';

                        div.addEventListener('mousedown', function (ev) {
                            ev.preventDefault();
                            input.value = div.textContent;
                            const ui = { item: item };
                            self.handleSelect(ev, ui);
                            dropdown.style.display = 'none';
                        });

                        dropdown.appendChild(div);
                    });

                    positionDropdown();
                    dropdown.style.display = 'block';
                });
            });

            document.addEventListener('click', function (e) {
                if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                    dropdown.style.display = 'none';
                }
            });

            let selectedIndex = -1;
            input.addEventListener('keydown', function (e) {
                const items = dropdown.querySelectorAll('div');
                if (!items.length) return;

                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    selectedIndex = (selectedIndex + 1) % items.length;
                    items.forEach((el, i) => el.style.background = i === selectedIndex ? '#ddd' : '');
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    selectedIndex = (selectedIndex - 1 + items.length) % items.length;
                    items.forEach((el, i) => el.style.background = i === selectedIndex ? '#ddd' : '');
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (selectedIndex >= 0) {
                        items[selectedIndex].dispatchEvent(new Event('mousedown'));
                        selectedIndex = -1;
                    }
                }
            });

            window.addEventListener('resize', positionDropdown);
            window.addEventListener('scroll', positionDropdown);
        },

        fetchAddressSuggestions: function (request, response) {
            const self = this;

            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: {
                    action: 'searchAddress',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    address: request.term
                },
                dataType: 'json',
                success: function (data) {
                    if (data && data.data) {
                        const suggestions = self.mapAddressData(data.data);
                        response(suggestions);
                    }
                }
            });
        },

        mapAddressData: function (data) {
            return data.map(function (item) {
                return {
                    label: item.formatted_address,
                    value: item.formatted_address,
                    place_id: item.place_id,
                    geometry: item.geometry,

                };
            });
        },
        handleSelect: function (event, ui) {
            const self = this;
            $('.simplyin-pickup-list-item input[name="pickup-option"]').val(ui.item.value);
            let lat = ui.item.geometry.location.lat;
            let lng = ui.item.geometry.location.lng;

            let params = {
                action: 'getClosestParcelLockers',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                coordinates: {
                    lat: lat,
                    lng: lng,
                },
            };

            $.ajax({
                url: SimplyIn.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                    self.fillParcelsList(data);
                }
            });
        },
        initEventListenersEditAddress: function () {
            const self = this;
            $(document).on('click', '.simplyin-popup-addres-form button.simplyin-cancel', function (e) {
                e.preventDefault();
                self.retrieveDeliveryPopup();
            });

            $(document).on('click', '.simplyin-popup-addres-form button.simplyin-submit', function (e) {
                e.preventDefault();
                self.submitAddress();
            });
        },
        clearParcelsList: function () {
            const self = this;
            $('.pickup-placeholder').show();
            $('.pickup-list-container').empty().hide();
        },
        fillParcelsList: function (data) {
            const self = this;
            if (data.data.count) {
                let html = '';
                $.each(data.data.data, function (index, item) {
                    let locker = item.locker;
                    let info = item.info;
                    let address = locker.address;
                    let distance = Math.round(info.distance * 1000);
                    let provider = info.provider;
                    let desc = locker.desc;
                    html += `
                        <div class="simplyin-pickup-list-item">
                            <label class="pickup-item">
                                <input
                                    type="radio"
                                    name="pickup-option"
                                    value="${locker._id}"
                                    data-id="${locker.lockerId}"
                                    data-address="${address}"
                                    data-desc="${desc}"
                                    data-locker-id="${locker.lockerId}"
                                    data-logo-url="${provider.logoUrl}"
                                    data-label="${provider.name}"
                                    data-provider-id="${locker.providerId}"
                                    data-service-type="${locker.service_type}"
                                >
                                <div class="pickup-info">
                                    <img src="${provider.logoUrl}" alt="${provider.name}">
                                    <div class="pickup-details">
                                        <strong>${locker.lockerId}</strong>
                                        <span>${address}</span>
                                        <span>${simplyin.labels.edit}: ${distance} m</span>
                                    </div>
                                </div>
                            </label>
                        </div>
                    `;
                });
                self.clearParcelsList();
                $('.pickup-list-container').html(html);
                $('.pickup-placeholder').hide();
                $('.pickup-list-container').show();
            } else {
                self.clearParcelsList();
            }
        },
        selectNewParcel: function (el) {
            const self = this;
            let locker = $(el).data('id');
            let address = $(el).data('address');
            let desc = $(el).data('desc');
            $('#simplyin-pickup-number').html(locker);
            $('#simplyin-pickup-address').html(address);
            $('#simplyin-pickup-info').html(desc);
        },
        initEventListenersAddParcelLocker: function () {
            const self = this;
            $(document).on('change', '.simplyin-pickup-list-item input[name="pickup-option"]', function () {
                self.selectNewParcel(this)
            });

            $(document).on('click', '.simplyin-autocomplete button.simplyin-cancel', function (e) {
                e.preventDefault();
                self.retrieveDeliveryPopup();
                $('input[name="simplyin-delivery-type"][value="parcel_locker"]').prop('checked', true);
            });

            $(document).on('click', '.simplyin-autocomplete button.simplyin-submit', function (e) {
                e.preventDefault();
                const $checked_option = $('input[name="pickup-option"]:checked');
                if ($checked_option.length) {
                    self.addNewParcelLocker($checked_option);
                    $('input[name="simplyin-delivery-type"][value="parcel_locker"]').prop('checked', true);
                }
            });

            $(document).on('enter', '.simplyin-popup input[name="pickup-name"]', function (e) {
                const $checked_option = $('input[name="pickup-option"]:checked');
                if ($checked_option.length) {
                    self.addNewParcelLocker($checked_option);
                }
            });
        },
        addNewParcelLocker: function (obj) {
            const self = this;
            let params = {
                action: 'submitAddress',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                'parcel': {
                    'address_type': 'parcelLockers',
                    _id: $(obj).val(),
                    logoUrl: $(obj).data('logoUrl'),
                    addressName: $.trim($('#pickup-name').val()) ? $.trim($('#pickup-name').val()) : obj.data('id'),
                    lockerId: obj.data('id'),
                    address: obj.data('address'),
                    label: obj.data('label'),
                    providerId: obj.data('providerId'),
                    service_type: obj.data('service-type'),
                }
            };

            $.ajax({
                url: SimplyIn.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                    if (typeof (data.html) != 'undefined') {
                        let html = $(data.html);
                        let points = html.find('#simplyin-delivery-points').html();
                        let lockers = html.find('#simplyin-parcel-lockers').html();
                        self.retrieveDeliveryPopup();
                        $('#simplyin-parcel-lockers').html(lockers);
                        $('#simplyin-delivery-points').html(points);
                    }
                }
            });
        },
        submitAddress: function (e) {
            const self = this;
            let form = $('form.simplyin-popup-addres-form');
            let required_fields = form.find('input[required]');
            let is_valid = true;
            $.each(required_fields, function (index, field) {
                if ($(field).val() == '') {
                    $(field).parents('.form-group').addClass('error');
                    is_valid = false;
                } else {
                    $(field).parents('.form-group').removeClass('error');
                }
            });
            if (!is_valid) {
                return false;
            }

            let params = {
                action: 'submitAddress',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
            };
            var form_data = new FormData();
            $.each(params, function (key, value) {
                form_data.append(key, value);
            });
            $.each(form[0].elements, function (index, field) {
                if (field.name != '') {
                    form_data.append('address[' + field.name + ']', field.value);
                }
            });

            $.ajax({
                url: this.ajax,
                method: 'POST',
                data: form_data,
                processData: false,
                contentType: false,
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                    if (data.is_valid !== true && typeof (data.is_valid) == 'object') {
                        form.find('.form-group').removeClass('error');
                        $.each(data.is_valid, function (index, field) {
                            form.find('input[name="' + index + '"]').parents('.form-group').addClass('error');
                            form.find('input[name="' + index + '"]').parents('.form-group').find('.error-message').html(data.is_valid[index]);
                        });

                    } else if (data.is_valid === true && typeof (data.address) != 'undefined') {
                        self.retrieveDeliveryPopup();
                        self.upgradeAddress(data);
                    } else if (data.is_valid === true && typeof (data.add_address) != 'undefined') {
                        self.retrieveDeliveryPopup();
                        self.addAddress(data.address, data.address_type, data.html);
                    }
                    self.checkSelectedAddress();
                }
            });
        },
        checkSelectedAddress: function () {
            if ($('input[name="simplyin-invoice-address"]:checked').length == 0) {
                $('input[name="simplyin-invoice-address"]:first').prop('checked', true);
            }
            if ($('.popup-address-checkbox .checkbox:checked') && $('input[name="simplyin-delivery-address"]:checked').length == 0) {
                $('input[name="simplyin-delivery-address"]:first').prop('checked', true);
            }
        },
        upgradeAddress: function (data) {
            let address = data.address;
            let address_type = data.address_type;

            let address_element = '';
            address_element = $('div[data-id="' + address._id + '"]');
            let address_name = address.addressName;
            let address_line2 = address.street;
            if (address.appartmentNumber != '') {
                address_line2 = address.street + '/' + address.appartmentNumber;
            }
            address_line2 = address_line2 + ', ' + address.city;
            address_element.find('.popup-address-label-line-1').html(address_name);
            address_element.find('.popup-address-label-line-2').html(address_line2);
            address_element.find('.icon').html(address.icon);
        },
        addAddress: function (address, address_type, html) {
            let add_place = '';
            let new_form = $(html);
            let to_add = false;
            let address_name = '';
            if (address_type == 'billingAddresses') {
                to_add = new_form.find('#popup-invoice-address .popup-address-select-group:last');
                add_place = $('#popup-invoice-address');
                address_name = 'input[name="simplyin-invoice-address"]:last';
            } else if (address_type == 'shippingAddresses') {
                to_add = new_form.find('#popup-delivery-address .popup-address-select:last');
                add_place = $('#popup-delivery-address').find('.popup-address-select-group');
                address_name = 'input[name="simplyin-delivery-address"]:last';

            } else if (address_type == 'parcelLockers') {
                to_add = false
            }
            if (add_place.length && to_add !== false) {
                add_place.append(to_add);
                $(address_name).prop('checked', true);
                if (address_type == 'shippingAddresses') {
                    $('#popup-delivery-address .popup-address-checkbox input[type="checkbox"]').prop('checked', false);
                    add_place.show();
                    $('.popup-button-expand[data-target="popup-delivery-address"]').addClass('expanded');
                }
            }
        },
        selectDefaultAddress: function () {
            let invoice_address = $('input[name="simplyin-invoice-address"]:checked').data('id');
            if (!invoice_address) return;

            let delivery_address = invoice_address;
            let params = {
                action: 'selectAddress',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                invoice_address: invoice_address,
                service_type: '',
                delivery_address: delivery_address,
                selected_point: '',
            };

            $.ajax({
                url: this.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            });
        },
        selectAddress: function () {

            const self = this;
            let invoice_address = $('input[name="simplyin-invoice-address"]:checked').data('id');
            let delivery_address = ''
            let selected_point = '';
            let service_type = '';
            if ($('.simplyin-delivery-type[type="radio"]:checked').val() == 'address') {
                if ($('.popup-address-checkbox input[type="checkbox"]').is(':checked')) {
                    delivery_address = $('input[name="simplyin-invoice-address"]:checked').data('id')
                } else {
                    delivery_address = $('input[name="simplyin-delivery-address"]:checked').data('id');
                }
            } else {
                if ($('input[name="simplyin-parcel-locker-selected"]:checked').length) {
                    service_type = 'parcel';
                    selected_point = $('input[name="simplyin-parcel-locker-selected"]:checked').data('id');
                } else if ($('input[name="simplyin-delivery-point-selected"]:checked').length) {
                    service_type = 'delivery';
                    selected_point = $('input[name="simplyin-delivery-point-selected"]:checked').data('id');
                }
            }
            let params = {
                action: 'selectAddress',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                invoice_address: invoice_address,
                service_type: service_type,
                delivery_address: delivery_address,
                selected_point: selected_point,
            };

            $.ajax({
                url: this.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data.redirect) {
                    self.on_close_refresh_page = true;
                    self.hidePopup();
                } else {
                    self.hidePopup();
                    self.selectCheckbox();
                }
            });
        },
        submitEmail: function (logout) {
            this.last_popup = '';
            const self = this;
            if (this.is_login == false || logout) {
                this.is_login = false;
                var email = this.customer_email;
                if (!this.isValidEmailAddress(email) && this.force_login === false) {
                    return;
                }
                var params = {
                    action: 'submitEmail',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    email: email,
                    logout: logout,
                    force_login: this.force_login ? 1 : 0,
                };

                $.ajax({
                    url: self.ajax,
                    method: 'POST',
                    data: params,
                    dataType: 'json'
                }).done(data => {
                    // Email-first: a registered shop account exists for this email and the
                    // backend e-mailed a 6-digit login code — show the challenge popup INSTEAD of the
                    // SMS flow (no submitEmail bookkeeping: no push notification, no confirm-profile
                    // icon). validatePinCode reads mode + length from the popup DOM, and on verify
                    // success the page reloads with the shopper logged into the shop account.
                    if (data && data.success && data.show_popup && data.shop_login_challenge) {
                        // Stale-response guard (mirrors the Woo hardening): if the shopper kept typing
                        // and the current email no longer matches the one this request was fired for,
                        // discard — otherwise a slow challenge response could pop a 6-digit code prompt
                        // for a since-abandoned address.
                        if (email !== self.customer_email) {
                            return;
                        }
                        self.last_email = email;
                        self.last_code = false;
                        self.validate_code_sended = false;
                        self.showPopupByContent(data.html);
                        self.codeStartCounting();
                        self.focusOnCode();
                        return;
                    }
                    if (data && data.success && data.show_popup) {
                        self.userUsedPushNotifications = data.userUsedPushNotifications;
                        self.last_popup = data.html;
                        self.last_email = email;
                        self.login_request_send = true;
                        self.showPopupByContent(data.html);
                        self.focusOnCode();
                        self.showIcon();
                        if (!self.is_login && !simplyin.customer.has_token) {
                            $('.simplyin-show-popup').not('.simplyin-show-popup-login').addClass('simplyin-confirm-profile');
                            $('.simplyin-show-popup').not('.simplyin-show-popup-login').find('.simplyin-show-popup-edit > span').first().text(simplyin.labels.confirm_profile);
                            self.dockConfirmProfile();
                        }
                        if (self.phoneCheckboxManager) {
                            self.phoneCheckboxManager.state.userExistsInSimplyIn = true;
                            self.phoneCheckboxManager.hideCheckbox();
                        }
                        if (data.userUsedPushNotifications) {
                            self.checkPushNotification();
                        } else {
                            self.codeStartCounting();
                        }
                        return;
                    }

                    if (data && data.error == 'NOT_FOUND') {
                        self.hideIcon();
                        if (self.phoneCheckboxManager) {
                            self.phoneCheckboxManager.state.userExistsInSimplyIn = false;
                            if ($('#checkout-payment-step.-current').length && !$('#simplyin-phone-checkbox').length) {
                                self.phoneCheckboxManager.showCheckbox();
                            }
                        }
                        if (email === self.customer_email) {
                            simplyin.hide_phone_field = false;
                            self.initEventListenersNewAccount();
                        }
                        return;
                    }
                    // F6: any other {error} (e.g. BAD_REQUEST) / empty body at the OTP entry point must
                    // not be silent — surface it and let the buyer retry.
                    self.login_request_send = false;
                    self.notifyServerError();
                }).fail(() => {
                    self.login_request_send = false;
                    self.notifyServerError();
                });
            }
        },
        showLastPopup: function () {
            const self = this;
            if (self.customer_email == '' && simplyin.customer.logged == true && typeof (simplyin.customer.email) != 'undefined') {
                self.customer_email = simplyin.customer.email;
                self.submitEmail(false);
            }
            if (self.is_login) {
                if (self.last_popup) {
                    self.showPopupByContent(self.last_popup);
                } else {
                    self.showPopupByType('delivery', {
                        email: self.customer_email,
                    });
                }
            }
            if (!self.is_login && self.login_request_send && self.last_email != '' && self.last_popup != '') {
                self.customer_email = self.last_email;
                self.submitEmail(false);
            }
        },

        showPopupByContent: function (content) {
            this.last_popup = content;
            if ($('.simplyin-popup-box').length === 0) {
                this.popup = $('<div>').addClass('simplyin-popup-box').appendTo('body')[0];
            } else {
                this.popup = document.querySelector('.simplyin-popup-box');
            }
            $('.simplyin-popup-box').html(content);
            setTimeout(() => {
                $('.simplyin-popup-box').addClass('visible');
            }, 100);
        },
        showPopupByType: function (type, other_params = {}) {
            const self = this;
            var params = {
                action: 'getForm',
                type: type,
                ajax: 1,
                ajax_token: simplyin.ajax_token,
            };
            var form_data = new FormData();
            $.each(params, function (key, value) {
                form_data.append(key, value);
            });
            $.each(other_params, function (key, value) {
                form_data.append(key, value);
            });
            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: form_data,
                processData: false,
                contentType: false,
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                    self.showPopupByContent(data.html);
                } else if (data.error == 'Session expired') {
                    self.is_login = false;
                    self.submitEmail(false);
                }
            });
        },
        hidePopup: function () {
            const self = this;
            var $popup = $('.simplyin-popup-box');
            if ($popup.length) {
                $popup.removeClass('visible');
                setTimeout(() => {
                    $popup.remove();
                    if (self.on_close_refresh_page) {
                        window.location.reload();
                    }
                }, 300);
            }
        },
        notifyServerError: function (message) {
            // Never let a server/transport failure be silent. Prefer the in-popup code-error
            // slot when the OTP popup is open; otherwise fall back to a blocking notice so the buyer is
            // not left stuck without any feedback. An explicit message can be passed (e.g. the
            // consumed-code hint); otherwise a generic localized error is used.
            var text = message || ((simplyin.labels && simplyin.labels.generic_error)
                ? simplyin.labels.generic_error
                : 'Something went wrong. Please try again.');
            var $slot = $('.simplyin-popup-content .code-error-message');
            if ($slot.length) {
                $slot.show().text(text);
            } else {
                window.alert(text);
            }
        },
        sendSmsCode: function () {
            const self = this;
            if (self.send_sms_code_run) {
                return;
            }
            var params = {
                action: 'sendSmsCode',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                email: this.customer_email,
                force_login: this.force_login ? 1 : 0,
            };
            self.send_sms_code_run = true;
            setTimeout(function () {
                self.send_sms_code_run = false;
            }, 30000);
            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data && data.success) {
                    self.showPopupByContent(data.html);
                    self.codeStartCounting();
                    self.focusOnCode();
                    return;
                }
                // F4: {error:'NOT_FOUND'} means "user not in SIN" — a legitimate, neutral outcome; stay
                // silent as before. Only other errors / empty bodies are real server failures.
                if (data && data.error === 'NOT_FOUND') {
                    return;
                }
                self.send_sms_code_run = false;
                self.notifyServerError();
            }).fail(() => {
                self.send_sms_code_run = false;
                self.notifyServerError();
            });
        },
        sendEmailCode: function () {
            const self = this;
            if (self.send_email_code_run) {
                return;
            }
            var params = {
                action: 'sendEmailCode',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                email: this.customer_email,
                force_login: this.force_login ? 1 : 0,
            };
            self.send_email_code_run = true;
            setTimeout(function () {
                self.send_email_code_run = false;
            }, 30000);
            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data && data.success) {
                    self.showPopupByContent(data.html);
                    self.codeStartCounting();
                    self.focusOnCode();
                    return;
                }
                // F4: {error:'NOT_FOUND'} means "user not in SIN" — a legitimate, neutral outcome; stay
                // silent as before. Only other errors / empty bodies are real server failures.
                if (data && data.error === 'NOT_FOUND') {
                    return;
                }
                self.send_email_code_run = false;
                self.notifyServerError();
            }).fail(() => {
                self.send_email_code_run = false;
                self.notifyServerError();
            });
        },
        // Shop-login email-OTP challenge: the shopper's email isn't verified yet but a
        // registered PS account exists for it — send a code to their email and show the 6-digit
        // challenge popup. Reuses the #simplyin-input-code component + validatePinCode, which reads
        // both the code length and the verify-vs-checkCode routing from the popup DOM (stateless).
        startShopLoginEmailChallenge: function (isResend) {
            const self = this;
            if (self.shop_login_challenge_run) {
                return;
            }
            self.shop_login_challenge_run = true;
            setTimeout(function () {
                self.shop_login_challenge_run = false;
            }, 30000);
            var params = {
                action: 'sendShopLoginEmailOtp',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                isResend: isResend ? 1 : 0,
            };
            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: params,
                dataType: 'json',
            }).done(data => {
                if (data && data.success) {
                    self.last_code = false;
                    self.validate_code_sended = false;
                    self.showPopupByContent(data.html);
                    self.codeStartCounting();
                    self.focusOnCode();
                    return;
                }
                self.shop_login_challenge_run = false;
                self.notifyServerError();
            }).fail(() => {
                self.shop_login_challenge_run = false;
                self.notifyServerError();
            });
        },
        validatePinCode: function () {
            const self = window.SimplyIn;
            if (self.validate_code_sended) {
                return;
            }
            if (self.validate_code_timeout) {
                clearTimeout(self.validate_code_timeout);
            }
            self.validate_code_timeout = setTimeout(() => {
                var selector = '#simplyin-input-code input[type="text"]';
                var code = '';
                $(selector).each(function () {
                    code += this.value;
                });

                // Length-aware + mode-aware, both derived from the rendered popup: the
                // checkout code popup has 4 inputs, the shop-login email challenge popup carries
                // data-shop-login-challenge="1" and 6 inputs. Reading the DOM keeps this stateless.
                var isShopLoginChallenge =
                    $('#simplyin-input-code').attr('data-shop-login-challenge') === '1';
                var expectedLength = $(selector).length || 4;

                if (code.length == expectedLength) {
                    self.validate_code_sended = true;
                    var params = {
                        action: isShopLoginChallenge ? 'verifyShopLoginEmailOtp' : 'checkCode',
                        ajax: 1,
                        ajax_token: simplyin.ajax_token,
                        email: SimplyIn.customer_email,
                        code: code,
                        force_login: SimplyIn.force_login ? 1 : 0,
                    };

                    if (code == self.last_code) {
                        self.validate_code_sended = false;
                        return;
                    }

                    $.ajax({
                        url: self.ajax,
                        method: 'POST',
                        data: params,
                        dataType: 'json',
                    }).done(data => {
                        self.validate_code_sended = false;
                        // F3: the rate-limit branch is checked FIRST so an `error` field that may ride
                        // along on that payload cannot be shadowed by the generic-error handling below.
                        if (data && data.code == 'TOO_MANY_REQUESTS') {
                            $('.simplyin-popup-content .code-error-message').show();
                            var message = data.message.split('\n');
                            if (message.length > 1) {
                                self.startCountingMessage(message);
                            } else {
                                $('.simplyin-popup-content .code-error-message').html(message[0]);
                            }
                        }
                        else if (data && data.isCodeValid == false) {
                            $('.simplyin-popup-content .code-error-message').show();
                            $('.simplyin-popup-content .code-error-message').text(simplyin.labels.code_invalid);
                            $(selector).addClass('invalid').removeClass('valid');
                        }
                        else if (data && data.success) {
                            self.stopCounting();
                            // Challenge verify succeeded (the popup carries the challenge
                            // marker) → the customer is now logged into the shop account; reload so the
                            // page reflects the session (addresses, logged-in state), like the login-page
                            // path does for the checkout code.
                            if ($('#simplyin-input-code').attr('data-shop-login-challenge') === '1') {
                                window.location.reload();
                                return;
                            }
                            // The initial checkout code returned challenge_available (email not
                            // verified + a registered shop account exists) → offer the email-OTP
                            // challenge instead of proceeding as a guest.
                            if (data.login_result && data.login_result.challenge_available) {
                                self.startShopLoginEmailChallenge();
                                return;
                            }
                            self.showIcon();
                            $('.simplyin-show-popup').removeClass('simplyin-confirm-profile');
                            $('.simplyin-show-popup-edit > span').first().text(simplyin.labels.data_completed);

                            if (self.phoneCheckboxManager) {
                                self.phoneCheckboxManager.hideCheckbox(true);
                            }
                            if (typeof self.showChangeDataButton === 'function') {
                                self.showChangeDataButton();
                            }

                            if (self.is_login_page) {
                                window.location.reload();
                            } else {
                                self.showPopupByContent(data.html);
                                self.selectDefaultAddress();
                            }

                            self.loginCustomer(self.customer_email);

                            if (data.login_result.is_guest) {
                                $('#customer-form input[name="firstname"]').val(data.login_result.firstname).trigger('input').trigger('change');
                                $('#customer-form input[name="lastname"]').val(data.login_result.lastname).trigger('input').trigger('change');
                                self.selectCheckbox();
                            } else {
                                self.on_close_refresh_page = true;
                            }
                        }
                        else if (data && data.isCodeValid && !data.success) {
                            // F2: the code was VALID and is now consumed by the backend, but finishing
                            // sign-in failed (POST_VALIDATION_FAILURE). Retyping the SAME code will always
                            // come back "invalid", so tell the user to request a NEW code — not "try again".
                            self.last_code = false;
                            $('.simplyin-popup-content .code-error-message').show();
                            $('.simplyin-popup-content .code-error-message').text(simplyin.labels.code_consumed);
                            $(selector).removeClass('valid');
                        }
                        else {
                            // Unrecognized/empty outcome — an empty body from a failed API call
                            // (apiCall() returns false → controller returns {}), or a controller {error}.
                            // Generic message, allow a fresh attempt.
                            self.last_code = false;
                            $('.simplyin-popup-content .code-error-message').show();
                            $('.simplyin-popup-content .code-error-message').text(simplyin.labels.generic_error);
                            $(selector).removeClass('valid');
                        }
                    }).fail(() => {
                        // Transport / non-JSON failure: same rule — surface it, never go silent.
                        self.validate_code_sended = false;
                        self.last_code = false;
                        $('.simplyin-popup-content .code-error-message').show();
                        $('.simplyin-popup-content .code-error-message').text(simplyin.labels.generic_error);
                        $(selector).removeClass('valid');
                    });
                } else {
                    $('.simplyin-popup-content .code-error-message').hide();
                    $(selector).addClass('valid').removeClass('invalid');
                }
            }, 300);
        },
        isValidEmailAddress: function (email) {
            var pattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/;
            return pattern.test(email);
        },
        codeStartCounting: function () {
            const self = this;
            var buttons_selector = '.simplyin-popup-footer .buttons';
            var time_selector = '.simplyin-popup-footer .time';
            var send_messages_selector = '.simplyin-popup-footer .sent-messages';
            if (this.counting_interval) {
                clearInterval(this.counting_interval);
            }
            this.counting_value = 30;
            $(buttons_selector).hide();
            $(send_messages_selector).show();
            this.counting_interval = setInterval(() => {
                this.counting_value--;
                if (this.counting_value <= 0) {
                    clearInterval(this.counting_interval);
                    this.counting_value = 0;
                    $(buttons_selector).show();
                    $(send_messages_selector).hide();
                }
                $(time_selector).text(self.formatTime(this.counting_value));
            }, 1000);
        },
        stopPushNotifications: function () {
            if (this.push_notification_interval) {
                clearInterval(this.push_notification_interval);
                this.push_notification_interval = false;
            }
        },
        stopCounting: function () {
            if (this.counting_interval) {
                clearInterval(this.counting_interval);
                this.counting_interval = false;
            }
        },
        checkPushNotification: function () {
            const self = this;
            if (this.push_notification_interval) {
                clearInterval(this.push_notification_interval);
            }
            let i = 0;
            this.push_notification_interval = setInterval(() => {
                if (i++ > 60) {
                    self.stopPushNotifications();
                    return;
                }
                var params = {
                    action: 'checkPushNotification',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    email: this.customer_email,
                };

                $.ajax({
                    url: self.ajax,
                    method: 'POST',
                    data: params,
                    dataType: 'json'
                }).done(data => {
                    if (data && data.success) {
                        self.stopPushNotifications();
                        self.showIcon();
                        $('.simplyin-show-popup').removeClass('simplyin-confirm-profile');
                        $('.simplyin-show-popup-edit > span').first().text(simplyin.labels.data_completed);
                        self.loginCustomer(self.customer_email);
                        self.login_request_send = false;
                        if (self.phoneCheckboxManager) {
                            self.phoneCheckboxManager.hideCheckbox(true);
                        }
                        if (typeof self.showChangeDataButton === 'function') {
                            self.showChangeDataButton();
                        }
                        if (self.is_login_page) {
                            window.location.reload();
                        } else {
                            self.showPopupByContent(data.html);
                            self.selectDefaultAddress();
                        }
                        if (data.login_result.is_guest) {
                            $('#customer-form input[name="firstname"]').val(data.login_result.firstname).trigger('input').trigger('change');
                            $('#customer-form input[name="lastname"]').val(data.login_result.lastname).trigger('input').trigger('change');

                        } else {
                            self.on_close_refresh_page = true;
                        }
                        return;
                    }
                    // F5: a controller {error}, or push confirmed but finishing sign-in threw
                    // (POST_VALIDATION_FAILURE), is terminal — stop polling and tell the user to request a
                    // new code rather than poll silently to timeout. A still-pending {ok:false} carries no
                    // `error`, so ordinary polling is unaffected.
                    if (data && data.error) {
                        self.stopPushNotifications();
                        self.login_request_send = false;
                        self.notifyServerError(simplyin.labels.code_consumed);
                    }
                });

            }, 1000);
        },
        startCountingMessage: function (message) {
            const self = this;
            if (this.counting_message_interval) {
                clearInterval(this.counting_message_interval);
            }
            this.counting_value_message = parseInt(message[1]);
            var message_selector = '.simplyin-popup-content .code-error-message'
            $(message_selector).html(message[0] + '<br />' + self.formatTime(this.counting_value_message));
            this.counting_message_interval = setInterval(() => {
                this.counting_value_message--;
                if (this.counting_value_message <= 0) {
                    clearInterval(this.counting_message_interval);
                    this.counting_value_message = 0;
                    $(message_selector).html('');
                    $(message_selector).hide();
                }
                $(message_selector).html(message[0] + '<br />' + self.formatTime(this.counting_value_message));
            }, 1000);
        },
        formatTime: function (seconds) {
            if (seconds < 10) {
                return '00:0' + seconds.toString();
            } else {
                return '00:' + seconds.toString();
            }
        },
        loginCustomer: function (email) {
            this.customer_email = email;
            this.is_login = true;
            if (this.is_login_page) {

            }
        },
        storeDeliveryPopup: function () {
            const self = this;
            self.delivery_popup = $('.simplyin-popup-box').children().clone(true, true);

            self.delivery_popup_scroll = $('.simplyin-popup').scrollTop();

        },
        retrieveDeliveryPopup: function () {
            const self = this;
            if (self.delivery_popup) {
                self.showPopupByContent(self.delivery_popup);
                if ($('.simplyin-popup').length && self.delivery_popup_scroll) {
                    $('.simplyin-popup').scrollTop(self.delivery_popup_scroll);
                }
            }
        },
        editAddress: function (id, address_type) {
            const self = this;
            self.storeDeliveryPopup();
            var params = {
                action: 'editAddress',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                id: id,
                address_type: address_type
            };

            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                    self.showPopupByContent(data.html);
                }
            });
        },
        confirmationPopup: function (title, message, callback) {
            const self = this;
            const $overlay = $('<div class="simplyin-popup-overlay-confirmation"><div>');
            const $popup = $(`
                <div class="simplyin-confirmation-popup">
                    <div class="simplyin-popup-header-confirmation">
                        <span class="simplyin-title">
                            ${title}
                        </span>
                        <div class="simplyin-popup-close-button-confirmation">
                            <img width="20" height="21"
                                 src="${simplyin.files_url}/views/img/close_icon.svg"
                                 alt=""
                                 class="simplyin-close">
                        </div>
                    </div>
                    <div class="simplyin-message">
                        ${message}
                    </div>
                    <div class="simplyin-actions">
                        <button type="button"
                                class="simplyin-btn simplyin-btn-secondary">
                            ${simplyin.labels.cancel}
                        </button>
                        <button type="button"
                                class="simplyin-btn simplyin-btn-danger">
                            ${simplyin.labels.delete}
                        </button>
                    </div>
                </div>
            `);

            $('body').append($popup);
            $('body').append($overlay);
            const closePopup = () => {
                $popup.remove();
                $overlay.remove();
                $(document).off('keydown.simplyinConfirm');
            };
            $overlay.on('click', function () {
                closePopup();
            });

            $(document).on('keydown.simplyinConfirm', function (e) {
                if (e.key === 'Escape') {
                    closePopup();
                } else if (e.key === 'Enter') {
                    closePopup();
                    if ($.isFunction(callback)) callback();
                }
            });

            $popup
                .on('click', '.simplyin-popup-close-button-confirmation', closePopup)
                .on('click', '.simplyin-btn-secondary', closePopup)
                .on('click', '.simplyin-btn-danger', function () {
                    closePopup();
                    if ($.isFunction(callback)) callback();
                });
        },
        logout: function () {
            self.is_login = false;
            const self = this;
            var params = {
                action: 'logout',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
            };

            $.ajax({
                url: self.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {
                self.hidePopup();
            });
        },
        hideIcon: function () {
            if (typeof (this.hideIconCheckout) === 'function') {
                this.hideIconCheckout();
            }
            $('.simplyin-show-popup').hide();
            
            $('.simplyin-field-badge').show();
        },
        showIcon: function () {
            if (typeof (this.showIconCheckout) === 'function') {
                this.showIconCheckout();
            }
            $('.simplyin-show-popup').show();
            
            $('.simplyin-field-badge').hide();
        },

        

        
        dockConfirmProfile: function () {
            var $popup = $('.simplyin-show-popup').not('.simplyin-show-popup-login').filter('.simplyin-confirm-profile').first();
            if (!$popup.length || $popup.parent().hasClass('simplyin-field-wrap')) {
                return;
            }
            var $wrap = $(this.email_field).closest('.simplyin-field-wrap');
            if (!$wrap.length) {
                $wrap = $(this.email_field).siblings('.simplyin-field-wrap').first();
            }
            if (!$wrap.length) {
                return;
            }
            var $home = $('<span class="simplyin-show-popup-home" style="display:none"></span>');
            $popup.before($home);
            $popup.data('simplyinPopupHome', $home);
            $wrap.append($popup);
        },
        undockConfirmProfile: function () {
            $('.simplyin-field-wrap > .simplyin-show-popup').not('.simplyin-show-popup-login').each(function () {
                var $home = $(this).data('simplyinPopupHome');
                if ($home && $home.length) {
                    $home.replaceWith(this);
                    $(this).removeData('simplyinPopupHome');
                }
            });
        },
        // Move the main data-completed badge inside the e-mail field (same in-field spot
        // as the "confirm profile" state), so the status is shown in the input, not below it.
        dockBadge: function () {
            var $field = $(this.email_field);
            if (!$field.length) {
                return;
            }
            if (!$field.parent().hasClass('simplyin-field-wrap')) {
                $field.wrap('<div class="simplyin-field-wrap"></div>');
            }
            var $wrap = $field.parent();
            var $popup = $('.simplyin-show-popup').not('.simplyin-show-popup-login').first();
            if ($popup.length && !$popup.parent().hasClass('simplyin-field-wrap')) {
                $wrap.append($popup);
            }
        },
        focusOnCode: function () {
            if ($('#simplyin-input-code input[type="text"]:first').length) {
                $('#simplyin-input-code input[type="text"]:first').focus();
            }
        },

        placeOrder: function () {
            $.ajax({
                url: SimplyIn.ajax,
                method: 'POST',
                data: {
                    action: 'placeOrder',
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    order_token: simplyin.order.order_token,
                    id_cart: simplyin.order.id_cart,
                },
                dataType: 'json'
            }).done(data => {
                if (data.success) {
                }
            });
        },
        loadPhoneCountries: function () {
            const self = this;
            $.getJSON(simplyin.files_url + 'views/json/phones.json', function (data) {
                self.phones = data;
            });
        },
        validatePhoneNumber: function (blink_error = false) {
            const self = this;
            const phoneInput = $('#simplyin-phone-checkbox .phone-input input');
            if (phoneInput.length == 0) {
                return true;
            }
            const phoneNumberRaw = phoneInput.val().replace(/\D/g, '');
            const prefix = $('#simplyin-phone-checkbox #simplyin-phone-country')
                .find('option:selected')
                .data('prefix');

            const country = self.phones.find(c => c.country_code === prefix);

            const isValidLength = country.phone_number_lengths.includes(phoneNumberRaw.length);

            const isMobile = country.mobile_begin_with.some(start =>
                phoneNumberRaw.startsWith(start)
            );

            const fullNumber = prefix + phoneNumberRaw;

            let formatted = '';
            if (isMobile) {
                formatted = phoneNumberRaw.replace(/(\d{3})(\d{3})(\d{3})/, '$1 $2 $3');
            } else {
                formatted = phoneNumberRaw.replace(/(\d{2})(\d{3})(\d{2})(\d{2})/, '$1 $2 $3 $4');
            }

            $(phoneInput).val(formatted);

            if (!isValidLength || !country || !isMobile) {
                self.showValidateWarningMessage(blink_error);
                return false;
            } else {
                self.hideValidateWarningMessage();
                return true;
            }

        },
        showValidateWarningMessage: function (blink_error = false) {
            if (blink_error) {
                $('#simplyin-phone-checkbox .phone-input-warning').hide().fadeIn();
            } else {
                $('#simplyin-phone-checkbox .phone-input-warning').show();
            }
        },
        hideValidateWarningMessage: function () {
            $('#simplyin-phone-checkbox .phone-input-warning').hide();
        },
        bindNewAccountEvent: function () {
            const self = this;
            const button = document.querySelector('#payment-confirmation button');
            if (!button) return;

            const handler = (e) => {
                if (!self.validatePhoneNumber(true)) {
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();

                    return false;
                }
            };

            if (button._simplyinNewAccountHandler) {
                button.removeEventListener('click', button._simplyinNewAccountHandler, { capture: true });
            }

            button.addEventListener('click', handler, { capture: true });
            button._simplyinNewAccountHandler = handler;
        },

        unbindNewAccountEvent: function () {
            const button = document.querySelector('#payment-confirmation button');
            if (!button || !button._simplyinNewAccountHandler) return;

            button.removeEventListener('click', button._simplyinNewAccountHandler, { capture: true });
            button._simplyinNewAccountHandler = null;
        },

        storeNewAccountDetails: function (is_checked) {
            const phone_with_prefix = $('#simplyin-phone-checkbox .phone-input input').val();
            const prefix = $('#simplyin-phone-checkbox #simplyin-phone-country')
                .find('option:selected')
                .data('prefix');
            const phone_number = phone_with_prefix.replace(/\D/g, '');
            const phone = prefix + ' ' + phone_number;
            const params = {
                action: 'storeNewAccountDetails',
                ajax: 1,
                ajax_token: simplyin.ajax_token,
                phone: is_checked ? phone : 0,
            }
            $.ajax({
                url: SimplyIn.ajax,
                method: 'POST',
                data: params,
                dataType: 'json'
            }).done(data => {

            });
        },
        initEventListenersNewAccount: function () {
            const self = this;

            if (self.initialized_new_account_events) {
                return;
            }

            if (typeof SimplyInPhoneCheckboxManager !== 'undefined') {
                self.phoneCheckboxManager = new SimplyInPhoneCheckboxManager({
                    checkoutType: 'classic',
                    emailFieldSelector: '#customer-form input[name="email"]',
                    containerSelector: '#checkout-payment-step .payment-options',
                    ajaxUrl: self.ajax,
                    ajaxToken: simplyin.ajax_token,
                    debug: false
                });

                self.initialized_new_account_events = true;

                $(document).off('change.simplyin blur.simplyin', 'input[name="phone"]');
                $(document).on('change.simplyin blur.simplyin', 'input[name="phone"]', function () {
                    var simplyinPhoneInput = $('#simplyin-phone-checkbox .phone-input input');

                    if ($(this).closest('#simplyin-phone-checkbox').length > 0) {
                        return;
                    }

                    if (simplyinPhoneInput.length) {
                        let phone_value = $(this).val();

                        if (self.phoneCheckboxManager &&
                            typeof self.phoneCheckboxManager.removeCountryPrefix === 'function') {
                            var cleanPhone = self.phoneCheckboxManager.removeCountryPrefix(phone_value);
                            var digits = cleanPhone.replace(/\D/g, '');
                            var maxLength = self.phoneCheckboxManager.getMaxPhoneLengthForSelectedCountry();
                            simplyinPhoneInput.val(digits.substring(0, maxLength));
                            self.phoneCheckboxManager.validatePhoneNumber();
                            self.phoneCheckboxManager.storePhoneNumber();
                        } else if (self.phoneCheckboxManager &&
                            typeof self.phoneCheckboxManager.parseAndSetPhoneNumber === 'function') {
                            self.phoneCheckboxManager.parseAndSetPhoneNumber(phone_value);
                        } else {
                            if (phone_value.indexOf('+') !== 0) {
                                simplyinPhoneInput.val(phone_value);
                            }
                        }
                    }
                });

            } else {
            }
        },

        initDhlAssistantDisplay: function () {
            if (!simplyin.customer.point || simplyin.customer.point.label !== 'dhl') {
                return;
            }

            var lockerId = simplyin.customer.point.locker_id;
            if (!lockerId || lockerId.trim() === '') {
                return;
            }

            var pointAddress = simplyin.customer.point.address || '';
            var pointName = simplyin.customer.point.address_name || lockerId;
            var displayText = pointName + (pointAddress ? ' ' + pointAddress : '');

            this.waitForElement('#dhlassistant_messages .success.current-address', function () {
                $('#dhlassistant_messages .success.current-address').text(displayText).show();
                $('button[name="confirmDeliveryOption"]').attr('disabled', false);
            }, 20000);
        },
        dpdshippingmodule: function () {
            if ($('.dpdshipping-pudo-new-point').length && simplyin.customer.point.label == 'dpd') {
                if (typeof (dpdshippingSavePudoCode) != 'undefined' && typeof (dpdshipping_token) != 'undefined' && typeof (dpdshipping_csrf) != 'undefined' && typeof (dpdshipping_id_cart) != 'undefined') {
                    let modal = {
                        modal: function (toogle) { }
                    }
                    dpdshippingSavePudoCode(simplyin.customer.point.locker_id, modal);
                    let span = $('span.dpdshipping-selected-point');
                    dpdshippingGetPudoAddress(simplyin.customer.point.locker_id, span);
                }
            }
        },
        furgonetkamodule: function () {
            const self = this;

            if (typeof furgonetkaMapCallback !== 'function') {
                return;
            }

            const hasValidPoint = simplyin.customer.point &&
                simplyin.customer.point.locker_id &&
                simplyin.customer.point.locker_id.trim() !== '';

            if (!hasValidPoint) {
                return;
            }

            const checkButton = function () {
                if ($('.furgonetka-set-point').length) {
                    let type = simplyin.customer.point.label;
                    if (type === 'inpost') {
                        type = 'paczkomat';
                    }

                    const id_delivery = simplyin.id_carrier;
                    const targetElement = document.getElementById('furgonetka-machine-' + id_delivery);

                    if (targetElement) {
                        const observer = new MutationObserver(function (mutations) {
                            if (targetElement.textContent.trim() !== '' &&
                                !targetElement.classList.contains('furgonetka-hidden')) {
                                $('.shipping-radio input[type="radio"][value="' + id_delivery + ',"]').trigger('click');
                                observer.disconnect();
                            }
                        });

                        observer.observe(targetElement, {
                            childList: true,
                            attributes: true,
                            characterData: true,
                            subtree: true
                        });

                        setTimeout(function () { observer.disconnect(); }, 5000);
                    }

                    furgonetkaMapCallback({
                        code: simplyin.customer.point.locker_id,
                        name: simplyin.customer.point.locker_id,
                        type: type,
                    }, id_delivery);

                } else {
                    requestAnimationFrame(checkButton);
                }
            };

            requestAnimationFrame(checkButton);
        },
        authController: function () {
            const self = this;
            let email_login_field = '#login-form input[name="email"]';
            let login_section = 'section.login-form';
            if ($(email_login_field).length) {
                if (self.barEnabled()) {

                    
                    let $login_section = $(login_section);
                    if (!$login_section.length) {
                        $login_section = $(email_login_field).closest('form');
                    }

                    $login_section.prepend(self.barHtml());
                    $login_section.children('.simplyin-logo-container').first()
                        .addClass('simplyin-logo-container--login');
                }
                if (self.badgeEnabled()) {
                    self.injectFieldBadge(email_login_field);
                }
                self.email_login_field = $(email_login_field);
                customer_email = simplyin.customer_email;
                self.email_login_field.parent().append(`
                    <div class="simplyin-show-popup simplyin-show-popup-login">
                        <div class="simplyin-show-popup-icon">
                            <img width="30" height="30" src="${simplyin.files_url}/views/img/logo_smalln.svg"/>
                            <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                              <rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>
                              <path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>
                            </svg>
                        </div>
                        <div class="simplyin-show-popup-edit">
                            <span>${simplyin.labels.data_completed}</span>
                            <div class="simplyin-show-popup-edit-bottom">
                              <span>${simplyin.labels.change}</span>
                              <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path>
                              </svg>
                            </div>
                        </div>
                    </div>
                `);
                this.hideIconLogin();
                self.email_login_field.parent().addClass('simplyin-display-flex');
                $(document).on('input', email_login_field, function () {
                    let logout = false;
                    if (self.is_login && self.customer_email != $(this).val()) {
                        logout = true;
                    }
                    self.customer_email = $.trim($(this).val());
                    self.submitEmailLogin(logout);
                });
            }
        },
        submitEmailLogin: function (logout) {
            this.last_popup = '';
            const self = this;
            if (this.is_login == false || logout) {
                this.is_login = false;
                var email = this.customer_email;
                if (!this.isValidEmailAddress(email)) {
                    return;
                }
                if (self.login_request_send && self.last_email == email) {
                    return;
                }
                self.is_login_page = true;

                if (!this.isValidEmailAddress(email)) {
                    return;
                }
                if (self.login_request_send && self.last_email == email) {
                    return;
                }

                var params = {
                    action: 'submitEmail',
                    login: 1,
                    ajax: 1,
                    ajax_token: simplyin.ajax_token,
                    email: email,
                    logout: logout,
                };

                self.login_request_send = true;
                self.last_email = email;

                $.ajax({
                    url: self.ajax,
                    method: 'POST',
                    data: params,
                    dataType: 'json'
                }).done(data => {
                    // Email-first (login page): same challenge branch as submitEmail — show
                    // the 6-digit popup, skip the SMS/push bookkeeping; verify success reloads.
                    if (data && data.success && data.show_popup && data.shop_login_challenge) {
                        // Stale-response guard: a newer email was submitted while this AJAX was in
                        // flight — self.last_email holds the most recent one; drop this reply.
                        if (email !== self.last_email) {
                            return;
                        }
                        self.last_code = false;
                        self.validate_code_sended = false;
                        self.showPopupByContent(data.html);
                        self.codeStartCounting();
                        self.focusOnCode();
                        return;
                    }
                    if (data && data.success && data.show_popup) {
                        self.userUsedPushNotifications = data.userUsedPushNotifications;
                        self.showPopupByContent(data.html);
                        self.focusOnCode();
                        self.showIconLogin();
                        simplyin.hide_phone_field = true;
                        if (data.userUsedPushNotifications) {
                            self.checkPushNotification();
                        } else {
                            self.codeStartCounting();
                        }
                        return;
                    }
                    if (data && data.error == 'NOT_FOUND') {
                        self.hideIconLogin();
                        return;
                    }
                    // F6: other {error} (e.g. BAD_REQUEST) / empty body → surface, don't go silent.
                    self.login_request_send = false;
                    self.notifyServerError();
                }).fail(() => {
                    self.login_request_send = false;
                    self.notifyServerError();
                });
            }
        },
        hideIconLogin: function () {
            $('.simplyin-show-popup-login').hide();
        },
        showIconLogin: function () {
            $('.simplyin-show-popup-login').show();
        },
        selectCheckbox: function () {
            const self = this;
            if (self.select_customer_privacy) {
                if ($('input[name="customer_privacy"]').length) {
                    $('input[name="customer_privacy"]').prop('checked', true);
                }
            }
            if (self.select_psgdpr) {
                if ($('input[name="psgdpr"]').length) {
                    $('input[name="psgdpr"]').prop('checked', true);
                }
            }
            if (self.submit_guest_form) {
                $('#customer-form').find('button[type="submit"]').trigger('click');
            } else {
                return false;
            }
        }
    };
    if (simplyin.checkout == 'classic') {
        SimplyIn.init();
    }
});
