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

function Harness({ initial = [] }) {
  const [tags, setTags] = React.useState(initial)

  return (
    <TagInput
      value={tags}
      onChange={setTags}
      suggestedTags={['sunset', 'city']}
      searchEndpoint="/api/tags/search"
      popularEndpoint="/api/tags/popular"
    />
  )
}

describe('TagInput', () => {
  beforeEach(() => {
    window.axios = {
      get: vi.fn(async (url) => {
        if (url.startsWith('/api/tags/search')) {
          return {
            data: {
              data: [
                { id: 1, name: 'cityscape', slug: 'cityscape', usage_count: 10, recent_clicks: 2 },
                { id: 2, name: 'city', slug: 'city', usage_count: 30, recent_clicks: 14 },
              ],
            },
          }
        }

        return {
          data: {
            data: [
              { id: 3, name: 'popular', slug: 'popular', usage_count: 99 },
            ],
          },
        }
      }),
    }
  })

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

  it('adds and removes tags', async () => {
    render(<Harness />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.type(input, 'night,')

    expect(screen.getByText('night')).not.toBeNull()

    await userEvent.click(screen.getByRole('button', { name: 'Remove tag night' }))
    expect(screen.queryByText('night')).toBeNull()
  })

  it('supports keyboard suggestion accept with tab', async () => {
    render(<Harness />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.type(input, 'city')

    await waitFor(() => {
      expect(screen.getAllByRole('option').length).toBeGreaterThan(0)
    })

    await userEvent.keyboard('{Tab}')
    expect(screen.getByRole('button', { name: /Remove tag/i })).not.toBeNull()
  })

  it('shows recent click momentum when suggestions provide it', async () => {
    render(<Harness />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.type(input, 'city')

    await waitFor(() => {
      expect(screen.getByText('14 recent')).not.toBeNull()
    })
  })

  it('supports comma-separated paste', async () => {
    render(<Harness />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.click(input)
    await userEvent.paste('art, city, night')

    expect(screen.getByText('art')).not.toBeNull()
    expect(screen.getByText('city')).not.toBeNull()
    expect(screen.getByText('night')).not.toBeNull()
  })

  it('handles API failure gracefully', async () => {
    window.axios.get = vi.fn(async () => {
      throw new Error('network')
    })

    render(<Harness />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.type(input, 'cyber')

    await waitFor(() => {
      expect(screen.getByText('Tag search unavailable')).not.toBeNull()
    })
  })

  it('enforces max tags limit', async () => {
    render(<Harness initial={['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11', 'a12', 'a13', 'a14', 'a15']} />)

    const input = screen.getByLabelText('Tag input')
    await userEvent.type(input, 'overflow{enter}')

    expect(screen.getByText('Max tags reached')).not.toBeNull()
    expect(screen.queryByText('overflow')).toBeNull()
  })
})
