import { Component, OnInit, signal, computed, ChangeDetectionStrategy } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterLink } from '@angular/router'; import { ApiService } from '../../services'; import { Category } from '../../models'; import { environment } from '../../../environments/environment'; import { ItemsCarouselComponent } from '../../components/items-carousel/items-carousel.component'; @Component({ selector: 'app-home', standalone: true, imports: [CommonModule, RouterLink, ItemsCarouselComponent], templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class HomeComponent implements OnInit { brandName = environment.brandFullName; isnovo = environment.theme === 'novo'; categories = signal([]); loading = signal(true); error = signal(null); // Memoized computed values for performance topLevelCategories = computed(() => { return this.categories().filter(cat => cat.parentID === 0); }); // Cache subcategories by parent ID private subcategoriesCache = computed(() => { const cache = new Map(); this.categories().forEach(cat => { if (cat.parentID !== 0) { if (!cache.has(cat.parentID)) { cache.set(cat.parentID, []); } cache.get(cat.parentID)!.push(cat); } }); return cache; }); constructor(private apiService: ApiService) {} ngOnInit(): void { this.loadCategories(); } loadCategories(): void { this.loading.set(true); this.apiService.getCategories().subscribe({ next: (categories) => { this.categories.set(categories); this.loading.set(false); }, error: (err) => { this.error.set('Failed to load categories'); this.loading.set(false); console.error('Error loading categories:', err); } }); } getTopLevelCategories(): Category[] { return this.topLevelCategories(); } getSubCategories(parentID: number): Category[] { return this.subcategoriesCache().get(parentID) || []; } }