import { Component, Input, OnDestroy, ViewEncapsulation, DOCUMENT, inject } from '@angular/core';

import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';

@Component({
    selector: 'app-spinner',
    imports: [],
    templateUrl: './spinner.component.html',
    encapsulation: ViewEncapsulation.None,
})
export class SpinnerComponent implements OnDestroy {
    private router = inject(Router);
    private document = inject<Document>(DOCUMENT);

    public isSpinnerVisible = true;

    @Input()
    public backgroundColor = 'rgba(0, 115, 170, 0.69)';

    constructor() {
        this.router.events.subscribe(
            (event) => {
                if (event instanceof NavigationStart) {
                    this.isSpinnerVisible = true;
                } else if (
                    event instanceof NavigationEnd ||
                    event instanceof NavigationCancel ||
                    event instanceof NavigationError
                ) {
                    this.isSpinnerVisible = false;
                }
            },
            () => {
                this.isSpinnerVisible = false;
            },
        );
    }

    ngOnDestroy(): void {
        this.isSpinnerVisible = false;
    }
}
