import type { GameSnapshot } from "../game/simulation/types";

export interface HudController {
  update(snapshot: GameSnapshot): void;
  setVisible(visible: boolean): void;
  isLightingEnabled(): boolean;
  destroy(): void;
}

export function createHud(host: HTMLElement): HudController {
  host.classList.add("hud");
  const shell = host.closest<HTMLElement>(".game-shell");
  host.innerHTML = `
    <section class="hud-card hud-title"></section>
    <section class="hud-card hud-controls">
      <h3>Управление</h3>
      <p>Ходьба: WASD / стрелки</p>
      <p>В главное меню: Esc</p>
      <div class="hud-device-controls"></div>
      <label class="hud-lighting-toggle">
        <input class="hud-lighting-checkbox" type="checkbox" checked />
        <span>RTX Ray-Traced Lighting 4K DLSS 5.3</span>
      </label>
    </section>
  `;

  const title = host.querySelector<HTMLElement>(".hud-title");
  const deviceControls = host.querySelector<HTMLElement>(".hud-device-controls");
  const lightingCheckbox = host.querySelector<HTMLInputElement>(".hud-lighting-checkbox");

  if (!title || !deviceControls || !lightingCheckbox) {
    throw new Error("HUD elements were not created.");
  }

  const setVisible = (visible: boolean): void => {
    host.classList.toggle("is-hidden", !visible);
    if (shell) {
      shell.classList.toggle("hud-hidden", !visible);
    }
  };

  return {
    update(snapshot: GameSnapshot): void {
      const activeDevice = snapshot.activeDeviceId
        ? snapshot.devices.find((entry) => entry.id === snapshot.activeDeviceId) ?? null
        : null;
      const hasMultiRayDetector = snapshot.detectors.some((entry) => entry.requiredRayCount > 1);
      const multiRayHint = hasMultiRayDetector
        ? "<p>Есть детекторы, которым нужно несколько лучей одновременно.</p>"
        : "";

      title.innerHTML = `
        <h2>Уровень ${snapshot.levelIndex + 1}: ${snapshot.level.title}</h2>
        <p>Активировано детекторов: ${snapshot.matchedDetectorCount}/${snapshot.requiredDetectorCount}</p>
        ${multiRayHint}
      `;

      if (!activeDevice) {
        deviceControls.classList.remove("is-visible");
        deviceControls.replaceChildren();
        return;
      }

      const typeName = activeDevice.type === "mirror"
        ? "Зеркало"
        : activeDevice.type === "prism"
          ? "Призма"
          : "Разделитель";

      const lines = [
        `<p>Рядом элемент: ${typeName}</p>`,
        "<p>Поворот: Q/E (или R), ЛКМ + курсор</p>"
      ];
      if (activeDevice.type === "prism") {
        lines.push("<p>Покраска призмы: Z/X</p>");
      }

      deviceControls.classList.add("is-visible");
      deviceControls.innerHTML = lines.join("");
    },
    setVisible,
    isLightingEnabled(): boolean {
      return lightingCheckbox.checked;
    },
    destroy(): void {
      host.replaceChildren();
    }
  };
}
