import { describe, it, expect, vi } from "vitest";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderWithMantine } from "../../test/utils";
import RoomList from "../../components/RoomList";
import type { RoomSummary } from "../../types";

function room(over: Partial<RoomSummary> = {}): RoomSummary {
  return {
    room_id: "!room1:server",
    name: "Public Room",
    canonical_alias: undefined,
    avatar_mxc: undefined,
    topic: undefined,
    is_direct: false,
    is_space: false,
    is_encrypted: false,
    member_count: 3,
    last_event_ts: Date.now() - 5000,
    unread_count: 0,
    tags: [],
    ...over,
  } as RoomSummary;
}

describe("RoomList", () => {
  it("renders each room with its name", () => {
    const rooms: RoomSummary[] = [
      room({ room_id: "!a:s", name: "Alpha" }),
      room({ room_id: "!b:s", name: "Beta" }),
      room({ room_id: "!c:s", name: "Gamma" }),
    ];

    renderWithMantine(
      <RoomList rooms={rooms} activeRoomID={null} onSelect={() => {}} />,
    );

    expect(screen.getByText("Alpha")).toBeInTheDocument();
    expect(screen.getByText("Beta")).toBeInTheDocument();
    expect(screen.getByText("Gamma")).toBeInTheDocument();
  });

  it("invokes onSelect with the room id when a room is clicked", async () => {
    const user = userEvent.setup();
    const onSelect = vi.fn();
    const rooms = [room({ room_id: "!a:s", name: "Alpha" })];

    renderWithMantine(
      <RoomList rooms={rooms} activeRoomID={null} onSelect={onSelect} />,
    );

    await user.click(screen.getByText("Alpha"));
    expect(onSelect).toHaveBeenCalledWith("!a:s");
  });

  it("shows the lock icon for encrypted rooms", () => {
    const rooms = [
      room({ room_id: "!e:s", name: "Encrypted Room", is_encrypted: true }),
    ];

    const { container } = renderWithMantine(
      <RoomList rooms={rooms} activeRoomID={null} onSelect={() => {}} />,
    );

    // tabler IconLock renders an <svg class="...tabler-icon-lock...">.
    const lock = container.querySelector(".tabler-icon-lock");
    expect(lock).not.toBeNull();
  });

  it("shows empty placeholder when no rooms", () => {
    renderWithMantine(
      <RoomList rooms={[]} activeRoomID={null} onSelect={() => {}} />,
    );
    expect(screen.getByText(/no rooms yet/i)).toBeInTheDocument();
  });
});
