define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage'
], function ($, wrapper, quote, urlBuilder, storage) {
    '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 - Checking for shipping fields');
            
            // Get shipping fields from window storage (set by shipping mixin)
            if (window.shippingFieldsData) {
                var shippingDate = window.shippingFieldsData.shipping_date;
                var shippingMessage = window.shippingFieldsData.shipping_message;
                
                if (shippingDate || shippingMessage) {
                    console.log('📤 Sending shipping fields with quote ID:', quote.getQuoteId());
                    
                    // Save via URL builder (avoids hardcoded store code)
                    var serviceUrl = urlBuilder.createUrl('/V1/carts/mine/save-shipping-fields', {});
                    storage.post(
                        serviceUrl,
                        JSON.stringify({
                            shippingDate: shippingDate || '',
                            shippingMessage: shippingMessage || ''
                        })
                    );
                    console.log('✅ Shipping fields saved before order placement');
                }
            }

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