import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';

@Component({
    selector: 'scroll-up-button',
    templateUrl: './scroll-up-button.component.html',
    styleUrls: ['./scroll-up-button.component.scss'],
})
export class ScrollUpButtonComponent implements OnInit, OnDestroy {
    buttonVisible = false;
    observer: IntersectionObserver;
    interval: number;

    constructor(private cdRef: ChangeDetectorRef) {}

    ngOnInit(): void {
        this.observer = new IntersectionObserver(
            this.handleIntersection.bind(this),
            {
                root: null,
                rootMargin: '0px',
                threshold: [1],
            },
        );

        this.observer.observe(document.querySelector('#observer-target'));

        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        this.interval = setInterval(() => {
            // need to check if visibility changed because of programmatic scroll in scrollTo directive
            this.checkVisibility();
        }, 500);
    }

    ngOnDestroy() {
        this.observer.disconnect();
        clearInterval(this.interval);
    }

    setButtonVisible(visible: boolean) {
        this.buttonVisible = visible;
        this.cdRef.detectChanges();
    }

    checkVisibility() {
        if (this.buttonVisible) {
            return;
        }

        const header = document.querySelector('.page-layout__header');
        const { bottom } = header.getBoundingClientRect();

        this.setButtonVisible(bottom < 0);
    }

    handleIntersection(entries: IntersectionObserverEntry[]) {
        const entry = entries[0];

        // entry.boundingClientRect.top < 0 means that observable target crossed
        // top of the viewport. If top > 0 - target crossed the bottom of the
        // viewport, and we don't need to show button.
        const visible =
            entry.intersectionRatio !== 1 && entry.boundingClientRect.top < 0;
        this.setButtonVisible(visible);
    }

    handleClick() {
        const body = document.querySelector('body');
        // const bannerTop = document.querySelector('.wrapper-header');
        const flightsRoot = document.querySelector('flights-root');
        const { top } = flightsRoot.getBoundingClientRect();

        body.scrollTo(0, body.scrollTop + top);
        this.setButtonVisible(false);
    }

    get buttonClasses() {
        return {
            'scroll-up': true,
            'scroll-up--visible': this.buttonVisible,
        };
    }
}
