import { describe, it, expect, vi } from 'vitest'
import { render } from '@testing-library/react'
import { WidgetContext, useWidgetId } from './widget-context'

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = (): void => {}

function Probe({ onId }: { onId: (id: string) => void }) {
  onId(useWidgetId())
  return null
}

describe('useWidgetId', () => {
  it('throws a clear error when called outside a WidgetContext', () => {
    const spy = vi.spyOn(console, 'error').mockImplementation(noop)
    expect(() => render(<Probe onId={noop} />)).toThrow(
      /useWidgetId\(\) must be called inside <Widget\.Provider>/,
    )
    spy.mockRestore()
  })

  it('returns the id from the surrounding context', () => {
    let captured = ''
    render(
      <WidgetContext.Provider value='test-id'>
        <Probe onId={(id) => (captured = id)} />
      </WidgetContext.Provider>,
    )
    expect(captured).toBe('test-id')
  })

  it('isolates ids across sibling Providers', () => {
    const ids: string[] = []
    render(
      <>
        <WidgetContext.Provider value='a'>
          <Probe onId={(id) => ids.push(id)} />
        </WidgetContext.Provider>
        <WidgetContext.Provider value='b'>
          <Probe onId={(id) => ids.push(id)} />
        </WidgetContext.Provider>
      </>,
    )
    expect(ids).toEqual(['a', 'b'])
  })

  it('inner Provider value shadows outer', () => {
    let captured = ''
    render(
      <WidgetContext.Provider value='outer'>
        <WidgetContext.Provider value='inner'>
          <Probe onId={(id) => (captured = id)} />
        </WidgetContext.Provider>
      </WidgetContext.Provider>,
    )
    expect(captured).toBe('inner')
  })
})
