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: 'BOKANTE (Mastodon)'})
    expect(lien).toHaveAttribute('href', 'https://bokante.o-k-i.net/@pawol_nu/112233')
  })

  it('redirige vers BOKANTE par défaut quand on continue', async () => {
    window.open = vi.fn()
    const user = userEvent.setup()
    render(<ReponsMastodon bokanteStatusId='112233' />)

    await user.click(screen.getByRole('button', {name: /répondre sur mastodon/i}))
    await user.click(screen.getByRole('button', {name: /continuer/i}))

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

  it('permet de choisir une autre instance dans le select', async () => {
    window.open = vi.fn()
    const user = userEvent.setup()
    render(<ReponsMastodon bokanteStatusId='112233' />)

    await user.click(screen.getByRole('button', {name: /répondre sur mastodon/i}))
    await user.click(screen.getByLabelText(/instance mastodon/i))
    await user.click(screen.getByRole('option', {name: /autre instance/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(
      'https://mastodon.social/authorize_interaction?uri=' + encodeURIComponent('https://bokante.o-k-i.net/@pawol_nu/112233'),
      '_blank',
      'noopener,noreferrer'
    )
  })

  it('accepte un identifiant complet pour une autre instance', async () => {
    window.open = vi.fn()
    const user = userEvent.setup()
    render(<ReponsMastodon bokanteStatusId='112233' />)

    await user.click(screen.getByRole('button', {name: /répondre sur mastodon/i}))
    await user.click(screen.getByLabelText(/instance mastodon/i))
    await user.click(screen.getByRole('option', {name: /autre instance/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'
    )
  })
})
