import Plugin from 'src/plugin-system/plugin.class';

export default class BcAquaStickyHeader extends Plugin {
    init() {
        this.content = document.querySelector('.content-main');
        this.lastScrollTop = 0;

        this.onScroll = this.stickyNav.bind(this);
        this.onResize = this.stickyNav.bind(this);

        this.stickyNav();

        window.addEventListener('scroll', this.onScroll, { passive: true });
        window.addEventListener('resize', this.onResize);
    }

    stickyNav() {
        if (!this.content) return;
        const scrollTop = window.scrollY || window.pageYOffset;
        const headerHeight = this.el.offsetHeight;

        if (window.innerWidth > 991) {
            if (scrollTop >= 135) {
                this.el.classList.add('is--sticky');
                this.content.style.paddingTop = headerHeight + 'px';
            } else if (scrollTop < 90) {
                this.el.classList.remove('is--sticky', 'is-hidden');
                this.content.style.paddingTop = '';
            }

            if (scrollTop > 135) {
                if (scrollTop > this.lastScrollTop) {
                    this.el.classList.add('is-hidden');
                } else {
                    this.el.classList.remove('is-hidden');
                }
            }

            this.lastScrollTop = scrollTop;

        } else {
            this.el.classList.remove('is--sticky', 'is-hidden');
            this.content.style.paddingTop = '';
        }
    }

    destroy() {
        window.removeEventListener('scroll', this.onScroll);
        window.removeEventListener('resize', this.onResize);
        super.destroy();
    }
}