import { mount } from '@vue/test-utils';

import { describe, expect, it, vi } from 'vitest';

import CardList from '../CardList.vue';

const { hasAccessByCodes } = vi.hoisted(() => ({
  hasAccessByCodes: vi.fn((codes: string[]) => codes[0] !== 'blocked'),
}));

vi.mock('@easyflow/access', () => ({
  useAccess: () => ({
    hasAccessByCodes,
  }),
}));

vi.mock('#/locales', () => ({
  $t: (key: string) => {
    const labelMap: Record<string, string> = {
      'aiResource.created': '创建时间',
      'aiResource.createdBy': '创建者',
    };
    return labelMap[key] || key;
  },
}));

describe('cardList', () => {
  function mountCardList(props: Record<string, unknown>) {
    return mount(CardList, {
      props: {
        data: [
          {
            id: 'bot-1',
            title: '演示卡片',
            description: '用于验证主次交互是否正常工作',
          },
        ],
        defaultIcon: '/favicon.svg',
        ...props,
      },
      global: {
        stubs: {
          IconifyIcon: {
            props: ['icon'],
            template: '<span class="iconify-icon">{{ icon }}</span>',
          },
        },
      },
    });
  }

  it('点击卡片空白区域时触发主动作', async () => {
    const primaryAction = vi.fn();
    const wrapper = mountCardList({
      primaryAction: {
        text: '进入设置',
        onClick: primaryAction,
      },
    });

    await wrapper.get('.card-item').trigger('click');

    expect(primaryAction).toHaveBeenCalledTimes(1);
    expect(primaryAction).toHaveBeenCalledWith(
      expect.objectContaining({ id: 'bot-1' }),
    );
  });

  it('点击次级按钮时不会冒泡触发主动作', async () => {
    const primaryAction = vi.fn();
    const inlineAction = vi.fn();
    const wrapper = mountCardList({
      primaryAction: {
        text: '进入设置',
        onClick: primaryAction,
      },
      actions: [
        {
          text: '编辑',
          placement: 'inline',
          onClick: inlineAction,
        },
      ],
    });

    await wrapper.get('.card-action-btn').trigger('click');

    expect(inlineAction).toHaveBeenCalledTimes(1);
    expect(primaryAction).not.toHaveBeenCalled();
  });

  it('键盘 Enter 可以触发主动作', async () => {
    const primaryAction = vi.fn();
    const wrapper = mountCardList({
      primaryAction: {
        text: '进入设计',
        onClick: primaryAction,
      },
    });

    await wrapper.get('.card-item').trigger('keydown.enter');

    expect(primaryAction).toHaveBeenCalledTimes(1);
  });

  it('未提供主动作时保持旧卡片模式，不会把卡片变成可点击入口', async () => {
    const legacyAction = vi.fn();
    const wrapper = mountCardList({
      actions: [
        {
          text: '编辑',
          onClick: legacyAction,
        },
      ],
    });

    await wrapper.get('.card-item').trigger('click');
    await wrapper.get('.card-action-btn').trigger('click');

    expect(wrapper.get('.card-item').attributes('role')).toBeUndefined();
    expect(legacyAction).toHaveBeenCalledTimes(1);
  });

  it('同时展示创建人与创建时间', () => {
    const wrapper = mountCardList({
      data: [
        {
          id: 'bot-1',
          title: '演示卡片',
          description: '用于验证元信息展示',
          createdByName: '管理员',
          created: '2026-04-12 10:00:00',
        },
      ],
    });

    const metaText = wrapper.get('.card-meta-row').text();

    expect(metaText).toContain('创建者：管理员');
    expect(metaText).toContain('创建时间：2026-04-12 10:00:00');
  });

  it('缺少创建人时仅展示创建时间', () => {
    const wrapper = mountCardList({
      data: [
        {
          id: 'bot-1',
          title: '演示卡片',
          description: '用于验证元信息展示',
          created: '2026-04-12 10:00:00',
        },
      ],
    });

    const metaText = wrapper.get('.card-meta-row').text();

    expect(metaText).toContain('创建时间：2026-04-12 10:00:00');
    expect(metaText).not.toContain('创建者：');
  });

  it('缺少创建信息时不渲染元信息区', () => {
    const wrapper = mountCardList({
      data: [
        {
          id: 'bot-1',
          title: '演示卡片',
          description: '用于验证元信息展示',
        },
      ],
    });

    expect(wrapper.find('.card-meta-row').exists()).toBe(false);
  });
});
