import { Box, Typography } from '@mui/material'
import type { CategorySeriesConfig } from '../types'
import { styles } from '../style'

export interface CategoryLegendProps {
  /** Series metadata. Empty array → renders nothing. */
  series: readonly CategorySeriesConfig[]
  /**
   * Per-series colour resolver. Receives the series index and returns the
   * palette colour (or `undefined` to fall back to the MUI default). The
   * legend derives its dot colour from this on the fly — the caller does
   * NOT pre-compute a `colors` array (avoids passing two views of the
   * same source).
   */
  colorAt: (index: number) => string | undefined
}

/**
 * Sticky color legend rendered below a multi-series Category list.
 * Per-series `color` overrides the matching `colorAt(i)` result.
 */
export function CategoryLegend({ series, colorAt }: CategoryLegendProps) {
  if (series.length === 0) return null
  return (
    <Box sx={styles.legend}>
      {series.map((s, i) => (
        <Box key={s.name} sx={styles.legendItem}>
          <Box
            sx={styles.legendDot}
            style={{ backgroundColor: s.color ?? colorAt(i) }}
          />
          <Typography variant='caption' sx={styles.legendLabel}>
            {s.name}
          </Typography>
        </Box>
      ))}
    </Box>
  )
}
