import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SettingsProvider } from '@ablogcms/unit-editor/components/config-editor/stores/settings';
import { defaultConfigEditorSettings } from '@ablogcms/unit-editor/config';
import type { UnitConfigEditProps } from '@ablogcms/unit-editor/core/types';
import Config from './config';

vi.mock('./components/async-rich-editor', () => ({
  default: () => <div data-testid="rich-editor-stub" />,
}));

const config: UnitConfigEditProps['config'] = {
  id: 'config-1',
  parentId: null,
  name: 'text',
  type: 'text',
  group: 'group-a',
  field_1: '',
};

const mockUpdate = vi.fn();
const mockEditor = { update: mockUpdate } as unknown as UnitConfigEditProps['editor'];

describe('rich-editor unit-def Config', () => {
  it('unitGroup が無効な場合、グループ選択欄は表示されない', () => {
    render(
      <SettingsProvider settings={defaultConfigEditorSettings}>
        <Config config={config} editor={mockEditor} />
      </SettingsProvider>
    );

    expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
  });

  it('unitGroup が有効な場合、Select コンポーネントが acms-admin-form-select クラス付きでレンダリングされる', async () => {
    const user = userEvent.setup();

    render(
      <SettingsProvider
        settings={{
          ...defaultConfigEditorSettings,
          unitGroup: {
            enable: true,
            options: [
              { value: 'group-a', label: 'グループA' },
              { value: 'group-b', label: 'グループB' },
            ],
          },
        }}
      >
        <Config config={config} editor={mockEditor} />
      </SettingsProvider>
    );

    const select = screen.getByRole('combobox');
    expect(select).toHaveClass('acms-admin-form-select');
    expect(select).toHaveAttribute('id', `${config.id}-group`);
    expect(select).toHaveValue('group-a');

    await user.selectOptions(select, 'group-b');
    expect(mockUpdate).toHaveBeenCalledWith(config.id, expect.any(Function));
  });
});
