import { Box } from '@mui/material'
import { useLegendId, useLegendShallow } from '../../stores'
import { useLegendConfig } from '../../provider'
import { useLegendRow } from '../contexts'
import { LegendItemUI } from './legend-item-ui'
import { styles } from './styles'

/**
 * Store-connected item renderer — reads the layer's `variables` from the
 * enclosing `Legend.Row` context (plus the Provider's labels) and stacks one
 * pure renderer per variable, top-to-bottom with the design's 16px section
 * gap. Use `Legend.ItemUI` directly for store-free, single-variable
 * composition.
 *
 * @experimental This API is new and may change in a future release.
 */
export function LegendItem() {
  const id = useLegendId()
  const row = useLegendRow()
  const variables = useLegendShallow(id, (s) =>
    row ? s.layers[row.layerId]?.variables : undefined,
  )
  const { labels } = useLegendConfig()

  if (!variables || variables.length === 0) return null

  return (
    <Box sx={styles.stack}>
      {variables.map((variable, index) => (
        <LegendItemUI key={index} data={variable} labels={labels} />
      ))}
    </Box>
  )
}
