<template>
  <div class="space-y-1.5">
    <p class="text-xs font-bold uppercase tracking-widest" style="color: var(--nav-text-muted);">Fonction</p>
    <div class="space-y-1">
      <button
        v-for="fn in FONCTIONS"
        :key="fn"
        @click="toggle(fn)"
        :aria-pressed="modelValue.includes(fn)"
        class="flex items-center gap-2.5 w-full rounded px-1 py-0.5 transition-all text-left hover:opacity-80"
        :style="modelValue.includes(fn) ? 'background: rgba(26,34,56,0.06);' : ''"
      >
        <!-- Case : affiche le rang de priorité si actif, sinon le nombre d'orgs -->
        <span
          class="flex items-center justify-center shrink-0 text-xs font-bold transition-all"
          style="width: 24px; height: 24px; border: 1.5px solid; border-radius: 4px;"
          :style="modelValue.includes(fn)
            ? 'background: var(--nav-primary); border-color: var(--nav-primary); color: var(--nav-text-on-primary);'
            : 'background: var(--nav-bg-alt); border-color: var(--nav-bg-alt); color: var(--nav-text-muted);'"
        >
          {{ modelValue.includes(fn) ? (modelValue.indexOf(fn) + 1) : (counts[fn] ?? 0) }}
        </span>
        <!-- Label -->
        <span
          class="text-sm leading-tight"
          :style="modelValue.includes(fn) ? 'color: var(--nav-text); font-weight: 600;' : 'color: var(--nav-text);'"
        >{{ fn }}</span>
      </button>
    </div>
    <p v-if="modelValue.length" class="text-xs pt-0.5" style="color: var(--nav-text-muted);">
      {{ modelValue.length }} actif{{ modelValue.length > 1 ? 's' : '' }}
      <button @click="emit('update:modelValue', [])" class="ml-2 underline hover:opacity-70">Effacer</button>
    </p>
  </div>
</template>

<script setup lang="ts">
const FONCTIONS = [
  'Juridique',
  'Technique',
  'Économique',
  'Administratif',
  'Chantier',
  'Comptabilité',
  'Développement',
  'Formation',
  "Gestion d'agence",
  'Santé mentale',
] as const

const props = defineProps<{
  modelValue: string[]
  counts: Record<string, number>
}>()

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

function toggle(fn: string) {
  if (props.modelValue.includes(fn)) {
    emit('update:modelValue', props.modelValue.filter(f => f !== fn))
  } else {
    emit('update:modelValue', [...props.modelValue, fn])
  }
}
</script>
