<template>
    <div>
        <div v-if="permissions.length === 0" class="text-sm text-neutral-400">
            {{ t('admin.users.drawer.noEffectivePermissions') }}
        </div>
        <div v-else class="divide-y divide-neutral-100 rounded-lg border border-neutral-200">
            <div
                v-for="perm in groupedPermissions"
                :key="perm.module"
                class="px-4 py-2"
            >
                <!-- En-tête du module -->
                <p class="text-xs font-semibold uppercase text-neutral-400 mb-1">
                    {{ perm.module }}
                </p>
                <div
                    v-for="item in perm.items"
                    :key="item.code"
                    class="flex items-center justify-between py-1"
                >
                    <span class="text-sm text-neutral-700">{{ item.label }}</span>
                    <div class="flex gap-1">
                        <span
                            v-for="source in item.sources"
                            :key="source"
                            :class="[
                                'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
                                source === t('admin.users.drawer.sourceDirect')
                                    ? 'bg-green-100 text-green-800'
                                    : 'bg-blue-100 text-blue-800'
                            ]"
                        >
                            {{ source }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { EffectivePermission } from '~/shared/types/rbac'

const { t } = useI18n()

const props = defineProps<{
    permissions: EffectivePermission[]
}>()

// Grouper par module pour l'affichage
interface PermissionModuleGroup {
    module: string
    items: EffectivePermission[]
}

const groupedPermissions = computed<PermissionModuleGroup[]>(() => {
    const groups = new Map<string, EffectivePermission[]>()
    for (const perm of props.permissions) {
        const list = groups.get(perm.module) || []
        list.push(perm)
        groups.set(perm.module, list)
    }
    return Array.from(groups.entries())
        .map(([module, items]) => ({ module, items }))
        .sort((a, b) => a.module.localeCompare(b.module))
})
</script>
