// @vitest-environment jsdom
import { renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import type { RefObject } from "react";

import { useRestoreFocus } from "./useRestoreFocus";

const appended: HTMLElement[] = [];

function mountEl<T extends HTMLElement>(el: T): T {
  document.body.appendChild(el);
  appended.push(el);
  return el;
}

afterEach(() => {
  for (const el of appended.splice(0)) el.remove();
});

describe("useRestoreFocus（CR-H11）", () => {
  it("关闭时把焦点还给 triggerRef", () => {
    const trigger = mountEl(document.createElement("button"));
    const other = mountEl(document.createElement("input"));
    const ref: RefObject<HTMLElement | null> = { current: trigger };

    const { rerender } = renderHook(
      ({ open }) => useRestoreFocus(open, ref),
      { initialProps: { open: true } },
    );

    other.focus();
    expect(document.activeElement).toBe(other);

    rerender({ open: false });
    expect(document.activeElement).toBe(trigger);
  });

  it("从未打开过：关闭态不抢焦点（wasOpen 门闩）", () => {
    const trigger = mountEl(document.createElement("button"));
    const other = mountEl(document.createElement("input"));
    const ref: RefObject<HTMLElement | null> = { current: trigger };

    renderHook(({ open }) => useRestoreFocus(open, ref), {
      initialProps: { open: false },
    });

    other.focus();
    expect(document.activeElement).toBe(other);
  });

  it("triggerRef 为 null / undefined 时关闭不抛错", () => {
    const nullRef: RefObject<HTMLElement | null> = { current: null };
    const nullCase = renderHook(
      ({ open }) => useRestoreFocus(open, nullRef),
      { initialProps: { open: true } },
    );
    expect(() => nullCase.rerender({ open: false })).not.toThrow();

    const undefCase = renderHook(
      ({ open }) => useRestoreFocus(open, undefined),
      { initialProps: { open: true } },
    );
    expect(() => undefCase.rerender({ open: false })).not.toThrow();
  });
});
