import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/svelte";
import ArtistLinks from "./ArtistLinks.svelte";

const goto = vi.fn();
vi.mock("$app/navigation", () => ({
  goto: (...args: unknown[]) => goto(...args),
}));

describe("ArtistLinks", () => {
  beforeEach(() => goto.mockClear());

  it("renders a clickable link per artist that navigates to its detail page", async () => {
    render(ArtistLinks, {
      artistItems: [
        { id: "a1", name: "Radiohead" },
        { id: "a2", name: "Thom Yorke" },
      ],
    });

    const link = screen.getByRole("button", { name: "Radiohead" });
    await fireEvent.click(link);

    expect(goto).toHaveBeenCalledWith("/library/a1");
    expect(screen.getByRole("button", { name: "Thom Yorke" })).toBeTruthy();
  });

  it("falls back to plain text when only names (no ids) are available", () => {
    render(ArtistLinks, { artists: ["Unknown Artist"] });

    expect(screen.queryByRole("button")).toBeNull();
    expect(screen.getByText("Unknown Artist")).toBeTruthy();
  });

  it("ignores artistItems with blank ids and uses the names fallback", () => {
    render(ArtistLinks, {
      artistItems: [{ id: "  ", name: "No Id Artist" }],
      artists: ["No Id Artist"],
    });

    expect(screen.queryByRole("button")).toBeNull();
    expect(screen.getByText("No Id Artist")).toBeTruthy();
  });

  it("calls onNavigate before navigating (e.g. to close a player)", async () => {
    const onNavigate = vi.fn();
    render(ArtistLinks, {
      artistItems: [{ id: "a1", name: "Radiohead" }],
      onNavigate,
    });

    await fireEvent.click(screen.getByRole("button", { name: "Radiohead" }));

    expect(onNavigate).toHaveBeenCalledOnce();
    expect(goto).toHaveBeenCalledWith("/library/a1");
  });
});
