import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnChanges,
  SimpleChanges,
  inject,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { Card } from '@blackjack/models/blackjack.model';
import { PlayingCardComponent } from '../playing-card/playing-card.component';
import { GameControlsService } from '@blackjack/services/game-controls.service';

@Component({
  selector: 'app-dealer-hand',
  standalone: true,
  imports: [CommonModule, PlayingCardComponent],
  template: `
    <div class="space-y-4">
      <div class="flex justify-between items-center">
        <h3 class="section-heading text-2xl">Dealer's Karten</h3>
        <div class="flex items-center gap-2">
          <div class="text-text-secondary">Punkte:</div>
          <div class="text-xl font-bold text-accent-red">
            {{ gameControlsService.calculateHandValue(cards) }}
          </div>
        </div>
      </div>
      <div class="card p-6 !bg-accent-red">
        <div class="flex justify-center gap-4 min-h-[160px] p-4 border-2 border-red-400 rounded-lg">
          @if (cards.length > 0) {
            @for (card of cardsWithState; track card.id) {
              <app-playing-card
                [rank]="card.rank"
                [suit]="card.suit"
                [hidden]="card.hidden"
                [isNew]="card.isNew"
              ></app-playing-card>
            }
          } @else {
            <div class="flex items-center justify-center text-white/70 text-lg font-medium">
              Warte auf Spielstart...
            </div>
          }
        </div>
      </div>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DealerHandComponent implements OnChanges {
  @Input() cards: Card[] = [];
  cardsWithState: (Card & { isNew: boolean; id: string })[] = [];

  private lastCardCount = 0;

  protected gameControlsService = inject(GameControlsService);

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

  private updateCardsWithState(): void {
    const newCards = this.cards.length > this.lastCardCount;

    this.cardsWithState = this.cards.map((card, index) => {
      const isNew = newCards && index >= this.lastCardCount;

      return {
        ...card,
        isNew,
        id: `${card.suit}-${card.rank}-${index}`,
      };
    });

    this.lastCardCount = this.cards.length;
  }
}
