<template>
    <div class="rounded-lg border border-neutral-200 overflow-hidden">
        <!-- En-tete du groupe avec checkbox "tout selectionner" -->
        <div class="flex items-center gap-3 bg-neutral-50 px-4 py-3 border-b border-neutral-200">
            <MalioCheckbox
                :id="`group-${module}`"
                :label="moduleLabel"
                :model-value="allSelected"
                label-class="font-semibold text-sm text-neutral-700 capitalize"
                @update:model-value="toggleAll"
            />
            <span class="ml-auto text-xs text-neutral-400">
                {{ selectedCount }}/{{ permissions.length }}
            </span>
        </div>

        <!-- Liste des permissions individuelles -->
        <div class="grid grid-cols-1 gap-1 p-3 sm:grid-cols-2">
            <MalioCheckbox
                v-for="perm in permissions"
                :key="perm.id"
                :id="`perm-${perm.id}`"
                :label="perm.label"
                :model-value="selectedIds.has(perm.id)"
                label-class="text-sm text-neutral-600"
                @update:model-value="(val: boolean) => togglePermission(perm.id, val)"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
interface Permission {
    id: number
    code: string
    label: string
    module: string
    orphan: boolean
}

const props = defineProps<{
    module: string
    moduleLabel: string
    permissions: Permission[]
    selectedIds: Set<number>
}>()

const emit = defineEmits<{
    toggle: [permissionId: number, selected: boolean]
    toggleAll: [module: string, selected: boolean]
}>()

// Nombre de permissions selectionnees dans ce groupe
const selectedCount = computed(() =>
    props.permissions.filter(p => props.selectedIds.has(p.id)).length
)

// Vrai si toutes les permissions du groupe sont selectionnees
const allSelected = computed(() =>
    props.permissions.length > 0 && selectedCount.value === props.permissions.length
)

// Emet l'evenement de bascule pour une permission individuelle
function togglePermission(id: number, selected: boolean) {
    emit('toggle', id, selected)
}

// Emet l'evenement de bascule pour toutes les permissions du groupe
function toggleAll(selected: boolean) {
    emit('toggleAll', props.module, selected)
}
</script>
