import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { Product } from '../../../../../core/products/models/product-domain.model';
import { TranslatePipe } from '../../../../../i18n/translate.pipe';
import { LanguageService } from '../../../../../services/language.service';

interface SpecificationViewField {
  key: string;
  label: string;
  value: string;
}

interface SpecificationViewGroup {
  key: string;
  label: string;
  fields: SpecificationViewField[];
}

@Component({
  selector: 'app-product-specifications',
  standalone: true,
  imports: [TranslatePipe],
  templateUrl: './product-specifications.component.html',
  styleUrls: ['./product-specifications.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductSpecificationsComponent {
  @Input({ required: true }) product!: Product;

  constructor(private readonly languageService: LanguageService) {}

  get groups(): SpecificationViewGroup[] {
    const locale = this.languageService.currentLanguage();
    const groups = this.product.specificationGroups ?? [];

    if (groups.length > 0) {
      return groups
        .map(group => ({
          key: group.key,
          label: group.labels?.[locale] || group.label || group.key,
          fields: (group.attributes ?? []).map(attribute => ({
            key: attribute.key,
            label: attribute.labels?.[locale] || attribute.label || attribute.key,
            value: attribute.unit ? `${attribute.value} ${attribute.unit}` : attribute.value,
          }))
        }))
        .filter(group => group.fields.length > 0);
    }

    const fallbackFields = [
      ...(this.product.descriptionFields ?? []).map(field => ({
        key: field.key,
        label: field.key,
        value: field.value,
      })),
      ...(this.product.attributes ?? []).map(attribute => ({
        key: attribute.key,
        label: attribute.key,
        value: attribute.value,
      }))
    ];

    if (fallbackFields.length === 0) {
      return [];
    }

    return [{
      key: 'general',
      label: 'productDetails.specificationsGeneral',
      fields: fallbackFields,
    }];
  }
}
