/**
 * Pure Debug key mapping (§13). Shipped path used by UIScene.
 *
 * Important: with Shift held, browsers set `key` to '!'/'@'/… not '1'–'7'.
 * Day set MUST use `code` Digit1–Digit7.
 */

import { DEBUG_TELEPORT_SCENES } from '../data/constants';
import type { EndingId } from '../data/endings';

export type DebugKeyInput = {
  key: string;
  code: string;
  shiftKey: boolean;
};

export type DebugAction =
  | { type: 'happiness'; delta: number }
  | { type: 'awareness'; delta: number }
  | { type: 'setDay'; day: number }
  | { type: 'grantClues' }
  | { type: 'teleport'; sceneIndex: number; scene: string }
  | { type: 'teleportCycle' }
  | { type: 'negativeFlash' }
  | { type: 'forcedCelebration' }
  | { type: 'forceEnding'; id: EndingId }
  | { type: 'none' };

/** Map KeyboardEvent-like input → debug action (no Phaser / no Director). */
export function parseDebugKey(ev: DebugKeyInput): DebugAction {
  const k = ev.key;
  const code = ev.code;

  if (k === 'h' || k === 'H') return { type: 'happiness', delta: 10 };
  if (k === 'j' || k === 'J') return { type: 'happiness', delta: -10 };
  if (k === 'k' || k === 'K') return { type: 'awareness', delta: 10 };
  if (k === 'l' || k === 'L') return { type: 'awareness', delta: -10 };
  if (k === 'c' || k === 'C') return { type: 'grantClues' };
  if (k === 'n' || k === 'N') return { type: 'negativeFlash' };
  if (k === 'p' || k === 'P') return { type: 'forcedCelebration' };
  if (k === 'v' || k === 'V') return { type: 'teleportCycle' };
  if (k === 'F1') return { type: 'forceEnding', id: 'E1' };
  if (k === 'F2') return { type: 'forceEnding', id: 'E2' };
  if (k === 'F3') return { type: 'forceEnding', id: 'E3' };
  if (k === 'F4') return { type: 'forceEnding', id: 'E4' };

  // Shift + Digit1–7 → set day (use code; key becomes !@# with shift)
  if (ev.shiftKey && /^Digit[1-7]$/.test(code)) {
    const day = parseInt(code.replace('Digit', ''), 10);
    return { type: 'setDay', day };
  }

  // Plain Digit0–9 → teleport (also accept key when no shift)
  if (!ev.shiftKey && /^Digit[0-9]$/.test(code)) {
    const idx = parseInt(code.replace('Digit', ''), 10);
    const scene = DEBUG_TELEPORT_SCENES[idx];
    if (scene) return { type: 'teleport', sceneIndex: idx, scene };
  }
  // Fallback: unshifted key '0'-'9' without relying on code
  if (!ev.shiftKey && k >= '0' && k <= '9') {
    const idx = parseInt(k, 10);
    const scene = DEBUG_TELEPORT_SCENES[idx];
    if (scene) return { type: 'teleport', sceneIndex: idx, scene };
  }

  return { type: 'none' };
}
