document.addEventListener("DOMContentLoaded", function () {
    const cardBody = document.querySelector('.card-body.activeTabOnRefresh');
    const hash = window.location.hash;

    let selectedTab = hash ? cardBody.querySelector(`[href="${hash}"]`) : null;
    let selectedContent = hash ? cardBody.querySelector(hash) : null;

    if (!selectedTab || !selectedContent) {
        selectedTab = cardBody.querySelector(".nav-link");
        selectedContent = cardBody.querySelector(".tab-pane");
    }

    if (selectedTab && selectedContent) {
        cardBody.querySelectorAll('.nav-link').forEach(tab => tab.classList.remove('active'));
        cardBody.querySelectorAll('.tab-pane').forEach(content => content.classList.remove('show', 'active'));
        selectedTab.classList.add('active');
        selectedContent.classList.add('show', 'active');

        // Give the browser a moment to render the tab
        setTimeout(() => {
            $.fn.dataTable.tables({
                visible: true,
                api: true
            })
                .columns.adjust()
                .draw();
        }, 0);
    }

    cardBody.querySelectorAll('.nav-link').forEach(tab => {
        tab.addEventListener("click", function () {
            let targetTab = this.getAttribute("href");
            history.replaceState(null, null, targetTab);

            setTimeout(() => {
                $.fn.dataTable.tables({
                    visible: true,
                    api: true
                })
                    .columns.adjust()
                    .draw();
            }, 0);
        });
    });

    cardBody.style.opacity = "1";
});