import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { RecentPicksFeed } from "~/components/draft/RecentPicksFeed";

const makePick = (n: number) => ({
  id: String(n),
  pickNumber: n,
  participant: { name: `Participant ${n}` },
  sport: { name: "NFL" },
  team: { name: `Team ${n}` },
});

describe("RecentPicksFeed", () => {
  it("renders the Latest Picks header", () => {
    render(<RecentPicksFeed picks={[]} />);
    expect(screen.getByText("Latest Picks")).toBeInTheDocument();
  });

  it("shows picks by default (expanded)", () => {
    render(<RecentPicksFeed picks={[makePick(1), makePick(2)]} />);
    expect(screen.getByText("Participant 1")).toBeInTheDocument();
    expect(screen.getByText("Participant 2")).toBeInTheDocument();
  });

  it("shows empty message when no picks and expanded", () => {
    render(<RecentPicksFeed picks={[]} />);
    expect(screen.getByText("No picks yet")).toBeInTheDocument();
  });

  it("collapses picks when header button is clicked", async () => {
    const user = userEvent.setup();
    render(<RecentPicksFeed picks={[makePick(1), makePick(2)]} />);
    await user.click(screen.getByRole("button", { name: "Toggle latest picks" }));
    expect(screen.queryByText("Participant 1")).not.toBeInTheDocument();
    expect(screen.queryByText("Participant 2")).not.toBeInTheDocument();
  });

  it("re-expands when header button is clicked again", async () => {
    const user = userEvent.setup();
    render(<RecentPicksFeed picks={[makePick(1)]} />);
    const btn = screen.getByRole("button", { name: "Toggle latest picks" });
    await user.click(btn);
    await user.click(btn);
    expect(screen.getByText("Participant 1")).toBeInTheDocument();
  });

  it("limits display to the 3 most recent picks", () => {
    const picks = [makePick(1), makePick(2), makePick(3), makePick(4), makePick(5)];
    render(<RecentPicksFeed picks={picks} />);
    expect(screen.queryByText("Participant 1")).not.toBeInTheDocument();
    expect(screen.queryByText("Participant 2")).not.toBeInTheDocument();
    expect(screen.getByText("Participant 3")).toBeInTheDocument();
    expect(screen.getByText("Participant 4")).toBeInTheDocument();
    expect(screen.getByText("Participant 5")).toBeInTheDocument();
  });

  it("sets aria-expanded correctly", async () => {
    const user = userEvent.setup();
    render(<RecentPicksFeed picks={[makePick(1)]} />);
    const btn = screen.getByRole("button", { name: "Toggle latest picks" });
    expect(btn).toHaveAttribute("aria-expanded", "true");
    await user.click(btn);
    expect(btn).toHaveAttribute("aria-expanded", "false");
  });
});
