import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { TreeView, TreeNode } from './tree-view';
import React from 'react';

const testData: TreeNode[] = [
  {
    id: '1',
    label: 'Root 1',
    children: [
      { id: '1.1', label: 'Child 1.1' },
      { id: '1.2', label: 'Child 1.2' },
    ],
  },
  {
    id: '2',
    label: 'Root 2',
  },
];

describe('TreeView', () => {
  it('renders root nodes correctly', () => {
    render(<TreeView data={testData} />);

    expect(screen.getByText('Root 1')).toBeInTheDocument();
    expect(screen.getByText('Root 2')).toBeInTheDocument();
  });

  it('does not show children by default', () => {
    render(<TreeView data={testData} />);

    expect(screen.queryByText('Child 1.1')).not.toBeInTheDocument();
  });

  it('expands nodes on click', () => {
    render(<TreeView data={testData} />);

    const root1 = screen.getByText('Root 1');
    fireEvent.click(root1);

    expect(screen.getByText('Child 1.1')).toBeInTheDocument();
    expect(screen.getByText('Child 1.2')).toBeInTheDocument();
  });

  it('calls onNodeClick when a node is clicked', () => {
    const onNodeClick = vi.fn();
    render(<TreeView data={testData} onNodeClick={onNodeClick} />);

    fireEvent.click(screen.getByText('Root 2'));
    expect(onNodeClick).toHaveBeenCalledWith(testData[1]);
  });

  it('renders expanded nodes if defaultExpanded is provided', () => {
    render(<TreeView data={testData} defaultExpanded={['1']} />);

    expect(screen.getByText('Child 1.1')).toBeInTheDocument();
  });
});
