import { useWidgetId, useWidgetShallow } from '../stores'
import { SpreadUI } from './spread-ui'
import type { SpreadWidgetData } from './types'

interface SpreadSlice {
  data: SpreadWidgetData
  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: SpreadWidgetData = Object.freeze([]) as SpreadWidgetData

const spreadSelector = (s: {
  data: unknown
  formatter?: (value: number) => string
}): SpreadSlice => ({
  data: (s.data ?? EMPTY_DATA) as SpreadWidgetData,
  formatter: s.formatter,
})

/**
 * Stateful Spread bridge — reads `data` (post-pipeline) and `formatter` from
 * the per-widget store and forwards them to the pure {@link SpreadUI}.
 */
export function Spread() {
  const id = useWidgetId()
  const slice = useWidgetShallow(id, spreadSelector)
  return <SpreadUI items={slice.data} formatter={slice.formatter} />
}
