/**
 * native chart 内核：原生 Legend（图例）
 *
 * 不依赖 recharts，纯 div + svg dot/line 渲染。
 * 视觉与 dashboard 现有图例一致：12px 字号，圆点 / 短横线两种 marker。
 */
const ITEM_GAP = 16;
const FONT_SIZE = 12;

const POSITION_LAYOUT = {
  top:    { flexDirection: 'row', justifyContent: 'center' },
  bottom: { flexDirection: 'row', justifyContent: 'center' },
  left:   { flexDirection: 'column', alignItems: 'flex-start' },
  right:  { flexDirection: 'column', alignItems: 'flex-start' },
};

/**
 * @param {{
 *   items: Array<{ name:string, color:string, shape?:'dot'|'line' }>,
 *   shape?: 'dot'|'line',
 *   position?: 'top'|'bottom'|'left'|'right',
 *   textColor?: string,
 * }} props
 */
export default function Legend({
  items,
  shape = 'line',
  position = 'bottom',
  textColor = 'var(--color-foreground-secondary, #475467)',
}) {
  if (!Array.isArray(items) || items.length === 0) return null;
  const layout = POSITION_LAYOUT[position] || POSITION_LAYOUT.bottom;
  return (
    <div
      className="native-chart__legend"
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: ITEM_GAP,
        fontSize: FONT_SIZE,
        color: textColor,
        ...layout,
      }}
    >
      {items.map((it, i) => {
        // 每个 item 可自带 shape（如组合图里柱系列用 dot、线系列用 line），缺省回退到顶层 shape
        const itemShape = it.shape === 'dot' || it.shape === 'line' ? it.shape : shape;
        return (
          <div key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            {itemShape === 'dot' ? (
              <span
                aria-hidden
                style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: it.color, display: 'inline-block', flexShrink: 0,
                }}
              />
            ) : (
              <span
                aria-hidden
                style={{
                  width: 16, height: 2, borderRadius: 1,
                  background: it.color, display: 'inline-block', flexShrink: 0,
                }}
              />
            )}
            <span>{it.name}</span>
          </div>
        );
      })}
    </div>
  );
}
