import { fireEvent, screen, waitFor } from "@testing-library/react";
import { describe, expect, test, vi } from "bun:test";
import { createElement } from "react";

import type { Conversation } from "../../../src/shared/api";

import { ConversationCard } from "../../../src/web/features/chat/components/ConversationCard";
import { renderWithProviders } from "../test-utils";

const MOCK_CONVERSATION: Conversation = {
  createdAt: "2026-06-03T00:00:00.000Z",
  id: "conv-1",
  modelId: "model-1",
  projectId: "proj-1",
  title: "测试对话",
  updatedAt: "2026-06-03T00:00:00.000Z",
};

describe("ConversationCard", () => {
  test("渲染对话标题", () => {
    renderWithProviders(
      createElement(ConversationCard, {
        conversation: MOCK_CONVERSATION,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: false,
      }),
    );
    expect(screen.getByText("测试对话")).not.toBeNull();
  });

  test("点击卡片触发 onSelect", () => {
    const onSelect = vi.fn();
    renderWithProviders(
      createElement(ConversationCard, {
        conversation: MOCK_CONVERSATION,
        onDelete: vi.fn(),
        onSelect,
        selected: false,
      }),
    );
    const item = screen.getByText("测试对话").closest(".app-sidebar-list-item")!;
    fireEvent.click(item);
    expect(onSelect).toHaveBeenCalledTimes(1);
  });

  test("点击删除按钮弹出确认框，确认后触发 onDelete", async () => {
    const onDelete = vi.fn();
    renderWithProviders(
      createElement(ConversationCard, {
        conversation: MOCK_CONVERSATION,
        onDelete,
        onSelect: vi.fn(),
        selected: false,
      }),
    );
    fireEvent.click(screen.getByLabelText("删除"));

    await waitFor(() => {
      expect(screen.getByText("确认删除该对话？")).not.toBeNull();
    });

    fireEvent.click(screen.getByText("删 除"));

    await waitFor(() => {
      expect(onDelete).toHaveBeenCalledTimes(1);
    });
  });

  test("选中时包含 app-sidebar-list-item--selected 类名", () => {
    renderWithProviders(
      createElement(ConversationCard, {
        conversation: MOCK_CONVERSATION,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: true,
      }),
    );
    const item = screen.getByText("测试对话").closest(".app-sidebar-list-item--selected");
    expect(item).not.toBeNull();
  });

  test("未选中时不包含 app-sidebar-list-item--selected 类名", () => {
    renderWithProviders(
      createElement(ConversationCard, {
        conversation: MOCK_CONVERSATION,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: false,
      }),
    );
    const item = screen.getByText("测试对话").closest(".app-sidebar-list-item--selected");
    expect(item).toBeNull();
  });
});
