// @vitest-environment jsdom

import { mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";

import ConversationPanel from "./ConversationPanel.vue";

const store = vi.hoisted(() => ({
  activeSessionId: "ses_loading_progress",
  activeMessages: [] as Array<Record<string, unknown>>,
  error: null as string | null,
  sessionDetailLoading: false,
  sessionDetailLoadingProgress: {
    active: false,
    blocking: false,
    phase: "idle",
    label: ""
  },
  cancelAgentMessage: vi.fn(),
  retryAgentMessage: vi.fn()
}));

vi.mock("@/stores/workbench", () => ({ useWorkbenchStore: () => store }));
vi.mock("@/composables/useWorkbenchScrollRuntime", () => ({
  useWorkbenchBottomFollowScroll: () => ({
    following: { value: true },
    keepBottomAfterUpdate: vi.fn(),
    onScroll: vi.fn(),
    scrollToBottom: vi.fn()
  })
}));
vi.mock("@/utils/workbench-performance", () => ({ acknowledgeWorkbenchVisibleAfterPaint: vi.fn() }));

function mountPanel() {
  return mount(ConversationPanel, {
    global: {
      stubs: {
        LoadingState: { props: ["label"], template: "<div class='loading-state'>{{ label }}</div>" },
        WorkbenchMessageCard: { props: ["message"], template: "<article class='message-card'>{{ message.text }}</article>" },
        ApiErrorDiagnostic: { template: "<div />" },
        CodeAgentStatusSummary: { template: "<div />" },
        MessageActions: { template: "<div />" },
        MessageTraceDebugPanel: { template: "<div />" }
      }
    }
  });
}

describe("ConversationPanel progressive session loading", () => {
  beforeEach(() => {
    store.activeMessages = [];
    store.error = null;
    store.sessionDetailLoading = false;
    store.sessionDetailLoadingProgress = { active: false, blocking: false, phase: "idle", label: "" };
  });

  it("renders replayed messages while the SSE replay continues at the panel edge", () => {
    store.activeMessages = [{
      id: "msg_loading_progress",
      messageId: "msg_loading_progress",
      role: "user",
      title: "用户",
      text: "已经到达的回放消息",
      status: "sent",
      sessionId: store.activeSessionId,
      traceId: "trc_loading_progress",
      createdAt: "2026-07-21T12:00:00.000Z"
    }];
    store.sessionDetailLoadingProgress = {
      active: true,
      blocking: false,
      phase: "replaying",
      label: "实时流已连接，已显示 1 条，继续回放..."
    };

    const wrapper = mountPanel();
    expect(wrapper.get(".message-card").text()).toContain("已经到达的回放消息");
    expect(wrapper.get(".conversation-load-progress").text()).toContain("实时流已连接，已显示 1 条，继续回放...");
    expect(wrapper.find(".conversation-detail-loading").exists()).toBe(false);
    wrapper.unmount();
  });

  it("keeps the centered phase label before the first replay message", () => {
    store.sessionDetailLoading = true;
    store.sessionDetailLoadingProgress = {
      active: true,
      blocking: true,
      phase: "selecting",
      label: "正在选择会话并建立实时连接..."
    };

    const wrapper = mountPanel();
    expect(wrapper.get(".conversation-detail-loading").text()).toContain("正在选择会话并建立实时连接...");
    expect(wrapper.find(".conversation-empty-hint").exists()).toBe(false);
    expect(wrapper.find(".conversation-load-progress").exists()).toBe(false);
    wrapper.unmount();
  });
});
