<script setup lang="ts">
/**
 * Select — styled native <select> with chevron overlay.
 * With `label` the root becomes a <label> wrapping the control.
 * v-model binds to the selected value via defineModel<string>().
 */
import Icon from '@/components/ds/core/Icon.vue'

type SelectOption = string | { value: string; label: string }

const props = withDefaults(
  defineProps<{
    label?: string
    options?: SelectOption[]
    size?: 'md' | 'sm'
    id?: string
    disabled?: boolean
  }>(),
  { options: () => [], size: 'md', disabled: false },
)

const model = defineModel<string>()

function optionValue(o: SelectOption): string {
  return typeof o === 'string' ? o : o.value
}
function optionLabel(o: SelectOption): string {
  return typeof o === 'string' ? o : o.label
}
</script>

<template>
  <!-- With label: wrap in <label> matching React's cc-field layout -->
  <label v-if="label" class="cc-field" :for="id">
    <span class="cc-field__label">{{ label }}</span>
    <span :class="['cc-select', size === 'sm' && 'cc-select--sm']">
      <select
        :id="id"
        :disabled="disabled"
        :value="model"
        @change="model = ($event.target as HTMLSelectElement).value"
      >
        <option
          v-for="(o, i) in options"
          :key="i"
          :value="optionValue(o)"
        >{{ optionLabel(o) }}</option>
      </select>
      <span class="cc-select__chev">
        <Icon name="chevron-down" :size="15" />
      </span>
    </span>
  </label>

  <!-- Without label: bare control -->
  <span v-else :class="['cc-select', size === 'sm' && 'cc-select--sm']">
    <select
      :id="id"
      :disabled="disabled"
      :value="model"
      @change="model = ($event.target as HTMLSelectElement).value"
    >
      <option
        v-for="(o, i) in options"
        :key="i"
        :value="optionValue(o)"
      >{{ optionLabel(o) }}</option>
    </select>
    <span class="cc-select__chev">
      <Icon name="chevron-down" :size="15" />
    </span>
  </span>
</template>

<style>
.cc-select { position:relative; display:flex; align-items:center; }
.cc-select select {
  appearance:none; width:100%; height:var(--control-h-md); padding:0 32px 0 11px;
  background:var(--surface-inset); color:var(--text-primary); border:0; border-radius:var(--radius-md);
  box-shadow:var(--ring-default); font-family:var(--font-sans); font-size:var(--text-sm); cursor:pointer;
  transition:var(--transition-colors); outline:0;
}
.cc-select select:focus-visible { box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm); }
.cc-select--sm select { height:var(--control-h-sm); padding:0 28px 0 9px; }
.cc-select__chev { position:absolute; right:9px; pointer-events:none; color:var(--text-tertiary); display:flex; }
</style>
