/**
 * Place Order Mixin
 * Validates SimplyIN account creation data and adds it to all payment methods
 */
define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Magento_Ui/js/model/messageList',
    'mage/translate',
    'Simplyin_Payment/js/model/session-storage-manager'
], function ($, wrapper, quote, messageList, $t, sessionStorageManager) {
    'use strict';

    return function (placeOrderAction) {
        return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, messageContainer) {
            // Skip validation for SimplyIN payment - it handles its own validation
            var selectedPaymentMethod = quote.paymentMethod();
            if (selectedPaymentMethod && selectedPaymentMethod.method === 'simplyin_payment') {
                return originalAction(paymentData, messageContainer);
            }
            
            // Get the global SimplyIN account section component
            var simplyinSection = window.simplyinAccountSection;
            
            // Check if component exists and user opted in for SimplyIN account creation
            if (simplyinSection && 
                typeof simplyinSection.shouldShowNewAccountSection === 'function' &&
                simplyinSection.shouldShowNewAccountSection() && 
                simplyinSection.createSimplyInAccount()) {
                
                // Validate phone number
                var phone = simplyinSection.phoneNumber();
                
                if (!phone || phone.trim() === '') {
                    // Set error on the component
                    if (typeof simplyinSection.phoneNumberError === 'function') {
                        simplyinSection.phoneNumberError($t('The phone number is required.'));
                    }
                    messageList.addErrorMessage({
                        message: $t('The phone number is required for SimplyIN account creation.')
                    });
                    return $.Deferred().reject().promise();
                }
                
                var phoneRegex = /^\d{6,15}$/;
                if (!phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''))) {
                    // Set error on the component
                    if (typeof simplyinSection.phoneNumberError === 'function') {
                        simplyinSection.phoneNumberError($t('Please enter a valid phone number.'));
                    }
                    messageList.addErrorMessage({
                        message: $t('Please enter a valid phone number.')
                    });
                    return $.Deferred().reject().promise();
                }
                
                // Clear any previous error
                if (typeof simplyinSection.phoneNumberError === 'function') {
                    simplyinSection.phoneNumberError('');
                }
                
                // Store account data for the observer
                var fullPhone = simplyinSection.selectedCountryCode() + phone.trim();
                var email = quote.guestEmail || (window.customerData && window.customerData.email);
                var billingAddress = quote.billingAddress();
                
                var accountData = {
                    email: email,
                    firstName: billingAddress ? billingAddress.firstname : 'Customer',
                    lastName: billingAddress ? billingAddress.lastname : 'User',
                    phone: fullPhone
                };
                
                sessionStorageManager.setItem('simplyin_pending_account', JSON.stringify(accountData));
                
                // Add SimplyIN account creation data to payment additional data
                if (!paymentData.additional_data) {
                    paymentData.additional_data = {};
                }
                
                paymentData.additional_data.simplyin_create_account = true;
                paymentData.additional_data.simplyin_phone_number = fullPhone;
            }
            
            return originalAction(paymentData, messageContainer);
        });
    };
});
