// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";

import { cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { polyfillDialog } from "../../__tests__/polyfill-dialog.js";
import { ExportMethodDialog } from "../export-method-dialog.js";

afterEach(cleanup);

beforeAll(() => {
	polyfillDialog();
});

function renderDialog(open = true) {
	const onDownload = vi.fn();
	const onCopyToClipboard = vi.fn();
	const onClose = vi.fn();
	const result = render(
		<ExportMethodDialog
			open={open}
			onDownload={onDownload}
			onCopyToClipboard={onCopyToClipboard}
			onClose={onClose}
		/>,
	);
	return { ...result, onDownload, onCopyToClipboard, onClose };
}

describe("ExportMethodDialog", () => {
	it("renders filename input and unchecked history checkbox", () => {
		renderDialog();
		expect(
			screen.getByPlaceholderText("Filename (optional)"),
		).toBeInTheDocument();
		const checkbox = screen.getByRole("checkbox");
		expect(checkbox).not.toBeChecked();
	});

	it("download button calls onDownload with defaults", async () => {
		const user = userEvent.setup();
		const { onDownload } = renderDialog();

		await user.click(screen.getByText("Download file"));
		expect(onDownload).toHaveBeenCalledWith(false, "");
	});

	it("download with filename and history checked", async () => {
		const user = userEvent.setup();
		const { onDownload } = renderDialog();

		await user.type(
			screen.getByPlaceholderText("Filename (optional)"),
			"my-encounter",
		);
		await user.click(screen.getByRole("checkbox"));
		await user.click(screen.getByText("Download file"));
		expect(onDownload).toHaveBeenCalledWith(true, "my-encounter");
	});

	it("copy to clipboard calls onCopyToClipboard and shows Copied", async () => {
		const user = userEvent.setup();
		const { onCopyToClipboard } = renderDialog();

		await user.click(screen.getByText("Copy to clipboard"));
		expect(onCopyToClipboard).toHaveBeenCalledWith(false);
		expect(screen.getByText("Copied!")).toBeInTheDocument();
	});

	it("Copied! reverts after 2 seconds", async () => {
		const user = userEvent.setup();
		renderDialog();

		await user.click(screen.getByText("Copy to clipboard"));
		expect(screen.getByText("Copied!")).toBeInTheDocument();

		await waitFor(
			() => {
				expect(screen.queryByText("Copied!")).not.toBeInTheDocument();
			},
			{ timeout: 3000 },
		);
		expect(screen.getByText("Copy to clipboard")).toBeInTheDocument();
	});
});
