define([
    'jquery',
    'underscore',
    'Magento_Customer/js/customer-data',
    'jquery/ui',
    'jquery/jquery-storageapi'
], function ($, _, customerData) {
    $.widget('mage.productItems', {
        _create: function () {
            var self = this;
            self.wishlistBtn = self.element.find('.towishlist');
            self.wishlistPopup = self.element.find('.pop-up-box');

            /* On click wishlist button */
            self.wishlistBtn.on('click', function (event) {
                if (self._isUserLoggedIn()) {
                    /* Check if user logged in - Add to wishlist */
                    event.preventDefault();
                    event.stopImmediatePropagation();
                    self._toggleWishList(this);
                }
            });

            /* Listen for trigger for closing wish list. This is the *only* code that hides the popup */
            $(window).on('close-wishlist', function () {
                $('.wishlist-container').children().fadeOut(200).filter('.wishlist').remove();
                $('body').off('click.snb.wishlist.close');
            });

            self._checkWishListActive();
        },

        _toggleWishList: function (button) {
            var self = this;
            var remove = false;
            var wishListData = $(button).data('post');
            var formKey = $("input[name=form_key]").val();
            wishListData.data.form_key = formKey;
            window.currentProduct = $(self.element).parents('.product-item-information').find('.product-item-link').text().trim();
            var whishlistId = jQuery(self.element).find('.towishlist').attr('id');
            if (jQuery('.wl-' + whishlistId).hasClass('wishlisted') == true) {
                wishListData.action = window.location.origin+'/wishlist/index/remove/';
                var wishlistItemId = null;
                var wishlistCollection = JSON.parse(localStorage.getItem('mage-cache-storage')).wishlist;
                _.each(wishlistCollection.items, function(item) {
                    if (item.product_id == wishListData.data.product) {
                        wishlistItemId = item.wishlist_item_id
                    }
                });
                wishListData.data.item = wishlistItemId;
                remove = true;
            } else {
                wishListData.action = window.location.origin+'/wishlist/index/add/';
            }

            let $body = $('body');
            $body.trigger('processStart');

            $.post(wishListData.action, wishListData.data)
                .done(function (response) {
                    const isRemove = wishListData.action.includes("remove");

                    if (response && response.result) {
                        self.element
                            .addClass('added-to-wishlist')
                            .find('.towishlist')
                            .toggleClass('wishlisted', !isRemove);

                        let msg = isRemove
                            ? $.mage.__(' has been deleted from your Wish List.')
                            : $.mage.__(' has been added to your Wish List.');

                        let wishlistHtmlMsg = '<div class="message-success success message show"> ' + window.currentProduct + msg + '</div>';
                        $('.page.messages').html(wishlistHtmlMsg);

                        setTimeout(function () {
                            let wishlistStorage = JSON.parse(localStorage.getItem('mage-cache-storage') || '{}').wishlist;
                            if (wishlistStorage && wishlistStorage.counter !== undefined) {
                                $('.link.wishlist .counter.qty').text(wishlistStorage.counter);
                            }
                        }, 3000);

                        let storage = $.initNamespaceStorage('mage-cache-storage').localStorage;
                        storage.remove('messages');
                        $.cookieStorage.set('mage-messages', '');
                        $('.link.wishlist a').removeClass('empty');
                    } else {
                        showWishlistError(response.message || 'Failed to add product to wishlist.');
                    }

                    window.currentProduct = undefined;
                })
                .fail(function (jqXHR, textStatus, errorThrown) {
                    console.error('Wishlist AJAX failed:', textStatus, errorThrown);
                    showWishlistError('Something went wrong. Please try again.');
                })
                .always(function () {
                    self.element.trigger('processStop');
                    $body.trigger('processStop');
                });
            function showWishlistError(message) {
                let wishlistHtmlMsg = '<div class="message-error error message show">' + $.mage.__(message) + '</div>';
                $('.page.messages').html(wishlistHtmlMsg);
                self.element.find('.towishlist').removeClass('wishlisted added-to-wishlist');
            }

        },

        _isUserLoggedIn: function () {
            var customer = customerData.get('customer');
            return _.isString(customer().firstname);
        },

        _checkWishListActive: function () {
            var self = this;
            // get 'kemana_wishlist' section from local storage. reference module: Kemana_Wishlist
            var interval = setInterval(function () {
                var wishlistStorage = JSON.parse(localStorage.getItem('mage-cache-storage')).kemana_wishlist;
                if (typeof wishlistStorage !== 'undefined' && wishlistStorage !== '{}') {
                    var productIdValue = self.element.find('.towishlist').attr('id');
                    if (!_.isEmpty(wishlistStorage) && _.isArray(wishlistStorage.items) && wishlistStorage.items.length) {
                        _.each(wishlistStorage.items, function(item) {
                            if (item === productIdValue) {
                                self.element.addClass('added-to-wishlist');
                                const wishlistElements = document.getElementsByClassName('wl-' + item);

                                if (wishlistElements && typeof wishlistElements.length === 'number' && wishlistElements.length > 0) {
                                    Array.from(wishlistElements).forEach(el => {
                                        el.classList.add('wishlisted');
                                    });
                                } else {
                                    var wishlist = document.getElementById(item);
                                    wishlist.classList.add("wishlisted");
                                }
                            }
                        });
                    }

                    clearInterval(interval);
                }
            }, 500);
        }
    });
    return $.mage.productItems;
});
