import { getPriceInPersianAlphabet } from '@/utils';
import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[appPriceAlphabet]',
  standalone: true,
})
export class PriceAlphabetDirective implements OnChanges {
  /** Numeric price to render as Persian text */
  @Input('appPriceAlphabet') price: number | string | null = null;

  constructor(private el: ElementRef<HTMLElement>) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['price']) {
      this.render();
    }
  }

  private render() {
    const value = this.normalizeToNumber(this.price);
    if (value === null) {
      this.el.nativeElement.textContent = '';
      return;
    }
    this.el.nativeElement.textContent = getPriceInPersianAlphabet(value);
  }

  /**
   * Normalize various input shapes to a number; returns null when not parsable
   */
  private normalizeToNumber(raw: number | string | null): number | null {
    if (raw === null || raw === undefined) return null;
    if (typeof raw === 'number') {
      return isFinite(raw) ? raw : null;
    }
    // remove common separators and whitespace before parsing
    const cleaned = raw.replace(/[,\s]/g, '');
    const num = Number(cleaned);
    return isNaN(num) ? null : num;
  }
}
