/**
 * Simplyin Payment - Modal Handler
 * Handles OTP verification, new account creation, shipping method selection, and payment methods
 */
define([
    'jquery',
    'Magento_Ui/js/modal/modal',
    'mage/translate',
    'mage/url',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/shipping-service',
    'Magento_Checkout/js/model/shipping-rate-registry',
    'Magento_Checkout/js/action/select-shipping-method',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/action/select-shipping-address',
    'Magento_Customer/js/model/address-list',
    'Simplyin_Payment/js/model/session-storage-manager',
    'Simplyin_Payment/js/payment/cc-iframe-manager',
    'Simplyin_Payment/js/payment/payment-status-poller',
    'Simplyin_Payment/js/payment/three-d-secure-handler',
    'Simplyin_Payment/js/model/pickup-point-integration-manager',
    'Simplyin_Payment/js/model/ajax-client'
], function ($, modal, $t, urlBuilder, quote, shippingService, rateRegistry, selectShippingMethodAction, checkoutData, selectShippingAddress, addressList, sessionStorageManager, ccIframeManager, paymentStatusPoller, threeDSecureHandler, pickupPointIntegrationManager, ajaxClient) {
    'use strict';

    var modalElement = null;
    var modalWidget = null;
    var customerNumber = '';

    return {
        /**
         * Initialize modal
         */
        initModal: function () {
            if (!modalElement) {
                modalElement = $('#simplyin-modal');

                if (modalElement.length === 0) {
                    // Create modal element if it doesn't exist
                    modalElement = $('<div id="simplyin-modal" class="simplyin-modal-content"></div>');
                    $('body').append(modalElement);
                }

                var options = {
                    type: 'popup',
                    responsive: true,
                    innerScroll: true,
                    title: $t('Simply.IN Verification'),
                    modalClass: 'simplyin-modal',
                    buttons: []
                };

                modalWidget = modal(options, modalElement);
            }

            return modalElement;
        },

        /**
         * Show OTP verification modal
         */
        showOtpModal: function (config) {
            var self = this;
            var element = this.initModal();

            // Logo URL - handling require/url context
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');
            var googleplayUrl = require.toUrl('Simplyin_Payment/images/simplyin_google_play.svg');
            var appleplayUrl = require.toUrl('Simplyin_Payment/images/simplyin_app_store.svg');
            var footerlogoUrl = require.toUrl('Simplyin_Payment/images/simplyin_app_logo.svg');

            // Determine delivery method (default to SMS)
            var deliveryMethod = config.authStrategy || 'sms';
            var maskedInfo = '';
            var messageText = '';

            // Check if user used push notifications - show push modal instead
            if (config.userUsedPushNotifications || (config.data && config.data.userUsedPushNotifications)) {
                this.showPushNotificationModal(config);
                return;
            }

            // Get masked info from API response
            if (config.data && config.data.data) {
                maskedInfo = config.data.data;
            }

            // If no masked info from API, try to get from customerNumber variable
            if (!maskedInfo && customerNumber) {
                maskedInfo = customerNumber;
            }

            // Fallback: try to get and mask phone number
            if (!maskedInfo) {
                var phoneNumber = '';

                // Try to find phone in config.data
                if (config.data) {
                    if (config.data.user && config.data.user.phoneNumber) {
                        phoneNumber = config.data.user.phoneNumber;
                    } else if (config.data.phoneNumber) {
                        phoneNumber = config.data.phoneNumber;
                    } else if (config.data.phone) {
                        phoneNumber = config.data.phone;
                    }
                }

                // Fallback to quote if not found in API response
                if (!phoneNumber) {
                    var billing = quote.billingAddress();
                    if (billing && billing.telephone) {
                        phoneNumber = billing.telephone;
                    } else {
                        var shipping = quote.shippingAddress();
                        if (shipping && shipping.telephone) {
                            phoneNumber = shipping.telephone;
                        }
                    }
                }

                // Mask phone number: ***********48
                if (phoneNumber && phoneNumber.length > 2) {
                    var visible = phoneNumber.slice(-2);
                    maskedInfo = '***********' + visible;
                } else {
                    maskedInfo = '***********'; // Fallback if no phone
                }
            }

            // Set message based on delivery method
            if (deliveryMethod === 'email') {
                messageText = $t('Enter the code sent to your email');
                // For email, show masked email if available
                if (config.email) {
                    var emailParts = config.email.split('@');
                    if (emailParts.length === 2) {
                        var localPart = emailParts[0];
                        var domain = emailParts[1];
                        var maskedLocal = localPart.substring(0, 2) + '***' + localPart.substring(localPart.length - 1);
                        maskedInfo = maskedLocal + '@' + domain;
                    } else {
                        maskedInfo = config.email;
                    }
                }
            } else {
                messageText = $t('Enter the code sent to the number');
            }

            var html = `
                <div class="simplyin-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Confirm it\'s you')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-popup-content mobile-pb-0">
                            <div class="popup-caption custom-spaces" id="simplyin-otp-message">
                                ${messageText}<br>
                                <strong id="simplyin-masked-info">${maskedInfo}</strong>
                            </div>
                            
                            <div class="popup-input-code">
                                <form id="simplyin-input-code" onsubmit="return false;">
                                     <div class="simplyin-otp-inputs-container">
                                        <input type="text" class="simplyin-otp-digit" maxlength="1" id="simplyin-otp-1" autocomplete="one-time-code" aria-label="Digit 1" inputmode="numeric" pattern="[0-9]*" />
                                        <input type="text" class="simplyin-otp-digit" maxlength="1" id="simplyin-otp-2" autocomplete="one-time-code" aria-label="Digit 2" inputmode="numeric" pattern="[0-9]*" />
                                        <input type="text" class="simplyin-otp-digit" maxlength="1" id="simplyin-otp-3" autocomplete="one-time-code" aria-label="Digit 3" inputmode="numeric" pattern="[0-9]*" />
                                        <input type="text" class="simplyin-otp-digit" maxlength="1" id="simplyin-otp-4" autocomplete="one-time-code" aria-label="Digit 4" inputmode="numeric" pattern="[0-9]*" />
                                     </div>
                                </form>
                            </div>
                            
                            <div class="simplyin-status" id="simplyin-otp-status"></div>
                        </div>
                        
                        <div class="simplyin-popup-footer">
                            <div class="sent-messages">
				                <span>${$t('The code has been resent')}</span>
				                <span class="time">00:30</span>
			                </div>
                            <div class="popup-buttons">
                                <div class="popup-text popup-text-footer popup-text-footer-code">${$t('Didn’t receive the code?')}</div>
                                <button type="button" class="simplyin-round-btn simplyin-btn-primary" id="simplyin-button-send-sms">
                                    ${$t('Send SMS')}
                                </button>
                                &nbsp;&nbsp; or &nbsp;&nbsp;
                                <button type="button" class="simplyin-round-btn simplyin-btn-secondary" id="simplyin-button-send-email">
                                    ${$t('Send Email')}
                                </button>
                            </div>
                        </div>
                        
                        <div class="simplyin-popup-divider"></div>
                        
                        <div class="simplyin-popup-apps">
                            <div class="simplyin-login-text">
                                Log in via the app 
                                <img src="${footerlogoUrl}" alt="SimplyIn Logo">
                                 Install the app right now
                            </div>
                            <div class="simplyin-app-buttons">
                                 <!-- Simple Text Links/Buttons mimicking the app store badges if images missing, or we can use generic logic later -->
                                 <a href="https://play.google.com/store/apps/details?id=simplyin.app&hl=pl&pli=1" class="simplyin-app-btn">
                                    <img src="${googleplayUrl}" alt="SimplyIn Logo">
                                 </a>
                                 <a href="https://apps.apple.com/pl/app/simply-in/id6476778468" class="simplyin-app-btn">
                                    <img src="${appleplayUrl}" alt="SimplyIn Logo">
                                 </a>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            element.html(html);
            element.modal('openModal');

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                if (self.resendTimer) {
                    clearInterval(self.resendTimer);
                }
                element.modal('closeModal');
            });

            // Focus first input
            setTimeout(function () {
                $('#simplyin-otp-1').focus();
            }, 500);

            // Bind OTP input logic
            $('.simplyin-otp-digit').on('keyup', function (e) {
                var key = e.which || e.keyCode;
                var val = $(this).val();
                var id = $(this).attr('id');
                var index = parseInt(id.split('-')[2]);

                // Allow numbers only or control keys
                // Not strictly preventing char input here handled by inputmode/pattern 
                // but behavior logic:

                // If backspace pressed and empty, move to previous
                if (key === 8 && val === '') {
                    if (index > 1) {
                        $('#simplyin-otp-' + (index - 1)).focus();
                    }
                    return;
                }

                // If value entered is a number, move to next
                // Note: keyup happens after value is in.
                if (val.length === 1 && index < 4) {
                    $('#simplyin-otp-' + (index + 1)).focus();
                }

                // If all filled, verify
                var otp = '';
                $('.simplyin-otp-digit').each(function () {
                    otp += $(this).val();
                });
                if (otp.length === 4) {
                    self.verifyOtp(config);
                }
            });

            // Handle paste event for full code
            $('#simplyin-otp-1').on('paste', function (e) {
                var pastedData = e.originalEvent.clipboardData.getData('text');
                e.preventDefault();
                if (pastedData) {
                    var chars = pastedData.trim().split('');
                    for (var i = 0; i < 4 && i < chars.length; i++) {
                        $('#simplyin-otp-' + (i + 1)).val(chars[i]);
                    }
                    if (chars.length >= 4) {
                        self.verifyOtp(config);
                    } else {
                        $('#simplyin-otp-' + chars.length).next().focus();
                    }
                }
            });

            // Bind resend buttons
            // Using the new IDs from the design
            $('#simplyin-button-send-sms').on('click', function () {
                self.resendOtp(config.email, 'sms');
            });

            $('#simplyin-button-send-email').on('click', function () {
                self.resendOtp(config.email, 'email');
            });

            // Start timer initially
            self.startResendTimer();
        },

        /**
         * Start Resend Timer
         */
        startResendTimer: function () {
            var self = this;
            var duration = 30; // 30 seconds
            var timerElement = $('.sent-messages .time');
            var messageContainer = $('.sent-messages');
            var buttonsContainer = $('.popup-buttons');

            // Reset UI state
            messageContainer.show();
            buttonsContainer.hide();
            timerElement.text('00:30');

            if (this.resendTimer) {
                clearInterval(this.resendTimer);
            }

            this.resendTimer = setInterval(function () {
                duration--;

                var minutes = Math.floor(duration / 60);
                var seconds = duration % 60;
                var formattedTime =
                    (minutes < 10 ? '0' : '') + minutes + ':' +
                    (seconds < 10 ? '0' : '') + seconds;

                timerElement.text(formattedTime);

                if (duration <= 0) {
                    clearInterval(self.resendTimer);
                    messageContainer.hide();
                    buttonsContainer.css('display', 'inline-block'); // Restore flex display
                }
            }, 1000);
        },

        /**
         * Show Push Notification Modal
         * Displays simplified UI when user has push notifications enabled
         */
        showPushNotificationModal: function (config) {
            var self = this;
            var element = this.initModal();

            // Logo URL
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');

            // Get notificationTokenId from config for polling
            var notificationTokenId = config.notificationTokenId ||
                (config.data && config.data.notificationTokenId) || null;

            // Store notificationTokenId and email in session storage for persistence
            if (notificationTokenId) {
                sessionStorageManager.setNotificationTokenId(notificationTokenId);
            }
            if (config.email) {
                sessionStorageManager.setPendingEmail(config.email);
            }

            var html = `
                <div class="simplyin-popup simplyin-push-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Confirm it\'s you')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-popup-content mobile-pb-0">
                            <div class="popup-caption custom-spaces" id="simplyin-push-message">
                                ${$t('We\'ve sent you a notification - accept it and the data will be filled in automatically.')}
                            </div>
                            
                            <div class="simplyin-push-loading">
                                <div class="simplyin-spinner"></div>
                                <p>${$t('Waiting for confirmation...')}</p>
                            </div>
                            
                            <div class="simplyin-status" id="simplyin-otp-status"></div>
                        </div>
                        
                        <div class="simplyin-popup-divider"></div>
                        
                        <div class="simplyin-popup-footer simplyin-push-footer">
                            <div class="popup-text popup-text-footer">${$t('Don\'t have access to the application?')}</div>
                            <div class="popup-buttons simplyin-push-buttons">
                                <button type="button" class="simplyin-round-btn simplyin-btn-secondary" id="simplyin-button-send-sms">
                                    ${$t('Send SMS code')}
                                </button>
                                <span class="simplyin-or-text">or</span>
                                <button type="button" class="simplyin-round-btn simplyin-btn-secondary" id="simplyin-button-send-email">
                                    ${$t('Send by email')}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            element.html(html);
            element.modal('openModal');

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                if (self.pushPollingTimer) {
                    clearInterval(self.pushPollingTimer);
                }
                // Clear stored notification data
                sessionStorageManager.clearNotificationTokenId();
                sessionStorageManager.clearPendingEmail();
                element.modal('closeModal');
            });

            // Start polling for push notification approval
            self.startPushNotificationPolling(config, notificationTokenId);

            // Bind SMS fallback button
            $('#simplyin-button-send-sms').on('click', function () {
                if (self.pushPollingTimer) {
                    clearInterval(self.pushPollingTimer);
                }
                // Clear push notification flag
                config.userUsedPushNotifications = false;
                if (config.data) {
                    config.data.userUsedPushNotifications = false;
                }
                config.authStrategy = 'sms';

                // Clear stored notification data
                sessionStorageManager.clearNotificationTokenId();

                // Send SMS and then show OTP modal
                self.sendOtpAndShowModal(config, 'sms');
            });

            // Bind Email fallback button
            $('#simplyin-button-send-email').on('click', function () {
                if (self.pushPollingTimer) {
                    clearInterval(self.pushPollingTimer);
                }
                // Clear push notification flag
                config.userUsedPushNotifications = false;
                if (config.data) {
                    config.data.userUsedPushNotifications = false;
                }
                config.authStrategy = 'email';

                // Clear stored notification data
                sessionStorageManager.clearNotificationTokenId();

                // Send Email and then show OTP modal
                self.sendOtpAndShowModal(config, 'email');
            });
        },

        /**
         * Send OTP and show OTP modal
         * Used when switching from push notification to SMS/Email
         */
        sendOtpAndShowModal: function (config, method) {
            var self = this;
            var deliveryMethod = method === 'email' ? 'email' : 'phone';

            // Show loading in current modal
            this.showStatus('loading', $t('Sending OTP to your ' + deliveryMethod + '...'));

            $('body').trigger('processStart');
            ajaxClient.postSilent('simplyin/api/resendOtp', {
                email: config.email,
                method: method
            }).done(function (response) {
                $('body').trigger('processStop');
                if (response.success) {
                    // Update config with response data
                    config.data = response.data || {};
                    config.authStrategy = method;

                    // Show OTP modal
                    self.showOtpModal(config);

                    // Start the resend timer
                    self.startResendTimer();
                } else {
                    self.showStatus('error', response.message || $t('Failed to send OTP'));
                }
            }).fail(function () {
                $('body').trigger('processStop');
                self.showStatus('error', $t('Failed to send OTP. Please try again.'));
            });
        },

        /**
         * Start polling for push notification approval
         */
        startPushNotificationPolling: function (config, notificationTokenId) {
            var self = this;
            var pollCount = 0;
            var maxPolls = 60; // Poll for 2 minutes (every 2 seconds)

            // Clear any existing polling timer
            if (this.pushPollingTimer) {
                clearInterval(this.pushPollingTimer);
            }

            // Get notificationTokenId from session storage if not provided
            if (!notificationTokenId) {
                notificationTokenId = sessionStorageManager.getNotificationTokenId();
            }

            if (!notificationTokenId) {
                console.error('SimplyIn: No notificationTokenId available for polling');
                self.showStatus('error', $t('Missing notification token. Please try SMS or Email.'));
                return;
            }

            this.pushPollingTimer = setInterval(function () {
                pollCount++;

                if (pollCount >= maxPolls) {
                    clearInterval(self.pushPollingTimer);
                    self.showStatus('error', $t('Notification timed out. Please use SMS or Email.'));
                    // Clear stored notification data
                    sessionStorageManager.clearNotificationTokenId();
                    return;
                }

                // Poll the API to check if push notification was approved
                ajaxClient.postSilent('simplyin/api/checkPushStatus', {
                    email: config.email,
                    notificationTokenId: notificationTokenId
                }).done(function (response) {
                        if (response.success && response.approved) {
                            clearInterval(self.pushPollingTimer);

                            // Clear stored notification data
                            sessionStorageManager.clearNotificationTokenId();
                            sessionStorageManager.clearPendingEmail();

                            self.showStatus('success', $t('✓ Approved!'));

                            if (config.onVerified) {
                                config.onVerified(response.authToken, response.userData);
                            }

                            setTimeout(function () {
                                self.showAccountDetailsModal({
                                    email: config.email,
                                    authToken: response.authToken,
                                    userData: response.userData,
                                    onAddressSelected: null
                                });
                            }, 1000);
                        } else if (!response.success && response.error) {
                            // Handle specific errors
                            // Don't stop polling for transient errors, only for permanent ones
                            if (response.error === 'MISSING_DATA' || response.error === 'UNAUTHORIZED') {
                                clearInterval(self.pushPollingTimer);
                                self.showStatus('error', response.message || $t('Authentication error. Please try SMS or Email.'));
                                sessionStorageManager.clearNotificationTokenId();
                            }
                            // For other errors, continue polling
                        }
                        // If not approved yet, continue polling (do nothing)
                });
            }, 2000); // Poll every 2 seconds
        },

        /**
         * Verify OTP
         */
        verifyOtp: function (config) {
            var self = this;

            // Combine inputs
            var otp = '';
            $('.simplyin-otp-digit').each(function () {
                otp += $(this).val();
            });
            otp = otp.trim();

            if (otp.length < 4) {
                this.showStatus('error', $t('Please enter complete 4-digit code'));
                return;
            }

            this.showStatus('loading', $t('Verifying...'));

            ajaxClient.postSilent('simplyin/api/verifyOtp', {
                email: config.email,
                code: otp
            }).done(function (response) {
                    if (response.success && response.authToken) {
                        this.showStatus('success', $t('✓ OTP verified successfully!'));

                        if (config.onVerified) {
                            config.onVerified(response.authToken, response.userData);
                        }

                        setTimeout(function () {
                            self.showAccountDetailsModal({
                                email: config.email,
                                authToken: response.authToken,
                                userData: response.userData,
                                onAddressSelected: null
                            });
                        }, 1000);
                    } else {
                        this.showStatus('error', response.message || $t('Invalid OTP'));
                        // Clear inputs on error
                        $('.simplyin-otp-digit').val('');
                        $('#simplyin-otp-1').focus();
                    }
                }.bind(this)).fail(function () {
                    this.showStatus('error', $t('Verification failed. Please try again.'));
                }.bind(this));
        },

        /**
         * Resend OTP
         */
        resendOtp: function (email, authStrategy) {
            var self = this;
            authStrategy = authStrategy || 'sms'; // Default to SMS if not specified

            var deliveryMethod = authStrategy === 'email' ? 'email' : 'phone';
            this.showStatus('loading', $t('Sending OTP to your ' + deliveryMethod + '...'));

            $('body').trigger('processStart');
            ajaxClient.postSilent('simplyin/api/resendOtp', {
                email: email,
                method: authStrategy
            }).done(function (response) {
                    $('body').trigger('processStop');
                    if (response.success) {

                        this.showStatus('success', $t('✓ OTP sent to your ' + deliveryMethod + '!'));
                        this.startResendTimer();

                        // Update the modal message based on delivery method
                        var messageText = '';
                        var maskedInfo = '';

                        if (authStrategy === 'email') {
                            messageText = $t('Enter the code sent to your email');
                            // Mask email
                            if (email) {
                                var emailParts = email.split('@');
                                if (emailParts.length === 2) {
                                    var localPart = emailParts[0];
                                    var domain = emailParts[1];
                                    var maskedLocal = localPart.substring(0, 2) + '***' + localPart.substring(localPart.length - 1);
                                    maskedInfo = maskedLocal + '@' + domain;
                                } else {
                                    maskedInfo = email;
                                }
                            }
                        } else {
                            messageText = $t('Enter the code sent to the number');
                            // Get masked phone from response
                            if (response.data && response.data.data) {
                                maskedInfo = response.data.data;
                                customerNumber = response.data.data;
                            }
                        }

                        // Update the modal message
                        $('#simplyin-otp-message').html(messageText + '<br><strong id="simplyin-masked-info">' + maskedInfo + '</strong>');

                    } else {
                        this.showStatus('error', response.message || $t('Failed to send OTP'));
                    }
                }.bind(this)).fail(function () {
                    $('body').trigger('processStop');
                    this.showStatus('error', $t('Failed to send OTP. Please try again.'));
                }.bind(this));
        },

        /**
         * Show account details modal with addresses
         */
        showAccountDetailsModal: function (config) {
            var self = this;
            var element = this.initModal();
            var userData = config.userData || {};
            var billingAddresses = userData.billingAddresses || [];
            var shippingAddresses = userData.shippingAddresses || [];

            // Store auth token and user data
            sessionStorageManager.setAuthToken(config.authToken);
            sessionStorageManager.setUserData(userData);

            // Logo URL
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');

            // Get parcel lockers from user data
            var parcelLockers = userData.parcelLockers || [];

            // Separate parcel lockers by service_type
            var parcelMachines = parcelLockers.filter(function(locker) {
                return locker.service_type === 'parcel_machine';
            });
            var pickupPoints = parcelLockers.filter(function(locker) {
                return locker.service_type !== 'parcel_machine';
            });

            // Get saved delivery type from session storage
            var savedDeliveryType = sessionStorageManager.getSelectedDeliveryType() || 'courier';

            // Get saved parcel locker to determine which tab should be active
            var savedLocker = sessionStorageManager.getSelectedParcelLocker();
            var savedLockerIsPickupPoint = savedLocker && savedLocker.service_type !== 'parcel_machine';

            // Check which delivery options are available based on admin configuration
            var isCourierAvailable = self.isCourierDeliveryConfigured();
            var isParcelLockerAvailable = self.isParcelLockerDeliveryConfigured(parcelLockers);

            // If saved delivery type is not available, switch to the available one
            if (savedDeliveryType === 'courier' && !isCourierAvailable && isParcelLockerAvailable) {
                savedDeliveryType = 'parcel_locker';
                sessionStorageManager.setSelectedDeliveryType(savedDeliveryType);
            } else if (savedDeliveryType === 'parcel_locker' && !isParcelLockerAvailable && isCourierAvailable) {
                savedDeliveryType = 'courier';
                sessionStorageManager.setSelectedDeliveryType(savedDeliveryType);
            }

            // Generate billing addresses HTML
            var billingAddressesHtml = '';
            if (billingAddresses.length > 0) {
                billingAddressesHtml = '<div class="simplyin-addresses">';
                billingAddresses.forEach(function (address, index) {
                    var fullAddress = (address.street || '') + (address.appartmentNumber ? ', ' + address.appartmentNumber : '');
                    var cityStateZip = (address.city || '');

                    billingAddressesHtml += `
                        <div class="simplyin-address-item" data-index="${index}" data-address-id="${address._id || ''}" data-type="billing">
                            <input type="radio" 
                                   id="billing-address-${index}" 
                                   name="simplyin-billing-address" 
                                   value="${index}" 
                                   ${index === 0 ? 'checked' : ''}>
                            <label for="billing-address-${index}">
                                <div class="address-icon">🏡</div>
                                <div class="address-content">
                                    <strong>${address.addressName || (address.name + ' ' + address.surname)}</strong>
                                    <span>${fullAddress} ${cityStateZip}</span>
                                </div>
                            </label>
                            <div class="address-actions">
                                <div class="action-menu" data-index="${index}" data-type="billing">
                                    <svg width="4" height="16" viewBox="0 0 4 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <circle cx="2" cy="2" r="2" fill="#1f1f1f"/>
                                        <circle cx="2" cy="8" r="2" fill="#1f1f1f"/>
                                        <circle cx="2" cy="14" r="2" fill="#1f1f1f"/>
                                    </svg>
                                </div>
                                <div class="dropdown-actions-menu" id="billing-menu-${index}">
                                    <ul>
                                        <li class="action-edit" data-address-id="${address._id || ''}" data-index="${index}" data-type="billing">
                                            <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="#3167b9f5" stroke-width="1.6"/>
                                            </svg>
                                            ${$t('Edit')}
                                        </li>
                                        <li class="action-delete" data-address-id="${address._id || ''}" data-index="${index}" data-type="billing">
                                            <svg width="14" height="16" viewBox="0 0 14 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M1 4H13M5.5 7V12M8.5 7V12M2 4L3 14C3 14.5304 3.21071 15.0391 3.58579 15.4142C3.96086 15.7893 4.46957 16 5 16H9C9.53043 16 10.0391 15.7893 10.4142 15.4142C10.7893 15.0391 11 14.5304 11 14L12 4M4.5 4V2C4.5 1.73478 4.60536 1.48043 4.79289 1.29289C4.98043 1.10536 5.23478 1 5.5 1H8.5C8.76522 1 9.01957 1.10536 9.20711 1.29289C9.39464 1.48043 9.5 1.73478 9.5 2V4" stroke="#3167b9f5" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            ${$t('Delete')}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    `;
                });
                billingAddressesHtml += '</div>';
            } else {
                billingAddressesHtml = '<p class="simplyin-message">' + $t('No saved addresses found.') + '</p>';
            }

            // Generate shipping addresses HTML
            var shippingAddressesHtml = '';
            if (shippingAddresses.length > 0) {
                shippingAddressesHtml = '<div class="simplyin-addresses" id="delivery-addresses-list">';
                shippingAddresses.forEach(function (address, index) {
                    var fullAddress = (address.street || '') + (address.appartmentNumber ? ', ' + address.appartmentNumber : '');
                    var cityStateZip = (address.city || '');
                    //var cityStateZip = (address.city || '') + (address.state ? ', ' + address.state : '') + ' ' + (address.postalCode || '');

                    shippingAddressesHtml += `
                        <div class="simplyin-address-item" data-index="${index}" data-address-id="${address._id || ''}" data-type="shipping">
                            <input type="radio" 
                                   id="shipping-address-${index}" 
                                   name="simplyin-shipping-address" 
                                   value="${index}" 
                                   ${index === 0 ? 'checked' : ''}>
                            <label for="shipping-address-${index}">
                                <div class="address-icon">🏡</div>
                                <div class="address-content">
                                    <strong>${address.addressName || (address.name + ' ' + address.surname)}</strong>
                                    <span>${fullAddress} ${cityStateZip}</span>
                                </div>
                            </label>
                            <div class="address-actions">
                                <div class="action-menu" data-index="${index}" data-type="shipping">
                                    <svg width="4" height="16" viewBox="0 0 4 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <circle cx="2" cy="2" r="2" fill="#1f1f1f"/>
                                        <circle cx="2" cy="8" r="2" fill="#1f1f1f"/>
                                        <circle cx="2" cy="14" r="2" fill="#1f1f1f"/>
                                    </svg>
                                </div>
                                <div class="dropdown-actions-menu" id="shipping-menu-${index}">
                                    <ul>
                                        <li class="action-edit" data-address-id="${address._id || ''}" data-index="${index}" data-type="shipping">
                                            <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="#3167b9f5" stroke-width="1.6"/>
                                            </svg>
                                            ${$t('Edit')}
                                        </li>
                                        <li class="action-delete" data-address-id="${address._id || ''}" data-index="${index}" data-type="shipping">
                                            <svg width="14" height="16" viewBox="0 0 14 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M1 4H13M5.5 7V12M8.5 7V12M2 4L3 14C3 14.5304 3.21071 15.0391 3.58579 15.4142C3.96086 15.7893 4.46957 16 5 16H9C9.53043 16 10.0391 15.7893 10.4142 15.4142C10.7893 15.0391 11 14.5304 11 14L12 4M4.5 4V2C4.5 1.73478 4.60536 1.48043 4.79289 1.29289C4.98043 1.10536 5.23478 1 5.5 1H8.5C8.76522 1 9.01957 1.10536 9.20711 1.29289C9.39464 1.48043 9.5 1.73478 9.5 2V4" stroke="#3167b9f5" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            ${$t('Delete')}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    `;
                });
                shippingAddressesHtml += '</div>';
            } else {
                shippingAddressesHtml = '<p class="simplyin-message" id="delivery-addresses-list">' + $t('No saved delivery addresses found.') + '</p>';
            }

            var html = `
                <div class="simplyin-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Choose your data')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-account-details">
                            <div class="simplyin-status" id="simplyin-details-status"></div>
                            
                            <!-- Billing Section -->
                            <div class="simplyin-billing-header">
                                <div class="simplyin-section-title">${$t('Billing')}</div>
                                <button type="button" class="simplyin-add-address-link" id="simplyin-add-billing-address">
                                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M7 1V13M1 7H13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                    </svg>
                                    ${$t('Add new address')}
                                </button>
                            </div>
                            ${billingAddressesHtml}
                            
                            <!-- Delivery Section Title -->
                            <div class="simplyin-section-title simplyin-delivery-section-title">${$t('Delivery')}</div>
                            
                            <!-- Delivery Type Selector -->
                            <div class="simplyin-delivery-type-selector">
                                ${isCourierAvailable ? `
                                <div class="simplyin-delivery-option ${savedDeliveryType === 'courier' ? 'selected' : ''}">
                                    <input type="radio" 
                                           id="delivery-type-courier" 
                                           name="simplyin-delivery-type" 
                                           value="courier"
                                           ${savedDeliveryType === 'courier' ? 'checked' : ''}>
                                    <label for="delivery-type-courier">
                                        <span class="delivery-option-title">${$t('Courier')}<span id="simplyin-courier-price" class="delivery-price"></span></span>
                                        <span class="delivery-option-subtitle">${$t('Delivery to your door')}</span>
                                    </label>
                                </div>
                                ` : ''}
                                ${isParcelLockerAvailable ? `
                                <div class="simplyin-delivery-option ${savedDeliveryType === 'parcel_locker' ? 'selected' : ''}">
                                    <input type="radio" 
                                           id="delivery-type-parcel" 
                                           name="simplyin-delivery-type" 
                                           value="parcel_locker"
                                           ${savedDeliveryType === 'parcel_locker' ? 'checked' : ''}>
                                    <label for="delivery-type-parcel">
                                        <span class="delivery-option-title">${$t('Delivery to a parcel locker')}<span id="simplyin-parcel-locker-price" class="delivery-price"></span></span>
                                        <span class="delivery-option-subtitle">${$t('or pickup point')}</span>
                                    </label>
                                </div>
                                ` : ''}
                            </div>
                            
                            <!-- Courier Delivery Section -->
                            <div id="courier-delivery-section" class="simplyin-delivery-section" style="display: ${savedDeliveryType === 'courier' ? 'block' : 'none'};">
                                <div class="simplyin-section-title simplyin-delivery-data-title">${$t('Delivery data')}</div>
                                
                                <div class="simplyin-same-address-checkbox">
                                    <input type="checkbox" id="same-as-billing" checked>
                                    <label for="same-as-billing">
                                        <span class="checkbox-custom"></span>
                                        <span class="checkbox-label">${$t('Billing data is the same as delivery data')}</span>
                                    </label>
                                </div>
                                
                                <!-- Delivery addresses list - Collapsible -->
                                <div id="delivery-address-section" class="simplyin-hidden">
                                    ${shippingAddressesHtml}
                                </div>
                                
                                <!-- Add new address link -->
                                <div class="simplyin-centered-action">
                                    <button type="button" class="simplyin-add-address-link" id="simplyin-add-shipping-address">
                                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M7 1V13M1 7H13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                        </svg>
                                        ${$t('Add new address')}
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Parcel Locker Section -->
                            <div id="parcel-locker-section" class="simplyin-delivery-section" style="display: ${savedDeliveryType === 'parcel_locker' ? 'block' : 'none'};">
                                <div class="simplyin-section-title simplyin-delivery-data-title">${$t('Choose a parcel locker or pickup point')}</div>
                                
                                <!-- Parcel Tabs -->
                                <div class="simplyin-parcel-tabs">
                                    <button type="button" class="simplyin-tab-btn ${savedLockerIsPickupPoint ? '' : 'active'}" data-tab="parcel-lockers">${$t('Parcel lockers')}</button>
                                    <button type="button" class="simplyin-tab-btn ${savedLockerIsPickupPoint ? 'active' : ''}" data-tab="pickup-points">${$t('Pickup points')}</button>
                                </div>
                                
                                <!-- Parcel Lockers Tab Content -->
                                <div id="parcel-lockers-tab" class="simplyin-tab-content ${savedLockerIsPickupPoint ? '' : 'active'}" style="display: ${savedLockerIsPickupPoint ? 'none' : 'block'};">
                                    <div class="simplyin-parcel-list" id="parcel-lockers-list">
                                        ${self.generateParcelLockersHtml(parcelMachines, 'parcel-locker')}
                                    </div>
                                </div>
                                
                                <!-- Pickup Points Tab Content -->
                                <div id="pickup-points-tab" class="simplyin-tab-content ${savedLockerIsPickupPoint ? 'active' : ''}" style="display: ${savedLockerIsPickupPoint ? 'block' : 'none'};">
                                    <div class="simplyin-parcel-list" id="pickup-points-list">
                                        ${self.generateParcelLockersHtml(pickupPoints, 'pickup-point')}
                                    </div>
                                </div>
                                
                                <!-- Add parcel locker link -->
                                <div class="simplyin-centered-action">
                                    <button type="button" class="simplyin-add-address-link" id="simplyin-add-parcel-locker">
                                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M7 1V13M1 7H13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                                        </svg>
                                        ${$t('Add')}
                                    </button>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                </div>
                    <div class="popup-buttons-footer">
                            <button type="button" 
                                    class="action primary" 
                                    id="simplyin-use-address">
                                <span>${$t('Select data')}</span>
                            </button>
                        </div>
            `;

            element.html(html);
            element.modal('openModal');

            // Update delivery costs with shipping method prices
            self.updateDeliveryCosts();

            // Subscribe to shipping rate changes to update delivery costs
            shippingService.getShippingRates().subscribe(function (rates) {
                if (rates && rates.length > 0) {
                    self.updateDeliveryCosts();
                }
            });

            // Initialize delivery type switching
            // Initialize delivery type switching (Requirements 4.1, 4.2, 4.3, 4.4)
            $('input[name="simplyin-delivery-type"]').on('change', function () {
                var deliveryType = $(this).val();

                // Requirement 4.4: Persist delivery type in session storage
                sessionStorageManager.setSelectedDeliveryType(deliveryType);

                // Update selected class on options
                $('.simplyin-delivery-option').removeClass('selected');
                $(this).closest('.simplyin-delivery-option').addClass('selected');

                if (deliveryType === 'courier') {
                    // Requirement 4.2: Show courier section and auto-select default courier method
                    $('#courier-delivery-section').slideDown();
                    $('#parcel-locker-section').slideUp();

                    // Auto-select default courier shipping method if configured
                    self.autoSelectDefaultCourierMethod();
                } else {
                    // Requirement 4.3: Show parcel locker selection tabs
                    $('#courier-delivery-section').slideUp();
                    $('#parcel-locker-section').slideDown();
                }
            });

            // Initialize parcel tabs
            $('.simplyin-tab-btn').on('click', function () {
                var tabId = $(this).data('tab');

                // Update active tab button
                $('.simplyin-tab-btn').removeClass('active');
                $(this).addClass('active');

                // Show/hide tab content
                $('.simplyin-tab-content').hide().removeClass('active');
                $('#' + tabId + '-tab').show().addClass('active');
            });

            // Bind parcel locker selection
            $(document).on('change', 'input[name="simplyin-parcel-locker"]', function () {
                var lockerData = $(this).data('locker');
                sessionStorageManager.setSelectedParcelLocker(lockerData);

                // Auto-select shipping method based on provider
                var providerName = lockerData.providerName || lockerData.provider || '';
                if (providerName) {
                    self.autoSelectShippingMethodByProvider(providerName.toLowerCase());
                }
            });

            // Bind radio change event to update shipping rates for billing
            $('input[name="simplyin-billing-address"]').on('change', function () {
                var selectedIndex = $(this).val();
                if (billingAddresses[selectedIndex]) {
                    self.updateShippingRates(billingAddresses[selectedIndex]);
                }
            });

            // Bind radio change event for shipping addresses
            $('input[name="simplyin-shipping-address"]').on('change', function () {
                var selectedIndex = $(this).val();
                if (shippingAddresses[selectedIndex]) {
                    self.updateShippingRates(shippingAddresses[selectedIndex]);
                }
            });

            // Trigger initial update if addresses exist
            if (billingAddresses.length > 0) {
                this.updateShippingRates(billingAddresses[0]);
            }

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                element.modal('closeModal');
            });

            // Handle checkbox toggle
            $('#same-as-billing').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#delivery-address-section').slideUp();
                } else {
                    $('#delivery-address-section').slideDown();
                }
            });

            // Bind three-dot menu toggle
            $('.action-menu').on('click', function (e) {
                e.stopPropagation();
                var index = $(this).data('index');
                var type = $(this).data('type');
                var menuId;

                if (type === 'billing') {
                    menuId = 'billing-menu-' + index;
                } else if (type === 'shipping') {
                    menuId = 'shipping-menu-' + index;
                } else {
                    // For parcel-locker and pickup-point types, use the type directly
                    menuId = type + '-menu-' + index;
                }

                var menu = $('#' + menuId);

                // Close all other menus
                $('.dropdown-actions-menu').removeClass('show');

                // Toggle current menu
                menu.toggleClass('show');
            });

            // Close menu when clicking outside
            $(document).on('click', function (e) {
                if (!$(e.target).closest('.address-actions').length && !$(e.target).closest('.parcel-actions').length) {
                    $('.dropdown-actions-menu').removeClass('show');
                }
            });

            // Bind use address button
            $('#simplyin-use-address').on('click', function () {
                var deliveryType = $('input[name="simplyin-delivery-type"]:checked').val();
                var sameAsBilling = $('#same-as-billing').is(':checked');
                var selectedBillingIndex = $('input[name="simplyin-billing-address"]:checked').val();
                var selectedShippingIndex = $('input[name="simplyin-shipping-address"]:checked').val();

                if (selectedBillingIndex === undefined || !billingAddresses[selectedBillingIndex]) {
                    self.showStatus('error', $t('Please select a billing address'), 'simplyin-details-status');
                    $('#simplyin-details-status').css('display', 'block');
                    return;
                }

                var billingAddress = billingAddresses[selectedBillingIndex];

                // Store the COMPLETE billing address object in session storage for order creation
                // This ensures all fields (including _id, icon, addressName, taxId, etc.) are preserved
                if (billingAddress) {
                    sessionStorageManager.setItem('selected_billing_address', JSON.stringify(billingAddress));

                    // Also store just the ID for backward compatibility
                    if (billingAddress._id) {
                        sessionStorageManager.setItem('selected_billing_address_id', billingAddress._id);
                    }
                }

                if (deliveryType === 'parcel_locker') {
                    // Handle parcel locker selection
                    var selectedParcelLocker = $('input[name="simplyin-parcel-locker"]:checked');
                    if (selectedParcelLocker.length === 0) {
                        self.showStatus('error', $t('Please select a parcel locker or pickup point'), 'simplyin-details-status');
                        $('#simplyin-details-status').css('display', 'block');
                        return;
                    }

                    var lockerData = selectedParcelLocker.data('locker');
                    self.useSelectedParcelLocker(lockerData, billingAddress, config);
                } else {
                    // Handle courier delivery
                    var shippingAddress = sameAsBilling ? billingAddress :
                        (selectedShippingIndex !== undefined && shippingAddresses[selectedShippingIndex] ?
                            shippingAddresses[selectedShippingIndex] : billingAddress);

                    // Store the COMPLETE shipping address object in session storage for order creation
                    // This ensures all fields (including _id, icon, addressName, etc.) are preserved
                    if (shippingAddress) {
                        sessionStorageManager.setItem('selected_shipping_address', JSON.stringify(shippingAddress));

                        // Also store just the ID for backward compatibility
                        if (shippingAddress._id) {
                            sessionStorageManager.setItem('selected_shipping_address_id', shippingAddress._id);
                        }
                    }

                    self.useSelectedAddress(shippingAddress, config);
                }
            });

            // Bind add billing address button
            $('#simplyin-add-billing-address').on('click', function () {
                self.showAddAddressForm(config, 'billing');
            });

            // Bind add shipping address button
            $('#simplyin-add-shipping-address').on('click', function () {
                self.showAddAddressForm(config, 'shipping');
            });

            // Bind add parcel locker button
            $('#simplyin-add-parcel-locker').on('click', function () {
                self.showAddParcelLockerModal(config);
            });

            // Bind edit buttons
            $('.action-edit').on('click', function () {
                var index = $(this).data('index');
                var addressId = $(this).data('address-id');
                var type = $(this).data('type');
                $('.dropdown-actions-menu').removeClass('show');

                var addressList = type === 'billing' ? billingAddresses : shippingAddresses;
                self.showEditAddressForm(addressList[index], addressId, config, type);
            });

            // Bind delete buttons
            $('.action-delete').on('click', function () {
                var addressId = $(this).data('address-id');
                var type = $(this).data('type');
                $('.dropdown-actions-menu').removeClass('show');
                if (confirm($t('Are you sure you want to delete this address?'))) {
                    self.deleteAddress(addressId, config, type);
                }
            });

            // Bind delete parcel locker buttons
            $(document).on('click', '.action-delete-parcel', function () {
                var lockerId = $(this).data('id');
                $('.dropdown-actions-menu').removeClass('show');
                if (confirm($t('Are you sure you want to delete this parcel locker?'))) {
                    self.deleteParcelLocker(lockerId, config);
                }
            });
        },


        /**
         * Initialize shipping methods display
         */
        initShippingMethods: function (addresses) {
            var self = this;

            // Subscribe to shipping rates updates
            shippingService.getShippingRates().subscribe(function (rates) {
                self.renderShippingRates(rates);
            });
        },

        /**
         * Normalize provider name to match mapping keys
         * Handles various formats: "ORLEN Paczka", "orlen_paczka", "Orlen", etc.
         * @param {string} providerName - The provider name from API
         * @returns {string} - Normalized provider key (e.g., 'orlen', 'dpd', 'inpost')
         */
        normalizeProviderName: function (providerName) {
            if (!providerName) {
                return '';
            }

            // Convert to lowercase and remove extra spaces
            var normalized = providerName.toLowerCase().trim();

            // Provider name mappings - API names to config keys
            var providerAliases = {
                // ORLEN variations
                'orlen': 'orlen',
                'orlen paczka': 'orlen',
                'orlen_paczka': 'orlen',
                'orlenpaczka': 'orlen',
                'orlen punkty': 'orlen',
                'orlen punkty odbioru': 'orlen',
                // InPost variations
                'inpost': 'inpost',
                'inpost paczkomat': 'inpost',
                'inpost_paczkomat': 'inpost',
                'paczkomat': 'inpost',
                // DPD variations
                'dpd': 'dpd',
                'dpd pickup': 'dpd',
                'dpd_pickup': 'dpd',
                'dpd polska': 'dpd',
                // DHL variations
                'dhl': 'dhl',
                'dhl box': 'dhl',
                'dhl pop': 'dhl',
                'dhl box i pop': 'dhl',
                'dhl parcelshop': 'dhl',
                // UPS variations
                'ups': 'ups',
                'ups pickup': 'ups',
                'ups access point': 'ups',
                'ups_access_point': 'ups'
            };

            // Check for exact match first
            if (providerAliases[normalized]) {
                return providerAliases[normalized];
            }

            // Check if normalized name starts with or contains a known provider
            var knownProviders = ['orlen', 'inpost', 'dpd', 'dhl', 'ups'];
            for (var i = 0; i < knownProviders.length; i++) {
                if (normalized.indexOf(knownProviders[i]) !== -1) {
                    return knownProviders[i];
                }
            }

            // Return the first word as fallback
            return normalized.split(/[\s_-]/)[0];
        },

        /**
         * Get shipping price for a provider from Magento shipping rates
         * @param {string} providerName - The provider name (e.g., 'inpost', 'dpd', 'ORLEN Paczka')
         * @returns {number|null} - The shipping price or null if not found
         */
        getShippingPriceForProvider: function (providerName) {
            var self = this;
            var shippingMethodMapping = {};
            var rates = [];

            // Get shipping method mapping from checkout config
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            // Get current shipping rates
            try {
                rates = require('Magento_Checkout/js/model/shipping-service').getShippingRates()() || [];
            } catch (e) {
                return null;
            }

            // Normalize the provider name to match mapping keys
            var normalizedProvider = self.normalizeProviderName(providerName);

            // Get the mapped method for this provider
            var mappedMethod = shippingMethodMapping[normalizedProvider];
            if (!mappedMethod) {
                // Try to find a rate by provider name in carrier code (fallback when no mapping configured)
                var fallbackRate = rates.find(function (r) {
                    var carrierLower = r.carrier_code.toLowerCase();
                    return carrierLower.indexOf(normalizedProvider) !== -1 ||
                        normalizedProvider.indexOf(carrierLower) !== -1;
                });

                if (fallbackRate && fallbackRate.price_incl_tax !== undefined) {
                    return parseFloat(fallbackRate.price_incl_tax);
                }

                return null;
            }

            // Find the matching rate - try multiple matching strategies
            var matchingRate = null;

            // Strategy 1: Exact match
            matchingRate = rates.find(function (r) {
                var rateCode = r.carrier_code + '_' + r.method_code;
                return rateCode === mappedMethod;
            });

            // Strategy 2: Carrier code match (for cases where method code varies)
            if (!matchingRate) {
                var mappedCarrier = mappedMethod.split('_')[0];
                matchingRate = rates.find(function (r) {
                    return r.carrier_code === mappedCarrier ||
                        r.carrier_code.toLowerCase() === mappedCarrier.toLowerCase();
                });
                if (matchingRate) {
                }
            }

            // Strategy 3: Substring match
            if (!matchingRate) {
                matchingRate = rates.find(function (r) {
                    var rateCode = r.carrier_code + '_' + r.method_code;
                    return rateCode.indexOf(mappedMethod) !== -1 ||
                        mappedMethod.indexOf(rateCode) !== -1 ||
                        rateCode.toLowerCase().indexOf(mappedMethod.toLowerCase()) !== -1 ||
                        mappedMethod.toLowerCase().indexOf(rateCode.toLowerCase()) !== -1;
                });
            }

            // Strategy 4: Provider name in carrier code (fallback for ORLEN, etc.)
            if (!matchingRate && normalizedProvider) {
                matchingRate = rates.find(function (r) {
                    var carrierLower = r.carrier_code.toLowerCase();
                    return carrierLower.indexOf(normalizedProvider) !== -1 ||
                        normalizedProvider.indexOf(carrierLower) !== -1;
                });
                if (matchingRate) {
                }
            }

            if (matchingRate && matchingRate.price_incl_tax !== undefined) {
                return parseFloat(matchingRate.price_incl_tax);
            }

            return null;
        },

        /**
         * Check if courier delivery is configured in admin settings
         * @returns {boolean} - True if default_courier is configured (not "None" or empty)
         */
        isCourierDeliveryConfigured: function () {
            var shippingMethodMapping = {};
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            var defaultCourier = shippingMethodMapping['default_courier'];
            return !!(defaultCourier && defaultCourier !== 'none' && defaultCourier !== '');
        },

        /**
         * Check if parcel locker delivery is configured in admin settings
         * At least one parcel locker provider must be configured and user must have lockers
         * @param {Array} parcelLockers - Array of user's parcel lockers
         * @returns {boolean} - True if at least one parcel locker provider is configured
         */
        isParcelLockerDeliveryConfigured: function (parcelLockers) {
            var self = this;

            if (!parcelLockers || parcelLockers.length === 0) {
                // Even if no lockers saved, check if any provider is configured
                // User can still add new lockers if providers are configured
                return self.hasAnyParcelLockerProviderConfigured();
            }

            // Check if any of the user's parcel lockers have a configured provider
            var filteredLockers = self.filterLockersByConfiguredProviders(parcelLockers);
            return filteredLockers.length > 0 || self.hasAnyParcelLockerProviderConfigured();
        },

        /**
         * Check if any parcel locker provider is configured in admin settings
         * @returns {boolean} - True if at least one provider (inpost, dpd, dhl, orlen, ups) is configured
         */
        hasAnyParcelLockerProviderConfigured: function () {
            var shippingMethodMapping = {};
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            // Check if any parcel locker provider is configured
            var parcelLockerProviders = ['inpost', 'dpd', 'dhl', 'orlen', 'ups'];
            return parcelLockerProviders.some(function (provider) {
                var mappedMethod = shippingMethodMapping[provider];
                return mappedMethod && mappedMethod !== 'none' && mappedMethod !== '';
            });
        },

        /**
         * Check if a provider has a shipping method configured
         * @param {string} providerName - The provider name (e.g., 'inpost', 'dpd', 'ORLEN Paczka')
         * @returns {boolean} - True if provider has a configured shipping method
         */
        isProviderConfigured: function (providerName) {
            var self = this;
            var shippingMethodMapping = {};

            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            // Normalize the provider name to match mapping keys
            var normalizedProvider = self.normalizeProviderName(providerName);

            // Check if this provider has an explicit mapping in admin config
            // If the provider key exists in the mapping, respect the admin's choice
            // Only return true if a valid (non-empty, non-none) method is configured
            var mappedMethod = shippingMethodMapping[normalizedProvider];

            // If explicit mapping exists and is valid, provider is configured
            if (mappedMethod && mappedMethod !== 'none' && mappedMethod !== '') {
                return true;
            }

            // If the provider is a known provider (inpost, dpd, dhl, orlen, ups),
            // and it's not in the mapping or set to none/empty, it's NOT configured
            var knownProviders = ['inpost', 'dpd', 'dhl', 'orlen', 'ups'];
            if (knownProviders.indexOf(normalizedProvider) !== -1) {
                return false;
            }

            // For unknown providers, use fallback: check if there's a shipping rate with carrier code matching the provider
            var rates = [];
            try {
                rates = require('Magento_Checkout/js/model/shipping-service').getShippingRates()() || [];
            } catch (e) {
                return false;
            }

            // Check if any rate's carrier code contains the provider name
            var hasMatchingRate = rates.some(function (r) {
                var carrierLower = r.carrier_code.toLowerCase();
                return carrierLower.indexOf(normalizedProvider) !== -1 ||
                    normalizedProvider.indexOf(carrierLower) !== -1;
            });

            return hasMatchingRate;
        },

        /**
         * Filter parcel lockers to only include providers with configured shipping methods
         * @param {Array} lockers - Array of parcel locker objects
         * @returns {Array} - Filtered array of parcel lockers
         */
        filterLockersByConfiguredProviders: function (lockers) {
            var self = this;

            if (!lockers || lockers.length === 0) {
                return [];
            }

            return lockers.filter(function (locker) {
                var providerName = locker.providerName || locker.provider || '';
                if (!providerName) {
                    return true; // Keep lockers without provider info
                }
                return self.isProviderConfigured(providerName);
            });
        },

        /**
         * Get sort order for a provider from admin config
         * @param {string} providerName - Provider name (e.g., 'InPost', 'DPD', 'DHL', 'Orlen', 'UPS')
         * @returns {number} - Sort order (lower = higher priority)
         */
        getProviderSortOrder: function (providerName) {
            if (!providerName) {
                return 999;
            }

            var providerSortOrder = {};
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.providerSortOrder) {
                providerSortOrder = window.checkoutConfig.payment.simplyin_payment.providerSortOrder;
            }

            // Normalize provider name to match config keys
            var normalizedName = providerName.toLowerCase();

            // Map provider names to config keys
            if (normalizedName.indexOf('inpost') !== -1) {
                return providerSortOrder['inpost'] || 999;
            } else if (normalizedName.indexOf('dpd') !== -1) {
                return providerSortOrder['dpd'] || 999;
            } else if (normalizedName.indexOf('dhl') !== -1) {
                return providerSortOrder['dhl'] || 999;
            } else if (normalizedName.indexOf('orlen') !== -1) {
                return providerSortOrder['orlen'] || 999;
            } else if (normalizedName.indexOf('ups') !== -1) {
                return providerSortOrder['ups'] || 999;
            }

            return 999;
        },

        /**
         * Sort parcel lockers by provider sort order from admin config
         * @param {Array} lockers - Array of parcel locker objects
         * @returns {Array} - Sorted array of parcel lockers
         */
        sortLockersByProviderOrder: function (lockers) {
            var self = this;

            if (!lockers || lockers.length === 0) {
                return [];
            }

            return lockers.slice().sort(function (a, b) {
                var providerA = a.providerName || a.provider || '';
                var providerB = b.providerName || b.provider || '';

                var sortOrderA = self.getProviderSortOrder(providerA);
                var sortOrderB = self.getProviderSortOrder(providerB);

                return sortOrderA - sortOrderB;
            });
        },

        /**
         * Generate HTML for parcel lockers list
         * Only shows providers with configured shipping methods and includes prices
         */
        generateParcelLockersHtml: function (lockers, type) {
            var self = this;
            var $t = require('mage/translate');

            // Filter lockers to only show providers with configured shipping methods
            var filteredLockers = self.filterLockersByConfiguredProviders(lockers);

            // Sort lockers by provider sort order from admin config
            filteredLockers = self.sortLockersByProviderOrder(filteredLockers);

            if (!filteredLockers || filteredLockers.length === 0) {
                return '<p class="simplyin-message">' + $t('No parcel lockers found.') + '</p>';
            }

            // Get currency symbol
            var currencySymbol = 'zł';
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.currencySymbol) {
                currencySymbol = window.checkoutConfig.payment.simplyin_payment.currencySymbol;
            }

            // Get previously selected parcel locker from session storage
            var savedLocker = sessionStorageManager.getSelectedParcelLocker();
            var savedLockerId = savedLocker ? (savedLocker._id || savedLocker.lockerId || '') : '';

            var html = '';
            filteredLockers.forEach(function (locker, index) {
                var lockerName = locker.addressName || locker.lockerId || locker.name || '';
                var lockerAddress = locker.address || (locker.street + ', ' + locker.city) || '';
                var logoUrl = locker.logoUrl || '';
                // Ensure full URL for logo
                if (logoUrl && logoUrl.indexOf('http') !== 0) {
                    logoUrl = 'https://assets.simply.in/' + logoUrl.replace(/^\//, '');
                }
                var icon = locker.icon || '📦';
                var lockerJson = JSON.stringify(locker).replace(/'/g, "&#39;").replace(/"/g, "&quot;");
                var menuId = type + '-menu-' + index;

                // Get shipping price for this provider
                var providerName = locker.providerName || locker.provider || '';
                var price = self.getShippingPriceForProvider(providerName);
                var priceHtml = '';
                if (price !== null) {
                    var formattedPrice = price.toFixed(2).replace('.', ',');
                    priceHtml = '<span class="parcel-price">' + formattedPrice + ' ' + currencySymbol + '</span>';
                }

                // Check if this locker matches the saved selection
                var currentLockerId = locker._id || locker.lockerId || '';
                var isChecked = savedLockerId && currentLockerId && savedLockerId === currentLockerId;
                var checkedAttr = isChecked ? 'checked' : '';

                html += `
                    <div class="simplyin-parcel-item" data-id="${locker._id || ''}" data-provider="${locker.providerName || ''}">
                        <input type="radio" 
                               id="${type}-${index}" 
                               name="simplyin-parcel-locker" 
                               value="${index}"
                               data-id="${locker._id || ''}"
                               data-locker='${JSON.stringify(locker).replace(/'/g, "&#39;")}'
                               ${checkedAttr}>
                        <label for="${type}-${index}">
                            <div class="parcel-logo">
                                ${logoUrl ? '<img src="' + logoUrl + '" alt="' + (locker.providerName || '') + '">' : '<span class="parcel-icon">' + icon + '</span>'}
                            </div>
                            <div class="parcel-content">
                                <strong>${lockerName}</strong>
                                <span class="parcel-address">${lockerAddress}</span>
                                ${priceHtml}
                            </div>
                            <div class="parcel-type-icon">${icon}</div>
                        </label>
                        <div class="parcel-actions">
                            <div class="action-menu parcel-action-menu" data-index="${index}" data-type="${type}" data-id="${locker._id || ''}">
                                <svg width="4" height="16" viewBox="0 0 4 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <circle cx="2" cy="2" r="2" fill="#1f1f1f"/>
                                    <circle cx="2" cy="8" r="2" fill="#1f1f1f"/>
                                    <circle cx="2" cy="14" r="2" fill="#1f1f1f"/>
                                </svg>
                            </div>
                            <div class="dropdown-actions-menu" id="${menuId}">
                                <ul>
                                    <li class="action-delete-parcel" data-id="${locker._id || ''}" data-index="${index}">
                                        <svg width="14" height="16" viewBox="0 0 14 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M1 4H13M5.5 7V12M8.5 7V12M2 4L3 14C3 14.5304 3.21071 15.0391 3.58579 15.4142C3.96086 15.7893 4.46957 16 5 16H9C9.53043 16 10.0391 15.7893 10.4142 15.4142C10.7893 15.0391 11 14.5304 11 14L12 4M4.5 4V2C4.5 1.73478 4.60536 1.48043 4.79289 1.29289C4.98043 1.10536 5.23478 1 5.5 1H8.5C8.76522 1 9.01957 1.10536 9.20711 1.29289C9.39464 1.48043 9.5 1.73478 9.5 2V4" stroke="#3167b9f5" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        Delete
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                `;
            });

            return html;
        },

        /**
         * Update shipping rates based on selected address
         */
        updateShippingRates: function (address) {
            var container = $('#simplyin-shipping-methods-container');
            var list = $('#simplyin-shipping-methods-list');
            var self = this;

            container.show();
            list.html('<div class="simplyin-loading">' + $t('Loading shipping options...') + '</div>');

            // Map SimplyIn address to Magento address structure
            var street = [address.street || ''];
            if (address.appartmentNumber) {
                street.push(address.appartmentNumber);
            }

            var magentoAddress = {
                firstname: address.name || '',
                lastname: address.surname || '',
                street: street,
                city: address.city || '',
                postcode: address.postalCode || '',
                countryId: address.country || 'US', // Default to US if missing
                telephone: address.phoneNumber || '0000000000',
                regionId: 0, // Simplified, finding region ID requires more logic or lookup
                region: address.state || address.county || '',
                regionCode: address.state || address.county || '', // Assuming state is code or name
                saveInAddressBook: 0,
                // Add required methods for the address object to play nice with Magento
                getType: function () { return 'new-customer-address'; },
                getKey: function () { return new Date().getTime(); },
                getCacheKey: function () { return this.getKey(); },
                isEditable: function () { return true; },
                canUseForBilling: function () { return true; },
                isDefaultShipping: function () { return false; },
                isDefaultBilling: function () { return false; }
            };

            // Ensure quote exists
            if (!quote) {
                console.error('SimplyIn: Quote object is undefined');
                return;
            }

            // Set the address on the quote
            // This triggers the shipping rate service
            selectShippingAddress(magentoAddress);

            // Force rate reload just in case
            var addressKey = magentoAddress.countryId + magentoAddress.postcode + magentoAddress.region;
            rateRegistry.set(addressKey, null);

            // Note: selectShippingAddress logic usually triggers getRates. 
            // If it doesn't, we might need to manually trigger the processor.
            // But typically updating quote.shippingAddress is enough.
        },

        /**
         * Render shipping rates in the modal
         */
        renderShippingRates: function (rates) {
            var list = $('#simplyin-shipping-methods-list');
            var self = this;

            if (!rates || rates.length === 0) {
                list.html('<div class="message error">' + $t('No shipping methods available for this address.') + '</div>');
                return;
            }

            var html = '';
            var currentMethod = quote.shippingMethod();
            var selectedMethodCode = currentMethod ? currentMethod.method_code + '_' + currentMethod.carrier_code : '';

            rates.forEach(function (rate) {
                var methodCode = rate.method_code + '_' + rate.carrier_code;
                var isSelected = selectedMethodCode === methodCode;
                var price = window.checkoutConfig.priceFormat ?
                    rate.price_excl_tax : rate.price_excl_tax; // Simplified formatting

                // Format price if possible, or just raw
                var formattedPrice = rate.amount + ' ' + quote.getPriceFormat().pattern.replace('%s', '');

                html += `
                    <div class="simplyin-shipping-method-item simplyin-address-item">
                        <input type="radio" 
                               name="simplyin_shipping_method" 
                               id="s_method_${methodCode}" 
                               value="${methodCode}" 
                               data-carrier="${rate.carrier_code}"
                               data-method="${rate.method_code}"
                               ${isSelected ? 'checked' : ''} />
                        <label for="s_method_${methodCode}">
                            <span class="method-title">${rate.carrier_title} - ${rate.method_title}</span>
                            <span class="method-price">${formattedPrice}</span>
                        </label>
                    </div>
                `;
            });

            list.html(html);

            // Bind change event
            $('input[name="simplyin_shipping_method"]').on('change', function () {
                var carrier = $(this).data('carrier');
                var method = $(this).data('method');
                self.selectShippingMethod(carrier, method);
            });
        },

        /**
         * Select shipping method
         */
        selectShippingMethod: function (carrier, method) {
            var rates = shippingService.getShippingRates()();
            var rate = rates.find(function (r) {
                return r.carrier_code == carrier && r.method_code == method;
            });

            if (rate) {
                selectShippingMethodAction(rate);
            }
        },

        /**
         * Use selected address and fill checkout form
         */
        useSelectedAddress: function (address, config) {
            var self = this;

            this.showStatus('loading', $t('Loading address...'), 'simplyin-details-status');
            $('#simplyin-details-status').css('display', 'block');

            // Store delivery type as courier
            sessionStorageManager.setSelectedDeliveryType('courier');
            sessionStorageManager.clearSelectedParcelLocker();

            // Auto-select default courier shipping method if configured
            self.autoSelectDefaultCourierMethod();

            // Get phone number from user data if not in address
            var userData = config.userData || sessionStorageManager.getUserData() || {};
            if (!address.phoneNumber && userData.phoneNumber) {
                address.phoneNumber = userData.phoneNumber;
            }

            // Close modal
            setTimeout(function () {
                modalElement.modal('closeModal');

                // Fill shipping address in Magento checkout (final commit)
                self.fillShippingAddress(address, false);

                // Trigger callback
                if (config.onAddressSelected) {
                    config.onAddressSelected(config.authToken, config.userData, address);
                }
            }, 500);
        },

        /**
         * Auto-select default courier shipping method from admin configuration
         */
        autoSelectDefaultCourierMethod: function () {
            var self = this;

            // Get shipping method mapping from checkout config
            var shippingMethodMapping = {};
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            var defaultCourier = shippingMethodMapping['default_courier'];

            if (!defaultCourier) {
                return;
            }

            // Parse the method code
            var methodParts = defaultCourier.split('_');
            var carrierCode = methodParts[0];
            var methodCode = methodParts.slice(1).join('_');

            // Wait for shipping rates and select the method
            self.waitAndSelectShippingMethod(carrierCode, methodCode, defaultCourier);
        },

        /**
         * Fill shipping address in Magento checkout form
         */
        fillShippingAddress: function (address, isPreview) {

            // If it's just a preview for rates, we might not want to visibly fill the form if possible,
            // but for simplicity and reliability with Magento's knockout bindings, interacting with the form
            // is often the most robust way to trigger all necessary observers.

            // Wait for shipping form to be available
            var checkInterval = setInterval(function () {
                var shippingForm = $('form[id="co-shipping-form"]');

                if (shippingForm.length > 0) {
                    clearInterval(checkInterval);

                    // Fill address fields
                    $('input[name="firstname"]').val(address.name || '').trigger('change');
                    $('input[name="lastname"]').val(address.surname || '').trigger('change');
                    $('input[name="street[0]"]').val(address.street || '').trigger('change');
                    $('input[name="street[1]"]').val(address.appartmentNumber || '').trigger('change');
                    $('input[name="city"]').val(address.city || '').trigger('change');
                    $('input[name="postcode"]').val(address.postalCode || '').trigger('change');

                    // Fill phone number - ensure it's populated on first click
                    var phoneNumber = address.phoneNumber || '';
                    if (phoneNumber) {
                        $('input[name="telephone"]').val(phoneNumber).trigger('change');
                    }

                    // Set country
                    if (address.country) {
                        $('select[name="country_id"]').val(address.country).trigger('change');
                    }

                    // Set region/state if available (prefer state, fallback to county)
                    setTimeout(function () {
                        var regionValue = address.state || address.county || '';
                        if (regionValue) {
                            var regionSelect = $('select[name="region_id"]');
                            var regionInput = $('input[name="region"]');

                            if (regionSelect.length > 0) {
                                // Try to find matching region - use contains for better matching
                                var matchingOption = regionSelect.find('option').filter(function () {
                                    var optionText = $(this).text().toLowerCase();
                                    var stateText = regionValue.toLowerCase();

                                    // Try exact match first
                                    if (optionText === stateText) {
                                        return true;
                                    }

                                    // Try contains match (e.g., "podlaskie" in "Podlaskie Voivodeship")
                                    if (optionText.indexOf(stateText) !== -1 || stateText.indexOf(optionText) !== -1) {
                                        return true;
                                    }

                                    return false;
                                });

                                if (matchingOption.length > 0) {
                                    regionSelect.val(matchingOption.val()).trigger('change');
                                }
                            } else if (regionInput.length > 0) {
                                regionInput.val(regionValue).trigger('change');
                            }
                        }
                    }, 1000);

                    // Trigger event for other components
                    $(document).trigger('simplyin:addressFilled', [address]);
                }
            }, 500);

            // Stop checking after 10 seconds
            setTimeout(function () {
                clearInterval(checkInterval);
            }, 10000);
        },

        /**
         * Show status message
         */
        showStatus: function (type, message, elementId) {
            elementId = elementId || 'simplyin-otp-status';
            var statusElement = $('#' + elementId);
            var className = 'simplyin-status-' + type;

            statusElement.removeClass('simplyin-status-success simplyin-status-error simplyin-status-loading');
            statusElement.addClass(className);

            if (type === 'loading') {
                message += ' <span class="simplyin-loader"></span>';
            }

            statusElement.html(message);
        },

        /**
         * Show edit address form
         */
        showEditAddressForm: function (address, addressId, config, addressType) {
            var self = this;
            var element = this.initModal();
            addressType = addressType || 'billing';

            // Logo URL
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');
            var title = addressType === 'billing' ? $t('Billing details') : $t('Delivery details');

            var html = `
                <div class="simplyin-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${title}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-edit-address-form">
                            <div class="simplyin-status" id="simplyin-edit-status"></div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <input type="text" id="edit-firstname" value="${address.name || ''}" placeholder="${$t('First name')}" required />
                                </div>
                                <div class="form-group">
                                    <input type="text" id="edit-lastname" value="${address.surname || ''}" placeholder="${$t('Last name')}" required />
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="edit-street" value="${address.street || ''}" placeholder="${$t('Street and house number')}" required />
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="edit-apartment" value="${address.appartmentNumber || ''}" placeholder="${$t('Apartment number (optional)')}" />
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <input type="text" id="edit-postcode" value="${address.postalCode || ''}" placeholder="${$t('Postal code')}" required />
                                </div>
                                <div class="form-group">
                                    <input type="text" id="edit-city" value="${address.city || ''}" placeholder="${$t('City')}" required />
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <select id="edit-country" required>
                                    <option value="PL" ${address.country === 'PL' ? 'selected' : ''}>Poland</option>
                                    <option value="US" ${address.country === 'US' ? 'selected' : ''}>United States</option>
                                    <option value="GB" ${address.country === 'GB' ? 'selected' : ''}>United Kingdom</option>
                                    <option value="DE" ${address.country === 'DE' ? 'selected' : ''}>Germany</option>
                                    <option value="FR" ${address.country === 'FR' ? 'selected' : ''}>France</option>
                                    <option value="IT" ${address.country === 'IT' ? 'selected' : ''}>Italy</option>
                                    <option value="ES" ${address.country === 'ES' ? 'selected' : ''}>Spain</option>
                                </select>
                            </div>
                            
                            <div class="form-section-title">${$t('Company details (optional)')}</div>
                            
                            <div class="form-group">
                                <input type="text" id="edit-tax-id" value="${address.taxId || ''}" placeholder="${$t('Tax ID (optional)')}" />
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="edit-company-name" value="${address.companyName || ''}" placeholder="${$t('Company name (optional)')}" />
                            </div>
                            
                            <div class="form-section-title">${$t('Address name')}</div>
                            <div class="form-section-description">
                                ${$t('A personalised name will help you find or associate the address on your list more quickly.')}
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="edit-address-name" value="${address.addressName || ''}" placeholder="${$t('Address name')}" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="popup-buttons-footer">
                            <button type="button" class="action primary" id="save-address">
                                <span>${$t('Save')}</span>
                            </button>
                            <button type="button" class="action secondary" id="cancel-edit">
                                <span>${$t('Cancel')}</span>
                            </button>
                        </div>
            `;

            element.html(html);

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                element.modal('closeModal');
            });

            $('#save-address').on('click', function () {
                var updatedAddress = {
                    name: $('#edit-firstname').val().trim(),
                    surname: $('#edit-lastname').val().trim(),
                    street: $('#edit-street').val().trim(),
                    appartmentNumber: $('#edit-apartment').val().trim(),
                    city: $('#edit-city').val().trim(),
                    postalCode: $('#edit-postcode').val().trim(),
                    country: $('#edit-country').val(),
                    taxId: $('#edit-tax-id').val().trim(),
                    companyName: $('#edit-company-name').val().trim(),
                    addressName: $('#edit-address-name').val().trim()
                };

                // Validate required fields
                if (!updatedAddress.name || !updatedAddress.surname || !updatedAddress.street ||
                    !updatedAddress.city || !updatedAddress.postalCode || !updatedAddress.country) {
                    self.showStatus('error', $t('Please fill all required fields'), 'simplyin-edit-status');
                    return;
                }

                self.saveAddress(addressId, updatedAddress, 'update', config, addressType);
            });

            $('#cancel-edit').on('click', function () {
                self.showAccountDetailsModal(config);
            });
        },

        /**
         * Show add address form
         */
        showAddAddressForm: function (config, addressType) {
            var self = this;
            var element = this.initModal();
            addressType = addressType || 'billing'; // Default to billing

            // Logo URL
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');
            var title = addressType === 'billing' ? $t('Billing details') : $t('Delivery details');

            var html = `
                <div class="simplyin-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${title}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-add-address-form">
                            <div class="simplyin-status" id="simplyin-add-status"></div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <input type="text" id="add-firstname" placeholder="${$t('First name')}" required />
                                </div>
                                <div class="form-group">
                                    <input type="text" id="add-lastname" placeholder="${$t('Last name')}" required />
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="add-street" placeholder="${$t('Street and house number')}" required />
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="add-apartment" placeholder="${$t('Apartment number (optional)')}" />
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <input type="text" id="add-postcode" placeholder="${$t('Postal code')}" required />
                                </div>
                                <div class="form-group">
                                    <input type="text" id="add-city" placeholder="${$t('City')}" required />
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <select id="add-country" required>
                                    <option value="PL">Poland</option>
                                    <option value="US">United States</option>
                                    <option value="GB">United Kingdom</option>
                                    <option value="DE">Germany</option>
                                    <option value="FR">France</option>
                                    <option value="IT">Italy</option>
                                    <option value="ES">Spain</option>
                                </select>
                            </div>
                            
                            <div class="form-section-title">${$t('Company details (optional)')}</div>
                            
                            <div class="form-group">
                                <input type="text" id="add-tax-id" placeholder="${$t('Tax ID (optional)')}" />
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="add-company-name" placeholder="${$t('Company name (optional)')}" />
                            </div>
                            
                            <div class="form-section-title">${$t('Address name')}</div>
                            <div class="form-section-description">
                                ${$t('A personalised name will help you find or associate the address on your list more quickly.')}
                            </div>
                            
                            <div class="form-group">
                                <input type="text" id="add-address-name" placeholder="${$t('Address name')}" />
                            </div>
                        </div>
                    </div>
                </div>
                <div class="popup-buttons-footer">
                            <button type="button" class="action primary" id="save-new-address">
                                <span>${$t('Add')}</span>
                            </button>
                            <button type="button" class="action secondary" id="cancel-add">
                                <span>${$t('Cancel')}</span>
                            </button>
                        </div>
            `;

            element.html(html);

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                element.modal('closeModal');
            });

            $('#save-new-address').on('click', function () {
                var newAddress = {
                    name: $('#add-firstname').val().trim(),
                    surname: $('#add-lastname').val().trim(),
                    street: $('#add-street').val().trim(),
                    appartmentNumber: $('#add-apartment').val().trim(),
                    city: $('#add-city').val().trim(),
                    postalCode: $('#add-postcode').val().trim(),
                    country: $('#add-country').val(),
                    taxId: $('#add-tax-id').val().trim(),
                    companyName: $('#add-company-name').val().trim(),
                    addressName: $('#add-address-name').val().trim()
                };

                // Validate required fields
                if (!newAddress.name || !newAddress.surname || !newAddress.street ||
                    !newAddress.city || !newAddress.postalCode || !newAddress.country) {
                    self.showStatus('error', $t('Please fill all required fields'), 'simplyin-add-status');
                    return;
                }

                self.saveAddress(null, newAddress, 'add', config, addressType);
            });

            $('#cancel-add').on('click', function () {
                self.showAccountDetailsModal(config);
            });
        },

        /**
         * Delete address
         */
        deleteAddress: function (addressId, config, addressType) {
            var self = this;
            addressType = addressType || 'billing';

            this.showStatus('loading', $t('Deleting address...'), 'simplyin-details-status');
            $('#simplyin-details-status').css('display', 'block');

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            $('body').trigger('processStart');
            ajaxClient.post('simplyin/api/deleteAddress', {
                authToken: freshAuthToken,
                addressId: addressId,
                addressType: addressType === 'billing' ? 'billingAddresses' : 'shippingAddresses'
            }).done(function (response) {
                if (response.success) {
                    self.showStatus('success', $t('Address deleted successfully'), 'simplyin-details-status');
                    setTimeout(function () {
                        self.refreshAddressList(config);
                    }, 1000);
                } else {
                    self.showStatus('error', response.message || $t('Failed to delete address'), 'simplyin-details-status');
                }
                $('#simplyin-details-status').css('display', 'block');
            }).fail(function () {
                self.showStatus('error', $t('Failed to delete address'), 'simplyin-details-status');
                $('#simplyin-details-status').css('display', 'block');
            }).always(function () {
                $('body').trigger('processStop');
            });
        },

        /**
         * Delete parcel locker
         */
        deleteParcelLocker: function (lockerId, config) {
            var self = this;

            this.showStatus('loading', $t('Deleting parcel locker...'), 'simplyin-details-status');
            $('#simplyin-details-status').css('display', 'block');

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            $('body').trigger('processStart');
            ajaxClient.post('simplyin/api/deleteParcelLocker', {
                authToken: freshAuthToken,
                lockerId: lockerId
            }).done(function (response) {
                if (response.success) {
                    self.showStatus('success', $t('Parcel locker deleted successfully'), 'simplyin-details-status');
                    setTimeout(function () {
                        self.refreshAddressList(config);
                    }, 1000);
                } else {
                    self.showStatus('error', response.message || $t('Failed to delete parcel locker'), 'simplyin-details-status');
                }
                $('#simplyin-details-status').css('display', 'block');
            }).fail(function () {
                self.showStatus('error', $t('Failed to delete parcel locker'), 'simplyin-details-status');
                $('#simplyin-details-status').css('display', 'block');
            }).always(function () {
                $('body').trigger('processStop');
            });
        },

        /**
         * Save address (add or update)
         */
        saveAddress: function (addressId, addressData, action, config, addressType) {
            var self = this;
            addressType = addressType || 'billing';
            var statusId = action === 'add' ? 'simplyin-add-status' : 'simplyin-edit-status';
            var endpoint = action === 'add' ? 'simplyin/api/addAddress' : 'simplyin/api/updateAddress';

            this.showStatus('loading', $t('Saving address...'), statusId);

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            var requestData = {
                authToken: freshAuthToken,
                address: addressData,
                addressType: addressType === 'billing' ? 'billingAddresses' : 'shippingAddresses'
            };

            if (action === 'update') {
                requestData.addressId = addressId;
            }

            $('body').trigger('processStart');
            ajaxClient.post(endpoint, requestData).done(function (response) {
                if (response.success) {
                    self.showStatus('success', $t('Address saved successfully'), statusId);
                    setTimeout(function () {
                        self.refreshAddressList(config);
                    }, 1000);
                } else {
                    if (response.errors) {
                        var errorMsg = Object.values(response.errors).join(', ');
                        self.showStatus('error', errorMsg, statusId);
                    } else {
                        self.showStatus('error', response.message || $t('Failed to save address'), statusId);
                    }
                }
            }).fail(function () {
                self.showStatus('error', $t('Failed to save address'), statusId);
            }).always(function () {
                $('body').trigger('processStop');
            });
        },

        /**
         * Refresh address list
         */
        refreshAddressList: function (config) {
            var self = this;

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            $('body').trigger('processStart');
            ajaxClient.post('simplyin/api/getUserData', {
                authToken: freshAuthToken
            }).done(function (response) {
                if (response.success) {
                    config.userData = response.userData;
                    // Also update config.authToken with fresh token for future calls
                    config.authToken = freshAuthToken;
                    self.showAccountDetailsModal(config);
                }
            }).always(function () {
                $('body').trigger('processStop');
            });
        },

        /**
         * Render parcel lockers in the specified container
         */
        renderParcelLockers: function (lockers, containerId) {
            var self = this;
            var container = $('#' + containerId + ' .simplyin-parcel-items');

            // Filter lockers to only show providers with configured shipping methods
            var filteredLockers = self.filterLockersByConfiguredProviders(lockers);

            if (!filteredLockers || filteredLockers.length === 0) {
                container.html('<p class="simplyin-message">' + $t('No parcel lockers found.') + '</p>');
                return;
            }

            // Get currency symbol
            var currencySymbol = 'zł';
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.currencySymbol) {
                currencySymbol = window.checkoutConfig.payment.simplyin_payment.currencySymbol;
            }

            // Get previously selected parcel locker from session storage
            var savedLocker = sessionStorageManager.getSelectedParcelLocker();
            var savedLockerId = savedLocker ? (savedLocker._id || savedLocker.lockerId || '') : '';

            var html = '';
            filteredLockers.forEach(function (locker, index) {
                var lockerName = locker.addressName || locker.lockerId || locker.name || '';
                var lockerAddress = locker.address || (locker.street + ', ' + locker.city) || '';
                var logoUrl = locker.logoUrl || '';
                // Ensure full URL for logo
                if (logoUrl && logoUrl.indexOf('http') !== 0) {
                    logoUrl = 'https://assets.simply.in/' + logoUrl.replace(/^\//, '');
                }
                var icon = locker.icon || '📦';

                // Get shipping price for this provider
                var providerName = locker.providerName || locker.provider || '';
                var price = self.getShippingPriceForProvider(providerName);
                var priceHtml = '';
                if (price !== null) {
                    var formattedPrice = price.toFixed(2).replace('.', ',');
                    priceHtml = '<span class="parcel-price">' + formattedPrice + ' ' + currencySymbol + '</span>';
                }

                // Check if this locker matches the saved selection
                var currentLockerId = locker._id || locker.lockerId || '';
                var isChecked = savedLockerId && currentLockerId && savedLockerId === currentLockerId;
                var checkedAttr = isChecked ? 'checked' : '';

                html += `
                    <div class="simplyin-parcel-item" data-id="${locker._id || ''}" data-provider="${locker.providerName || ''}">
                        <input type="radio" 
                               id="parcel-locker-${containerId}-${index}" 
                               name="simplyin-parcel-locker" 
                               value="${index}"
                               data-id="${locker._id || ''}"
                               data-locker='${JSON.stringify(locker).replace(/'/g, "&#39;")}'
                               ${checkedAttr}>
                        <label for="parcel-locker-${containerId}-${index}">
                            <div class="parcel-logo">
                                ${logoUrl ? '<img src="' + logoUrl + '" alt="' + (locker.providerName || '') + '">' : '<span class="parcel-icon">' + icon + '</span>'}
                            </div>
                            <div class="parcel-content">
                                <strong>${lockerName}</strong>
                                <span class="parcel-address">${lockerAddress}</span>
                                ${priceHtml}
                            </div>
                            <div class="parcel-type-icon">${icon}</div>
                        </label>
                        <div class="parcel-actions">
                            <div class="action-menu" data-index="${index}" data-type="parcel" data-id="${locker._id || ''}">
                                <svg width="4" height="16" viewBox="0 0 4 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <circle cx="2" cy="2" r="2" fill="#1f1f1f"/>
                                    <circle cx="2" cy="8" r="2" fill="#1f1f1f"/>
                                    <circle cx="2" cy="14" r="2" fill="#1f1f1f"/>
                                </svg>
                            </div>
                        </div>
                    </div>
                `;
            });

            container.html(html);
        },

        /**
         * Use selected parcel locker
         */
        useSelectedParcelLocker: function (lockerData, billingAddress, config) {
            var self = this;

            this.showStatus('loading', $t('Processing...'), 'simplyin-details-status');
            $('#simplyin-details-status').css('display', 'block');

            // Store the selected parcel locker in session
            sessionStorageManager.setSelectedParcelLocker(lockerData);
            // Note: setSelectedParcelLocker now automatically sets delivery type to 'parcel_locker'

            // Get phone number from user data if not in billing address
            var userData = config.userData || sessionStorageManager.getUserData() || {};
            if (!billingAddress.phoneNumber && userData.phoneNumber) {
                billingAddress.phoneNumber = userData.phoneNumber;
            }

            // Auto-select Magento shipping method based on provider
            var providerName = lockerData.providerName || lockerData.provider || '';
            if (providerName) {
                self.autoSelectShippingMethodByProvider(providerName.toLowerCase());
            }

            // Wait for shipping method to be selected before processing pickup point
            // This ensures the shipping method is set before we try to save pickup point data
            setTimeout(function () {
                // Call PickupPointIntegrationManager to set extension attributes via backend API
                // This sets module-specific extension attributes (InPost, Orlen, DPD) on the quote
                pickupPointIntegrationManager.processParcelLockerSelection(lockerData)
                    .always(function (result) {
                        // Close modal after integration (whether successful or not)
                        setTimeout(function () {
                            modalElement.modal('closeModal');

                            // Fill billing address in Magento checkout
                            self.fillShippingAddress(billingAddress, false);

                            // Store parcel locker info for order creation
                            if (config.onParcelLockerSelected) {
                                config.onParcelLockerSelected(config.authToken, config.userData, lockerData, billingAddress);
                            }

                            // Trigger event for other components
                            $(document).trigger('simplyin:parcelLockerSelected', [lockerData, billingAddress]);
                        }, 500);
                    });
            }, 1000); // Wait 1 second for shipping method selection to complete
        },

        /**
         * Auto-select Magento shipping method based on parcel locker provider
         * Uses admin configuration mapping from "Ustawienia metod dostawy"
         */
        autoSelectShippingMethodByProvider: function (providerName) {
            var self = this;

            // Get shipping method mapping from checkout config
            var shippingMethodMapping = {};
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping;
            }

            // Normalize the provider name to match mapping keys (e.g., "ORLEN Paczka" -> "orlen")
            var normalizedProvider = self.normalizeProviderName(providerName);

            // Get the mapped Magento shipping method for this provider
            var mappedMethod = shippingMethodMapping[normalizedProvider];

            if (!mappedMethod) {
                console.log('SimplyIN: No shipping method mapping found for provider:', providerName, '(normalized:', normalizedProvider + ')');
                return;
            }

            // Parse the method code (format: carrier_method or carrier_method_instance)
            var methodParts = mappedMethod.split('_');
            var carrierCode = methodParts[0];
            var methodCode = methodParts.slice(1).join('_');

            // Wait for shipping rates to be available and select the method
            self.waitAndSelectShippingMethod(carrierCode, methodCode, mappedMethod);
        },

        /**
         * Wait for shipping rates and select the specified method
         * Implements matching precedence per Requirements 7.1, 7.2, 7.3:
         * 1. Exact full method code match (carrier_code + method_code)
         * 2. Carrier code only match
         * 3. Partial string matching for method codes with instance IDs
         *
         * @param {string} carrierCode - The carrier code (e.g., 'inpost', 'flatrate')
         * @param {string} methodCode - The method code (e.g., 'paczkomat', 'flatrate')
         * @param {string} fullMethodCode - The full method code (e.g., 'inpost_paczkomat')
         */
        waitAndSelectShippingMethod: function (carrierCode, methodCode, fullMethodCode) {
            var self = this;
            var attempts = 0;
            var maxAttempts = 20;
            var retryDelay = 300; // milliseconds

            /**
             * Find matching rate using precedence: exact → carrier → partial
             * @param {Array} rates - Available shipping rates
             * @returns {Object|null} - Matching rate object or null
             */
            var findMatchingRate = function (rates) {
                var matchingRate = null;
                var matchType = null;

                // Step 1: Try exact full method code match (Requirement 7.1)
                matchingRate = rates.find(function (r) {
                    return r.carrier_code + '_' + r.method_code === fullMethodCode;
                });
                if (matchingRate) {
                    matchType = 'exact';
                    return { rate: matchingRate, type: matchType };
                }

                // Step 2: Try carrier code only match (Requirement 7.2)
                matchingRate = rates.find(function (r) {
                    return r.carrier_code === carrierCode;
                });
                if (matchingRate) {
                    matchType = 'carrier';
                    return { rate: matchingRate, type: matchType };
                }

                // Step 3: Try partial string matching for method codes with instance IDs (Requirement 7.3)
                // This handles cases like 'inpost_paczkomat_123' matching 'inpost_paczkomat'
                matchingRate = rates.find(function (r) {
                    var rateCode = r.carrier_code + '_' + r.method_code;
                    // Check if rate code starts with full method code (e.g., 'inpost_paczkomat_123' starts with 'inpost_paczkomat')
                    if (rateCode.indexOf(fullMethodCode) === 0) {
                        return true;
                    }
                    // Check if full method code starts with rate code
                    if (fullMethodCode.indexOf(rateCode) === 0) {
                        return true;
                    }
                    // Check if method codes partially match (for instance IDs)
                    if (r.method_code.indexOf(methodCode) !== -1 || methodCode.indexOf(r.method_code) !== -1) {
                        return true;
                    }
                    return false;
                });
                if (matchingRate) {
                    matchType = 'partial';
                    return { rate: matchingRate, type: matchType };
                }

                return null;
            };

            /**
             * Select the shipping method in Magento checkout
             * @param {Object} rate - The shipping rate to select
             */
            var selectRate = function (rate) {
                var rateCode = rate.carrier_code + '_' + rate.method_code;

                // First, deselect all shipping method radio buttons to prevent double selection
                $('input[type="radio"][name="ko_unique_1"]').prop('checked', false);
                $('#checkout-shipping-method-load input[type="radio"]').prop('checked', false);

                // Update Knockout.js model (Requirement 3.5)
                selectShippingMethodAction(rate);

                // Also update the UI radio button for visual consistency
                // Use more specific selector to find the correct radio button
                var $radio = null;

                // Try different selectors in order of specificity
                var selectors = [
                    '#checkout-shipping-method-load input[type="radio"][value="' + rateCode + '"]',
                    'input[name="ko_unique_1"][value="' + rateCode + '"]',
                    'input[type="radio"][value="' + rateCode + '"]'
                ];

                for (var i = 0; i < selectors.length; i++) {
                    $radio = $(selectors[i]);
                    if ($radio.length > 0) {
                        break;
                    }
                }

                if ($radio && $radio.length > 0) {
                    // Ensure only this radio is checked
                    $radio.first().prop('checked', true).trigger('change');
                }

                // Trigger checkout update event
                $(document).trigger('simplyin:shippingMethodSelected', [rate]);
            };

            var trySelect = function () {
                attempts++;

                // Get current shipping rates (Requirement 3.3 - wait for rates to be loaded)
                var rates = shippingService.getShippingRates()();

                // Edge case: No rates available yet
                if (!rates || rates.length === 0) {
                    if (attempts < maxAttempts) {
                        setTimeout(trySelect, retryDelay);
                    } else {
                        // Requirement 3.4 - Log warning when rates not available
                        console.warn('SimplyIn: No shipping rates available after ' + maxAttempts + ' attempts. Cannot auto-select shipping method.');
                    }
                    return;
                }

                // Find matching rate using precedence algorithm
                var availableRates = rates.map(function(r) {
                    return r.carrier_code + '_' + r.method_code;
                });
                var matchResult = findMatchingRate(rates);

                if (matchResult && matchResult.rate) {
                    selectRate(matchResult.rate);
                } else {
                    // Requirement 3.4 - Log warning and do not force invalid selection
                    console.warn('SimplyIn: Mapped shipping method "' + fullMethodCode + '" is not available in current shipping rates.');
                    console.warn('SimplyIn: Available methods:', availableRates.join(', '));
                }
            };

            // Start trying after a short delay to allow rates to load initially
            setTimeout(trySelect, 500);
        },

        /**
         * Show add parcel locker modal
         */
        showAddParcelLockerModal: function (config) {
            var self = this;
            var element = this.initModal();
            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');

            var html = `
                <div class="simplyin-popup simplyin-autocomplete">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Add a pickup point')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-add-parcel-form">
                            <div class="simplyin-status" id="simplyin-parcel-status"></div>
                            
                            <div class="form-group search-input-group">
                                <div class="search-icon">
                                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M9 17C13.4183 17 17 13.4183 17 9C17 4.58172 13.4183 1 9 1C4.58172 1 1 4.58172 1 9C1 13.4183 4.58172 17 9 17Z" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M19 19L14.65 14.65" stroke="#999" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </div>
                                <input type="text" id="pickup-search" placeholder="${$t('Enter address or postal code')}" autocomplete="off" />
                            </div>
                            
                            <div id="parcel-search-results" class="simplyin-parcel-search-results">
                                <div class="pickup-placeholder">
                                    <div class="placeholder-icon">
                                        <svg width="60" height="80" viewBox="0 0 60 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M30 0C13.4315 0 0 13.4315 0 30C0 52.5 30 80 30 80C30 80 60 52.5 60 30C60 13.4315 46.5685 0 30 0Z" fill="#E74C3C"/>
                                            <circle cx="30" cy="30" r="12" fill="white"/>
                                        </svg>
                                    </div>
                                    <p class="placeholder-text">${$t('Enter an address to search for nearby pickup points')}</p>
                                </div>
                            </div>
                            
                            <!-- Address Details Section (always visible) -->
                            <div id="address-details-section">
                                <div class="form-section-title">${$t('Address details')}</div>
                                <div class="address-detail-row">
                                    <span class="detail-label">${$t('Number')}:</span>
                                    <span class="detail-value" id="selected-locker-number"></span>
                                </div>
                                <div class="address-detail-row">
                                    <span class="detail-label">${$t('Address')}:</span>
                                    <span class="detail-value" id="selected-locker-address"></span>
                                </div>
                                <div class="address-detail-row">
                                    <span class="detail-label">${$t('Additional information')}:</span>
                                    <span class="detail-value" id="selected-locker-info"></span>
                                </div>
                                
                                <div class="form-section-title" style="margin-top: 24px;">${$t('Address name')}</div>
                                <p class="form-section-description">${$t('A personalised name will help you find or associate the address on your list more quickly.')}</p>
                                <div class="form-group">
                                    <input type="text" id="pickup-name" placeholder="${$t('Enter name')}" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="popup-buttons-footer">
                        <button type="button" class="action primary" id="add-parcel-locker-btn" style="display: block !important;">
                            <span>${$t('Add')}</span>
                        </button>
                        <button type="button" class="action secondary" id="cancel-parcel-search">
                            <span>${$t('Cancel')}</span>
                        </button>
                    </div>
            `;

            element.html(html);
            element.modal('openModal');

            // Store selected locker data
            self.selectedParcelLocker = null;

            // Close button handler
            $('#simplyin-modal-close').off('click').on('click', function () {
                element.modal('closeModal');
            });

            // Cancel button
            $('#cancel-parcel-search').on('click', function () {
                self.showAccountDetailsModal(config);
            });

            // Add button
            $('#add-parcel-locker-btn').on('click', function () {
                if (self.selectedParcelLocker) {
                    var customName = $('#pickup-name').val().trim();
                    self.addParcelLockerToProfile(self.selectedParcelLocker, customName, config);
                } else {
                    self.showStatus('error', $t('Please select a pickup point first'), 'simplyin-parcel-status');
                }
            });

            // Focus on search input
            setTimeout(function () {
                $('#pickup-search').focus();
            }, 500);

            // Initialize autocomplete for address search
            self.initAddressAutocomplete(config);
        },

        /**
         * Initialize address autocomplete
         */
        initAddressAutocomplete: function (config) {
            var self = this;
            var searchInput = $('#pickup-search');
            var searchTimeout;

            // Create autocomplete dropdown container
            if (!$('#address-autocomplete-dropdown').length) {
                searchInput.after('<div id="address-autocomplete-dropdown" class="simplyin-autocomplete-dropdown"></div>');
            }

            searchInput.on('input', function () {
                var query = $(this).val().trim();

                clearTimeout(searchTimeout);

                if (query.length < 3) {
                    $('#address-autocomplete-dropdown').hide().empty();
                    return;
                }

                searchTimeout = setTimeout(function () {
                    self.fetchAddressSuggestions(query, config);
                }, 300);
            });

            // Hide dropdown when clicking outside
            $(document).on('click.autocomplete', function (e) {
                if (!$(e.target).closest('.search-input-group').length) {
                    $('#address-autocomplete-dropdown').hide();
                }
            });

            // Handle keyboard navigation
            searchInput.on('keydown', function (e) {
                var dropdown = $('#address-autocomplete-dropdown');
                var items = dropdown.find('.autocomplete-item');
                var focused = dropdown.find('.autocomplete-item.focused');

                if (e.keyCode === 40) { // Down arrow
                    e.preventDefault();
                    if (focused.length) {
                        focused.removeClass('focused');
                        var next = focused.next('.autocomplete-item');
                        if (next.length) {
                            next.addClass('focused');
                        } else {
                            items.first().addClass('focused');
                        }
                    } else {
                        items.first().addClass('focused');
                    }
                } else if (e.keyCode === 38) { // Up arrow
                    e.preventDefault();
                    if (focused.length) {
                        focused.removeClass('focused');
                        var prev = focused.prev('.autocomplete-item');
                        if (prev.length) {
                            prev.addClass('focused');
                        } else {
                            items.last().addClass('focused');
                        }
                    } else {
                        items.last().addClass('focused');
                    }
                } else if (e.keyCode === 13) { // Enter
                    e.preventDefault();
                    if (focused.length) {
                        focused.click();
                    }
                } else if (e.keyCode === 27) { // Escape
                    dropdown.hide();
                }
            });
        },

        /**
         * Fetch address suggestions for autocomplete
         */
        fetchAddressSuggestions: function (query, config) {
            var self = this;
            var dropdown = $('#address-autocomplete-dropdown');

            dropdown.html('<div class="autocomplete-loading">' + $t('Searching...') + '</div>').show();

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            ajaxClient.postSilent('simplyin/api/searchAddress', {
                authToken: freshAuthToken,
                query: query
            }).done(function (response) {
                if (response.success && response.addresses && response.addresses.length > 0) {
                    self.displayAddressSuggestions(response.addresses, config);
                } else if (response.message && (response.message.indexOf('authenticated') !== -1 || response.message.indexOf('Authentication') !== -1)) {
                    // Session expired - show re-authentication message
                    dropdown.html('<div class="autocomplete-error">' + $t('Session expired. Please close and try again.') + '</div>');
                    self.showStatus('error', $t('Session expired. Please re-authenticate.'), 'simplyin-parcel-status');
                } else {
                    dropdown.html('<div class="autocomplete-no-results">' + $t('No addresses found') + '</div>');
                }
            }).fail(function () {
                dropdown.html('<div class="autocomplete-error">' + $t('Search failed') + '</div>');
            });
        },

        /**
         * Display address suggestions in dropdown
         */
        displayAddressSuggestions: function (addresses, config) {
            var self = this;
            var dropdown = $('#address-autocomplete-dropdown');
            var html = '';

            addresses.forEach(function (address, index) {
                // Handle different response structures
                var formattedAddress = address.formatted_address || address.address || '';

                // If no formatted_address, build from address_components
                if (!formattedAddress && address.address_components) {
                    var parts = [];
                    address.address_components.forEach(function(component) {
                        if (component.long_name) {
                            parts.push(component.long_name);
                        }
                    });
                    formattedAddress = parts.join(', ');
                }

                // Get coordinates - handle different structures
                var lat = 0, lng = 0;
                if (address.geometry && address.geometry.location) {
                    lat = address.geometry.location.lat || 0;
                    lng = address.geometry.location.lng || 0;
                } else if (address.lat && address.lng) {
                    lat = address.lat;
                    lng = address.lng;
                } else if (address.latitude && address.longitude) {
                    lat = address.latitude;
                    lng = address.longitude;
                }

                html += `
                    <div class="autocomplete-item" 
                         data-lat="${lat}" 
                         data-lng="${lng}" 
                         data-address="${formattedAddress.replace(/"/g, '&quot;')}">
                        <div class="autocomplete-icon">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8 0C4.68629 0 2 2.68629 2 6C2 10.5 8 16 8 16C8 16 14 10.5 14 6C14 2.68629 11.3137 0 8 0Z" fill="#E74C3C"/>
                                <circle cx="8" cy="6" r="2.5" fill="white"/>
                            </svg>
                        </div>
                        <span class="autocomplete-text">${formattedAddress}</span>
                    </div>
                `;
            });

            dropdown.html(html).show();

            // Bind click event to suggestions
            dropdown.find('.autocomplete-item').on('click', function () {
                var lat = $(this).data('lat');
                var lng = $(this).data('lng');
                var address = $(this).data('address');

                // Update search input with selected address
                $('#pickup-search').val(address);
                dropdown.hide();

                // Fetch parcel lockers near selected address
                self.getParcelLockersNearCoordinates(lat, lng, config);
            });

            // Hover effect
            dropdown.find('.autocomplete-item').on('mouseenter', function () {
                dropdown.find('.autocomplete-item').removeClass('focused');
                $(this).addClass('focused');
            });
        },

        /**
         * Show pickup placeholder
         */
        showPickupPlaceholder: function () {
            var html = `
                <div class="pickup-placeholder">
                    <div class="placeholder-icon">
                        <svg width="60" height="80" viewBox="0 0 60 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M30 0C13.4315 0 0 13.4315 0 30C0 52.5 30 80 30 80C30 80 60 52.5 60 30C60 13.4315 46.5685 0 30 0Z" fill="#E74C3C"/>
                            <circle cx="30" cy="30" r="12" fill="white"/>
                        </svg>
                    </div>
                    <p class="placeholder-text">${$t('Enter an address to search for nearby pickup points')}</p>
                </div>
            `;
            $('#parcel-search-results').html(html);
            // Clear address details values but keep section visible
            $('#selected-locker-number').text('-');
            $('#selected-locker-address').text('-');
            $('#selected-locker-info').text('-');
            $('#pickup-name').val('');
            this.selectedParcelLocker = null;
        },

        /**
         * Get parcel lockers near coordinates
         */
        getParcelLockersNearCoordinates: function (lat, lng, config) {
            var self = this;
            var resultsContainer = $('#parcel-search-results');

            // Show loading state
            resultsContainer.html('<div class="simplyin-loading">' + $t('Searching...') + '</div>');

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            ajaxClient.postSilent('simplyin/api/getParcelLockers', {
                authToken: freshAuthToken,
                action: 'getClosest',
                coordinates: {
                    lat: lat,
                    lng: lng
                },
                limit: 20,
                radius: 10000
            }).done(function (response) {
                if (response.success) {
                    self.displayParcelLockerResults(response, config);
                } else {
                    self.showNoResultsPlaceholder();
                }
            }).fail(function () {
                self.showNoResultsPlaceholder();
            });
        },

        /**
         * Show no results placeholder (after search)
         */
        showNoResultsPlaceholder: function () {
            var html = `
                <div class="pickup-placeholder">
                    <div class="placeholder-icon">
                        <svg width="60" height="80" viewBox="0 0 60 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M30 0C13.4315 0 0 13.4315 0 30C0 52.5 30 80 30 80C30 80 60 52.5 60 30C60 13.4315 46.5685 0 30 0Z" fill="#E74C3C"/>
                            <circle cx="30" cy="30" r="12" fill="white"/>
                        </svg>
                    </div>
                    <p class="placeholder-text">${$t('No pickup points found near the provided address')}</p>
                </div>
            `;
            $('#parcel-search-results').html(html);
            // Clear address details values but keep section visible
            $('#selected-locker-number').text('-');
            $('#selected-locker-address').text('-');
            $('#selected-locker-info').text('-');
            $('#pickup-name').val('');
            this.selectedParcelLocker = null;
        },

        /**
         * Display parcel locker search results
         */
        displayParcelLockerResults: function (response, config) {
            var self = this;
            var resultsContainer = $('#parcel-search-results');

            // Combine parcel machines and pickup points
            var allLockers = [];

            if (response.parcelMachines && response.parcelMachines.length > 0) {
                allLockers = allLockers.concat(response.parcelMachines);
            }
            if (response.pickupPoints && response.pickupPoints.length > 0) {
                allLockers = allLockers.concat(response.pickupPoints);
            }
            // Also check for allLockers in response
            if (response.allLockers && response.allLockers.length > 0 && allLockers.length === 0) {
                allLockers = response.allLockers;
            }

            if (allLockers.length === 0) {
                self.showNoResultsPlaceholder();
                return;
            }

            // Filter lockers to only show providers with configured shipping methods
            var filteredLockers = allLockers.filter(function (item) {
                var locker = item.locker || item;
                var info = item.info || {};
                var providerName = locker.providerName || (info.provider && info.provider.name) || '';
                if (!providerName) {
                    return true; // Keep lockers without provider info
                }
                return self.isProviderConfigured(providerName);
            });

            if (filteredLockers.length === 0) {
                self.showNoResultsPlaceholder();
                return;
            }

            // Get currency symbol
            var currencySymbol = 'zł';
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment &&
                window.checkoutConfig.payment.simplyin_payment.currencySymbol) {
                currencySymbol = window.checkoutConfig.payment.simplyin_payment.currencySymbol;
            }

            // Get previously selected parcel locker from session storage
            var savedLocker = sessionStorageManager.getSelectedParcelLocker();
            var savedLockerId = savedLocker ? (savedLocker._id || savedLocker.lockerId || '') : '';

            var html = '<div class="pickup-list-container">';
            filteredLockers.forEach(function (item, index) {
                // Handle nested structure: {locker: {...}, info: {...}}
                var locker = item.locker || item;
                var info = item.info || {};

                var lockerId = locker.lockerId || locker._id || '';
                var lockerAddress = locker.address || '';
                var logoUrl = (info.provider && info.provider.logoUrl) || locker.logoUrl || '';
                // Ensure full URL for logo
                if (logoUrl && logoUrl.indexOf('http') !== 0) {
                    logoUrl = 'https://assets.simply.in/' + logoUrl.replace(/^\//, '');
                }
                var addressName = locker.addressName || locker.label || lockerId;
                var providerName = locker.providerName || (info.provider && info.provider.name) || '';
                var distance = info.distance ? Math.round(info.distance * 1000) : (locker.distance ? Math.round(locker.distance * 1000) : '');
                var serviceType = locker.service_type || 'parcel_machine';
                var desc = locker.desc || locker.description || '';

                // Get shipping price for this provider
                var price = self.getShippingPriceForProvider(providerName);
                var priceHtml = '';
                if (price !== null) {
                    var formattedPrice = price.toFixed(2).replace('.', ',');
                    priceHtml = '<span class="pickup-price">' + formattedPrice + ' ' + currencySymbol + '</span>';
                }

                // Check if this locker matches the saved selection
                var currentLockerId = locker._id || locker.lockerId || '';
                var isChecked = savedLockerId && currentLockerId && savedLockerId === currentLockerId;
                var checkedAttr = isChecked ? 'checked' : '';

                // Merge provider info into locker data for storage
                var lockerWithProvider = Object.assign({}, locker, {
                    providerName: providerName,
                    logoUrl: logoUrl
                });
                var lockerJson = JSON.stringify(lockerWithProvider).replace(/'/g, "&#39;");

                html += `
                    <div class="simplyin-pickup-list-item">
                        <label class="pickup-item">
                            <input type="radio" 
                                   name="pickup-option" 
                                   value="${locker._id || ''}"
                                   data-id="${lockerId}"
                                   data-address="${lockerAddress}"
                                   data-desc="${desc}"
                                   data-logo-url="${logoUrl}"
                                   data-label="${addressName}"
                                   data-provider-id="${locker.providerId || ''}"
                                   data-service-type="${serviceType}"
                                   data-locker='${lockerJson}'
                                   ${checkedAttr}>
                            <div class="pickup-info">
                                <div class="pickup-logo">
                                    ${logoUrl ? '<img src="' + logoUrl + '" alt="' + providerName + '">' : '<span class="parcel-icon">📦</span>'}
                                </div>
                                <div class="pickup-details">
                                    <strong>${addressName}</strong>
                                    <span class="pickup-address">${lockerAddress}</span>
                                    ${priceHtml}
                                    ${distance ? '<span class="pickup-distance">' + $t('Distance') + ': ' + distance + ' m</span>' : ''}
                                </div>
                            </div>
                        </label>
                    </div>
                `;
            });
            html += '</div>';

            resultsContainer.html(html);

            // Bind selection event
            resultsContainer.find('input[name="pickup-option"]').on('change', function () {
                self.selectParcelLockerFromSearch($(this));
            });
        },

        /**
         * Handle parcel locker selection from search results
         */
        selectParcelLockerFromSearch: function ($input) {
            var self = this;
            var lockerData = $input.data('locker');
            var lockerId = $input.data('id');
            var lockerAddress = $input.data('address');
            var lockerDesc = $input.data('desc');

            // Store selected locker
            self.selectedParcelLocker = lockerData;

            // Update address details section with selected locker values
            $('#selected-locker-number').text(lockerId || '-');
            $('#selected-locker-address').text(lockerAddress || '-');
            $('#selected-locker-info').text(lockerDesc || '-');

            // Pre-fill address name with locker ID
            if (!$('#pickup-name').val()) {
                $('#pickup-name').val(lockerId);
            }

            // Auto-select shipping method based on provider
            var providerName = lockerData.providerName || lockerData.provider || '';
            if (providerName) {
                self.autoSelectShippingMethodByProvider(providerName.toLowerCase());
            }
        },

        /**
         * Update delivery costs in the delivery type selector
         * Shows shipping method prices for courier and parcel locker options
         */
        updateDeliveryCosts: function (retryCount) {
            var self = this;
            retryCount = retryCount || 0;

            // Get shipping rates from Magento
            var rates = shippingService.getShippingRates()();

            if (!rates || rates.length === 0) {
                if (retryCount < 10) {
                    setTimeout(function () {
                        self.updateDeliveryCosts(retryCount + 1);
                    }, 300);
                }
                return;
            }

            // Get shipping method mapping from checkout config
            var shippingMethodMapping = {};
            var currencySymbol = '';
            if (window.checkoutConfig &&
                window.checkoutConfig.payment &&
                window.checkoutConfig.payment.simplyin_payment) {
                shippingMethodMapping = window.checkoutConfig.payment.simplyin_payment.shippingMethodMapping || {};
                currencySymbol = window.checkoutConfig.payment.simplyin_payment.currencySymbol || '';
            }

            // Provider to config key mapping (same as in ConfigProvider)
            var providerMapping = {
                'dpd': 'dpd',
                'dhl': 'dhl',
                'fedex': 'fedex',
                'inpost': 'inpost',
                'orlen': 'orlen',
                'ups': 'ups'
            };

            // Update courier price
            var courierPriceElement = $('#simplyin-courier-price');
            if (courierPriceElement.length > 0) {
                var defaultCourier = shippingMethodMapping['default_courier'];
                if (defaultCourier) {
                    var courierRate = rates.find(function (r) {
                        var rateCode = r.carrier_code + '_' + r.method_code;
                        return rateCode === defaultCourier ||
                            rateCode.indexOf(defaultCourier) !== -1 ||
                            defaultCourier.indexOf(rateCode) !== -1;
                    });

                    if (courierRate && courierRate.price_incl_tax !== undefined) {
                        var price = parseFloat(courierRate.price_incl_tax).toFixed(2).replace('.', ',');
                        courierPriceElement.text(' - ' + price + ' ' + currencySymbol);
                    }
                }
            }

            // Update parcel locker price (minimum from all configured providers)
            var parcelLockerPriceElement = $('#simplyin-parcel-locker-price');
            if (parcelLockerPriceElement.length > 0) {
                var allParcelLockerPrices = [];

                Object.keys(providerMapping).forEach(function (provider) {
                    var mappedMethod = shippingMethodMapping[provider];
                    if (mappedMethod) {
                        var matchingRate = rates.find(function (r) {
                            var rateCode = r.carrier_code + '_' + r.method_code;
                            return rateCode === mappedMethod ||
                                rateCode.indexOf(mappedMethod) !== -1 ||
                                mappedMethod.indexOf(rateCode) !== -1;
                        });

                        if (matchingRate && matchingRate.price_incl_tax !== undefined) {
                            allParcelLockerPrices.push(parseFloat(matchingRate.price_incl_tax));
                        }
                    }
                });

                if (allParcelLockerPrices.length > 0) {
                    var minPrice = Math.min.apply(null, allParcelLockerPrices);
                    var formattedPrice = minPrice.toFixed(2).replace('.', ',');
                    parcelLockerPriceElement.text(' - ' + $t('from') + ' ' + formattedPrice + ' ' + currencySymbol);
                }
            }

            // Update individual parcel locker item prices
            self.updateParcelLockerItemPrices(rates, shippingMethodMapping, currencySymbol);
        },

        /**
         * Update prices for individual parcel locker items in the list
         */
        updateParcelLockerItemPrices: function (rates, shippingMethodMapping, currencySymbol) {
            var self = this;

            // Find all parcel locker items
            $('.simplyin-parcel-item').each(function () {
                var $item = $(this);
                var providerName = $item.data('provider') || '';

                if (!providerName) {
                    // Try to get provider from the locker data
                    var $input = $item.find('input[name="simplyin-parcel-locker"]');
                    if ($input.length) {
                        try {
                            var lockerData = $input.data('locker');
                            if (lockerData) {
                                providerName = lockerData.providerName || lockerData.provider || '';
                            }
                        } catch (e) {
                            // Could not parse locker data for price update
                        }
                    }
                }

                if (providerName) {
                    var price = self.getShippingPriceForProvider(providerName);
                    var $priceElement = $item.find('.parcel-price');

                    if (price !== null) {
                        var formattedPrice = price.toFixed(2).replace('.', ',') + ' ' + currencySymbol;

                        if ($priceElement.length) {
                            // Update existing price element
                            $priceElement.text(formattedPrice);
                        } else {
                            // Add price element if it doesn't exist
                            var $content = $item.find('.parcel-content');
                            if ($content.length) {
                                $content.append('<span class="parcel-price">' + formattedPrice + '</span>');
                            }
                        }
                    }
                }
            });
        },

        /**
         * Add parcel locker to user profile
         */
        addParcelLockerToProfile: function (lockerData, customName, config) {
            var self = this;

            this.showStatus('loading', $t('Adding parcel locker...'), 'simplyin-parcel-status');

            // Always get fresh token from sessionStorage (in case user re-authenticated)
            var freshAuthToken = sessionStorageManager.getAuthToken() || config.authToken;

            var parcelData = {
                lockerId: lockerData.lockerId || lockerData._id || '',
                addressName: customName || lockerData.lockerId || lockerData.addressName || '',
                address: lockerData.address || '',
                city: lockerData.city || '',
                logoUrl: lockerData.logoUrl || '',
                providerName: lockerData.providerName || lockerData.label || lockerData.provider?.name || '',
                label: lockerData.label || lockerData.providerName || lockerData.provider?.name || '',
                providerId: lockerData.providerId || '',
                service_type: lockerData.service_type || 'parcel_machine',
                desc: lockerData.desc || lockerData.description || ''
            };

            $('body').trigger('processStart');
            ajaxClient.post('simplyin/api/addParcelLocker', {
                authToken: freshAuthToken,
                parcelLocker: parcelData
            }).done(function (response) {
                if (response.success) {
                    self.showStatus('success', $t('Parcel locker added successfully'), 'simplyin-parcel-status');
                    setTimeout(function () {
                        self.refreshAddressList(config);
                    }, 1000);
                } else {
                    self.showStatus('error', response.message || $t('Failed to add parcel locker'), 'simplyin-parcel-status');
                }
            }).fail(function () {
                self.showStatus('error', $t('Failed to add parcel locker'), 'simplyin-parcel-status');
            }).always(function () {
                $('body').trigger('processStop');
            });
        },

        /**
         * Show payment method selection modal
         * @param {Object} config - Configuration with authToken, orderId, amount, currency
         */
        showPaymentMethodModal: function (config) {
            var self = this;
            var element = this.initModal();

            var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');

            // Show loading state
            var loadingHtml = `
                <div class="simplyin-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Payment Methods')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <div class="simplyin-loading-spinner">
                            <div class="simplyin-spinner"></div>
                            <span>${$t('Loading payment methods...')}</span>
                        </div>
                    </div>
                </div>
            `;

            element.html(loadingHtml);
            element.modal('openModal');

            // Bind close button
            $('#simplyin-modal-close').on('click', function () {
                element.modal('closeModal');
            });

            // Fetch payment methods from API
            this.fetchPaymentMethods(config).then(function (response) {
                self.renderPaymentMethodsUI(config, response);
            }).catch(function (error) {
                self.showPaymentError(error.message || $t('Failed to load payment methods'));
            });
        },

        /**
         * Fetch payment methods from API
         * @param {Object} config - Configuration with authToken
         * @returns {Promise}
         */
        fetchPaymentMethods: function (config) {
            return new Promise(function (resolve, reject) {
                ajaxClient.postSilent('simplyin/api/getPaymentMethods', {
                    authToken: config.authToken || ''
                }).done(function (response) {
                    if (response.success) {
                        resolve(response);
                    } else {
                        reject({ message: response.message || $t('Failed to fetch payment methods') });
                    }
                }).fail(function (response) {
                    reject({ message: response.message || $t('Network error') });
                });
            });
        },

        /**
         * Render payment methods UI
         * @param {Object} config - Configuration
         * @param {Object} response - API response with payment methods
         */
        renderPaymentMethodsUI: function (config, response) {
            var self = this;
            var element = modalElement;

            // Use local SVG files for logos
            var simplyinLogoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');
            var p24LogoUrl = require.toUrl('Simplyin_Payment/images/p24.svg');

            var paymentMethods = response.paymentMethods || [];
            var savedCards = response.savedCards || [];
            var iframeUrl = response.iframeUrl || '';
            var integratorId = response.integratorId || '';

            // Store for later use
            this.paymentConfig = {
                authToken: config.authToken,
                orderId: config.orderId,
                amount: config.amount,
                currency: config.currency || 'PLN',
                iframeUrl: iframeUrl,
                integratorId: integratorId,
                onSuccess: config.onSuccess,
                onError: config.onError
            };

            var html = `
                <div class="simplyin-popup simplyin-payment-popup">
                    <div class="simplyin-popup-header">
                        <img width="32" height="32" src="${logoUrl}" alt="SimplyIn">
                        <div class="popup-header-strong">${$t('Select Payment Method')}</div>
                        <div class="simplyin-popup-close-button" id="simplyin-modal-close">
                            <span>&times;</span>
                        </div>
                    </div>
                    <div class="simplyin-popup-container">
                        <!-- Payment processing by header with logos -->
                        <div class="simplyin-payment-providers-header">
                            <span class="simplyin-providers-text">${$t('Payment processing by')}</span>
                            <div class="simplyin-providers-logos">
                                <img src="${simplyinLogoUrl}" alt="SimplyIN" class="simplyin-provider-logo" onerror="this.style.display='none'">
                                <span class="simplyin-providers-separator">&</span>
                                <img src="${p24LogoUrl}" alt="Przelewy24" class="simplyin-provider-logo simplyin-p24-logo" onerror="this.style.display='none'">
                            </div>
                        </div>
                        
                        <div class="simplyin-payment-methods-wrapper">
                            ${this.renderSavedCardsHtml(savedCards)}
                            ${this.renderAddNewCardHtml(iframeUrl, integratorId)}
                            ${this.renderBlikOptionHtml()}
                        </div>
                        
                        <div id="simplyin-payment-status" class="simplyin-status" style="display: none;"></div>
                        
                        <div class="simplyin-payment-actions">
                            <button type="button" class="simplyin-btn simplyin-btn-primary" id="simplyin-pay-button" disabled>
                                ${$t('Pay')} ${config.amount ? config.currency + ' ' + config.amount : ''}
                            </button>
                        </div>
                    </div>
                </div>
            `;

            element.html(html);

            // Bind event handlers
            this.bindPaymentMethodEvents();

            // Bind close button
            $('#simplyin-modal-close').on('click', function () {
                element.modal('closeModal');
            });
        },

        /**
         * Render saved cards HTML
         * @param {Array} savedCards - Array of saved cards
         * @returns {string}
         */
        renderSavedCardsHtml: function (savedCards) {
            if (!savedCards || savedCards.length === 0) {
                return '';
            }

            var html = '<div class="simplyin-saved-cards-section">';
            html += '<div class="simplyin-section-title">' + $t('Saved Cards') + '</div>';

            savedCards.forEach(function (card, index) {
                var cardIcon = ccIframeManager.getCardBrandIcon(card.organization || 'visa');
                var isFirst = index === 0;

                html += `
                    <div class="simplyin-payment-option-item simplyin-saved-card ${isFirst ? 'selected' : ''}">
                        <label>
                            <input type="radio" name="simplyin-payment-option" 
                                   value="${card.paymentMethodId || card.id}"
                                   data-payment-type="saved_card"
                                   data-last-digits="${card.last4digits || ''}"
                                   data-card-provider="${card.organization || ''}"
                                   ${isFirst ? 'checked' : ''}>
                            <span class="simplyin-card-info">
                                <img src="${cardIcon}" alt="${card.organization}" class="simplyin-card-icon">
                                <span class="simplyin-card-number">**** **** **** ${card.last4digits || '****'}</span>
                            </span>
                        </label>
                    </div>
                `;
            });

            html += '</div>';
            return html;
        },

        /**
         * Render add new card HTML
         * @param {string} iframeUrl - CCIframe library URL
         * @param {string} integratorId - Integrator ID
         * @returns {string}
         */
        renderAddNewCardHtml: function (iframeUrl, integratorId) {
            var hasSavedCards = this.paymentConfig && this.paymentConfig.savedCards && this.paymentConfig.savedCards.length > 0;

            return `
                <div class="simplyin-add-card-section">
                    <div class="simplyin-payment-option-item" id="simplyin-add-card-payment-method">
                        <label class="simplyin-add-card-label">
                            <input type="radio" name="simplyin-payment-option" 
                                   value="add_card"
                                   data-payment-type="add_card"
                                   data-iframe-url="${iframeUrl}"
                                   data-integrator-id="${integratorId}"
                                   data-toggle-add-card="true"
                                   ${!hasSavedCards ? 'checked' : ''}>
                            <span>${$t('Add New Card')}</span>
                        </label>
                    </div>
                    
                    <div id="simplyin-add-card-iframe-container" class="simplyin-card-form-container" style="display: none;">
                        <div class="simplyin-iframe-wrapper">
                            <div id="simplyin-iframe-loading" class="simplyin-loading-spinner" style="display: none;">
                                <div class="simplyin-spinner"></div>
                            </div>
                            <form id="simplyin-card-data-form">
                                <div class="simplyin-form-group">
                                    <label>${$t('Card Number')}</label>
                                    <div id="simplyin-card-number" class="simplyin-card-field"></div>
                                </div>
                                <div class="simplyin-form-row">
                                    <div class="simplyin-form-group">
                                        <label>${$t('Expiry Date')}</label>
                                        <div id="simplyin-expiry-date" class="simplyin-card-field"></div>
                                    </div>
                                    <div class="simplyin-form-group">
                                        <label>${$t('CVV')}</label>
                                        <div id="simplyin-cvv" class="simplyin-card-field"></div>
                                    </div>
                                </div>
                                <div class="simplyin-save-card-option">
                                    <label>
                                        <input type="checkbox" id="simplyin-save-card" name="saveCard">
                                        <span>${$t('Save card for future payments')}</span>
                                    </label>
                                </div>
                                <div class="simplyin-card-name-group" style="display: none;">
                                    <label>${$t('Card Name')}</label>
                                    <input type="text" id="simplyin-card-name" placeholder="${$t('My Card')}">
                                </div>
                            </form>
                            <div id="simplyin-card-error" class="simplyin-field-error" style="display: none;"></div>
                            <div id="simplyin-card-success" class="simplyin-card-success" style="display: none;">
                                <strong>✓</strong> ${$t('Card data is valid')}
                            </div>
                        </div>
                    </div>
                </div>
            `;
        },

        /**
         * Render BLIK option HTML
         * @returns {string}
         */
        renderBlikOptionHtml: function () {
            return `
                <div class="simplyin-blik-section">
                    <div class="simplyin-payment-option-item">
                        <label>
                            <input type="radio" name="simplyin-payment-option" 
                                   value="blik"
                                   data-payment-type="blik">
                            <span class="simplyin-blik-label">
                                <img src="${require.toUrl('Simplyin_Payment/images/blik.svg')}" alt="BLIK" class="simplyin-blik-icon">
                                <span>BLIK</span>
                            </span>
                        </label>
                    </div>
                    
                    <div id="simplyin-blik-container" class="simplyin-blik-field-container" style="display: none;">
                        <div class="simplyin-blik-input-wrapper">
                            <label>${$t('Enter 6-digit BLIK code')}</label>
                            <div class="simplyin-blik-inputs-grid">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="0" inputmode="numeric" pattern="[0-9]*">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="1" inputmode="numeric" pattern="[0-9]*">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="2" inputmode="numeric" pattern="[0-9]*">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="3" inputmode="numeric" pattern="[0-9]*">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="4" inputmode="numeric" pattern="[0-9]*">
                                <input type="text" class="simplyin-blik-digit-input" maxlength="1" data-index="5" inputmode="numeric" pattern="[0-9]*">
                            </div>
                            <div class="simplyin-blik-error" style="display: none;">${$t('Please enter a valid 6-digit BLIK code')}</div>
                        </div>
                    </div>
                </div>
            `;
        },

        /**
         * Bind payment method event handlers
         */
        bindPaymentMethodEvents: function () {
            var self = this;

            // Payment option change handler
            $(document).off('change', 'input[name="simplyin-payment-option"]').on('change', 'input[name="simplyin-payment-option"]', function () {
                self.handlePaymentMethodChange($(this));
            });

            // Save card checkbox handler
            $(document).off('change', '#simplyin-save-card').on('change', '#simplyin-save-card', function () {
                if ($(this).is(':checked')) {
                    $('.simplyin-card-name-group').fadeIn();
                } else {
                    $('.simplyin-card-name-group').fadeOut();
                }
            });

            // BLIK input handlers
            self.bindBlikInputHandlers();

            // Pay button handler
            $(document).off('click', '#simplyin-pay-button').on('click', '#simplyin-pay-button', function () {
                if (!$(this).prop('disabled')) {
                    self.submitPayment();
                }
            });

            // Trigger initial selection
            var selectedOption = $('input[name="simplyin-payment-option"]:checked');
            if (selectedOption.length) {
                self.handlePaymentMethodChange(selectedOption);
            }
        },

        /**
         * Handle payment method change
         * @param {jQuery} selectedOption - Selected radio button
         */
        handlePaymentMethodChange: function (selectedOption) {
            var self = this;
            var paymentType = selectedOption.data('payment-type');

            // Update selected state
            $('.simplyin-payment-option-item').removeClass('selected');
            selectedOption.closest('.simplyin-payment-option-item').addClass('selected');

            // Hide all payment-specific containers
            $('#simplyin-add-card-iframe-container').hide();
            $('#simplyin-blik-container').hide();

            // Show relevant container based on payment type
            switch (paymentType) {
                case 'add_card':
                    $('#simplyin-add-card-iframe-container').show();
                    this.initializeCCIframe();
                    break;

                case 'blik':
                    $('#simplyin-blik-container').show();
                    $('.simplyin-blik-digit-input').first().focus();
                    break;

                case 'saved_card':
                    // Enable pay button for saved cards
                    $('#simplyin-pay-button').prop('disabled', false);
                    break;
            }

            // Update pay button state
            this.updatePayButtonState();
        },

        /**
         * Initialize CCIframe for new card input
         */
        initializeCCIframe: function () {
            var self = this;
            var iframeUrl = this.paymentConfig.iframeUrl;
            var integratorId = this.paymentConfig.integratorId;

            if (!iframeUrl || !integratorId) {
                this.showPaymentError($t('Payment configuration error'));
                return;
            }

            // Show loading
            $('#simplyin-iframe-loading').show();

            // Load CCIframe library
            ccIframeManager.loadLibrary(iframeUrl).then(function () {
                // Initialize with integrator ID
                if (ccIframeManager.initialize(integratorId)) {
                    // Create input components
                    ccIframeManager.createInputComponents({
                        cardNumber: '#simplyin-card-number',
                        expiry: '#simplyin-expiry-date',
                        cvv: '#simplyin-cvv'
                    });

                    $('#simplyin-iframe-loading').hide();
                    $('#simplyin-card-data-form').show();
                    $('#simplyin-pay-button').prop('disabled', false);
                } else {
                    self.showPaymentError($t('Failed to initialize card form'));
                }
            }).catch(function (error) {
                $('#simplyin-iframe-loading').hide();
                self.showPaymentError(error.message || $t('Failed to load card form'));
            });
        },

        /**
         * Bind BLIK input handlers
         */
        bindBlikInputHandlers: function () {
            var self = this;

            // Input handler
            $(document).off('input', '.simplyin-blik-digit-input').on('input', '.simplyin-blik-digit-input', function () {
                var $input = $(this);
                var value = $input.val().replace(/\D/g, '');
                $input.val(value.substring(0, 1));

                if (value && $input.data('index') < 5) {
                    $input.next('.simplyin-blik-digit-input').focus();
                }

                self.validateBlikCode();
            });

            // Keydown handler for backspace
            $(document).off('keydown', '.simplyin-blik-digit-input').on('keydown', '.simplyin-blik-digit-input', function (e) {
                if (e.key === 'Backspace' && !$(this).val() && $(this).data('index') > 0) {
                    $(this).prev('.simplyin-blik-digit-input').focus();
                }
            });

            // Paste handler
            $(document).off('paste', '.simplyin-blik-digit-input').on('paste', '.simplyin-blik-digit-input', function (e) {
                e.preventDefault();
                var paste = (e.originalEvent.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
                var inputs = $('.simplyin-blik-digit-input');

                paste.split('').slice(0, 6).forEach(function (digit, i) {
                    $(inputs[i]).val(digit);
                });

                self.validateBlikCode();
            });
        },

        /**
         * Validate BLIK code
         * @returns {boolean}
         */
        validateBlikCode: function () {
            var code = this.getBlikCode();
            var isValid = /^[0-9]{6}$/.test(code);

            if (isValid) {
                $('.simplyin-blik-digit-input').removeClass('error').addClass('valid');
                $('.simplyin-blik-error').hide();
                $('#simplyin-pay-button').prop('disabled', false);
            } else {
                $('.simplyin-blik-digit-input').removeClass('valid');
                if (code.length === 6) {
                    $('.simplyin-blik-digit-input').addClass('error');
                    $('.simplyin-blik-error').show();
                }
                $('#simplyin-pay-button').prop('disabled', true);
            }

            return isValid;
        },

        /**
         * Get BLIK code from inputs
         * @returns {string}
         */
        getBlikCode: function () {
            return $('.simplyin-blik-digit-input').map(function () {
                return $(this).val();
            }).get().join('');
        },

        /**
         * Update pay button state
         */
        updatePayButtonState: function () {
            var selectedOption = $('input[name="simplyin-payment-option"]:checked');
            var paymentType = selectedOption.data('payment-type');
            var isEnabled = false;

            switch (paymentType) {
                case 'saved_card':
                    isEnabled = true;
                    break;
                case 'add_card':
                    isEnabled = ccIframeManager.isReady();
                    break;
                case 'blik':
                    isEnabled = this.validateBlikCode();
                    break;
            }

            $('#simplyin-pay-button').prop('disabled', !isEnabled);
        },

        /**
         * Submit payment
         */
        submitPayment: function () {
            var self = this;
            var selectedOption = $('input[name="simplyin-payment-option"]:checked');
            var paymentType = selectedOption.data('payment-type');

            // Show loading state
            this.showPaymentLoading(true);

            switch (paymentType) {
                case 'add_card':
                    this.submitNewCardPayment(selectedOption);
                    break;
                case 'saved_card':
                    this.submitSavedCardPayment(selectedOption);
                    break;
                case 'blik':
                    this.submitBlikPayment();
                    break;
                default:
                    this.showPaymentError($t('Please select a payment method'));
                    this.showPaymentLoading(false);
            }
        },

        /**
         * Submit new card payment
         * @param {jQuery} selectedOption - Selected option element
         */
        submitNewCardPayment: function (selectedOption) {
            var self = this;

            // Create token from CCIframe
            ccIframeManager.createToken().then(function (tokenData) {
                // Submit payment with token
                self.processPayment({
                    paymentType: 'add_card',
                    oneTimeToken: tokenData.oneTimeToken,
                    last4digits: tokenData.last4digits,
                    organization: tokenData.organization,
                    first6digits: tokenData.first6digits,
                    saveCard: $('#simplyin-save-card').is(':checked'),
                    cardName: $('#simplyin-card-name').val()
                });
            }).catch(function (error) {
                self.showPaymentError(error.message || $t('Card validation failed'));
                self.showPaymentLoading(false);
            });
        },

        /**
         * Submit saved card payment
         * @param {jQuery} selectedOption - Selected option element
         */
        submitSavedCardPayment: function (selectedOption) {
            this.processPayment({
                paymentType: 'saved_card',
                paymentMethodId: selectedOption.val(),
                last4digits: selectedOption.data('last-digits'),
                cardProvider: selectedOption.data('card-provider')
            });
        },

        /**
         * Submit BLIK payment
         */
        submitBlikPayment: function () {
            var blikCode = this.getBlikCode();

            if (!this.validateBlikCode()) {
                this.showPaymentError($t('Please enter a valid 6-digit BLIK code'));
                this.showPaymentLoading(false);
                return;
            }

            this.processPayment({
                paymentType: 'blik',
                blikCode: blikCode
            });
        },

        /**
         * Process payment via API
         * @param {Object} paymentData - Payment data
         */
        processPayment: function (paymentData) {
            var self = this;

            var requestData = $.extend({
                authToken: this.paymentConfig.authToken,
                orderId: this.paymentConfig.orderId,
                amount: this.paymentConfig.amount,
                currency: this.paymentConfig.currency
            }, paymentData);

            ajaxClient.postSilent('simplyin/api/processPayment', requestData).done(function (response) {
                if (response.success) {
                    self.handlePaymentResponse(response);
                } else {
                    var errorMsg = response.error ? response.error.message : $t('Payment failed');
                    self.showPaymentError(errorMsg);
                    self.showPaymentLoading(false);
                }
            }).fail(function () {
                self.showPaymentError($t('Network error. Please try again.'));
                self.showPaymentLoading(false);
            });
        },

        /**
         * Handle payment response
         * @param {Object} response - Payment API response
         */
        handlePaymentResponse: function (response) {
            var self = this;

            if (response.redirectUrl) {
                // 3D Secure required
                threeDSecureHandler.handleRedirect(
                    response.redirectUrl,
                    response.redirectIframeAllowed,
                    {
                        paymentId: response.paymentId,
                        authToken: this.paymentConfig.authToken,
                        callbacks: {
                            onComplete: function (result) {
                                self.onPaymentComplete(result);
                            },
                            onCancel: function (error) {
                                self.showPaymentError($t('Payment was cancelled'));
                                self.showPaymentLoading(false);
                            },
                            onError: function (error) {
                                self.showPaymentError(error.message || $t('Payment verification failed'));
                                self.showPaymentLoading(false);
                            }
                        }
                    }
                ).catch(function (error) {
                    console.error('SimplyIN: 3D Secure handler error', error);
                    self.showPaymentError(error.message || $t('3D Secure verification failed'));
                    self.showPaymentLoading(false);
                });
            } else if (response.status === 'COMPLETED' || response.status === 'PAID') {
                // Payment completed without 3D Secure
                this.onPaymentComplete(response);
            } else {
                // Start polling for status
                paymentStatusPoller.startPolling(response.paymentId, this.paymentConfig.authToken, {
                    onCompleted: function (result) {
                        self.onPaymentComplete(result);
                    },
                    onFailed: function (error) {
                        self.showPaymentError(error.message || $t('Payment was declined'));
                        self.showPaymentLoading(false);
                    },
                    onTimeout: function () {
                        self.showPaymentError($t('Payment verification timed out'));
                        self.showPaymentLoading(false);
                    }
                }).catch(function (error) {
                    self.showPaymentError(error.message || $t('Payment verification failed'));
                    self.showPaymentLoading(false);
                });
            }
        },

        /**
         * Handle payment completion
         * @param {Object} result - Payment result
         */
        onPaymentComplete: function (result) {
            var self = this;

            // Show processing message
            this.showPaymentLoading(true);
            $('#simplyin-payment-status').html($t('Creating order...')).show();

            // Create Magento order
            this.createMagentoOrder(result).then(function(orderResponse) {
                self.showPaymentLoading(false);
                modalElement.modal('closeModal');

                // Clear only payment-related session data, NOT the auth token
                // Auth token should persist for 1 hour to allow subsequent orders without re-login
                sessionStorageManager.clearPaymentState();
                sessionStorageManager.clearAllPaymentData();

                // Call success callback if provided
                if (self.paymentConfig.onSuccess) {
                    self.paymentConfig.onSuccess(result);
                }

                // Redirect to success page
                var successUrl = window.checkoutConfig && window.checkoutConfig.defaultSuccessPageUrl
                    ? window.checkoutConfig.defaultSuccessPageUrl
                    : '/checkout/onepage/success';

                window.location.href = successUrl;

            }).catch(function(error) {
                console.error('SimplyIN: Order creation failed', error);
                self.showPaymentError(error.message || $t('Order creation failed. Please contact support.'));
                self.showPaymentLoading(false);
            });
        },

        /**
         * Create Magento order after successful payment
         * @param {Object} paymentResult - Payment result from API
         * @returns {Promise}
         */
        createMagentoOrder: function (paymentResult) {
            var self = this;

            return new Promise(function(resolve, reject) {
                // Get quote ID from checkout
                var quoteId = window.checkoutConfig && window.checkoutConfig.quoteData
                    ? window.checkoutConfig.quoteData.entity_id
                    : null;

                // For guest checkout, use masked quote ID
                if (!quoteId && window.checkoutConfig && window.checkoutConfig.quoteItemData) {
                    quoteId = window.checkoutConfig.quoteItemData[0]
                        ? window.checkoutConfig.quoteItemData[0].quote_id
                        : null;
                }

                // Try to get from checkout data
                if (!quoteId) {
                    quoteId = require('Magento_Checkout/js/model/quote').getQuoteId();
                }

                if (!quoteId) {
                    reject({ message: $t('Quote ID not found') });
                    return;
                }

                var orderData = {
                    quoteId: quoteId,
                    authToken: self.paymentConfig.authToken,
                    simplyinOrderId: self.paymentConfig.orderId,
                    simplyinPaymentId: paymentResult.paymentId || '',
                    providerPaymentId: paymentResult.providerPaymentId || '',
                    paymentStatus: paymentResult.status || 'COMPLETED',
                    paymentType: paymentResult.paymentType || '',
                    cardLast4: paymentResult.last4digits || '',
                    cardBrand: paymentResult.organization || ''
                };

                ajaxClient.postSilent('simplyin/api/placeMagentoOrder', orderData).done(function (response) {
                    if (response.success) {
                        resolve(response);
                    } else {
                        reject({ message: response.message || $t('Failed to create order') });
                    }
                }).fail(function (response) {
                    reject({ message: response.message || $t('Network error while creating order') });
                });
            });
        },

        /**
         * Show payment error
         * @param {string} message - Error message
         */
        showPaymentError: function (message) {
            var statusEl = $('#simplyin-payment-status');
            statusEl.removeClass('success').addClass('error');
            statusEl.html('<span class="error-icon">✕</span> ' + message);
            statusEl.show();
        },

        /**
         * Show/hide payment loading state
         * @param {boolean} isLoading - Loading state
         */
        showPaymentLoading: function (isLoading) {
            var payButton = $('#simplyin-pay-button');

            if (isLoading) {
                payButton.prop('disabled', true);
                payButton.html('<span class="simplyin-spinner-small"></span> ' + $t('Processing...'));
            } else {
                payButton.prop('disabled', false);
                var amount = this.paymentConfig.amount;
                var currency = this.paymentConfig.currency;
                payButton.html($t('Pay') + (amount ? ' ' + currency + ' ' + amount : ''));
            }
        }
    };
});