import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  output,
  signal,
} from '@angular/core';
import { MissionStateResponse } from '@fog-explorer/api-interfaces';
import { killerAvatarUrl } from '@fog-explorer/encounter-library';
import { avatarUrl, survivorInitials } from './survivor-initials';

/** Most-recent entry is index 0; older entries fade toward 0 opacity. */
const LOG_OPACITY_STEP = 0.18;
const LOG_MAX_VISIBLE = 8;

@Component({
  selector: 'app-expanded-panel',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './expanded-panel.component.html',
  styleUrl: './expanded-panel.component.css',
})
export class ExpandedPanelComponent {
  missionState = input.required<NonNullable<MissionStateResponse>>();
  panelClose = output<void>();
  abandonRequest = output<void>();

  protected readonly confirmingAbandon = signal(false);

  protected mission = computed(() => this.missionState().mission);
  protected survivor = computed(() => this.missionState().survivors[0] ?? null);
  protected initials = computed(() => {
    const name = this.missionState().survivors[0]?.name ?? '';
    return name ? survivorInitials(name) : '?';
  });

  protected avatarSrc = computed(() => {
    const name = this.missionState().survivors[0]?.name ?? '';
    return avatarUrl(name);
  });

  protected readonly imgError = signal(false);

  protected killerName = computed(() => this.missionState().mission.killerName ?? null);

  protected killerAvatarSrc = computed(() => {
    const name = this.killerName();
    return name ? killerAvatarUrl(name) : null;
  });

  protected readonly killerImgError = signal(false);

  protected survivorStateColor = computed(() => {
    const state = this.missionState().survivors[0]?.state ?? 'idle';
    const map: Record<string, string> = {
      active:    'var(--fog-amber)',
      injured:   'var(--fog-amber-dim)',
      downed:    'var(--fog-red)',
      sacrificed:'var(--fog-red)',
      idle:      'var(--fog-text-dim)',
    };
    return map[state] ?? 'var(--fog-text-dim)';
  });

  protected logEntries = computed(() =>
    this.missionState().recentLog.slice(0, LOG_MAX_VISIBLE)
  );

  protected difficultyPips = computed(() => {
    const d = this.missionState().mission.difficulty;
    return [1, 2, 3].map((n) => n <= d);
  });

  protected entryOpacity(index: number): number {
    return Math.max(0.15, 1 - index * LOG_OPACITY_STEP);
  }
}
