import { render, screen, fireEvent } from '@testing-library/react';
import { NodePalette } from '../NodePalette';
import type { NodeTypeDef } from '../types';

const nodeTypes: NodeTypeDef[] = [
  { slug: 'trigger.event', name: 'Event trigger', category: 'trigger' },
  { slug: 'action.email', name: 'Send email', category: 'action' },
  { slug: 'action.http', name: 'HTTP request', category: 'action' },
  { slug: 'condition.if', name: 'If', category: 'condition' },
];

describe('NodePalette', () => {
  it('lists all node types grouped by category', () => {
    render(<NodePalette nodeTypes={nodeTypes} />);
    expect(screen.getByText('Event trigger')).toBeInTheDocument();
    expect(screen.getByText('Send email')).toBeInTheDocument();
    expect(screen.getByText('HTTP request')).toBeInTheDocument();
    expect(screen.getByText('If')).toBeInTheDocument();
    // group headings (category labels)
    expect(screen.getByText('Trigger')).toBeInTheDocument();
    expect(screen.getByText('Action')).toBeInTheDocument();
  });

  it('filters node types by search query', () => {
    render(<NodePalette nodeTypes={nodeTypes} />);
    const search = screen.getByRole('searchbox');
    fireEvent.change(search, { target: { value: 'email' } });
    expect(screen.getByText('Send email')).toBeInTheDocument();
    expect(screen.queryByText('HTTP request')).not.toBeInTheDocument();
    expect(screen.queryByText('If')).not.toBeInTheDocument();
  });

  it('sets the node type slug on dataTransfer when dragging', () => {
    render(<NodePalette nodeTypes={nodeTypes} />);
    const item = screen.getByText('Send email').closest('[draggable="true"]');
    expect(item).not.toBeNull();
    const setData = jest.fn();
    fireEvent.dragStart(item as Element, {
      dataTransfer: { setData, effectAllowed: '' },
    });
    expect(setData).toHaveBeenCalledWith(
      'application/x-workflow-node',
      'action.email'
    );
  });
});
