import { describe, it, expect, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import BackupRunsTable from "../BackupRunsTable";
import type { BackupRun } from "../../types/backups";

function run(overrides: Partial<BackupRun> = {}): BackupRun {
	return {
		id: "r1",
		job_id: "job-1",
		started_at: 1_700_000_000,
		ended_at: null,
		status: "success",
		bytes_transferred: 2048,
		duration_ms: 1500,
		error_message: null,
		details_json: null,
		created_at: 1_700_000_000,
		...overrides,
	};
}

describe("BackupRunsTable", () => {
	it("maps run status onto Badge variants per design §2.3", () => {
		render(
			<BackupRunsTable
				runs={[
					run({ id: "a", status: "success" }),
					run({ id: "b", status: "failure" }),
					run({ id: "c", status: "in_progress" }),
				]}
			/>,
		);
		expect(screen.getByText("success").getAttribute("data-variant")).toBe(
			"success",
		);
		expect(screen.getByText("failure").getAttribute("data-variant")).toBe(
			"destructive",
		);
		expect(screen.getByText("in_progress").getAttribute("data-variant")).toBe(
			"warning",
		);
	});

	it("renders the formatted duration and transferred size", () => {
		render(
			<BackupRunsTable
				runs={[
					run({
						id: "fmt",
						duration_ms: 1500,
						bytes_transferred: 2048,
					}),
				]}
			/>,
		);
		expect(screen.getByText("1.5s")).toBeInTheDocument();
		expect(screen.getByText("2.0 KB")).toBeInTheDocument();
	});
});

// jsdom lacks matchMedia; default to desktop so existing tests are unaffected.
function setMatchMedia(matches: boolean) {
	window.matchMedia = ((query: string) => ({
		matches: query.includes("768") ? matches : false,
		media: query,
		onchange: null,
		addEventListener: () => {},
		removeEventListener: () => {},
		addListener: () => {},
		removeListener: () => {},
		dispatchEvent: () => false,
	})) as unknown as typeof window.matchMedia;
}

beforeEach(() => setMatchMedia(false));

describe("BackupRunsTable (mobile card layout — slice 5)", () => {
	it("renders cards with job_id as primary below md", () => {
		setMatchMedia(true);
		render(<BackupRunsTable runs={[run({ id: "r1", job_id: "nightly" })]} />);
		expect(screen.getByText("nightly")).toBeInTheDocument();
		expect(screen.getAllByText("Status")).toHaveLength(1);
		expect(screen.getAllByText("Duration")).toHaveLength(1);
	});
});
