/* @vitest-environment jsdom */

import {
  fireEvent,
  render,
  screen,
  waitFor,
  within,
} from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';

import * as clipboardService from '../../services/clipboard';
import { PublishShareModal } from './PublishShareModal';
import {
  buildPublishShareText,
  type PublishShareModalPayload,
} from './publishShareModalModel';

vi.mock('../../services/clipboard', () => ({
  copyTextToClipboard: vi.fn(),
}));

const payload: PublishShareModalPayload = {
  title: '暖灯猫街',
  publicWorkCode: 'PZ-00000001',
  stage: 'puzzle-gallery-detail',
};

afterEach(() => {
  vi.clearAllMocks();
});

describe('PublishShareModal', () => {
  test('builds the publish share text with title, code and public url', () => {
    const text = buildPublishShareText(payload);

    expect(text).toContain('邀请你来玩《暖灯猫街》');
    expect(text).toContain('作品号：PZ-00000001');
    expect(text).toContain('/gallery/puzzle/detail?work=PZ-00000001');
  });

  test('renders share text and channel icons, then copies from main button', async () => {
    vi.mocked(clipboardService.copyTextToClipboard).mockResolvedValue(true);

    render(
      <PublishShareModal open payload={payload} onClose={() => {}} />,
    );

    const dialog = screen.getByRole('dialog', { name: '分享给朋友' });
    expect(dialog.parentElement?.className).toContain('!items-center');
    expect(dialog.parentElement?.className).toContain('platform-theme--light');
    expect(dialog.className).toContain('platform-modal-shell');
    expect(dialog.className).toContain('rounded-[1.75rem]');
    expect(dialog.getAttribute('style')).toBeNull();
    expect(within(dialog).getByText(/邀请你来玩《暖灯猫街》/u)).toBeTruthy();
    expect(within(dialog).getByRole('button', { name: '分享' })).toBeTruthy();
    expect(within(dialog).getByRole('button', { name: '分享到微信' })).toBeTruthy();
    expect(within(dialog).getByRole('button', { name: '分享到QQ' })).toBeTruthy();
    expect(within(dialog).getByRole('button', { name: '分享到抖音' })).toBeTruthy();

    fireEvent.click(within(dialog).getByRole('button', { name: '分享' }));

    expect(clipboardService.copyTextToClipboard).toHaveBeenCalledWith(
      expect.stringContaining('作品号：PZ-00000001'),
    );
    await waitFor(() => {
      expect(within(dialog).getByRole('button', { name: '已复制' })).toBeTruthy();
    });
  });
});
