define([
    'jquery',
    'mage/utils/wrapper',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/url-builder',
    'mage/storage',
    'uiRegistry',
    'Magento_Checkout/js/model/full-screen-loader'
], function ($, wrapper, quote, urlBuilder, storage, registry, fullScreenLoader) {
    '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');

            var shippingDate = null;
            var shippingW3w = null;
            var shippingMessage = null;

            try {
                // 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;
                        shippingW3w = shippingFields.shipping_w3w || null;
                        shippingMessage = shippingFields.shipping_message || null;
                        console.log('📅 checkoutProvider shipping_date:', shippingDate);
                        console.log('📍 checkoutProvider shipping_w3w:', shippingW3w);
                        console.log('📝 checkoutProvider shipping_message:', shippingMessage);
                    } else {
                        console.log('⚠️ No shippingFields in checkoutProvider');
                    }
                } else {
                    console.log('⚠️ checkoutProvider not found in registry');
                }
            } catch (error) {
                console.error('❌ Error reading shipping fields:', error);
            }

            // Block progression to payment step if date is not set
            if (!shippingDate) {
                console.warn('❌ SHIPPING FIELDS: Preferred Shipping Date is required.');
                fullScreenLoader.stopLoader();

                // Show inline error below the date field
                var $dateField = $('[name="shippingFields[shipping_date]"], #shipping_date, [data-bind*="shipping_date"]').closest('.field');
                if (!$dateField.length) {
                    $dateField = $('.fieldset.shipping-information').find('.field').first();
                }
                $('#shipping-date-error').remove();
                $dateField.after(
                    $('<div>', {
                        id: 'shipping-date-error',
                        class: 'message message-error error',
                        css: { marginTop: '5px', marginBottom: '10px' }
                    }).append(
                        $('<div>').text($.mage.__('Please select a Preferred Shipping Date to continue.'))
                    )
                );
                $('html, body').animate({ scrollTop: $dateField.offset() ? $dateField.offset().top - 100 : 0 }, 400);

                return $.Deferred().reject().promise();
            }

            // Clear any previous inline error
            $('#shipping-date-error').remove();

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

            // Save to backend immediately when shipping method is set
            var serviceUrl = urlBuilder.createUrl('/carts/mine/save-shipping-fields', {});
            storage.post(
                serviceUrl,
                JSON.stringify({
                    shippingDate: shippingDate || '',
                    shippingW3w: shippingW3w || '',
                    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);
            });

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