import { Component, Input, OnChanges } from '@angular/core';
import { FormsModule } from '@angular/forms';

type ExportKind = 'fen' | 'pgn';

@Component({
  selector: 'app-export-panel',
  standalone: true,
  imports: [FormsModule],
  templateUrl: './export-panel.component.html',
  styleUrl: './export-panel.component.css'
})
export class ExportPanelComponent implements OnChanges {
  @Input() fen = '';
  @Input() pgn = '';

  exportKind: ExportKind = 'fen';
  exportValue = '';
  copyNotice = '';
  private copyNoticeTimer: ReturnType<typeof setTimeout> | null = null;

  get exportPlaceholder(): string {
    return this.exportKind === 'fen' ? 'FEN will appear here' : 'PGN will appear here';
  }

  ngOnChanges(): void {
    this.syncValue();
  }

  setKind(kind: ExportKind): void {
    this.exportKind = kind;
    this.syncValue();
  }

  copy(): void {
    if (!this.exportValue.trim()) {
      return;
    }

    if (!navigator.clipboard?.writeText) {
      this.showNotice('Ready in the text box.');
      return;
    }

    void navigator.clipboard
      .writeText(this.exportValue)
      .then(() => this.showNotice('Copied!'))
      .catch(() => this.showNotice('Ready in the text box.'));
  }

  download(): void {
    if (!this.exportValue.trim()) {
      return;
    }

    const ext = this.exportKind === 'pgn' ? 'pgn' : 'txt';
    const blob = new Blob([this.exportValue], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `game.${ext}`;
    a.click();
    URL.revokeObjectURL(url);
  }

  private syncValue(): void {
    this.exportValue = this.exportKind === 'fen' ? this.fen : this.pgn;
  }

  private showNotice(msg: string): void {
    this.copyNotice = msg;
    if (this.copyNoticeTimer !== null) {
      clearTimeout(this.copyNoticeTimer);
    }
    this.copyNoticeTimer = setTimeout(() => {
      this.copyNotice = '';
    }, 1800);
  }
}
