import { createRef } from 'react';

import { Position } from '..';
import { render } from '../../test-utils';

import Panel from './Panel';
import type { PanelProps } from './Panel';

const mockAnchorRef: React.MutableRefObject<HTMLAnchorElement | null> = {
  current: document.createElement('a'),
};

describe('Panel', () => {
  const props = {
    arrow: true,
    children: <div>children</div>,
    open: true,
    position: Position.TOP,
    anchorRef: mockAnchorRef,
    onClose: jest.fn(),
  } satisfies PanelProps;

  it('renders arrow', () => {
    const { rerender } = render(<Panel {...props} arrow={false} />);

    expect(getArrow()).not.toBeInTheDocument();

    rerender(<Panel {...props} />);

    expect(getArrow()).toBeInTheDocument();
  });

  it('opens/closes Panel based on open', () => {
    const { rerender } = render(<Panel {...props} open={false} />);

    expect(getPanel()).not.toBeInTheDocument();

    rerender(<Panel {...props} open />);

    expect(getPanel()).toBeInTheDocument();
  });

  it('does not set width for content as width of an anchor (by default)', () => {
    const anchorReference = createRef<HTMLDivElement>();
    const panelReference = createRef<HTMLDivElement>();

    render(
      <>
        <div ref={anchorReference}>Anchor for panel</div>
        <Panel
          {...props}
          ref={panelReference}
          anchorRef={anchorReference}
          anchorWidth={false}
          open
        />
      </>,
    );

    expect(panelReference.current).toHaveStyle({ width: undefined });
  });

  it('sets same width for content as width of an anchor (anchorWidth={true})', () => {
    const anchorReference = createRef<HTMLDivElement>();
    const panelReference = createRef<HTMLDivElement>();

    render(
      <>
        <div ref={anchorReference}>Anchor for panel</div>
        <Panel {...props} ref={panelReference} anchorRef={anchorReference} anchorWidth open />
      </>,
    );

    expect(panelReference.current).toHaveStyle({ width: '0px' });
  });

  const getPanel = () => document.querySelector('.np-panel--open');
  const getArrow = () => document.querySelector('.np-panel__arrow');
});
