import { describe, it, expect, vi } from 'vitest'
import * as React from 'react'
import { render, act } from '@testing-library/react'

import { LiveLogTail, type LiveLogTailHandle } from '../live-log-tail'

describe('LiveLogTail', () => {
  it('mounts the host slot', () => {
    const { container } = render(<LiveLogTail />)
    expect(container.querySelector('[data-slot="live-log-tail"]')).toBeTruthy()
  })

  it('forwards className and props onto the wrapper', () => {
    const { container } = render(<LiveLogTail className="custom-llt" data-testid="llt" />)
    const el = container.querySelector('[data-slot="live-log-tail"]')
    expect(el?.className).toContain('custom-llt')
    expect(el?.getAttribute('data-testid')).toBe('llt')
  })

  it('seeds initial lines without throwing', () => {
    expect(() =>
      render(<LiveLogTail lines={['first', 'second']} maxLines={500} follow={false} />)
    ).not.toThrow()
  })

  it('exposes append() and clear() on the imperative ref', () => {
    const ref = React.createRef<LiveLogTailHandle>()
    render(<LiveLogTail ref={ref} />)
    expect(ref.current).not.toBeNull()
    expect(typeof ref.current?.append).toBe('function')
    expect(typeof ref.current?.clear).toBe('function')
    act(() => {
      ref.current?.append('hello world')
      ref.current?.clear()
    })
  })

  it('uses the lineParser when supplied to derive severity + text', () => {
    const ref = React.createRef<LiveLogTailHandle>()
    const parser = vi.fn(() => ({ text: 'mapped', severity: 'error' as const }))
    render(<LiveLogTail ref={ref} lineParser={parser} />)
    act(() => {
      ref.current?.append('raw line')
    })
    expect(parser).toHaveBeenCalledWith('raw line')
  })

  it('updates follow-mode and maxLines without remounting', () => {
    const ref = React.createRef<LiveLogTailHandle>()
    const { rerender } = render(<LiveLogTail ref={ref} follow maxLines={100} />)
    rerender(<LiveLogTail ref={ref} follow={false} maxLines={50} />)
    expect(ref.current).not.toBeNull()
  })
})
