import { describe, it, expect, vi } from 'vitest'
import { render } from '@testing-library/react'
import { Formula } from './formula'
import { Provider } from '../provider/widget-provider'
import type { FormulaWidgetData } from './types'

vi.mock('./formula-ui', () => ({
  FormulaUI: ({
    items,
    formatter,
  }: {
    items: FormulaWidgetData
    formatter?: (value: number) => string
  }) => (
    <div data-testid='formula-ui' data-count={items.length}>
      {items
        .map(
          (it) =>
            `${it.prefix ?? ''}${formatter ? formatter(it.value) : it.value}${it.suffix ?? ''}`,
        )
        .join('|')}
    </div>
  ),
}))

describe('<Formula> bridge', () => {
  it('forwards data + formatter from the store to FormulaUI', () => {
    const data: FormulaWidgetData = [
      { value: 12, prefix: '$' },
      { value: 34, suffix: '%' },
    ]
    const { getByTestId } = render(
      <Provider id='f-1' data={data} formatter={(n) => `[${n.toFixed(1)}]`}>
        <Formula />
      </Provider>,
    )
    const ui = getByTestId('formula-ui')
    expect(ui.dataset.count).toBe('2')
    expect(ui.textContent).toBe('$[12.0]|[34.0]%')
  })

  it('falls back to an empty items array when data is null', () => {
    const { getByTestId } = render(
      <Provider id='f-2' data={null}>
        <Formula />
      </Provider>,
    )
    expect(getByTestId('formula-ui').dataset.count).toBe('0')
  })
})
