import { ViewportScroller } from '@angular/common';
import { inject, Injectable } from '@angular/core';
import { Event, Router, Scroll } from '@angular/router';

import { filter } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ScrollPositionGuard {
  private viewportScroller = inject(ViewportScroller);
  private router = inject(Router);

  canActivate(): boolean {
    this.router.events
      .pipe(filter((e: Event): e is Scroll => e instanceof Scroll))
      .subscribe(_e => {
        if (this.router.url.includes('collections') || this.router.url.includes('account')) {
          this.viewportScroller.scrollToPosition([150, 150]);
        } else {
          this.viewportScroller.scrollToPosition([0, 0]);
        }
      });
    return true;
  }
}
