// @vitest-environment jsdom

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

import type { PuzzleCreativeTemplateSelection } from '../../../packages/shared/src/contracts/puzzleCreativeTemplate';
import { CreativeAgentTemplateConfirmPanel } from './CreativeAgentTemplateConfirmPanel';

function createSelection(
  overrides: Partial<PuzzleCreativeTemplateSelection> = {},
): PuzzleCreativeTemplateSelection {
  return {
    templateId: 'puzzle.default-creative',
    title: '创意拼图',
    reason: '这份素材适合转成可编辑、可试玩的拼图草稿。',
    costRange: {
      minPoints: 2,
      maxPoints: 12,
      pricingUnit: 'point',
      reason: '按关卡数和每关图片生成次数估算',
    },
    supportedLevelMode: 'single_or_multi',
    selectedLevelMode: 'single_level',
    plannedLevelCount: 1,
    requiresUserConfirmation: true,
    ...overrides,
  };
}

test('shows cost range and opens an independent adjustment dialog', () => {
  const onConfirm = vi.fn();

  render(
    <CreativeAgentTemplateConfirmPanel
      selection={createSelection()}
      isBusy={false}
      onConfirm={onConfirm}
      onCancel={() => {}}
    />,
  );

  const confirmDialog = screen.getByRole('dialog', { name: '确认拼图模板' });
  expect(within(confirmDialog).getByText('预计 2 到 12 泥点')).toBeTruthy();
  expect(within(confirmDialog).getByText('创意拼图')).toBeTruthy();

  fireEvent.click(within(confirmDialog).getByRole('button', { name: /调整/u }));
  const adjustDialog = screen.getByRole('dialog', { name: '调整拼图模板' });
  expect(adjustDialog.parentElement).not.toBe(confirmDialog);

  fireEvent.click(within(adjustDialog).getByRole('button', { name: '多关卡' }));
  fireEvent.change(within(adjustDialog).getByLabelText('计划关卡数'), {
    target: { value: '4' },
  });
  fireEvent.click(within(adjustDialog).getByRole('button', { name: '完成' }));
  fireEvent.click(within(confirmDialog).getByRole('button', { name: /确认/u }));

  expect(onConfirm).toHaveBeenCalledWith(
    expect.objectContaining({
      selectedLevelMode: 'multi_level',
      plannedLevelCount: 4,
    }),
  );
});
