<template>
    <div class="relative">
        <button
            type="button"
            class="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-600 hover:border-slate-300"
            @click="open = !open"
        >
            <span
                class="flex h-7 w-7 items-center justify-center rounded-full bg-slate-100 text-xs font-semibold text-slate-600"
            >
                {{ initials }}
            </span>
            <span class="hidden text-left md:block">
                <span class="block text-[11px] font-semibold text-slate-700">
                    {{ user?.name || 'User' }}
                </span>
                <span class="block text-[10px] text-slate-400">
                    {{ user?.role || 'Administrator' }}
                </span>
            </span>
        </button>

        <div
            v-if="open"
            class="absolute right-0 mt-2 w-56 rounded-xl border border-slate-200 bg-white p-3 shadow-lg"
        >
            <p class="text-xs font-semibold text-slate-700">
                {{ user?.name || 'User' }}
            </p>
            <p class="text-[11px] text-slate-400">
                {{ user?.email || 'user@aurora.test' }}
            </p>
            <div v-if="showAdminLinks" class="mt-3 space-y-1">
                <a
                    href="/account"
                    class="block rounded-lg px-3 py-2 text-xs text-slate-600 hover:bg-slate-50"
                >
                    Account settings
                </a>
                <a
                    href="/users"
                    class="block rounded-lg px-3 py-2 text-xs text-slate-600 hover:bg-slate-50"
                >
                    Team members
                </a>
            </div>
            <form method="post" action="/logout" class="mt-3">
                <input type="hidden" name="_token" :value="csrf" />
                <button
                    type="submit"
                    class="w-full rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                >
                    Sign out
                </button>
            </form>
        </div>
    </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { resolveRoleBucket } from '../data/aurora';

const props = defineProps({
    user: {
        type: Object,
        default: null,
    },
    csrf: {
        type: String,
        default: '',
    },
});

const open = ref(false);
const initials = computed(() => {
    const name = props.user?.name || 'User';
    return name
        .split(' ')
        .slice(0, 2)
        .map((part) => part[0])
        .join('')
        .toUpperCase();
});

const showAdminLinks = computed(() => {
    const bucket = resolveRoleBucket(props.user?.role);
    return ['super_admin', 'admin'].includes(bucket);
});
</script>
