import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { MemoryRouter } from "react-router-dom";
import { FileBrowser } from "./FileBrowser";

// Mock apiClient
vi.mock("../../../api/client", () => ({
	apiClient: {
		get: vi.fn(),
	},
}));

import { apiClient } from "../../../api/client";

describe("FileBrowser", () => {
	it("renders loading state initially", () => {
		render(
			<MemoryRouter>
				<FileBrowser projectId="p1" repoId="r1" gitStatus={null} />
			</MemoryRouter>,
		);
		expect(screen.getByText(/loading files/i)).toBeInTheDocument();
	});

	it("renders file entries after loading", async () => {
		const mockedGet = apiClient.get as ReturnType<typeof vi.fn>;
		mockedGet.mockResolvedValueOnce({
			data: {
				entries: [
					{ name: "src", type: "directory", path: "src" },
					{ name: "README.md", type: "file", path: "README.md" },
				],
			},
		});

		render(
			<MemoryRouter>
				<FileBrowser projectId="p1" repoId="r1" gitStatus={null} />
			</MemoryRouter>,
		);

		await waitFor(() => {
			expect(screen.getByText("src")).toBeInTheDocument();
		});
		expect(screen.getByText("README.md")).toBeInTheDocument();
	});

	it("renders error state on failure", async () => {
		const mockedGet = apiClient.get as ReturnType<typeof vi.fn>;
		mockedGet.mockRejectedValueOnce(new Error("Network error"));

		render(
			<MemoryRouter>
				<FileBrowser projectId="p1" repoId="r1" gitStatus={null} />
			</MemoryRouter>,
		);

		await waitFor(() => {
			expect(screen.getByText(/failed to load files/i)).toBeInTheDocument();
		});
	});
});
