import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import ItemOperation from '../index'

describe('ItemOperation', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  const renderComponent = (overrides: Partial<React.ComponentProps<typeof ItemOperation>> = {}) => {
    const props: React.ComponentProps<typeof ItemOperation> = {
      isPinned: false,
      isShowDelete: true,
      togglePin: vi.fn(),
      onDelete: vi.fn(),
      ...overrides,
    }
    return {
      props,
      ...render(<ItemOperation {...props} />),
    }
  }

  describe('Rendering', () => {
    it('should render pin and delete actions when menu is open', async () => {
      renderComponent()

      fireEvent.click(screen.getByTestId('item-operation-trigger'))

      expect(await screen.findByText('explore.sidebar.action.pin')).toBeInTheDocument()
      expect(screen.getByText('explore.sidebar.action.delete')).toBeInTheDocument()
    })
  })

  describe('Props', () => {
    it('should render rename action when isShowRenameConversation is true', async () => {
      renderComponent({ isShowRenameConversation: true })

      fireEvent.click(screen.getByTestId('item-operation-trigger'))

      expect(await screen.findByText('explore.sidebar.action.rename')).toBeInTheDocument()
    })

    it('should render unpin label when isPinned is true', async () => {
      renderComponent({ isPinned: true })

      fireEvent.click(screen.getByTestId('item-operation-trigger'))

      expect(await screen.findByText('explore.sidebar.action.unpin')).toBeInTheDocument()
    })
  })

  describe('User Interactions', () => {
    it('should call togglePin when clicking pin action', async () => {
      const { props } = renderComponent()

      fireEvent.click(screen.getByTestId('item-operation-trigger'))
      fireEvent.click(await screen.findByText('explore.sidebar.action.pin'))

      expect(props.togglePin).toHaveBeenCalledTimes(1)
    })

    it('should call onDelete when clicking delete action', async () => {
      const { props } = renderComponent()

      fireEvent.click(screen.getByTestId('item-operation-trigger'))
      fireEvent.click(await screen.findByText('explore.sidebar.action.delete'))

      expect(props.onDelete).toHaveBeenCalledTimes(1)
    })
  })

  describe('Edge Cases', () => {
    it('should close the menu when mouse leaves the panel and item is not hovering', async () => {
      renderComponent()
      fireEvent.click(screen.getByTestId('item-operation-trigger'))
      const pinText = await screen.findByText('explore.sidebar.action.pin')
      const menu = pinText.closest('div')?.parentElement as HTMLElement

      fireEvent.mouseEnter(menu)
      fireEvent.mouseLeave(menu)

      await waitFor(() => {
        expect(screen.queryByText('explore.sidebar.action.pin')).not.toBeInTheDocument()
      })
    })
  })
})
