<script setup lang="ts">
/**
 * Dropdown/select to pick a voting protocol.
 *
 * Fetches protocols from the store and renders them in a USelect
 * with protocol name, mode params, and vote type badge.
 */
import type { VotingProtocol } from '~/stores/protocols'

const props = defineProps<{
  modelValue: string | null
  voteType?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string | null]
}>()

const protocols = useProtocolsStore()

onMounted(async () => {
  if (protocols.protocols.length === 0) {
    await protocols.fetchProtocols(props.voteType ? { vote_type: props.voteType } : undefined)
  }
})

const filteredProtocols = computed(() => {
  if (!props.voteType) return protocols.protocols
  return protocols.protocols.filter(p => p.vote_type === props.voteType)
})

const options = computed(() => {
  return filteredProtocols.value.map(p => ({
    label: buildLabel(p),
    value: p.id,
  }))
})

function buildLabel(p: VotingProtocol): string {
  const typeLabel = p.vote_type === 'binary' ? 'Binaire' : 'Nuance'
  const params = p.mode_params ? ` [${p.mode_params}]` : ''
  return `${p.name} - ${typeLabel}${params}`
}

function onSelect(value: string) {
  emit('update:modelValue', value || null)
}
</script>

<template>
  <div>
    <USelect
      :model-value="modelValue ?? undefined"
      :items="options"
      placeholder="Selectionnez un protocole..."
      :loading="protocols.loading"
      value-key="value"
      @update:model-value="onSelect"
    />
    <p v-if="protocols.error" class="text-xs text-red-500 mt-1">
      {{ protocols.error }}
    </p>
  </div>
</template>
