import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { render } from '@testing-library/react'
import { Provider } from '../../provider/widget-provider'
import { clearAllWidgetStores, getWidgetStore } from '../../stores'
import { RelativeData } from './relative-data'

beforeEach(() => clearAllWidgetStores())
afterEach(() => clearAllWidgetStores())

const fmtA = (n: number) => `A${n}`
const fmtB = (n: number) => `B${n}`

describe('<RelativeData> — rawFormatter-driven restoration', () => {
  it('Provider mirrors the formatter prop into both rawFormatter and formatter', () => {
    render(
      <Provider id='rd1' data={[]} formatter={fmtA}>
        <RelativeData initialEnabled={false} />
      </Provider>,
    )
    const s = getWidgetStore('rd1').getState()
    expect(s.rawFormatter).toBe(fmtA)
    expect(s.formatter).toBe(fmtA)
  })

  it('initialEnabled=true installs the percent formatter and leaves rawFormatter untouched', () => {
    render(
      <Provider id='rd2' data={[]} formatter={fmtA}>
        <RelativeData initialEnabled={true} />
      </Provider>,
    )
    const s = getWidgetStore('rd2').getState()
    expect(s.rawFormatter).toBe(fmtA)
    expect(typeof s.formatter).toBe('function')
    expect(s.formatter).not.toBe(fmtA)
    // Sanity: the override is the percent formatter (50 → "50%" via Intl).
    expect(s.formatter?.(50)).toMatch(/%$/)
  })

  it('consumer prop change while enabled updates rawFormatter; effect re-applies percent', () => {
    const { rerender } = render(
      <Provider id='rd3' data={[]} formatter={fmtA}>
        <RelativeData initialEnabled={true} />
      </Provider>,
    )
    const store = getWidgetStore('rd3')
    expect(store.getState().rawFormatter).toBe(fmtA)
    const beforePercent = store.getState().formatter

    rerender(
      <Provider id='rd3' data={[]} formatter={fmtB}>
        <RelativeData initialEnabled={true} />
      </Provider>,
    )
    const after = store.getState()
    expect(after.rawFormatter).toBe(fmtB)
    // Formatter is still the percent formatter (re-applied via the effect).
    expect(after.formatter).not.toBe(fmtB)
    expect(after.formatter).toBe(beforePercent)
  })

  it('initialEnabled=false leaves formatter equal to rawFormatter', () => {
    render(
      <Provider id='rd4' data={[]} formatter={fmtA}>
        <RelativeData initialEnabled={false} />
      </Provider>,
    )
    const s = getWidgetStore('rd4').getState()
    expect(s.formatter).toBe(s.rawFormatter)
    expect(s.formatter).toBe(fmtA)
  })
})
