/**
 * Set Payment Information Mixin
 * Adds SimplyIN account creation data to payment information
 */
define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Simplyin_Payment/js/model/session-storage-manager'
], function ($, wrapper, quote, sessionStorageManager) {
    'use strict';

    return function (setPaymentInformationAction) {
        return wrapper.wrap(setPaymentInformationAction, function (originalAction, messageContainer, paymentData) {
            // Skip for SimplyIN payment - it handles its own data
            var selectedPaymentMethod = quote.paymentMethod();
            if (selectedPaymentMethod && selectedPaymentMethod.method === 'simplyin_payment') {
                return originalAction(messageContainer, paymentData);
            }
            
            // 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()) {
                
                var phone = simplyinSection.phoneNumber();
                
                if (phone && phone.trim() !== '') {
                    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(messageContainer, paymentData);
        });
    };
});
