import { ChangeDetectionStrategy, Component, Input, computed, inject } from '@angular/core';
import { ProductCardComponent } from '../../../../../components/product-card/product-card.component';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { UserExperienceFacade } from '../../../../../facades/platform/user-experience.facade';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { TranslateService } from '../../../../../i18n/translate.service';
import { CartService } from '../../../../../services';
import { UserNotificationService } from '../../services/user-notification.service';

@Component({
  selector: 'app-recently-viewed-strip',
  standalone: true,
  imports: [ProductCardComponent, TranslatePipe],
  templateUrl: './recently-viewed-strip.component.html',
  styleUrls: ['./recently-viewed-strip.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RecentlyViewedStripComponent {
  @Input() title = '';
  @Input() maxItems = 8;
  @Input() showClear = false;

  private readonly uxFacade = inject(UserExperienceFacade);
  private readonly cartService = inject(CartService);
  private readonly notifications = inject(UserNotificationService);
  private readonly translate = inject(TranslateService);

  readonly items = computed(() => this.uxFacade.recentlyViewed().slice(0, Math.max(1, this.maxItems)));
  readonly hasItems = computed(() => this.items().length > 0);

  addToCart(itemID: number, event: Event): void {
    event.preventDefault();
    event.stopPropagation();
    this.cartService.addItem(itemID);
    this.notifications.show(this.translate.t('catalog.addToCart'), 'success');
  }

  clear(): void {
    this.uxFacade.clearRecentlyViewed();
    this.notifications.show(this.translate.t('ux.clearRecentlyViewed'), 'info');
  }

  itemProduct(index: number): Product {
    return this.items()[index].product;
  }
}
