import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { NgOptimizedImage } from '@angular/common';
import { ButtonComponent } from '../button/button.component';

@Component({
  selector: 'app-product-card',
  standalone: true,
  imports: [ButtonComponent, NgOptimizedImage],
  templateUrl: './product-card.component.html',
  styleUrl: './product-card.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProductCardComponent {
  // Configurable inputs
  readonly imageUrl = input<string | null>(null);
  readonly title = input<string>('');
  readonly originalPrice = input<number>(0);
  readonly discount = input<number | null>(null);
  readonly transferPrice = input<number | null>(null);
  readonly buttonText = input<string>('Comprar');
  readonly imagePriority = input<boolean>(false);

  // Interactive events
  readonly buy = output<void>();

  // Computed discounted price
  readonly discountedPrice = computed(() => {
    const original = this.originalPrice();
    const disc = this.discount();
    if (!disc || disc <= 0) {
      return original;
    }
    return original * (1 - disc / 100);
  });

  // Computed transfer price
  readonly computedTransferPrice = computed(() => {
    const givenTransfer = this.transferPrice();
    if (givenTransfer !== null) {
      return givenTransfer;
    }
    // Fallback if not specified: use the discounted price
    return this.discountedPrice();
  });

  // Formatted string for discounted price: "$ 76.000"
  readonly formattedDiscountedPrice = computed(() => {
    return this.formatCurrency(this.discountedPrice());
  });

  // Formatted string for original price (if has discount): "$ 95.000"
  readonly formattedOriginalPrice = computed(() => {
    return this.formatCurrency(this.originalPrice());
  });

  // Formatted string for transfer price: "$ 74.800"
  readonly formattedTransferPrice = computed(() => {
    return this.formatCurrency(this.computedTransferPrice());
  });

  /**
   * Helper method to format currency numbers to Argentine Pesos style "$ XX.XXX".
   * This manual implementation is safe from runtime/SSR locale variations.
   */
  private formatCurrency(value: number): string {
    const rounded = Math.round(value);
    const parts = rounded.toString().split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    return `$${parts.join(',')}`;
  }
}
