import { CommonModule } from '@angular/common';
import { Component, computed, inject, signal } from '@angular/core';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { filter } from 'rxjs';
import { PosSplashComponent } from '../components/splash.component';
import { PosPagesLayoutComponent } from './pagesLayout/layout.component';

@Component({
  selector: 'pos-layout',
  templateUrl: 'layout.component.html',
  imports: [PosSplashComponent, PosPagesLayoutComponent, RouterOutlet, CommonModule],
})
export class PosLayoutComponent {
  private readonly router = inject(Router);

  showSplash = signal(true);
  private readonly currentUrl = signal(this.router.url);
  isAuth = computed(() => this.currentUrl() === '/auth');

  private touchStartY = 0;
  private pulling = false;
  pullDistance = signal(0);
  readonly pullThreshold = 80;

  constructor() {
    this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe(() => this.currentUrl.set(this.router.url));
  }

  onSplashCompleted() {
    this.showSplash.set(false);
  }

  onTouchStart(event: TouchEvent) {
    if (window.scrollY > 0 || event.touches.length !== 1) return;
    this.touchStartY = event.touches[0].clientY;
    this.pulling = true;
  }

  onTouchMove(event: TouchEvent) {
    if (!this.pulling) return;
    const delta = event.touches[0].clientY - this.touchStartY;
    if (delta <= 0) {
      this.pullDistance.set(0);
      return;
    }

    const damped = Math.min(delta * 0.5, 140);
    this.pullDistance.set(damped);
    event.preventDefault();
  }

  onTouchEnd() {
    if (!this.pulling) return;
    const shouldRefresh = this.pullDistance() >= this.pullThreshold;
    this.pulling = false;
    this.pullDistance.set(0);
    if (shouldRefresh) {
      this.showSplash.set(true);
    }
  }
}
