import { IGoodResponse } from '@/domains/pos/models/good.io';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  EventEmitter,
  HostListener,
  inject,
  Output,
  signal,
} from '@angular/core';
import { ButtonDirective } from 'primeng/button';
import { Skeleton } from 'primeng/skeleton';
import images from 'src/assets/images';
import { PosLandingStore } from '../store/main.store';
import { FavoriteCTAComponent } from './favorite-CTA.component';

@Component({
  selector: 'pos-good-grid-view',
  templateUrl: './grid-view.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ButtonDirective, Skeleton, FavoriteCTAComponent],
})
export class PosGoodsGridViewComponent {
  @Output() onAdd = new EventEmitter<IGoodResponse>();

  private readonly store = inject(PosLandingStore);
  private readonly pageSize = 80;
  readonly renderLimit = signal(this.pageSize);

  goodPlaceholder = images.placeholders.default;

  onFavItemsLoading = signal<string[]>([]);

  goods = computed(() => this.store.filteredGoods());
  visibleGoods = computed(() => this.goods()?.slice(0, this.renderLimit()));
  hasMore = computed(() => (this.goods()?.length || 0) > (this.visibleGoods()?.length || 0));
  loading = computed(() => this.store.getGoodsLoading());

  addProduct(good: IGoodResponse) {
    this.onAdd.emit(good);
  }

  loadMore() {
    this.renderLimit.update((limit) => limit + this.pageSize);
  }

  @HostListener('window:scroll')
  onWindowScroll() {
    if (!this.hasMore()) return;
    const nearBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight - 300;
    if (nearBottom) this.loadMore();
  }
}
