import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'

import PostImportThumbnailPreview from '@/components/posts/import/PostImportThumbnailPreview'

describe ('PostImportThumbnailPreview', () => {
  beforeEach (() => {
    vi.clearAllMocks ()
    globalThis.URL.createObjectURL = vi.fn (() => 'blob:preview')
    globalThis.URL.revokeObjectURL = vi.fn ()
  })

  it ('renders the remote URL directly without a backend proxy', () => {
    render (
	<PostImportThumbnailPreview
	    url="https://example.com/thumbnail.jpg"
	    className="h-10 w-10"/>)

    expect (screen.getByRole ('img')).toHaveAttribute (
	'src',
	'https://example.com/thumbnail.jpg')
    expect (screen.getByRole ('img')).toHaveAttribute (
	'referrerpolicy',
	'no-referrer')
  })

  it ('shows the empty frame after the remote image fails', () => {
    const { container } = render (
	<PostImportThumbnailPreview
	    url="https://example.com/missing.jpg"
	    className="h-10 w-10"/>)

    fireEvent.error (screen.getByRole ('img'))

    expect (screen.queryByRole ('img')).toBeNull ()
    expect (container.querySelector ('div.rounded.border.bg-muted')).not.toBeNull ()
    expect (container.textContent).toBe ('')
  })

  it ('uses and revokes an object URL only when the remote URL is blank', () => {
    const file = new File (['image'], 'thumbnail.png', { type: 'image/png' })
    const { rerender, unmount } = render (
	<PostImportThumbnailPreview url="" file={file} className="h-10 w-10"/>)

    expect (screen.getByRole ('img')).toHaveAttribute ('src', 'blob:preview')

    rerender (
	<PostImportThumbnailPreview
	    url="https://example.com/remote.jpg"
	    file={file}
	    className="h-10 w-10"/>)
    expect (screen.getByRole ('img')).toHaveAttribute (
	'src',
	'https://example.com/remote.jpg')

    unmount ()
    expect (globalThis.URL.revokeObjectURL).toHaveBeenCalledWith ('blob:preview')
  })
})
