import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import type { Root } from 'react-dom/client';
import type { ProjectDocument } from '../../types/project';
import { executeAction } from '../../api/proxyApi';
import { usePreviewRuntime } from './usePreviewRuntime';

jest.mock('../../api/proxyApi', () => ({ executeAction: jest.fn() }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

const doc: ProjectDocument = {
  schemaVersion: '0.1.0',
  project: {
    id: 'project', name: 'Project', variables: {}, bindings: [],
    settings: {},
    actions: [{ id: 'action_a', name: 'Action A', method: 'GET', url: 'https://example.com', authenticationType: 'anonymous' }],
    pages: [{
      id: 'page', name: 'Page', order: 0,
      components: [{
        id: 'button', name: 'runButton', type: 'Button',
        position: { x: 0, y: 0 }, size: { width: 100, height: 40 },
        properties: { label: 'Run' },
        events: [{ event: 'onClick', actionId: 'action_a' }],
      }],
    }],
  },
};

describe('Preview Button event dispatch', () => {
  let container: HTMLDivElement;
  let root: Root;
  let runtime: ReturnType<typeof usePreviewRuntime>;
  function Harness(): React.ReactElement {
    runtime = usePreviewRuntime(doc);
    return <div>{runtime.componentState.button?.error ?? ''}</div>;
  }

  beforeEach(() => {
    container = document.createElement('div');
    root = createRoot(container);
    (executeAction as jest.Mock).mockResolvedValue({ ok: true, status: 200, headers: {}, body: { ran: true } });
    act(() => root.render(<Harness />));
  });
  afterEach(() => {
    act(() => root.unmount());
    jest.clearAllMocks();
  });

  test('executes the REST action selected by canonical onClick configuration', async () => {
    await act(async () => {
      runtime.handleButtonClick('button');
      await Promise.resolve();
      await Promise.resolve();
    });
    expect(executeAction).toHaveBeenCalledWith(expect.objectContaining({ id: 'action_a' }));
  });
});
