import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

test("outside dismiss also closes menus on Escape", async () => {
  const source = await readFile(new URL("./useOutsideDismiss.js", import.meta.url), "utf8");

  assert.match(source, /function handleKeyDown\(event\)/);
  assert.match(source, /event\.key !== "Escape"/);
  assert.match(source, /document\.addEventListener\("keydown", handleKeyDown\)/);
  assert.match(source, /document\.removeEventListener\("keydown", handleKeyDown\)/);
});

test("outside dismiss can return focus to the trigger after closing", async () => {
  const source = await readFile(new URL("./useOutsideDismiss.js", import.meta.url), "utf8");
  const contextBar = await readFile(new URL("../../features/context/ContextBar.jsx", import.meta.url), "utf8");

  assert.match(source, /returnFocusRef/);
  assert.match(source, /returnFocusRef\?\.current\?\.focus\?\.\(\)/);
  assert.match(contextBar, /const accountButtonRef = useRef\(null\)/);
  assert.match(contextBar, /ref=\{accountButtonRef\}/);
  assert.match(contextBar, /useOutsideDismiss\(accountMenuRef,[\s\S]*\{ returnFocusRef: accountButtonRef \}/);
});
