// Debug 面板（PRD §13，服务验收）：反引号键 `` ` `` 开关的 DOM 面板。
// 默认 display:none，无 UI 痕迹，不影响正常游玩。
// 功能：设幸福 / 设觉知 / 设日 1-7 / 传送任意场景（10 选）/ 置齐全部线索 / 强制触发 E1-E4。

import Phaser from 'phaser';
import { director } from '../core/CorruptionDirector';
import { audio } from '../audio/AudioEngine';
import { gameRef } from '../core/gameRef';
import { MAP_SCENES, type EndingId } from '../types';

const MAP_SCENE_KEYS = Object.values(MAP_SCENES);
const ENDINGS: EndingId[] = ['E1', 'E2', 'E3', 'E4'];

export class DebugPanel {
  private root: HTMLDivElement;

  constructor() {
    const root = document.createElement('div');
    root.style.cssText =
      'position:absolute;top:8px;right:8px;z-index:99;display:none;' +
      'background:#111;color:#eee;font:11px monospace;padding:8px;border:1px solid #444;' +
      'flex-direction:column;gap:6px;min-width:170px;';
    const parent = document.getElementById('game') ?? document.body;
    parent.appendChild(root);
    this.root = root;

    const title = document.createElement('div');
    title.textContent = 'DEBUG（` 关闭）';
    title.style.cssText = 'color:#F5A623;font-weight:bold;';
    root.appendChild(title);

    // 数值行
    root.appendChild(this.row('幸福', '30', (v) => director.setHappiness(Number(v)), 0, 100));
    root.appendChild(this.row('觉知', '0', (v) => director.setAwareness(Number(v)), 0, 100));
    root.appendChild(this.row('日(1-7)', '1', (v) => director.setDay(Number(v)), 1, 7));

    // 传送
    const sceneRow = document.createElement('div');
    const sel = document.createElement('select');
    sel.style.cssText = 'background:#222;color:#eee;font:11px monospace;';
    for (const [mapKey, sceneKey] of Object.entries(MAP_SCENES)) {
      const opt = document.createElement('option');
      opt.value = sceneKey;
      opt.textContent = `${mapKey}`;
      sel.appendChild(opt);
    }
    sceneRow.appendChild(sel);
    const tpBtn = this.btn('传送', () => this.startScene(sel.value));
    sceneRow.appendChild(tpBtn);
    root.appendChild(sceneRow);

    // 全部线索
    root.appendChild(this.btn('置齐全部线索', () => director.giveAllClues()));

    // 强制结局
    const endRow = document.createElement('div');
    endRow.style.cssText = 'display:flex;gap:4px;';
    for (const e of ENDINGS) {
      endRow.appendChild(this.btn(`强制 ${e}`, () => this.forceEnding(e)));
    }
    root.appendChild(endRow);

    window.addEventListener('keydown', (ev) => {
      if (ev.code === 'Backquote') {
        this.root.style.display = this.root.style.display === 'none' ? 'flex' : 'none';
      }
    });
  }

  private row(label: string, def: string, apply: (v: string) => void, min: number, max: number): HTMLDivElement {
    const row = document.createElement('div');
    row.style.cssText = 'display:flex;gap:4px;align-items:center;';
    const span = document.createElement('span');
    span.textContent = label;
    span.style.cssText = 'width:52px;';
    const input = document.createElement('input');
    input.type = 'number';
    input.value = def;
    input.min = String(min);
    input.max = String(max);
    input.style.cssText = 'width:50px;background:#222;color:#eee;border:1px solid #444;font:11px monospace;';
    const btn = this.btn('设', () => apply(input.value));
    row.append(span, input, btn);
    return row;
  }

  private btn(text: string, onClick: () => void): HTMLButtonElement {
    const b = document.createElement('button');
    b.textContent = text;
    b.style.cssText = 'background:#333;color:#eee;border:1px solid #555;font:11px monospace;cursor:pointer;';
    b.addEventListener('click', onClick);
    return b;
  }

  /** 场景操作：SceneManager 类型不含 start/launch，借 ScenePlugin（BootScene 恒在） */
  private scenePlugin(): Phaser.Scenes.ScenePlugin | null {
    const g = gameRef.game;
    if (!g) return null;
    return g.scene.getScene('BootScene').scene;
  }

  /** 停止全部地图场景，启动目标场景 */
  private startScene(sceneKey: string): void {
    const sp = this.scenePlugin();
    if (!sp) return;
    director.forceIdle();
    audio.restoreMaster(500);
    for (const key of MAP_SCENE_KEYS) {
      if (key !== sceneKey && sp.isActive(key)) sp.stop(key);
    }
    if (sp.isActive('DreamScene')) sp.stop('DreamScene');
    if (sp.isActive('EndingScene')) sp.stop('EndingScene');
    if (!sp.isActive('UIScene')) sp.launch('UIScene');
    sp.start(sceneKey, { spawn: 'default' });
  }

  private forceEnding(e: EndingId): void {
    const sp = this.scenePlugin();
    if (!sp) return;
    director.forceIdle();
    audio.restoreMaster(500);
    for (const key of MAP_SCENE_KEYS) {
      if (sp.isActive(key)) sp.stop(key);
    }
    if (sp.isActive('UIScene')) sp.stop('UIScene');
    if (sp.isActive('DreamScene')) sp.stop('DreamScene');
    director.startEnding(e);
    sp.start('EndingScene', { ending: e });
  }
}
