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

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

	const onToggleFiles = fn();
	const onSetAllOpen = fn();

	const { Story } = defineMeta({
		title: "Repo/DiffTopbar",
		component: DiffTopbar,
		tags: ["autodocs"],
		args: {
			stat: { insertions: 19, deletions: 11, files_changed: 1 },
			fileCount: 1
		}
	});
</script>

<Story name="Default" />

<Story
	name="Downloads"
	args={{
		downloadUrls: {
			patch: "/dawn/tangled/commit/0123456789abcdef0123456789abcdef01234567.patch",
			diff: "/dawn/tangled/commit/0123456789abcdef0123456789abcdef01234567.diff"
		}
	}}
	play={async ({ canvas }: PlayContext) => {
		await expect(canvas.getByRole("link", { name: ".patch" })).toHaveAttribute(
			"href",
			expect.stringContaining(".patch")
		);
		await expect(canvas.getByRole("link", { name: ".diff" })).toHaveAttribute(
			"href",
			expect.stringContaining(".diff")
		);
		// reloads on purpose, the client router would shadow the endpoint with the
		// commit page's [ref] route and 404
		for (const link of canvas.getAllByRole("link", { name: /^\./ })) {
			await expect(link).toHaveAttribute("data-sveltekit-reload");
		}
	}}
/>

<Story
	name="Toggles"
	args={{
		onToggleFiles,
		onSetAllOpen,
		allOpen: true,
		filesOpen: true
	}}
	play={async ({ canvas, userEvent }: PlayContext) => {
		await userEvent.click(canvas.getByTitle("Toggle file list"));
		await expect(onToggleFiles).toHaveBeenCalledOnce();

		await userEvent.click(canvas.getByRole("button", { name: /collapse all/i }));
		await expect(onSetAllOpen).toHaveBeenCalledWith(false);
	}}
/>

<Story
	name="Collapsed"
	args={{ allOpen: false, onSetAllOpen: fn() }}
	play={async ({ canvas }: PlayContext) => {
		await expect(canvas.getByRole("button", { name: /expand all/i })).toBeInTheDocument();
	}}
/>

<Story
	name="Split mode"
	args={{ diffStyle: "split" }}
	play={async ({ canvas }: PlayContext) => {
		await expect(canvas.getByTitle("Unified diff")).toHaveAttribute("href", "?diff=unified");
		await expect(canvas.getByTitle("Split diff")).toHaveAttribute("href", "?diff=split");
		// replacestate navigation, no noscroll means it jumps to top
		for (const link of [canvas.getByTitle("Unified diff"), canvas.getByTitle("Split diff")]) {
			await expect(link).toHaveAttribute("data-sveltekit-noscroll");
		}
	}}
/>

<Story name="Topbar slots" asChild>
	<DiffTopbar stat={{ insertions: 19, deletions: 11, files_changed: 1 }} fileCount={1}>
		{#snippet center()}
			<span class="font-mono typography-monospace-small text-foreground-muted">Round #2</span>
		{/snippet}
		{#snippet actions()}
			<span class="typography-paragraph-small text-foreground-muted">review panel</span>
		{/snippet}
	</DiffTopbar>
</Story>
