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());
                    
                    // Send directly to our custom endpoint
                    $.ajax({
                        url: '/rest/default/V1/carts/mine/save-shipping-fields',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            shippingDate: shippingDate,
                            shippingMessage: shippingMessage
                        }),
                        async: false, // Wait for this to complete before placing order
                        success: function(response) {
                            console.log('✅ Shipping fields saved before order placement');
                        },
                        error: function(xhr) {
                            console.warn('⚠️ Could not save shipping fields (will try in plugin):', xhr.responseText);
                        }
                    });
                }
            }

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