(function(window, document, $) {
    'use strict';

    $(document).ready(function() {
        var currentPath = window.location.pathname.replace(/\/+$/, '');
        var element = $('a.sidebar-menu-button').filter(function() {
            var href = $(this).attr('href');

            if (!href || href.startsWith('#')) {
                return false;
            }

            var linkPath = new URL(href, document.baseURI).pathname.replace(/\/+$/, '');

            return currentPath === linkPath || currentPath.startsWith(linkPath + '/');
        });

        element.each(function() {
            var $li = $(this).parent().addClass('active');

            $li.parents('ul.collapse').each(function() {
                $(this).addClass('show');
                $(this)
                    .prev("a[data-toggle='collapse']")
                    .parent()
                    .addClass('open');
            });
        });
    });

    $(function() {
        $('#toggle-all-modules').on('click', function(event) {
            event.preventDefault();
            event.stopPropagation();

            var shouldOpenAll = $('.sidebar-submenu').toArray().some(function(element) {
                return !element.classList.contains('show');
            });

            $('.sidebar-submenu').each(function() {
                var $ul = $(this);
                var $li = $ul.parent('.sidebar-menu-item');

                $ul.toggleClass('show', shouldOpenAll);
                $li.toggleClass('open', shouldOpenAll);
            });
        });
    });

    document.addEventListener('DOMContentLoaded', function() {
        var storageKey = 'sisgep:side-menu-collapsed';
        var body = document.body;
        var sideMenu = document.getElementById('sisgepSideMenu');
        var sideMenuToggle = document.getElementById('sisgepSideMenuToggle');
        var tooltip = document.getElementById('sisgepMenuTooltip');
        var tooltipTargets = document.querySelectorAll('[data-sisgep-tooltip]');
        var mobileMenu = document.getElementById('sisgepMobileMenu');
        var mobileMenuToggle = document.getElementById('mobileHeaderMenuToggle');
        var mobileMenuClosers = document.querySelectorAll('[data-sisgep-mobile-close]');
        var accountMenuToggle = document.getElementById('accountMenuToggle');
        var darvinToggle = document.getElementById('sisgepDarvinToggle');
        var darvinPanel = document.getElementById('sisgepDarvinPanel');
        var darvinClose = document.getElementById('sisgepDarvinClose');
        var darvinComposer = document.getElementById('sisgepDarvinComposer');
        var darvinInput = document.getElementById('sisgepDarvinInput');
        var darvinMessages = document.getElementById('sisgepDarvinMessages');
        var darvinTypingTemplate = document.getElementById('sisgepDarvinTypingTemplate');
        var darvinGreetingTemplate = document.getElementById('sisgepDarvinGreetingTemplate');
        var darvinTypingTimer = null;
        var darvinPlaceholderReply = 'Meus desenvolvedores ainda estao implementando esta nova funcionalidade. Ate breve!';

        var hideTooltip = function() {
            if (!tooltip) {
                return;
            }

            tooltip.classList.remove('is-visible');
            tooltip.setAttribute('aria-hidden', 'true');
        };

        var showTooltip = function(label, element) {
            if (!tooltip || !label || !element) {
                return;
            }

            tooltip.textContent = label;
            tooltip.classList.add('is-visible');
            tooltip.setAttribute('aria-hidden', 'false');

            var rect = element.getBoundingClientRect();
            var top = Math.max(12, rect.top + (rect.height / 2) - (tooltip.offsetHeight / 2));
            var position = element.getAttribute('data-sisgep-tooltip-position') || 'right';
            var left = rect.right + 12;

            if (position === 'left') {
                left = rect.left - tooltip.offsetWidth - 12;
            }

            tooltip.style.left = Math.max(12, left) + 'px';
            tooltip.style.top = top + 'px';
        };

        var applyCollapsedState = function(collapsed) {
            body.classList.toggle('sisgep-menu-collapsed', collapsed);

            if (sideMenu) {
                sideMenu.classList.toggle('is-collapsed', collapsed);
            }

            if (sideMenuToggle) {
                sideMenuToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
                sideMenuToggle.setAttribute(
                    'aria-label',
                    collapsed ? 'Expandir menu lateral' : 'Minimizar menu lateral'
                );
            }

            hideTooltip();
        };

        var setDarvinOpen = function(open) {
            if (!darvinToggle || !darvinPanel) {
                return;
            }

            darvinPanel.classList.toggle('is-open', open);
            darvinPanel.setAttribute('aria-hidden', open ? 'false' : 'true');
            darvinToggle.setAttribute('aria-expanded', open ? 'true' : 'false');

            if (open && darvinInput) {
                window.setTimeout(function() {
                    darvinInput.focus();
                }, 120);
            }
        };

        var clearDarvinTypingTimer = function() {
            if (darvinTypingTimer) {
                window.clearTimeout(darvinTypingTimer);
                darvinTypingTimer = null;
            }
        };

        var scrollDarvinToBottom = function() {
            if (!darvinMessages) {
                return;
            }

            darvinMessages.scrollTop = darvinMessages.scrollHeight;
        };

        var appendDarvinFragment = function(template) {
            if (!darvinMessages || !template) {
                return;
            }

            darvinMessages.appendChild(template.content.cloneNode(true));
            scrollDarvinToBottom();
        };

        var removeDarvinTypingMessage = function() {
            if (!darvinMessages) {
                return;
            }

            var typingMessage = darvinMessages.querySelector('.sisgep-darvin-message--typing');

            if (typingMessage) {
                typingMessage.remove();
            }
        };

        var appendDarvinMessage = function(role, text) {
            if (!darvinMessages || !text) {
                return;
            }

            var message = document.createElement('div');
            var bubble = document.createElement('div');

            message.className = 'sisgep-darvin-message sisgep-darvin-message--' + role;
            bubble.className = 'sisgep-darvin-message__bubble';
            bubble.textContent = text;

            message.appendChild(bubble);
            darvinMessages.appendChild(message);
            scrollDarvinToBottom();
        };

        var appendDarvinGreeting = function() {
            if (!darvinMessages || !darvinGreetingTemplate) {
                return;
            }

            appendDarvinFragment(darvinGreetingTemplate);
        };

        var ensureDarvinGreeting = function() {
            if (!darvinMessages) {
                return;
            }

            if (!darvinMessages.querySelector('.sisgep-darvin-message--greeting')) {
                removeDarvinTypingMessage();
                appendDarvinGreeting();
            }
        };

        var playDarvinAssistantReply = function(replyText, delay) {
            if (!darvinMessages || !darvinTypingTemplate) {
                return;
            }

            clearDarvinTypingTimer();
            removeDarvinTypingMessage();
            appendDarvinFragment(darvinTypingTemplate);

            darvinTypingTimer = window.setTimeout(function() {
                removeDarvinTypingMessage();

                if (replyText === '__greeting__') {
                    appendDarvinGreeting();
                } else {
                    appendDarvinMessage('assistant', replyText);
                }

                darvinTypingTimer = null;
            }, delay || 900);
        };

        var playDarvinGreeting = function() {
            if (!darvinMessages) {
                return;
            }

            darvinMessages.innerHTML = '';
            playDarvinAssistantReply('__greeting__', 1100);
        };

        var setMobileMenuOpen = function(open) {
            if (!mobileMenu || !mobileMenuToggle) {
                return;
            }

            mobileMenu.classList.toggle('is-open', open);
            mobileMenu.setAttribute('aria-hidden', open ? 'false' : 'true');
            mobileMenuToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            body.classList.toggle('sisgep-mobile-menu-open', open);
        };

        try {
            applyCollapsedState(window.localStorage.getItem(storageKey) === 'true');
        } catch (error) {
            applyCollapsedState(false);
        }

        if (sideMenuToggle) {
            sideMenuToggle.addEventListener('click', function() {
                var collapsed = !body.classList.contains('sisgep-menu-collapsed');

                applyCollapsedState(collapsed);

                try {
                    window.localStorage.setItem(storageKey, collapsed ? 'true' : 'false');
                } catch (error) {
                    /* noop */
                }
            });
        }

        if (darvinToggle) {
            darvinToggle.addEventListener('click', function(event) {
                event.preventDefault();
                hideTooltip();
                var shouldOpen = !darvinPanel.classList.contains('is-open');

                setDarvinOpen(shouldOpen);

                if (shouldOpen) {
                    playDarvinGreeting();
                } else {
                    clearDarvinTypingTimer();
                }
            });
        }

        if (darvinClose) {
            darvinClose.addEventListener('click', function() {
                clearDarvinTypingTimer();
                setDarvinOpen(false);
            });
        }

        if (darvinComposer) {
            darvinComposer.addEventListener('submit', function(event) {
                event.preventDefault();

                if (!darvinInput) {
                    return;
                }

                var messageText = (darvinInput.value || '').trim();

                if (!messageText) {
                    return;
                }

                clearDarvinTypingTimer();
                ensureDarvinGreeting();
                appendDarvinMessage('user', messageText);
                darvinInput.value = '';
                playDarvinAssistantReply(darvinPlaceholderReply, 950);
            });
        }

        tooltipTargets.forEach(function(target) {
            target.addEventListener('mouseenter', function() {
                showTooltip(target.getAttribute('data-sisgep-tooltip'), target);
            });

            target.addEventListener('focus', function() {
                showTooltip(target.getAttribute('data-sisgep-tooltip'), target);
            });

            target.addEventListener('mouseleave', hideTooltip);
            target.addEventListener('blur', hideTooltip);
        });

        if (mobileMenuToggle) {
            mobileMenuToggle.addEventListener('click', function() {
                setMobileMenuOpen(!mobileMenu.classList.contains('is-open'));
            });
        }

        mobileMenuClosers.forEach(function(closer) {
            closer.addEventListener('click', function() {
                setMobileMenuOpen(false);
            });
        });

        if (mobileMenu) {
            mobileMenu.querySelectorAll('a').forEach(function(link) {
                link.addEventListener('click', function() {
                    setMobileMenuOpen(false);
                });
            });
        }

        if (window.jQuery && accountMenuToggle) {
            var $accountMenuToggle = window.jQuery(accountMenuToggle);
            var $accountDropdown = $accountMenuToggle.closest('.dropdown');

            var syncAccountMenuState = function(isOpen) {
                accountMenuToggle.classList.toggle('is-open', isOpen);
                accountMenuToggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
            };

            $accountDropdown.on('show.bs.dropdown', function() {
                syncAccountMenuState(true);
            });

            $accountDropdown.on('hide.bs.dropdown', function() {
                syncAccountMenuState(false);
            });

            $accountDropdown.on('hidden.bs.dropdown', function() {
                syncAccountMenuState(false);
            });
        }

        window.addEventListener('resize', hideTooltip);
        window.addEventListener('scroll', hideTooltip, {
            passive: true
        });

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                setMobileMenuOpen(false);
                clearDarvinTypingTimer();
                setDarvinOpen(false);
                hideTooltip();
            }
        });

        document.addEventListener('click', function(event) {
            if (!darvinPanel || !darvinToggle) {
                return;
            }

            if (!darvinPanel.classList.contains('is-open')) {
                return;
            }

            if (darvinPanel.contains(event.target) || darvinToggle.contains(event.target)) {
                return;
            }

            clearDarvinTypingTimer();
            setDarvinOpen(false);
        });
    });
})(window, document, window.jQuery);
