export const sidebar = ($) => {
    // Initialization
    initialize();
};

function initialize() {
    let sidebarHeader = document.querySelector('.sidebar-header');
    let sidebarBody = document.querySelector('.sidebar-body');
    let sidebarFooter = document.querySelector('.sidebar-footer');

    sidebarBody.style.marginTop = sidebarHeader.offsetHeight + 'px';
    sidebarBody.style.marginBottom = sidebarFooter.offsetHeight + 'px';

    sidebarHeader.style.width = sidebarBody.offsetWidth + 'px';
    sidebarFooter.style.width = sidebarBody.offsetWidth + 'px';

    dynamicHeader(sidebarHeader, sidebarBody);
    dynamicFooter(sidebarFooter, sidebarBody);
    scrollActive(sidebarBody);
}

function dynamicHeader(sidebarHeader, sidebarBody) {
    new ResizeObserver(function(entries) {
        sidebarBody.style.marginTop = entries[0].contentRect.height + 'px';
    }).observe(sidebarHeader);
}

function dynamicFooter(sidebarFooter, sidebarBody) {
    new ResizeObserver(function(entries) {
        sidebarBody.style.marginBottom = entries[0].contentRect.height + 'px';
    }).observe(sidebarFooter);
}

function scrollActive(sidebarBody) {
    let activeItem = sidebarBody.querySelector('.nav-item.active');

    if (activeItem) {
        sidebarBody.scrollTop = activeItem.offsetTop - ((sidebarBody.offsetHeight + sidebarBody.offsetTop) - activeItem.offsetHeight);
    }
}