import { render, screen } from '@testing-library/react'
import { describe, it, expect } from 'vitest'
import { OptimizedImage } from '@/shared/ui/OptimizedImage'

describe('OptimizedImage', () => {
  it('renders a plain img for non-upload URLs', () => {
    render(<OptimizedImage src="https://example.com/photo.jpg" alt="test" />)
    const img = screen.getByAltText('test') as HTMLImageElement
    expect(img.src).toBe('https://example.com/photo.jpg')
    expect(img.getAttribute('loading')).toBe('lazy')
  })

  it('renders picture element with srcset for upload URLs', () => {
    render(<OptimizedImage src="/uploads/abc123.png" alt="product" />)
    const picture = screen.getByAltText('product').closest('picture')
    expect(picture).not.toBeNull()

    const avifSource = picture?.querySelector('source[type="image/avif"]') as HTMLSourceElement
    expect(avifSource).not.toBeNull()
    const srcSet = avifSource.getAttribute('srcset') ?? ''
    expect(srcSet).toContain('/uploads-resized/abc123.avif?w=320')
    expect(srcSet).toContain('/uploads-resized/abc123.avif?w=640')
    expect(srcSet).toContain('/uploads-resized/abc123.avif?w=1024')
    expect(srcSet).toContain('/uploads-resized/abc123.avif?w=1600')
  })

  it('handles review subdir correctly', () => {
    render(<OptimizedImage src="/uploads/reviews/def456.jpg" alt="review" />)
    const avifSource = screen
      .getByAltText('review')
      .closest('picture')
      ?.querySelector('source[type="image/avif"]') as HTMLSourceElement
    const srcSet = avifSource?.getAttribute('srcset') ?? ''
    expect(srcSet).toContain('/uploads-resized/reviews/def456.avif?w=320')
  })

  it('uses eager loading when priority is true', () => {
    render(<OptimizedImage src="/uploads/abc123.png" alt="hero" priority />)
    const img = screen.getByAltText('hero') as HTMLImageElement
    expect(img.getAttribute('loading')).toBe('eager')
  })

  it('respects custom widths', () => {
    render(<OptimizedImage src="/uploads/abc123.png" alt="test" widths={[320, 640]} />)
    const avifSource = screen
      .getByAltText('test')
      .closest('picture')
      ?.querySelector('source[type="image/avif"]') as HTMLSourceElement
    const srcSet = avifSource?.getAttribute('srcset') ?? ''
    expect(srcSet).toContain('?w=320')
    expect(srcSet).toContain('?w=640')
    expect(srcSet).not.toContain('?w=1024')
  })
})
