<template>
  <span v-if="multiple" class="select-display">
    <span
      v-for="v in (value as string[] | null | undefined) ?? []"
      :key="v"
      class="select-display__chip"
      :style="chipStyle(colorKeyFor(v))"
    >
      {{ labelOf(v) }}
    </span>
  </span>
  <span
    v-else-if="value != null && value !== ''"
    class="select-display__chip"
    :style="chipStyle(colorKeyFor(value as string))"
  >
    {{ labelOf(value as string) }}
  </span>
</template>

<script setup lang="ts">
import { computed } from 'vue'

export interface ISelectOption {
  label: string
  value: string
  color?: string
}

const props = defineProps<{
  value: string | string[] | null | undefined
  options: ISelectOption[] | string[] | undefined
  multiple?: boolean
}>()

// 8 色 token 调色板语义 key（与 bitable-tokens.css --bitable-cf-* 对齐）
const COLOR_KEYS = [
  'red',
  'orange',
  'yellow',
  'green',
  'blue',
  'purple',
  'gray',
  'neutral',
] as const
type ColorKey = (typeof COLOR_KEYS)[number]

const COLOR_KEY_SET = new Set<string>(COLOR_KEYS)

// Normalize options to a lookup map
const optionMap = computed<Map<string, ISelectOption>>(() => {
  const m = new Map<string, ISelectOption>()
  if (!props.options) return m
  for (const opt of props.options) {
    if (typeof opt === 'string') {
      m.set(opt, { label: opt, value: opt })
    } else {
      const o = opt as ISelectOption
      m.set(o.value, o)
    }
  }
  return m
})

function labelOf(value: string): string {
  return optionMap.value.get(value)?.label ?? value
}

// ponytail: 简单确定性 hash → 8 色之一。已知 ceiling: hash 分布对短字符串
// 可能聚集（不抗冲突），但 chip 着色仅做视觉区分，冲突无功能影响。
// 升级路径: 用更均匀的字符串 hash（如 FNV-1a）若实测分布不均。
function hashColorKey(value: string): ColorKey {
  let h = 0
  for (let i = 0; i < value.length; i++) {
    h = (h * 31 + value.charCodeAt(i)) | 0
  }
  return COLOR_KEYS[Math.abs(h) % COLOR_KEYS.length]
}

// 解析选项颜色：接受 8 色语义 key；非法值（含 Ant Design preset 名如
// 'default'/'pink'）回退为确定性 hash 着色，确保每选项有可区分颜色。
function colorKeyFor(value: string): ColorKey {
  const explicit = optionMap.value.get(value)?.color
  if (explicit && COLOR_KEY_SET.has(explicit)) {
    return explicit as ColorKey
  }
  return hashColorKey(value)
}

// chip 样式：-bg 浅底 + -fg 深字/边框，对比度 ~12:1（WCAG AA 远超 4.5:1）
function chipStyle(key: ColorKey): Record<string, string> {
  return {
    backgroundColor: `var(--bitable-cf-${key}-bg)`,
    color: `var(--bitable-cf-${key}-fg)`,
    borderColor: `var(--bitable-cf-${key}-fg)`,
  }
}
</script>

<style scoped>
.select-display {
  display: inline-flex;
  flex-wrap: wrap;
  gap: var(--bitable-spacing-xs);
}

.select-display__chip {
  display: inline-flex;
  align-items: center;
  padding: 0 var(--bitable-spacing-sm);
  border-radius: var(--bitable-radius-sm);
  border: 1px solid;
  font-size: var(--bitable-font-xs);
  line-height: 1.5;
  white-space: nowrap;
}
</style>
