import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { QbittorrentTotalsWidget } from "../QbittorrentTotalsWidget";
import type { WidgetInstance } from "../../types";
import * as useWidgets from "../../hooks/useWidgets";

vi.mock("../../hooks/useWidgets", () => ({
	useWidgetData: vi.fn(),
}));

const widget: WidgetInstance = {
	id: "w1",
	service_id: "s1",
	widget_kind: "totals",
	title: "Torrent Totals",
	config: {},
	enabled: true,
	sort_order: 0,
	created_at: 0,
	updated_at: 0,
};

function mockData(data: unknown, error?: string) {
	vi.mocked(useWidgets.useWidgetData).mockReturnValue({
		data: error
			? { widget_id: "w1", error, fetched_at: 0 }
			: { widget_id: "w1", data, fetched_at: 0 },
		isLoading: false,
	} as unknown as ReturnType<typeof useWidgets.useWidgetData>);
}

describe("QbittorrentTotalsWidget", () => {
	it("renders skeleton while loading", () => {
		vi.mocked(useWidgets.useWidgetData).mockReturnValue({
			data: undefined,
			isLoading: true,
		} as unknown as ReturnType<typeof useWidgets.useWidgetData>);
		render(
			<QbittorrentTotalsWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(
			document.querySelector('[data-slot="skeleton"]'),
		).toBeInTheDocument();
	});

	it("renders total count and state badges", () => {
		mockData({
			total: 4,
			by_state: { downloading: 1, uploading: 1, pausedDL: 2 },
		});
		render(
			<QbittorrentTotalsWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(screen.getByText("4")).toBeInTheDocument();
		expect(screen.getByText("downloading: 1")).toBeInTheDocument();
		expect(screen.getByText("pausedDL: 2")).toBeInTheDocument();
	});

	it("shows error alert on error", () => {
		mockData(null, "qBittorrent fetch failed");
		render(
			<QbittorrentTotalsWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(screen.getByText(/qBittorrent fetch failed/i)).toBeInTheDocument();
	});
});
