document.addEventListener("DOMContentLoaded", function() {
    var tabGroups = document.querySelectorAll("[data-case-tabs]");

    Array.prototype.forEach.call(tabGroups, function(group) {
        var buttons = group.querySelectorAll("[data-case-tab]");
        var panes = group.querySelectorAll("[data-case-pane]");
        var params = new URLSearchParams(window.location.search);
        var requestedTab = params.get("tab");
        var defaultTab = group.getAttribute("data-default-tab");
        var initialTab = requestedTab || defaultTab;

        function activateTab(tabName, updateUrl) {
            var hasMatch = false;

            Array.prototype.forEach.call(buttons, function(button) {
                var isActive = button.getAttribute("data-case-tab") === tabName;
                button.classList.toggle("is-active", isActive);
                button.setAttribute("aria-selected", isActive ? "true" : "false");
                button.setAttribute("tabindex", isActive ? "0" : "-1");
                if (isActive) {
                    hasMatch = true;
                }
            });

            Array.prototype.forEach.call(panes, function(pane) {
                var isActive = pane.getAttribute("data-case-pane") === tabName;
                pane.classList.toggle("is-active", isActive);
                pane.hidden = !isActive;
            });

            if (!hasMatch) {
                if (defaultTab && defaultTab !== tabName) {
                    activateTab(defaultTab, updateUrl);
                }
                return;
            }

            if (updateUrl) {
                params.set("tab", tabName);
                window.history.replaceState({}, "", window.location.pathname + "?" + params.toString() + window.location.hash);
            }
        }

        Array.prototype.forEach.call(buttons, function(button) {
            button.addEventListener("click", function() {
                activateTab(button.getAttribute("data-case-tab"), true);
            });
        });

        activateTab(initialTab, Boolean(requestedTab));
    });
});
