define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote'
], function ($, wrapper, quote) {
    'use strict';

    console.log('🔧 SHIPPING FIELDS: Default Processor Mixin LOADED!');

    return function (target) {
        target.saveShippingInformation = wrapper.wrap(
            target.saveShippingInformation,
            function (originalAction) {
                console.log('🚢 Default Processor: Preparing to save');
                
                // Get shipping address from quote
                var shippingAddress = quote.shippingAddress();
                
                // Get field values from DOM
                var shippingDate = null;
                var shippingW3w = null;
                var shippingMessage = null;
                
                $('input[name="shipping_date"], input[name="shipping_w3w"], textarea[name="shipping_message"]').each(function() {
                    var name = $(this).attr('name');
                    var value = $(this).val();
                    
                    if (name === 'shipping_date' && value) {
                        shippingDate = value;
                    }
                    if (name === 'shipping_message' && value) {
                        shippingMessage = value;
                    }
                    if (name === 'shipping_w3w' && value) {
                        shippingW3w = value;
                    }
                });
                
                // Add to shipping address custom attributes
                if ((shippingDate || shippingW3w || shippingMessage) && shippingAddress) {
                    if (!shippingAddress.customAttributes) {
                        shippingAddress.customAttributes = {};
                    }
                    
                    if (shippingDate) {
                        shippingAddress.customAttributes.shipping_date = shippingDate;
                        console.log('✅ Added shipping_date to customAttributes:', shippingDate);
                    }
                    
                    if (shippingMessage) {
                        shippingAddress.customAttributes.shipping_message = shippingMessage;
                        console.log('✅ Added shipping_message to customAttributes:', shippingMessage);
                    }

                    if (shippingW3w) {
                        shippingAddress.customAttributes.shipping_w3w = shippingW3w;
                        console.log('✅ Added shipping_w3w to customAttributes:', shippingW3w);
                    }
                }
                
                return originalAction();
            }
        );
        
        return target;
    };
});
