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 TagPicker from './TagPicker'

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

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

describe('TagPicker', () => {
  beforeEach(() => {
    window.axios = {
      get: vi.fn(async (url) => {
        if (url.startsWith('/api/tags/search')) {
          return {
            data: {
              data: [
                { id: 2, name: 'High Contrast', slug: 'high-contrast', usage_count: 120, recent_clicks: 18 },
                { id: 3, name: 'High Detail', slug: 'high-detail', usage_count: 90, recent_clicks: 0 },
              ],
            },
          }
        }

        return {
          data: {
            data: [
              { id: 1, name: 'Popular Pick', slug: 'popular-pick', usage_count: 300, recent_clicks: 9 },
            ],
          },
        }
      }),
    }
  })

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

  it('shows recent click momentum for popular tags on mount', async () => {
    render(<Harness />)

    await waitFor(() => {
      expect(screen.getByText('Popular Pick')).not.toBeNull()
    })

    expect(screen.getByText('9 recent clicks')).not.toBeNull()
  })

  it('shows recent click momentum in search results and lets the user select a tag', async () => {
    render(<Harness />)

    const input = screen.getByLabelText('Search or add tags')
    await userEvent.type(input, 'high')

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

    await userEvent.click(screen.getByRole('button', { name: /High Contrast/i }))

    expect(screen.getByText('High Contrast')).not.toBeNull()
    expect(screen.getByRole('button', { name: 'Remove tag High Contrast' })).not.toBeNull()
  })
})