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

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

const widget: WidgetInstance = {
	id: "w1",
	service_id: "s1",
	widget_kind: "now_playing",
	title: "Now Playing",
	config: {},
	enabled: true,
	sort_order: 0,
	created_at: 0,
	updated_at: 0,
};

describe("JellyfinNowPlayingWidget", () => {
	it("renders sessions when data is present", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w1",
				data: {
					sessions: [
						{
							user: "alice",
							title: "Movie",
							state: "playing",
							type: "Movie",
							device: "Web",
							session_id: "s1",
							transcoding: "no",
							transcoding_type: "",
						},
					],
				},
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		render(
			<JellyfinNowPlayingWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(screen.getByText("alice")).toBeInTheDocument();
		expect(screen.getAllByText("Movie").length).toBeGreaterThan(0);
	});

	it("renders the now-playing empty message when no sessions", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w1",
				data: { sessions: [] },
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		render(
			<JellyfinNowPlayingWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(
			screen.getByText("No one is playing right now."),
		).toBeInTheDocument();
	});

	it("renders error state", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w1",
				error: "Connection failed",
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		render(
			<JellyfinNowPlayingWidget widget={widget} refreshIntervalMs={30000} />,
		);
		expect(screen.getByText("Connection failed")).toBeInTheDocument();
	});
});
