require(['jquery', 'mage/cookies'], function($){
    $(document).ready(function () {
        if ($.cookie('customer-registered')) {
            dataLayer.push({'event': 'completed_account_creation'});
            // Delete the 'customer-registered' cookie
            $.removeCookie('customer-registered', { path: '/' });
        }

        if($.cookie('wishlist-add')){
            pushProductDataToDataLayerFromCookie("wishlist-add", "added_item_wishlist");
            // Delete the 'wishlist-add' cookie
            $.removeCookie('wishlist-add', { path: '/' });
        }

        if($.cookie('wishlist-remove')){
            pushProductDataToDataLayerFromCookie("wishlist-remove", "removed_item_wishlist");
            // Delete the 'wishlist-remove' cookie
            $.removeCookie('wishlist-remove', { path: '/' });
        }

        if($.cookie('customer-login')){
            pushCustomerDataToDataLayerFromCookie("customer-login", "customer_login");
            // Delete the 'customer-login' cookie
            $.removeCookie('customer-login', { path: '/' });
        }

        if($.cookie('customer-logout')){
            pushCustomerDataToDataLayerFromCookie("customer-logout", "customer_logout");
            // Delete the 'customer-logout' cookie
            $.removeCookie('customer-logout', { path: '/' });
        }
    });

    function pushProductDataToDataLayerFromCookie(cookieName, event) {
        let data = JSON.parse($.cookie(cookieName));
        dataLayer.push({
            "event": event,
            "ecommerce": {
                "product_name": data["product_name"],
                "price": data["price"],
                "product_category": data["product_category"],
                "product_image": data["product_image"],
                "product_url": data["product_url"]
            }
        });
    }

    function pushCustomerDataToDataLayerFromCookie(cookieName, event) {
        let data = JSON.parse($.cookie(cookieName));

        const commonData = {
            "event": event,
            "ecommerce": {
                "customerId": data["customerId"],
            }
        };

        if (cookieName === 'customer-login') {
            commonData.ecommerce.firstname = data["firstname"];
            commonData.ecommerce.vip_delivery = data["vip_delivery"];
            commonData.ecommerce.birthdate = data["birthdate"];
        }

        dataLayer.push(commonData);
    }
});
