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

    console.log('🔧 SHIPPING FIELDS: Place Order Mixin LOADED!');

    return function (targetModule) {
        return wrapper.wrap(targetModule, function (originalAction, paymentData, messageContainer) {
            console.log('💳 SHIPPING FIELDS: Place Order - Reading shipping fields from checkoutProvider');
            
            var shippingDate = null;
            var shippingMessage = null;

            // Read directly from checkoutProvider at order placement time (user has filled fields by now)
            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('📅 shipping_date at order placement:', shippingDate);
                    console.log('📝 shipping_message at order placement:', shippingMessage);
                } else {
                    console.log('⚠️ No shippingFields in checkoutProvider at order placement');
                }
            }

            // Fallback to window data if checkoutProvider was empty
            if (!shippingDate && !shippingMessage && window.shippingFieldsData) {
                shippingDate = window.shippingFieldsData.shipping_date;
                shippingMessage = window.shippingFieldsData.shipping_message;
                console.log('⚠️ Using fallback window.shippingFieldsData');
            }

            if (shippingDate || shippingMessage) {
                console.log('📤 Saving shipping fields before placing order');
                $.ajax({
                    url: '/rest/default/V1/carts/mine/save-shipping-fields',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        shippingDate: shippingDate || '',
                        shippingMessage: shippingMessage || ''
                    }),
                    async: false,
                    success: function () {
                        console.log('✅ Shipping fields saved before order placement');
                    },
                    error: function (xhr) {
                        console.warn('⚠️ Could not save shipping fields:', xhr.responseText);
                    }
                });
            } else {
                console.log('ℹ️ No shipping fields to save at order placement');
            }

            return originalAction(paymentData, messageContainer);
        });
    };
});
