export function createToast(config = {}) {
    const settings = {
        containerClass: 'toast-container',
        toastClass: 'toast',
        closeSelector: '.notification__close',
        backdropClass: 'modal-backdrop--toast',
        duration: 3000,
        template: null,
        getData(type, text) {
            return {
                text,
                classModifier: `${settings.toastClass} notification_${type}`,
                success: type === 'success',
                warning: type === 'warning',
                error: type === 'error',
            };
        },
        ...config,
    };

    let closeTimer = null;

    function clearCloseTimer() {
        if (closeTimer) {
            window.clearTimeout(closeTimer);
            closeTimer = null;
        }
    }

    function hide() {
        clearCloseTimer();

        $(`.${settings.containerClass}`).remove();
        $(`.${settings.backdropClass}`).removeClass(settings.backdropClass);

        if (window.Wick && Wick.Backdrop) {
            Wick.Backdrop.hide();
        }

        $(document).off('click.toast');
    }

    function show({ type = 'success', text = '' }) {
        if (!settings.template) {
            return;
        }

        hide();

        const toastHtml = settings.template(settings.getData(type, text));

        if (window.Wick && Wick.Backdrop) {
            Wick.Backdrop.show();
            $('.modal-backdrop').addClass(settings.backdropClass);
        }

        $('body').append(`<div class="${settings.containerClass}">${toastHtml}</div>`);

        $(`.${settings.containerClass}`)
            .off('click.toastClose', settings.closeSelector)
            .on('click.toastClose', settings.closeSelector, function (event) {
                event.preventDefault();
                hide();
            });

        $(document)
            .off('click.toast')
            .on('click.toast', `.${settings.backdropClass}`, function () {
                hide();
            });

        closeTimer = window.setTimeout(hide, settings.duration);
    }

    return {
        show,
        hide,
    };
}
