define([
    'uiRegistry'
], function (registry) {
    'use strict';

    /**
     * Restore previously saved shipping field values into checkoutProvider
     * so they survive page refreshes.
     */
    function restoreSavedShippingFields() {
        var config = window.checkoutConfig && window.checkoutConfig.portalpeopleShippingFields;
        if (!config) {
            return;
        }

        var savedDate    = config.savedDate    || '';
        var savedMessage = config.savedMessage || '';
        var savedW3w     = config.savedW3w     || '';

        if (!savedDate && !savedMessage && !savedW3w) {
            return;
        }

        var checkoutProvider = registry.get('checkoutProvider');
        if (!checkoutProvider) {
            return;
        }

        var existing = checkoutProvider.get('shippingFields') || {};

        if (savedDate && !existing.shipping_date) {
            checkoutProvider.set('shippingFields.shipping_date', savedDate);
            console.log('♻️ SHIPPING FIELDS: Restored shipping_date in provider:', savedDate);

            // Also directly update the date UI component so the picker shows the value visually
            registry.async('checkout.steps.shipping-step.shippingAddress.portalpeople-shipping-fields.shipping-fields-fieldset.shipping-date')(function (dateComponent) {
                if (!dateComponent.value()) {
                    dateComponent.value(savedDate);
                    console.log('♻️ SHIPPING FIELDS: Restored shipping_date on date component:', savedDate);
                }
            });
        }
        if (savedMessage && !existing.shipping_message) {
            checkoutProvider.set('shippingFields.shipping_message', savedMessage);
        }
        if (savedW3w && !existing.shipping_w3w) {
            checkoutProvider.set('shippingFields.shipping_w3w', savedW3w);
        }
    }

    return function (targetComponent) {
        return targetComponent.extend({
            initialize: function () {
                this._super();
                var self = this;
                // Restore saved values after KO finishes rendering
                setTimeout(function () {
                    restoreSavedShippingFields();
                }, 300);
                return self;
            }
        });
    };
});
