import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
import { SectionConfig } from '../../shared/models/config';
import { CatalogCategoryGridComponent } from '../../features/website/catalog/components/category-grid/category-grid.component';
import { CategoriesWidgetData } from '../contracts/widget-data.contract';

@Component({
  selector: 'app-categories-widget',
  standalone: true,
  imports: [CommonModule, CatalogCategoryGridComponent],
  template: `
    <section class="categories-widget">
      @if (data; as widgetData) {
        @if (widgetData.title) {
          <h2 class="categories-widget__title">{{ widgetData.title }}</h2>
        }

        @if (widgetData.categories.length) {
          <app-catalog-category-grid
            [categories]="widgetData.categories"
            (categorySelected)="handleCategorySelected($event)"
          />
        } @else if (widgetData.emptyMessage) {
          <p class="categories-widget__empty">{{ widgetData.emptyMessage }}</p>
        }
      }
    </section>
  `,
  styles: [
    `
      .categories-widget { display: grid; gap: var(--space-lg, 24px); }

      .categories-widget__title {
        margin: 0;
        font-size: 1.75rem;
        font-weight: 700;
        color: var(--text-primary, #1e3c38);
      }

      .categories-widget__empty { margin: 0; color: var(--text-secondary, #667a77); }
    `
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CategoriesWidgetComponent {
  @Input() section: SectionConfig | null = null;
  @Input() data: CategoriesWidgetData | null = null;
  @Input() categorySelectedCallback: ((category: unknown) => void) | null = null;
  @Output() categorySelected = new EventEmitter<unknown>();

  handleCategorySelected(category: unknown): void {
    this.categorySelectedCallback?.(category);
    this.categorySelected.emit(category);
  }
}