import { mount } from '@vue/test-utils';
import Antd, { Alert, Result, Spin, Tag } from 'ant-design-vue';
import { describe, expect, it } from 'vitest';

import OperationStatus from '../../src/components/OperationStatus.vue';
import type { OperationState, RuntimeStatus } from '../../src/stores/annotation';

function mountStatus(status: RuntimeStatus, operation: OperationState, extra: { fatalMessage?: string; sdkAvailable?: boolean } = {}) {
  return mount(OperationStatus, { props: { status, operation, ...extra }, global: { plugins: [Antd] } });
}

describe('OperationStatus', () => {
  it('initializing 显示 Spin 和加载状态', () => {
    const wrapper = mountStatus('initializing', { kind: 'idle', message: '' });

    expect(wrapper.findComponent(Spin).exists()).toBe(true);
    expect(wrapper.get('[data-test="runtime-message"]').text()).toBe('正在连接 ONLYOFFICE...');
    expect(wrapper.get('[data-test="connection-status"]').text()).toBe('加载中');
  });

  it('working 显示 Spin 和业务消息', () => {
    const wrapper = mountStatus('working', { kind: 'working', message: '正在定位字段...' });

    expect(wrapper.findComponent(Spin).exists()).toBe(true);
    expect(wrapper.get('[data-test="runtime-message"]').text()).toBe('正在定位字段...');
  });

  it('ready 使用绿色 Tag 显示已连接，idle 不渲染操作提示', () => {
    const wrapper = mountStatus('ready', { kind: 'idle', message: '' });

    expect(wrapper.findComponent(Tag).props('color')).toBe('success');
    expect(wrapper.get('[data-test="connection-status"]').text()).toBe('已连接');
    expect(wrapper.get('[data-test="plugin-version"]').text()).toBe('v0.1.0');
    expect(wrapper.find('[data-test="operation-message"]').exists()).toBe(false);
  });

  it('不持续显示自动刷新成功文案', () => {
    const wrapper = mountStatus('ready', { kind: 'success', message: '文档字段已刷新' });

    expect(wrapper.find('[data-test="operation-message"]').exists()).toBe(false);
  });

  it('保留用户主动操作的成功反馈', () => {
    const wrapper = mountStatus('ready', { kind: 'success', message: '字段已定位' });

    expect(wrapper.get('[data-test="operation-message"]').text()).toBe('字段已定位');
  });

  it('operation error 使用 error Alert', () => {
    const wrapper = mountStatus('error', { kind: 'error', message: '读取内容控件失败' });

    expect(wrapper.findComponent(Alert).props('type')).toBe('error');
    expect(wrapper.text()).toContain('读取内容控件失败');
  });

  it('SDK 缺失显示不可继续的 fatal 结果', () => {
    const wrapper = mountStatus('error', { kind: 'idle', message: '' }, { sdkAvailable: false });

    expect(wrapper.findComponent(Result).exists() || wrapper.findComponent(Alert).exists()).toBe(true);
    expect(wrapper.text()).toContain('ONLYOFFICE SDK 未加载，无法初始化插件');
  });
});
