import {AfterViewInit, Directive, ElementRef, QueryList, ViewChildren} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {UntilDestroy, untilDestroyed} from '@ngneat/until-destroy';


@UntilDestroy()
@Directive()
export abstract class CdContentComponent implements AfterViewInit {

    @ViewChildren('sectionRef') sectionRefs: QueryList<ElementRef<HTMLElement>>;

    protected activatedRoute?: ActivatedRoute;


    ngAfterViewInit(): void {
        if (this.activatedRoute) {
            this.activatedRoute.fragment
                .pipe(untilDestroyed(this))
                .subscribe(fragment => {
                    if (fragment) {
                        const section = this.sectionRefs.find(s => s.nativeElement.id === fragment);
                        section?.nativeElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
                    }
                });
        }
    }

}
