import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import ArtworkRecommendationsRails from './ArtworkRecommendationsRails'

describe('ArtworkRecommendationsRails', () => {
  beforeEach(() => {
    global.fetch = vi.fn((url) => {
      if (String(url).includes('/similar-ai')) {
        return Promise.resolve({
          ok: true,
          json: async () => ({ data: [] }),
        })
      }

      if (String(url).includes('/api/rank/category/5?type=trending')) {
        return Promise.resolve({
          ok: true,
          json: async () => ({
            data: [
              {
                id: 11,
                title: 'Star map drift',
                urls: { direct: '/art/11/star-map-drift' },
                author: { name: 'Pilot' },
                thumbnail_url: '/thumbs/11.webp',
              },
            ],
          }),
        })
      }

      return Promise.resolve({
        ok: true,
        json: async () => ({ data: [] }),
      })
    })
  })

  afterEach(() => {
    cleanup()
    vi.restoreAllMocks()
  })

  it('loads recommendation rails after mount', async () => {
    render(
      <ArtworkRecommendationsRails
        artwork={{
          id: 69827,
          user: { name: 'Pilot' },
          categories: [{ id: 5, name: 'Sci-Fi' }],
        }}
        related={[]}
      />,
    )

    await waitFor(() => {
      expect(screen.getByText('Trending in Sci-Fi')).not.toBeNull()
    })

    expect(global.fetch).toHaveBeenCalledWith('/api/art/69827/similar-ai', { credentials: 'same-origin' })
    expect(global.fetch).toHaveBeenCalledWith('/api/rank/category/5?type=trending', { credentials: 'same-origin' })
  })
})