"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const test = require("node:test");

const root = path.resolve(__dirname, "..", "..");
const app = fs.readFileSync(path.join(
  root,
  "src",
  "MBN_STOCK_WEBVIEW.LegacyParityApp",
  "Web",
  "app.js"), "utf8");

function loadKeydownHandler() {
  const marker = 'document.addEventListener("keydown", function (event) {';
  const start = app.lastIndexOf(marker);
  const bodyStart = start + marker.length;
  const end = app.indexOf("\n  });", bodyStart);
  assert.ok(start >= 0 && end > bodyStart);
  return new Function(
    "event",
    "modalFocusManager",
    "closeActiveChildModalFromAltF4",
    app.slice(bodyStart, end));
}

function altF4Event(repeat = false) {
  return {
    key: "F4",
    altKey: true,
    repeat,
    defaultPrevented: false,
    propagationStopped: false,
    preventDefault() { this.defaultPrevented = true; },
    stopPropagation() { this.propagationStopped = true; }
  };
}

test("main workspace Alt+F4 is consumed as the original no-op", () => {
  const handleKeydown = loadKeydownHandler();
  const event = altF4Event();
  const closed = [];

  handleKeydown(
    event,
    { getActiveModal() { return null; } },
    modal => closed.push(modal));

  assert.equal(event.defaultPrevented, true);
  assert.equal(event.propagationStopped, true);
  assert.deepEqual(closed, []);
});

test("child modal Alt+F4 keeps its explicit close behavior and ignores repeats", () => {
  const handleKeydown = loadKeydownHandler();
  const modal = {};
  const closed = [];
  const manager = { getActiveModal() { return modal; } };

  const initial = altF4Event();
  handleKeydown(initial, manager, active => closed.push(active));
  assert.equal(initial.defaultPrevented, true);
  assert.equal(initial.propagationStopped, true);
  assert.deepEqual(closed, [modal]);

  const repeated = altF4Event(true);
  handleKeydown(repeated, manager, active => closed.push(active));
  assert.equal(repeated.defaultPrevented, true);
  assert.equal(repeated.propagationStopped, true);
  assert.deepEqual(closed, [modal]);
});
