import {useEvent} from "../../core";
import {removeModules} from "../../core/removeModules";

let keydownHandler = null;
let clickHandler = null;

export function init() {
    const el = document.getElementById("sidebar-menu");
    const button = document.getElementById('menu-toggle');
    const aside = document.getElementById('sidebar');
    const backdrop = document.querySelector('.backdrop');

    const footer = document.querySelector('footer');
    const headerLink = document.querySelector('header a');


    useEvent(button, 'click', (e) => {
        aside.classList.toggle('show');
        //aside.toggleAttribute('inert')

        let isVisible = aside.classList.contains('show');

        if (isVisible) {
            backdrop.classList.add('visible');

            footer.setAttribute('inert', 'true');
            headerLink.setAttribute('inert', 'true');
        } else {
            backdrop.classList.remove('visible');

            footer.removeAttribute('inert');
            headerLink.removeAttribute('inert');
        }
    })

    keydownHandler = (e) => {
        if(e.key === 'Escape'){
            if(aside.classList.contains('show')){
                aside.classList.remove('show');
                backdrop.classList.remove('visible');
            }
        }
    }

    useEvent(document, 'keydown', keydownHandler)

    clickHandler = (e) => {
        aside.classList.remove('show');
        backdrop.classList.remove('visible');

        footer.removeAttribute('inert');
        headerLink.removeAttribute('inert');
    }

    useEvent(backdrop, 'click' , clickHandler)
}

export function destroy() {
    /*document.removeEventListener('keydown', keydownHandler);
    document.removeEventListener('click', clickHandler);*/
    removeModules('sidebar');
}
