import '@testing-library/jest-dom'

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

declare global {
  interface Window {
    pktFetch: () => Promise<{ ok: boolean; text: () => Promise<string> }>
    pktIconPath: string
  }
}

describe('PktIcon', () => {
  window.pktFetch = (file = 'filnavn.svg') =>
    Promise.resolve({
      ok: true,
      text: () => Promise.resolve(`<svg role="img" data-testid="icon" data-filename=${file}>Her er SVGen</svg>`),
    })
  window.pktIconPath = 'sti'

  describe('with default fetcher', () => {
    test('fetches SVG with default fetcher', async () => {
      await render(<PktIcon name="arrow" />)
      await window.customElements.whenDefined('pkt-icon')

      const icon = await screen.findByRole('img')
      expect(icon).toMatchInlineSnapshot(`
        <svg
          data-filename="stiarrow.svg"
          data-testid="icon"
          role="img"
        >
          Her er SVGen
        </svg>
      `)
    })

    test('fetches SVG', async () => {
      const { container } = await render(
        <div className="root">
          <PktIcon name={'some-icon'} />
          <PktIcon name={'some-other-icon'} />
          <PktIcon name={'some-icon'} />
        </div>,
      )
      await window.customElements.whenDefined('pkt-icon')

      await waitFor(async () => {
        const icons = await screen.findAllByTestId('icon')
        expect(icons).toHaveLength(3)
      })
    })
  })
})
