// @vitest-environment jsdom

import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentProps } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { NetworkAdminClubCard } from "@/components/network-admin-club-card";
import type { BallboxStoreClubDetail } from "@/lib/ballbox-store";

const clubs: BallboxStoreClubDetail[] = [
  {
    id: "club_1",
    atcSportclubId: "106",
    name: "Club One",
    locationName: "Buenos Aires",
    venues: [
      {
        id: "venue_1",
        name: "Venue One",
        slug: "venue-one",
        status: "active",
        machines: 1,
        screens: 2,
        screenIds: ["screen_a", "screen_b"],
        vendingMachines: [],
      },
    ],
  },
  {
    id: "club_2",
    atcSportclubId: "107",
    name: "Club Two",
    locationName: null,
    venues: [],
  },
];

function renderClubCard(overrides?: Partial<ComponentProps<typeof NetworkAdminClubCard>>) {
  return render(
    <NetworkAdminClubCard
      club={clubs[0]}
      busy={false}
      setClubs={vi.fn()}
      venueForm={{ name: "", slug: "", status: "active" }}
      setVenueForms={vi.fn()}
      emptyVenueForm={{ name: "", slug: "", status: "active" }}
      machineForms={{}}
      setMachineForms={vi.fn()}
      emptyMachineForm={{ label: "", active: true }}
      venueStatusOptions={["active", "inactive"]}
      selectClassName="select"
      articleCardClassName="article"
      mutedPanelClassName="muted"
      insetPanelClassName="inset"
      wellClassName="well"
      runMutation={vi.fn()}
      {...overrides}
    />
  );
}

describe("NetworkAdminClubCard", () => {
  afterEach(() => {
    cleanup();
  });

  it("updates the targeted club ATC id through setClubs", () => {
    const setClubs = vi.fn();
    renderClubCard({ setClubs });

    fireEvent.change(screen.getByDisplayValue("106"), { target: { value: "999" } });

    const update = setClubs.mock.calls[0]?.[0] as ((value: BallboxStoreClubDetail[]) => BallboxStoreClubDetail[]) | undefined;
    expect(update).toBeTypeOf("function");

    const nextClubs = update?.(clubs);
    expect(nextClubs?.[0].atcSportclubId).toBe("999");
    expect(nextClubs?.[1].atcSportclubId).toBe("107");
  });

  it("renders the empty venue state when the club has no venues", () => {
    renderClubCard({ club: clubs[1] });

    expect(screen.getByText("No venues yet.")).toBeTruthy();
  });
});
