<script module lang="ts">
	import { defineMeta } from "@storybook/addon-svelte-csf";
	import { expect, userEvent, waitFor, within } from "storybook/test";
	import CommentCard from "./CommentCard.svelte";
	import MockAuthProvider from "$lib/components/testing/MockAuthProvider.svelte";
	import {
		sampleComments,
		sampleMarkup,
		sampleSubjectCid,
		sampleSubjectUri,
		sampleThread,
		soloThread
	} from "./sampleComments";

	// a thread the logged-in user owns, so the edit affordance shows
	const myThread = { self: sampleComments.mine, replies: [] };

	const { Story } = defineMeta({
		title: "Comment/CommentCard",
		component: CommentCard,
		tags: ["autodocs"],
		args: {
			thread: soloThread,
			subjectUri: sampleSubjectUri,
			subjectCid: sampleSubjectCid,
			markup: sampleMarkup
		}
	});
</script>

<!-- logged out: the reply affordance is a login prompt -->
<Story name="Top level only" />
<Story name="With replies" args={{ thread: sampleThread }} />

<!-- logged in: clicking "Leave a reply" opens an inline reply box -->
<Story
	name="Replying"
	play={async ({ canvasElement }) => {
		const canvas = within(canvasElement);
		await userEvent.click(canvas.getByRole("button", { name: "Leave a reply..." }));
		const textarea = await waitFor(() => canvas.getByPlaceholderText(/write a reply/i));
		await expect(canvas.getByRole("button", { name: "Reply" })).toBeInTheDocument();
		await expect(canvas.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
		// the editor should be focused so the user can type immediately
		await waitFor(() => expect(textarea).toHaveFocus());
	}}
>
	{#snippet template(args)}
		<MockAuthProvider>
			<CommentCard {...args} />
		</MockAuthProvider>
	{/snippet}
</Story>

<!-- logged in as the author: the edit icon opens an inline editor prefilled with the body -->
<Story
	name="Editing"
	args={{ thread: myThread }}
	play={async ({ canvasElement }) => {
		const canvas = within(canvasElement);
		await userEvent.click(canvas.getByRole("button", { name: "Edit comment" }));
		const textarea = await waitFor(() => canvas.getByPlaceholderText(/edit your comment/i));
		await expect(textarea).toHaveValue(sampleComments.mine.body);
		await expect(canvas.getByRole("button", { name: "Save" })).toBeInTheDocument();
		await expect(canvas.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
	}}
>
	{#snippet template(args)}
		<MockAuthProvider>
			<CommentCard {...args} />
		</MockAuthProvider>
	{/snippet}
</Story>
