import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { ConfigService } from '../../../../../core/config/config.service';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { UserExperienceFacade } from '../../../../../facades/platform/user-experience.facade';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { LangRoutePipe } from '../../../../../pipes/lang-route.pipe';
import { LanguageService } from '../../../../../services/language.service';
import { getTranslatedField } from '../../../../../utils/item.utils';
import { DEFAULT_USER_EXPERIENCE_CONFIG } from '../../../../../shared/models/config';
import { CompareTableComponent } from '../components/compare-table.component';
import { EmptyStateComponent } from '../../../../../shared/ui/empty-state/empty-state.component';
import { ButtonComponent } from '../../../../../shared/ui/button/button.component';

@Component({
  selector: 'app-compare-page',
  standalone: true,
  imports: [RouterLink, TranslatePipe, LangRoutePipe, CompareTableComponent, EmptyStateComponent, ButtonComponent],
  templateUrl: './compare-page.component.html',
  styleUrls: ['./compare-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ComparePageComponent {
  private readonly uxFacade = inject(UserExperienceFacade);
  private readonly configService = inject(ConfigService);
  private readonly languageService = inject(LanguageService);

  private readonly compareConfig = this.resolveCompareConfig();

  readonly hideIdentical = signal(this.compareConfig.hideIdenticalDefault);
  readonly highlightDifferences = signal(this.compareConfig.highlightDifferencesDefault);

  readonly compared = this.uxFacade.comparedProducts;
  readonly products = computed<Product[]>(() => this.compared().map(entry => entry.product));
  readonly hasItems = computed(() => this.products().length > 0);

  remove(productId: number): void {
    this.uxFacade.removeFromCompare(productId);
  }

  clear(): void {
    this.uxFacade.clearCompare();
  }

  productTitle(product: Product): string {
    return getTranslatedField(product, 'name', this.languageService.currentLanguage());
  }

  private resolveCompareConfig() {
    const raw = (this.configService.getBootstrapSnapshot() as any)?.userExperience?.compare ?? {};
    return {
      ...DEFAULT_USER_EXPERIENCE_CONFIG.compare,
      ...raw,
      maxItems: Number.isFinite(raw.maxItems) ? Math.max(2, Number(raw.maxItems)) : DEFAULT_USER_EXPERIENCE_CONFIG.compare.maxItems
    };
  }
}
