<script setup>
const auth = useAuthStore()

const activeTenantName = computed(() => {
  return auth.activeTenantData?.name || auth.tenants?.find((tenant) => tenant.id === auth.activeTenant)?.name || 'Mandant waehlen'
})

const tenantInitials = computed(() => {
  return activeTenantName.value
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() || '')
    .join('') || 'M'
})

const activeTenants = computed(() =>
  auth.tenants.filter((tenant) => tenant.hasActiveLicense)
)

const tenantItems = computed(() => [
  activeTenants.value.map((tenant) => ({
    label: tenant.name,
    icon: tenant.id === auth.activeTenant ? 'i-heroicons-check' : undefined,
    disabled: Boolean(tenant.locked),
    onSelect: async (event) => {
      if (tenant.locked || tenant.id === auth.activeTenant) {
        event?.preventDefault?.()
        return
      }

      await auth.switchTenant(tenant.id)
    }
  }))
])
</script>

<template>
  <USelectMenu
      :items="tenantItems"
      :content="{ align: 'start', side: 'bottom', sideOffset: 6 }"
      :ui="{ content: 'w-[var(--reka-dropdown-menu-trigger-width)] max-w-[var(--reka-dropdown-menu-trigger-width)]' }"
      class="block w-40"
      :avatar="{
        alt: activeTenantName,
        text: tenantInitials,
        loading: 'lazy'
    }"
  >
    <template #default="{ open }">
      <UButton
          color="gray"
          variant="ghost"
          class="w-full min-w-0 max-w-full justify-start gap-2 rounded-lg px-2.5 py-2 text-left"
          :class="[open && 'bg-gray-100 dark:bg-gray-800']"
      >
        <span class="min-w-0 flex-1 truncate font-medium text-gray-900 dark:text-white">
          {{ activeTenantName }}
        </span>
      </UButton>
    </template>
  </USelectMenu>
</template>
