import { Component, EventEmitter, Input, Output } from '@angular/core';
import { AnnotatedMove, MoveQuality } from '../../models/analysis.models';

interface AnnotatedPair {
  white: AnnotatedMove | null;
  black: AnnotatedMove | null;
}

const QUALITY_LABELS: Record<MoveQuality, string> = {
  brilliant: '!!',
  best: '!',
  good: '',
  inaccuracy: '?!',
  mistake: '?',
  blunder: '??',
};

const QUALITY_CLASSES: Record<MoveQuality, string> = {
  brilliant: 'q-brilliant',
  best: 'q-best',
  good: 'q-good',
  inaccuracy: 'q-inaccuracy',
  mistake: 'q-mistake',
  blunder: 'q-blunder',
};

@Component({
  selector: 'app-annotated-move-list',
  standalone: true,
  imports: [],
  templateUrl: './annotated-move-list.component.html',
  styleUrl: './annotated-move-list.component.css',
})
export class AnnotatedMoveListComponent {
  @Input({ required: true }) moves: AnnotatedMove[] = [];
  @Input() activePly: number | null = null;
  @Output() plySelected = new EventEmitter<number>();

  get pairs(): AnnotatedPair[] {
    const result: AnnotatedPair[] = [];
    for (let i = 0; i < this.moves.length; i += 2) {
      result.push({
        white: this.moves[i] ?? null,
        black: this.moves[i + 1] ?? null,
      });
    }
    return result;
  }

  qualityLabel(move: AnnotatedMove | null): string {
    if (!move?.quality) return '';
    return QUALITY_LABELS[move.quality] ?? '';
  }

  qualityClass(move: AnnotatedMove | null): string {
    if (!move?.quality) return '';
    return QUALITY_CLASSES[move.quality] ?? '';
  }

  isWhiteActive(pairIndex: number): boolean {
    return this.activePly === pairIndex * 2;
  }

  isBlackActive(pairIndex: number): boolean {
    return this.activePly === pairIndex * 2 + 1;
  }

  selectWhite(pairIndex: number): void {
    this.plySelected.emit(pairIndex * 2);
  }

  selectBlack(pairIndex: number, black: AnnotatedMove | null): void {
    if (!black) return;
    this.plySelected.emit(pairIndex * 2 + 1);
  }

  formatEval(move: AnnotatedMove | null): string {
    if (!move || move.evalAfter === null) return '';
    const v = move.evalAfter;
    const sign = v > 0 ? '+' : '';
    return `${sign}${v.toFixed(2)}`;
  }
}
