import {describe, it, expect, vi, afterEach} from 'vitest'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ReponsMastodon from '../repons-mastodon'

describe('ReponsMastodon', () => {
  const originalOpen = window.open

  afterEach(() => {
    window.open = originalOpen
  })

  it('ne rend rien sans bokanteStatusId', () => {
    const {container} = render(<ReponsMastodon bokanteStatusId={null} />)
    expect(container).toBeEmptyDOMElement()
  })

  it('affiche un lien direct vers le fil bokante', () => {
    render(<ReponsMastodon bokanteStatusId='112233' />)
    const lien = screen.getByRole('link', {name: 'Mastodon'})
    expect(lien).toHaveAttribute('href', 'https://bokante.o-k-i.net/@pawol_nu/112233')
  })

  it('redirige vers authorize_interaction avec le domaine extrait d\'un identifiant complet', async () => {
    window.open = vi.fn()
    const user = userEvent.setup()
    render(<ReponsMastodon bokanteStatusId='112233' />)

    await user.click(screen.getByRole('button', {name: /répondre via mastodon/i}))
    await user.type(screen.getByLabelText(/@vous@votre-instance/i), '@quelqun@mastodon.social')
    await user.click(screen.getByRole('button', {name: /continuer/i}))

    expect(window.open).toHaveBeenCalledWith(
      'https://mastodon.social/authorize_interaction?uri=' + encodeURIComponent('https://bokante.o-k-i.net/@pawol_nu/112233'),
      '_blank',
      'noopener,noreferrer'
    )
  })

  it('accepte aussi juste un nom d\'instance sans @', async () => {
    window.open = vi.fn()
    const user = userEvent.setup()
    render(<ReponsMastodon bokanteStatusId='112233' />)

    await user.click(screen.getByRole('button', {name: /répondre via mastodon/i}))
    await user.type(screen.getByLabelText(/@vous@votre-instance/i), 'mastodon.social')
    await user.click(screen.getByRole('button', {name: /continuer/i}))

    expect(window.open).toHaveBeenCalledWith(
      expect.stringContaining('https://mastodon.social/authorize_interaction'),
      '_blank',
      'noopener,noreferrer'
    )
  })
})
