// @vitest-environment happy-dom
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

import { describe, it, expect } from "vitest";
import { renderHook, act } from "@testing-library/react";
import type { ReactNode } from "react";
import {
  DrillStackProvider,
  useDrillStack,
} from "@/components/drill/DrillStackProvider";

function wrapper({ children }: { children: ReactNode }) {
  return <DrillStackProvider>{children}</DrillStackProvider>;
}

describe("DrillStackProvider", () => {
  it("starts with an empty stack", () => {
    const { result } = renderHook(() => useDrillStack(), { wrapper });
    expect(result.current.stack).toEqual([]);
    expect(result.current.openPeek).toBeInstanceOf(Function);
    expect(result.current.closeTop).toBeInstanceOf(Function);
  });

  it("openPeek pushes one entry; closeTop pops it", () => {
    const { result } = renderHook(() => useDrillStack(), { wrapper });
    act(() => result.current.openPeek({ kind: "payer", payerId: "SKCO0" }));
    expect(result.current.stack).toEqual([
      { kind: "payer", payerId: "SKCO0" },
    ]);
    act(() => result.current.closeTop());
    expect(result.current.stack).toEqual([]);
  });

  it("openPeek replaces the previous peek when called twice", () => {
    const { result } = renderHook(() => useDrillStack(), { wrapper });
    act(() => result.current.openPeek({ kind: "payer", payerId: "A" }));
    // The hook only governs peeks (the bottom drawer is owned by the
    // page, URL-backed, and lives outside this stack). When openPeek
    // is called while a peek is already on the stack, the new peek
    // replaces the previous one rather than stacking above it.
    act(() => result.current.openPeek({ kind: "rule", rule: "R050" }));
    expect(result.current.stack).toHaveLength(1);
    expect(result.current.stack[0]).toEqual({ kind: "rule", rule: "R050" });
  });
});
