import "@testing-library/jest-dom/vitest";
import { afterEach, describe, expect, it, vi } from "vitest";

import { sheetDismiss } from "../src/lib/ui/sheet-dismiss";

// Only the tap-outside path is unit-tested; the swipe-down drag is
// pointer-gesture behaviour covered by manual / e2e checks.
describe("sheetDismiss — tap outside", () => {
	let cleanup: (() => void) | null = null;

	afterEach(() => {
		cleanup?.();
		cleanup = null;
		document.body.innerHTML = "";
	});

	it("dismisses on a pointer-down outside the sheet", () => {
		const node = document.createElement("div");
		const outside = document.createElement("button");
		document.body.append(node, outside);
		const onDismiss = vi.fn();
		const action = sheetDismiss(node, { onDismiss });
		cleanup = action.destroy;

		outside.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
		expect(onDismiss).toHaveBeenCalledOnce();
	});

	it("ignores a pointer-down inside the sheet", () => {
		const node = document.createElement("div");
		const inner = document.createElement("button");
		node.append(inner);
		document.body.append(node);
		const onDismiss = vi.fn();
		const action = sheetDismiss(node, { onDismiss });
		cleanup = action.destroy;

		inner.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
		expect(onDismiss).not.toHaveBeenCalled();
	});

	it("stops listening after destroy", () => {
		const node = document.createElement("div");
		const outside = document.createElement("button");
		document.body.append(node, outside);
		const onDismiss = vi.fn();
		sheetDismiss(node, { onDismiss }).destroy();

		outside.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));
		expect(onDismiss).not.toHaveBeenCalled();
	});
});
