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

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

	const copiesContents = async ({ canvas, userEvent }: PlayContext) => {
		const written: string[] = [];
		Object.defineProperty(navigator, "clipboard", {
			value: { writeText: async (text: string) => written.push(text) },
			configurable: true
		});
		await userEvent.click(canvas.getByRole("button", { name: "Copy contents" }));
		await expect(written).toEqual(["export const answer = 42;\n"]);

		await expect(canvas.getByRole("link", { name: "View raw" })).toHaveAttribute(
			"href",
			"/dawn/tangled/raw/main/web/src/lib/components/repo/BlobView.svelte"
		);
		const download = canvas.getByRole("link", { name: "Download" });
		await expect(download).toHaveAttribute("download", "BlobView.svelte");
	};

	const showsLanguageChip = async ({ canvas, canvasElement }: PlayContext) => {
		await expect(canvas.getByText("Svelte")).toBeVisible();
		await expect(canvasElement.querySelector(".size-2.rounded-full")).not.toBeNull();
	};

	const flipsView = async ({ canvas, userEvent }: PlayContext) => {
		await userEvent.click(canvas.getByRole("button", { name: "View code" }));
		await expect(canvas.getByRole("button", { name: "View rendered" })).toBeVisible();
	};

	const { Story } = defineMeta({
		title: "Repo/BlobHeader",
		component: BlobHeader,
		tags: ["autodocs"],
		args: {
			ownerHandle: "dawn",
			repoName: "tangled",
			ref: "main",
			path: "web/src/lib/components/repo/BlobView.svelte",
			kind: "code",
			sizeLabel: "4.2 kB",
			lines: 87,
			copyText: "export const answer = 42;\n"
		}
	});
</script>

<Story name="Code file" play={copiesContents} />

<Story
	name="Language chip"
	args={{ path: "web/src/App.svelte", language: "Svelte" }}
	play={showsLanguageChip}
/>

<Story
	name="Markdown rendered"
	args={{ kind: "markup", path: "docs/guide.md", view: "rendered" }}
	play={flipsView}
/>

<Story
	name="Wrap toggle"
	args={{ showWrap: true }}
	play={async ({ canvas, userEvent }: PlayContext) => {
		const toggle = canvas.getByRole("checkbox", { name: "Wrap" });
		await expect(toggle).not.toBeChecked();
		await userEvent.click(toggle);
		await expect(toggle).toBeChecked();
	}}
/>

<Story
	name="Submodule"
	args={{ kind: "submodule", path: "vendor/spindle", sizeLabel: null, lines: null, copyText: null }}
	play={async ({ canvas }: PlayContext) => {
		await expect(canvas.getByText("spindle")).toBeVisible();
		await expect(canvas.queryByRole("link", { name: "View raw" })).toBeNull();
		await expect(canvas.queryByRole("button", { name: "Download" })).toBeNull();
	}}
/>
