import Phaser from 'phaser';
import { AID_STEPS } from '../hazards';
import { AID_UI } from '../../../data/strings/floor';

const W = 640;
const H = 360;

/**
 * The first-aid QTE (docs/SCENARIOS.md). Deliberately NOT funny: plain panel,
 * plain words, generous windows. Wrong keys are ignored rather than punished —
 * the pressure is the timer bar, not your typing. The scene routes keys in and
 * calls update(dt); a step timing out ends the whole thing as a failure.
 */
export class AidOverlay {
  private root: Phaser.GameObjects.Container | null = null;
  private stepText: Phaser.GameObjects.Text | null = null;
  private barFill: Phaser.GameObjects.Rectangle | null = null;
  private stepIndex = 0;
  private msLeft = 0;
  private done: ((success: boolean) => void) | null = null;

  constructor(private readonly scene: Phaser.Scene) {}

  get isOpen(): boolean {
    return this.root !== null;
  }

  open(done: (success: boolean) => void): void {
    if (this.root) return;
    this.done = done;
    this.stepIndex = 0;
    this.msLeft = AID_STEPS[0]!.ms;

    const root = this.scene.add.container(0, 0).setDepth(900).setScrollFactor(0);
    this.root = root;
    root.add(this.scene.add.rectangle(W / 2, H / 2, W, H, 0x03030a, 0.72));
    root.add(this.scene.add.rectangle(W / 2, H / 2, 340, 118, 0x10121c).setStrokeStyle(1, 0x3a4054));
    root.add(
      this.scene.add
        .text(W / 2, H / 2 - 38, AID_UI.title, { fontFamily: 'monospace', fontSize: '13px', color: '#e8e4da' })
        .setOrigin(0.5),
    );
    this.stepText = this.scene.add
      .text(W / 2, H / 2 - 8, '', { fontFamily: 'monospace', fontSize: '11px', color: '#c8d2e0' })
      .setOrigin(0.5);
    root.add(this.stepText);
    root.add(this.scene.add.rectangle(W / 2, H / 2 + 26, 280, 8, 0x232838));
    this.barFill = this.scene.add.rectangle(W / 2 - 140, H / 2 + 26, 280, 8, 0x7a8aa8).setOrigin(0, 0.5);
    root.add(this.barFill);
    this.showStep();
  }

  private showStep(): void {
    const s = AID_STEPS[this.stepIndex]!;
    this.msLeft = s.ms;
    this.stepText?.setText(`${s.label}  —  ${s.key}`);
  }

  handleKey(key: string): void {
    if (!this.root) return;
    const s = AID_STEPS[this.stepIndex]!;
    if (key !== s.key) return; // ignored, not punished
    this.stepIndex++;
    if (this.stepIndex >= AID_STEPS.length) return this.finish(true);
    this.showStep();
  }

  update(dtMs: number): void {
    if (!this.root) return;
    this.msLeft -= dtMs;
    const s = AID_STEPS[this.stepIndex]!;
    this.barFill?.setDisplaySize(Math.max(0, 280 * (this.msLeft / s.ms)), 8);
    if (this.msLeft <= 0) this.finish(false);
  }

  private finish(success: boolean): void {
    const cb = this.done;
    this.root?.destroy();
    this.root = null;
    this.stepText = null;
    this.barFill = null;
    this.done = null;
    cb?.(success);
  }
}
