import { Component, ElementRef, Input, SimpleChanges, ViewChild, ViewContainerRef } from '@angular/core';
import { CommonNzModule } from '../../common.nz.module';

@Component({
  selector: 'scroll-images',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './scroll-images.component.html',
  styleUrl: './scroll-images.component.less',
})
export class ScrollImagesComponent {
  @ViewChild('innerContainer') innerContainer!: ElementRef<HTMLDivElement>;
  @ViewChild('outerContainer') outerContainer!: ElementRef<HTMLDivElement>;
  @Input() data: string[] = [];
  @Input() width = 154;
  @Input() height = 88;

  directorVisible = false;
  leftVisible = false;
  rightVisible = false;

  constructor(private viewContainerRef: ViewContainerRef) {}

  ngAfterViewInit() {
    this.setDirectorVisible();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      this.setDirectorVisible();
    }
  }

  setDirectorVisible() {
    setTimeout(() => {
      if (this.outer.scrollWidth > this.outer.offsetWidth) {
        this.directorVisible = true;
        this.rightVisible = true;
      }
    });
  }

  handleScroll(direction: 'left' | 'right') {
    const scrollLeft =
      direction === 'left' ? this.outer.scrollLeft - this.width * 3 : this.outer.scrollLeft + this.width * 3;
    this.outer.scrollTo({
      left: scrollLeft,
      behavior: 'smooth',
    });
    setTimeout(() => {
      this.checkSingleVisible();
    }, 300);
  }
  checkSingleVisible() {
    const { scrollWidth, scrollLeft, clientWidth } = this.outer;
    this.rightVisible = clientWidth + scrollLeft < scrollWidth;
    this.leftVisible = scrollLeft > 0;
  }

  get dom() {
    return this.viewContainerRef.element.nativeElement;
  }
  get container() {
    return this.innerContainer.nativeElement;
  }
  get outer() {
    return this.outerContainer.nativeElement;
  }
}
