import {createRef} from 'react'

import {describe, expect, it} from 'vitest'

import {render, screen} from '../../test-utils'

import {ProductReviewStars} from './product-review-stars'

describe('ProductReviewStars', () => {
  it('renders without crashing', () => {
    const {container} = render(
      <ProductReviewStars averageRating={3.5} reviewCount={100} />
    )

    // Component should render something
    expect(container.firstChild).toBeInTheDocument()
  })

  describe('review count display', () => {
    it('displays review count', () => {
      render(<ProductReviewStars averageRating={4} reviewCount={42} />)
      expect(screen.getByText('(42)')).toBeInTheDocument()
    })

    it('formats large numbers as K', () => {
      render(<ProductReviewStars averageRating={4} reviewCount={1500} />)
      expect(screen.getByText('(1K)')).toBeInTheDocument()
    })

    it('formats millions as M', () => {
      render(<ProductReviewStars averageRating={4} reviewCount={1500000} />)
      expect(screen.getByText('(1.5M)')).toBeInTheDocument()
    })

    it('does not display review count when zero', () => {
      render(<ProductReviewStars averageRating={4} reviewCount={0} />)
      expect(screen.queryByText('(0)')).not.toBeInTheDocument()
    })

    it('does not display review count when null', () => {
      render(<ProductReviewStars averageRating={4} reviewCount={null} />)
      expect(screen.queryByText(/\(\d+\)/)).not.toBeInTheDocument()
    })
  })

  describe('accessibility', () => {
    it('forwards ref to container element', () => {
      const ref = createRef<HTMLDivElement>()
      render(
        <ProductReviewStars ref={ref} averageRating={4} reviewCount={100} />
      )
      expect(ref.current).toBeInstanceOf(HTMLDivElement)
    })

    it('accepts aria-label for accessibility', () => {
      render(
        <ProductReviewStars
          averageRating={4.5}
          reviewCount={100}
          aria-label="4.5 out of 5 stars, 100 reviews"
          data-testid="rating-stars"
        />
      )

      const element = screen.getByTestId('rating-stars')
      expect(element).toHaveAttribute(
        'aria-label',
        '4.5 out of 5 stars, 100 reviews'
      )
    })
  })

  describe('edge cases', () => {
    it('handles negative ratings gracefully', () => {
      // Should not crash with invalid input
      const {container} = render(
        <ProductReviewStars averageRating={-1} reviewCount={10} />
      )
      expect(container.firstChild).toBeInTheDocument()
    })

    it('handles very large ratings gracefully', () => {
      // Should not crash with invalid input
      const {container} = render(
        <ProductReviewStars averageRating={10} reviewCount={10} />
      )
      expect(container.firstChild).toBeInTheDocument()
    })
  })
})
