define([
    'jquery',
    'mage/storage',
    'Magento_Checkout/js/model/quote',
    'Magento_Customer/js/customer-data'
], function ($, storage, quote, customerData) {
    'use strict';

    /**
     * Sync shipping method to SimplyIN
     */
    function syncShippingMethodToSimplyIN(authToken, shippingMethod) {
        var serviceUrl = '/simplyin/api/updateShippingMethod';

        var payload = {
            authToken: authToken,
            shippingMethod: shippingMethod
        };

        storage.post(
            serviceUrl,
            JSON.stringify(payload),
            false
        ).done(function (response) {
            if (!response.success) {
                console.warn('Failed to sync shipping method to SimplyIN:', response.message);
            }
        }).fail(function (error) {
            console.error('Error syncing shipping method to SimplyIN:', error);
        });
    }

    return function (target) {
        // Store the original saveShippingInformation function
        var originalSaveShippingInformation = target.saveShippingInformation;

        // Wrap the saveShippingInformation method
        target.saveShippingInformation = function () {
            // Call the original function
            var result = originalSaveShippingInformation.apply(this, arguments);

            // Get selected shipping method
            var shippingMethod = quote.shippingMethod();

            if (shippingMethod) {
                // Check if user is authenticated with SimplyIN
                var simplyinData = customerData.get('simplyin-data')();

                if (simplyinData && simplyinData.authToken) {
                    // Prepare shipping method data
                    var shippingMethodData = {
                        carrier_code: shippingMethod.carrier_code,
                        method_code: shippingMethod.method_code,
                        carrier_title: shippingMethod.carrier_title,
                        method_title: shippingMethod.method_title,
                        amount: shippingMethod.amount,
                        base_amount: shippingMethod.base_amount || shippingMethod.amount
                    };

                    // Sync to SimplyIN
                    syncShippingMethodToSimplyIN(simplyinData.authToken, shippingMethodData);
                }
            }

            return result;
        };

        return target;
    };
});
