<template>
  <div class="space-y-1.5">
    <p class="text-xs font-bold uppercase tracking-widest" style="color: var(--nav-text-muted);">Fonction (1–5)</p>
    <div class="space-y-1">
      <button
        v-for="fn in FONCTIONS"
        :key="fn"
        @click="toggle(fn)"
        :aria-pressed="modelValue.includes(fn)"
        :disabled="!modelValue.includes(fn) && modelValue.length >= 5"
        class="flex items-center gap-2.5 w-full rounded px-1 py-0.5 transition-all text-left"
        :class="!modelValue.includes(fn) && modelValue.length >= 5 ? 'cursor-not-allowed opacity-40' : 'hover:opacity-80'"
        :style="modelValue.includes(fn) ? 'background: rgba(26,34,56,0.06);' : ''"
      >
        <!-- Case checkbox -->
        <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);'"
        >
          {{ 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 }}/5 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 if (props.modelValue.length < 5) {
    emit('update:modelValue', [...props.modelValue, fn])
  }
}
</script>
