// DOM-overlay HUD: health ring avatar, 7-slot hotbar, pause/edit buttons, center messages.
import type { Mode, HudLike } from './game';

export interface HudHandlers {
  onPause(): void;
  onEdit(): void;
}

const RING_C = 2 * Math.PI * 30; // r=30 circle circumference

const SPIDER_SVG = `
<svg viewBox="0 0 40 40" fill="none" stroke="#5fe0ff" stroke-width="2" stroke-linecap="round">
  <ellipse cx="20" cy="21" rx="6.5" ry="5" fill="#11313d"/>
  <circle cx="20" cy="15" r="3" fill="#5fe0ff" stroke="none"/>
  <path d="M14 19 L7 13 M14 22 L6 22 M15 25 L8 30 M17 27 L13 34"/>
  <path d="M26 19 L33 13 M26 22 L34 22 M25 25 L32 30 M23 27 L27 34"/>
</svg>`;

export class HUD implements HudLike {
  private hpRing: SVGCircleElement;
  private hpLabel: HTMLElement;
  private scrapEl: HTMLElement;
  private msgBox: HTMLElement;
  private msgTitle: HTMLElement;
  private msgSub: HTMLElement;
  private modeTag: HTMLElement;
  private pauseBtn: HTMLButtonElement;
  private hotbar: HTMLElement;
  private cdEls: HTMLElement[] = [];
  private lastCds: number[] = [];
  private curTitle: string | null = null;

  constructor(parent: HTMLElement, handlers: HudHandlers) {
    const root = document.createElement('div');
    root.className = 'hud';
    root.innerHTML = `
      <div class="vignette"></div>
      <div class="hud-tl">
        <div class="avatar">
          <svg viewBox="0 0 72 72">
            <circle class="ring-bg" cx="36" cy="36" r="30"></circle>
            <circle class="ring-hp" cx="36" cy="36" r="30"
              stroke-dasharray="${RING_C.toFixed(1)}" stroke-dashoffset="0"></circle>
          </svg>
          <div class="avatar-icon">${SPIDER_SVG}</div>
        </div>
        <div class="tl-stats">
          <div class="hp-label">3/3</div>
          <div class="scrap-label" title="scrap collected">⚙ <span class="scrap-n">0</span></div>
        </div>
      </div>
      <div class="hud-tr">
        <button class="round-btn" data-btn="edit" title="Level editor (E)">✎</button>
        <button class="round-btn" data-btn="pause" title="Pause (P)">❚❚</button>
      </div>
      <div class="hotbar"></div>
      <div class="center-msg hidden"><h1></h1><p></p></div>
      <div class="mode-tag hidden">EDITOR MODE — press E to play</div>
      <div class="controls-hint">WASD move · LMB laser · SPACE bomb · F rocket · Q tesla · V blades · C orb · SHIFT dash</div>
    `;
    parent.appendChild(root);

    this.hpRing = root.querySelector('.ring-hp') as unknown as SVGCircleElement;
    this.hpLabel = root.querySelector('.hp-label') as HTMLElement;
    this.scrapEl = root.querySelector('.scrap-n') as HTMLElement;
    this.msgBox = root.querySelector('.center-msg') as HTMLElement;
    this.msgTitle = this.msgBox.querySelector('h1') as HTMLElement;
    this.msgSub = this.msgBox.querySelector('p') as HTMLElement;
    this.modeTag = root.querySelector('.mode-tag') as HTMLElement;
    this.pauseBtn = root.querySelector('[data-btn="pause"]') as HTMLButtonElement;
    this.hotbar = root.querySelector('.hotbar') as HTMLElement;

    (root.querySelector('[data-btn="edit"]') as HTMLButtonElement).addEventListener('click', () =>
      handlers.onEdit()
    );
    this.pauseBtn.addEventListener('click', () => handlers.onPause());

    // 7-slot hotbar, all live: indices match SLOT in game.ts
    const slots: { icon: string; label: string; title: string }[] = [
      { icon: '↯', label: 'LMB', title: 'Laser' },
      { icon: '◉', label: 'SPC', title: 'Bomb' },
      { icon: '⌖', label: 'F', title: 'Rocket' },
      { icon: 'ϟ', label: 'Q', title: 'Tesla arc — chains between bots' },
      { icon: '✶', label: 'V', title: 'Blade spin — close-range AoE' },
      { icon: '◎', label: 'C', title: 'Sentry orb — auto-fires nearby' },
      { icon: '≫', label: 'SHFT', title: 'Phase dash — brief invulnerability' },
    ];
    for (const s of slots) {
      const el = document.createElement('div');
      el.className = 'slot live';
      el.title = s.title;
      el.innerHTML = `<div class="cd"></div><span class="icon">${s.icon}</span><span class="key">${s.label}</span>`;
      this.hotbar.appendChild(el);
      this.cdEls.push(el.querySelector('.cd') as HTMLElement);
      this.lastCds.push(-1);
    }
  }

  setHP(hp: number, max: number): void {
    const f = Math.max(0, Math.min(1, hp / max));
    this.hpRing.style.strokeDashoffset = String(RING_C * (1 - f));
    this.hpRing.classList.toggle('low', hp <= 1);
    this.hpLabel.textContent = `${Math.max(0, hp)}/${max}`;
  }

  setCd(slot: number, frac: number): void {
    const el = this.cdEls[slot];
    if (!el) return;
    const v = Math.round(Math.max(0, Math.min(1, frac)) * 40) / 40;
    if (v === this.lastCds[slot]) return;
    this.lastCds[slot] = v;
    el.style.height = `${v * 100}%`;
  }

  setScrap(n: number): void {
    this.scrapEl.textContent = String(n);
  }

  setMessage(title: string | null, sub = ''): void {
    this.curTitle = title;
    if (!title) {
      this.msgBox.classList.add('hidden');
      return;
    }
    this.msgTitle.textContent = title;
    this.msgSub.textContent = sub;
    this.msgBox.classList.remove('hidden');
  }

  setMode(mode: Mode): void {
    const editing = mode === 'editor';
    this.modeTag.classList.toggle('hidden', !editing);
    document.body.classList.toggle('editor-mode', editing);
  }

  setPaused(p: boolean): void {
    this.pauseBtn.textContent = p ? '▶' : '❚❚';
    if (p) this.setMessage('PAUSED', 'press P to resume');
    else if (this.curTitle === 'PAUSED') this.setMessage(null);
  }
}
