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');
            }

            // Log if date is missing at this point (should have been caught on shipping step)
            if (!shippingDate) {
                console.warn('⚠️ SHIPPING FIELDS: No shipping date at order placement - was shipping step validation bypassed?');
            }

            if (shippingDate || shippingMessage) {
                console.log('📤 Saving shipping fields before placing order');
                var deferred = $.Deferred();
                $.ajax({
                    url: '/rest/default/V1/carts/mine/save-shipping-fields',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        shippingDate: shippingDate || '',
                        shippingMessage: shippingMessage || ''
                    })
                }).done(function () {
                    console.log('✅ Shipping fields saved before order placement');
                }).fail(function (xhr) {
                    console.warn('⚠️ Could not save shipping fields:', xhr.responseText);
                }).always(function () {
                    originalAction(paymentData, messageContainer)
                        .done(deferred.resolve)
                        .fail(deferred.reject);
                });
                return deferred.promise();
            }

            console.log('ℹ️ No shipping fields to save at order placement');
            return originalAction(paymentData, messageContainer);
        });
    };
});
