<script module lang="ts">
	import { defineMeta, type StoryContext } from "@storybook/addon-svelte-csf";
	import { expect } from "storybook/test";
	import DiffFileList from "./DiffFileList.svelte";

	const nestedFiles = [
		{ name: "src/lib/components/repo/DiffView.svelte" },
		{ name: "src/lib/components/repo/DiffStatPill.svelte" },
		{ name: "src/lib/api/diff.ts" },
		{ name: "package.json" }
	];

	type PlayContext = Pick<
		StoryContext<Record<string, unknown>>,
		"canvas" | "canvasElement" | "userEvent"
	>;

	const nestedTree = async ({ canvas, canvasElement, userEvent }: PlayContext) => {
		await expect(canvas.getByRole("link", { name: "DiffView.svelte" })).toHaveAttribute(
			"href",
			"#file-src/lib/components/repo/DiffView.svelte"
		);
		await expect(canvas.getByRole("link", { name: "package.json" })).toHaveAttribute(
			"href",
			"#file-package.json"
		);
		await expect(canvas.getByText("repo")).toBeVisible();
		expect(canvasElement.querySelectorAll("details").length).toBe(5);

		const firstDir = canvasElement.querySelector("details")!;
		expect(firstDir.open).toBe(true);
		await userEvent.click(firstDir.querySelector("summary")!);
		expect(firstDir.open).toBe(false);
	};

	const flatList = async ({ canvas, canvasElement }: PlayContext) => {
		expect(canvasElement.querySelector("details")).toBeNull();
		await expect(canvas.getAllByRole("link")).toHaveLength(2);
	};

	const { Story } = defineMeta({
		title: "Repo/DiffFileList",
		component: DiffFileList,
		tags: ["autodocs"],
		args: { files: nestedFiles }
	});
</script>

<Story name="Nested directories" play={nestedTree} />

<Story
	name="Flat files"
	args={{ files: [{ name: "README.md" }, { name: "package.json" }] }}
	play={flatList}
/>

<Story name="Empty" args={{ files: [] }} />
