define([
    'jquery',
    'uiComponent',
    'underscore',
    'Magento_Customer/js/customer-data',
    'jquery/jquery-storageapi'
], function ($, Component, _, customerData) {
    'use strict';

    return Component.extend({
        defaults: {
            cookieMessages: [],
            messages: [],
            isHidden: false,
            selector: '.page.messages .messages',
            listens: {
                isHidden: 'onHiddenChange'
            }
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            this.cookieMessages = $.cookieStorage.get('mage-messages');
            this.messages = customerData.get('messages').extend({
                disposableCustomerData: 'messages'
            });

            if (!_.isEmpty(this.messages().messages)) {
                customerData.set('messages', {});
            }

            $.cookieStorage.set('mage-messages', '');
        },
        initObservable: function () {
            this._super()
                .observe('isHidden');

            return this;
        },

        isVisible: function () {
            return this.isHidden(!_.isEmpty(this.messages().messages) || !_.isEmpty(this.cookieMessages));
        },

        removeAll: function (item, event) {
            var targetHref = $(event.target).attr('href');
            $(this.selector).hide();

            // If clicked target is a link, then follow the link
            if (targetHref) {
                window.location.href = targetHref;
            }
        },

        onHiddenChange: function (isHidden) {
            var self = this;

            if (isHidden) {
                setTimeout(function () {
                    $(self.selector).hide();
                }, 5000);
            }
        }
    });
});