/* @vitest-environment jsdom */

import { fireEvent, render, screen } from '@testing-library/react';
import { useState } from 'react';
import { describe, expect, it, vi } from 'vitest';

import type { GenerateDialogState } from './ImageCanvasEditorTypes';
import { ImageCanvasGenerationImageOptionsView } from './ImageCanvasGenerationImageOptionsView';
import {
  IMAGE_MODEL_GPT_IMAGE_2,
  IMAGE_MODEL_NANOBANANA2,
} from './ImageCanvasGenerationModel';

function ImageOptionsHarness({
  initialDialog,
  onRememberImageModel = vi.fn(),
}: {
  initialDialog: GenerateDialogState;
  onRememberImageModel?: (model: string) => void;
}) {
  const [dialog, setDialog] = useState<GenerateDialogState | null>(
    initialDialog,
  );

  return dialog ? (
    <div>
      <ImageCanvasGenerationImageOptionsView
        dialog={dialog}
        setGenerateDialog={setDialog}
        includeDimensions
        onRememberImageModel={onRememberImageModel}
      />
      <output aria-label="当前模型">{dialog.imageModel}</output>
      <output aria-label="当前比例">{dialog.aspectRatio}</output>
      <output aria-label="当前尺寸">{dialog.imageSize}</output>
      <output aria-label="当前状态">{dialog.status}</output>
      <output aria-label="当前错误">{dialog.errorMessage ?? '-'}</output>
    </div>
  ) : null;
}

describe('ImageCanvasGenerationImageOptionsView', () => {
  it('updates dimensions and resets failed dialog state', () => {
    render(
      <ImageOptionsHarness
        initialDialog={{
          mode: 'character',
          prompt: '',
          status: 'failed',
          errorMessage: '旧错误',
          imageModel: IMAGE_MODEL_NANOBANANA2,
          aspectRatio: '1:1',
          imageSize: '1K',
        }}
      />,
    );

    fireEvent.click(screen.getByRole('button', { name: '16:9' }));
    fireEvent.click(screen.getByRole('button', { name: '2K' }));

    expect(screen.getByLabelText('当前比例').textContent).toBe('16:9');
    expect(screen.getByLabelText('当前尺寸').textContent).toBe('2K');
    expect(screen.getByLabelText('当前状态').textContent).toBe('idle');
    expect(screen.getByLabelText('当前错误').textContent).toBe('-');
  });

  it('remembers model changes and keeps compatible dimensions', () => {
    const rememberImageModel = vi.fn();
    render(
      <ImageOptionsHarness
        initialDialog={{
          mode: 'icon',
          prompt: '',
          status: 'idle',
          imageModel: IMAGE_MODEL_NANOBANANA2,
          aspectRatio: '9:16',
          imageSize: '0.5K',
        }}
        onRememberImageModel={rememberImageModel}
      />,
    );

    fireEvent.click(screen.getByRole('button', { name: 'gpt-image-2' }));

    expect(rememberImageModel).toHaveBeenCalledWith(IMAGE_MODEL_GPT_IMAGE_2);
    expect(screen.getByLabelText('当前模型').textContent).toBe(
      IMAGE_MODEL_GPT_IMAGE_2,
    );
    expect(screen.getByLabelText('当前比例').textContent).toBe('9:16');
    expect(screen.getByLabelText('当前尺寸').textContent).toBe('1K');
  });
});
