import { UpdateController } from "@24tools/playable_template";
import { UI_IMAGES } from "../../resources/images/uiImages";
import { TimeC } from "../Timers/TimeC";

/** Секунд від 0% до 100% при FILL_SPEED = 1 */
const INVASION_PROGRESS_TOTAL_SEC = 120;

/** Множник швидкості заповнення */
const INVASION_PROGRESS_FILL_SPEED = 1;

export class InvasionProgressUIC {
  private static fillEl: HTMLElement | null = null;
  private static progressEl: HTMLElement | null = null;
  private static elapsedSec = 0;
  private static isRunning = false;

  static init() {
    const uiRoot = document.getElementById("ui");
    if (!uiRoot) return;

    const block = document.createElement("div");
    block.className = "hud-top-center";

    const title = document.createElement("h1");
    title.className = "hud-invasion-title";
    title.textContent = "ZOMBIE INVASION";

    const progress = document.createElement("div");
    progress.className = "hud-progress";

    const track = document.createElement("div");
    track.className = "hud-progress__track";

    const fill = document.createElement("div");
    fill.className = "hud-progress__fill";
    this.fillEl = fill;

    const icon = document.createElement("img");
    icon.className = "hud-progress__icon";
    icon.src = UI_IMAGES.zombieHead;
    icon.alt = "";

    track.appendChild(fill);
    progress.appendChild(track);
    progress.appendChild(icon);
    this.progressEl = progress;
    block.appendChild(title);
    block.appendChild(progress);
    uiRoot.appendChild(block);

    this.setProgress(0);

    UpdateController.Instance.onUpdate.addDelegate((delta) => this.tick(delta));
  }

  static startTimer() {
    this.elapsedSec = 0;
    this.isRunning = true;
    this.setProgress(0);
  }

  private static tick(delta: number) {
    if (!this.isRunning || !this.fillEl) return;

    this.elapsedSec +=
      delta * TimeC.TimeScale * INVASION_PROGRESS_FILL_SPEED;

    const ratio = Math.min(
      1,
      this.elapsedSec / INVASION_PROGRESS_TOTAL_SEC,
    );
    this.setProgress(ratio);

    if (ratio >= 1) {
      this.isRunning = false;
    }
  }

  static setProgress(ratio: number) {
    if (!this.fillEl) return;

    const clamped = Math.max(0, Math.min(1, ratio));
    this.fillEl.style.width = `${clamped * 100}%`;
    this.progressEl?.style.setProperty("--progress", String(clamped));
  }
}
