import type { ChatImageAttachment } from '../types';

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

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

import ChatImageAttachments from '../ChatImageAttachments.vue';

const image: ChatImageAttachment = {
  name: '界面截图.png',
  previewUrl: 'data:image/png;base64,aW1hZ2U=',
  status: 'ready',
};

afterEach(() => {
  document.body.innerHTML = '';
});

describe('chat image attachments', () => {
  it('opens the complete image preview from a ready thumbnail', async () => {
    const wrapper = mount(ChatImageAttachments, {
      attachTo: document.body,
      props: {
        items: [image],
      },
    });
    await flushPromises();

    const trigger = wrapper.get('[aria-label="查看完整图片：界面截图.png"]');
    expect(trigger.attributes('disabled')).toBeUndefined();
    expect(
      wrapper.get('.chat-image-attachments__image').attributes('src'),
    ).toBe(image.previewUrl);

    await trigger.trigger('click');
    await flushPromises();

    const dialog = document.body.querySelector('[role="dialog"]');
    const preview = document.body.querySelector<HTMLImageElement>(
      '.chat-image-preview__image',
    );
    expect(dialog).not.toBeNull();
    expect(preview?.src).toBe(image.previewUrl);
    expect(preview?.alt).toBe(image.name);

    wrapper.unmount();
  });

  it('keeps an uploading image unavailable for preview', async () => {
    const wrapper = mount(ChatImageAttachments, {
      props: {
        items: [{ ...image, status: 'uploading' }],
      },
    });
    await flushPromises();

    const trigger = wrapper.get('[aria-label="查看完整图片：界面截图.png"]');
    expect(trigger.attributes('disabled')).toBeDefined();

    await trigger.trigger('click');
    await flushPromises();

    expect(document.body.querySelector('[role="dialog"]')).toBeNull();
  });

  it('closes the preview when its image is removed', async () => {
    const wrapper = mount(ChatImageAttachments, {
      attachTo: document.body,
      props: {
        items: [image],
      },
    });
    await flushPromises();
    await wrapper
      .get('[aria-label="查看完整图片：界面截图.png"]')
      .trigger('click');
    await flushPromises();
    expect(document.body.querySelector('[role="dialog"]')).not.toBeNull();

    await wrapper.setProps({ items: [] });
    await flushPromises();

    expect(document.body.querySelector('[role="dialog"]')).toBeNull();
    wrapper.unmount();
  });
});
