define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage',
    'uiRegistry'
], function ($, wrapper, quote, urlBuilder, storage, registry) {
    'use strict';

    console.log('🔧 SHIPPING FIELDS: Set Shipping Information Mixin LOADED!');

    return function (targetModule) {
        return wrapper.wrap(targetModule, function (originalAction) {
            console.log('🚢 SHIPPING FIELDS: Mixin executing');
            
            try {
                var shippingDate = null;
                var shippingMessage = null;

                // Read values from Magento checkoutProvider (UI component data)
                var checkoutProvider = registry.get('checkoutProvider');
                if (checkoutProvider) {
                    var shippingFields = checkoutProvider.get('shippingFields');
                    if (shippingFields) {
                        shippingDate = shippingFields.shipping_date || null;
                        shippingMessage = shippingFields.shipping_message || null;
                        console.log('📅 checkoutProvider shipping_date:', shippingDate);
                        console.log('📝 checkoutProvider shipping_message:', shippingMessage);
                    } else {
                        console.log('⚠️ No shippingFields in checkoutProvider');
                    }
                } else {
                    console.log('⚠️ checkoutProvider not found in registry');
                }

                // Store for place-order-mixin fallback
                window.shippingFieldsData = {
                    shipping_date: shippingDate,
                    shipping_message: shippingMessage
                };
                console.log('✅ Stored shipping fields data:', window.shippingFieldsData);

                // Save to backend immediately when shipping method is set
                if (shippingDate || shippingMessage) {
                    var serviceUrl = urlBuilder.createUrl('/V1/carts/mine/save-shipping-fields', {});
                    storage.post(
                        serviceUrl,
                        JSON.stringify({
                            shippingDate: shippingDate || '',
                            shippingMessage: shippingMessage || ''
                        })
                    ).done(function() {
                        console.log('✅ Shipping fields saved on set-shipping-information');
                    }).fail(function(xhr) {
                        console.warn('⚠️ Could not save shipping fields at this step:', xhr.responseText);
                    });
                }
                
            } catch (error) {
                console.error('❌ Error in shipping fields mixin:', error);
            }

            return originalAction();
        });
    };
});
