import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import { describe, expect, it } from 'vitest';
import { useExpand } from './useExpand';

const TestWrapper: React.FC = () => {
  const { isExpanded, expand, collapse, toggleExpanded } = useExpand();

  return (
    <div>
      <span>{String(isExpanded)}</span>
      <button id="expand" onClick={expand}></button>
      <button id="collapse" onClick={collapse}></button>
      <button id="toggle" onClick={toggleExpanded}></button>
    </div>
  );
};

describe('useExpand', () => {
  it('isExpanded defaults to false', () => {
    const { container } = render(<TestWrapper />);
    const isExpanded = JSON.parse(
      container.querySelector('span')?.textContent || '',
    );

    expect(isExpanded).toBe(false);
  });

  it(`expand sets isExpanded to 'true'`, () => {
    const { container } = render(<TestWrapper />);
    const expand = container.querySelector('#expand') as HTMLButtonElement;

    fireEvent.click(expand);

    const isExpanded = JSON.parse(
      container.querySelector('span')?.textContent || '',
    );

    expect(isExpanded).toBe(true);
  });

  it(`collapse sets isExpanded to 'false'`, () => {
    const { container } = render(<TestWrapper />);
    const expand = container.querySelector('#expand') as HTMLButtonElement;
    const collapse = container.querySelector('#collapse') as HTMLButtonElement;

    fireEvent.click(expand);

    let isExpanded = JSON.parse(
      container.querySelector('span')?.textContent || '',
    );

    expect(isExpanded).toBe(true);

    fireEvent.click(collapse);

    isExpanded = JSON.parse(container.querySelector('span')?.textContent || '');

    expect(isExpanded).toBe(false);
  });

  it(`toggles isExpanded state`, () => {
    const { container } = render(<TestWrapper />);
    let isExpanded = JSON.parse(
      container.querySelector('span')?.textContent || '',
    );

    expect(isExpanded).toBe(false);

    const toggle = container.querySelector('#toggle') as HTMLButtonElement;
    fireEvent.click(toggle);

    isExpanded = JSON.parse(container.querySelector('span')?.textContent || '');

    expect(isExpanded).toBe(true);

    fireEvent.click(toggle);
    isExpanded = JSON.parse(container.querySelector('span')?.textContent || '');

    expect(isExpanded).toBe(false);
  });
});
