import { useWidgetId, useWidgetShallow } from '../stores'
import { FormulaUI } from './formula-ui'
import type { FormulaWidgetData } from './types'

interface FormulaSlice {
  data: FormulaWidgetData
  formatter?: (value: number) => string
}

// Stable empty-data sentinel — keeps the slice's `data` reference stable
// when the underlying store value is null/undefined so the shallow-equality
// gate in `useWidgetShallow` doesn't re-render every commit.
const EMPTY_DATA: FormulaWidgetData = Object.freeze([]) as FormulaWidgetData

const formulaSelector = (s: {
  data: unknown
  formatter?: (value: number) => string
}): FormulaSlice => ({
  data: (s.data ?? EMPTY_DATA) as FormulaWidgetData,
  formatter: s.formatter,
})

/**
 * Stateful Formula bridge — reads `data` (post-pipeline) and `formatter` from
 * the per-widget store and forwards them to the pure {@link FormulaUI}. Sits
 * inside `<Widget.Provider>`. Demonstrates that the composition shell
 * (Provider, Wrapper, State) doesn't care whether the rendered child is
 * ECharts (Bar) or a custom DOM tree (Formula).
 */
export function Formula() {
  const id = useWidgetId()
  const slice = useWidgetShallow(id, formulaSelector)
  return <FormulaUI items={slice.data} formatter={slice.formatter} />
}
