(function () {
    'use strict';

    var chatPanels = Array.prototype.slice.call(document.querySelectorAll('[data-chat-scroll]'));

    function scrollChatToLatest(panel, behavior) {
        if (!panel) return;
        var top = Math.max(0, panel.scrollHeight - panel.clientHeight);
        if (typeof panel.scrollTo === 'function') {
            panel.scrollTo({ top: top, behavior: behavior || 'auto' });
        } else {
            panel.scrollTop = top;
        }
    }

    chatPanels.forEach(function (panel) {
        var initialPositioning = true;
        panel.setAttribute('tabindex', '0');

        requestAnimationFrame(function () {
            scrollChatToLatest(panel, 'auto');
            requestAnimationFrame(function () { scrollChatToLatest(panel, 'auto'); });
        });

        Array.prototype.slice.call(panel.querySelectorAll('img')).forEach(function (image) {
            if (image.complete) return;
            image.addEventListener('load', function () {
                if (initialPositioning) scrollChatToLatest(panel, 'auto');
            }, { once: true });
        });

        window.addEventListener('load', function () {
            if (initialPositioning) scrollChatToLatest(panel, 'auto');
        }, { once: true });

        window.setTimeout(function () { initialPositioning = false; }, 1800);
    });

    var items = Array.prototype.slice.call(document.querySelectorAll('[data-message-item]'));
    if (!items.length) return;
    document.body.classList.add('message-actions-enabled');

    function closeAll(except) {
        items.forEach(function (item) {
            if (item !== except) {
                item.classList.remove('actions-open');
                item.setAttribute('aria-expanded', 'false');
            }
        });
    }

    function toggle(item, forceOpen) {
        var open = typeof forceOpen === 'boolean' ? forceOpen : !item.classList.contains('actions-open');
        closeAll(open ? item : null);
        item.classList.toggle('actions-open', open);
        item.setAttribute('aria-expanded', open ? 'true' : 'false');
    }

    items.forEach(function (item) {
        var bubble = item.querySelector('.message-bubble');
        if (!bubble) return;
        var pressTimer = null;
        var longPressed = false;

        bubble.setAttribute('role', 'button');
        bubble.setAttribute('aria-label', 'Mostrar opções desta mensagem');

        bubble.addEventListener('click', function (event) {
            event.stopPropagation();
            if (longPressed) {
                longPressed = false;
                return;
            }
            toggle(item);
        });

        bubble.addEventListener('pointerdown', function () {
            longPressed = false;
            clearTimeout(pressTimer);
            pressTimer = setTimeout(function () {
                longPressed = true;
                toggle(item, true);
                if (navigator.vibrate) navigator.vibrate(30);
            }, 550);
        });
        ['pointerup', 'pointercancel', 'pointerleave'].forEach(function (name) {
            bubble.addEventListener(name, function () { clearTimeout(pressTimer); });
        });

        item.addEventListener('keydown', function (event) {
            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                toggle(item);
            } else if (event.key === 'Escape') {
                toggle(item, false);
            }
        });

        var actions = item.querySelector('[data-message-actions]');
        if (actions) actions.addEventListener('click', function (event) { event.stopPropagation(); });
    });

    document.addEventListener('click', function () { closeAll(null); });
})();
