<template>
  <UDashboardGroup>
    <UDashboardSearch />

    <UDashboardSidebar
      v-model:open="open"
      collapsible
      resizable
      class="bg-(--ui-bg-elevated)/25"
      :ui="{ footer: 'lg:border-t lg:border-(--ui-border)' }"
    >
      <template #header>
        <NuxtLink to="/">
          <img src="/favicon.svg" alt="Logo" class="w-8 h-8" />
        </NuxtLink>
      </template>

      <template #default="{ collapsed }">
        <UDashboardSearchButton :collapsed="collapsed" class="bg-transparent ring-(--ui-border)" />

        <UNavigationMenu :collapsed="collapsed" :items="links[0]" orientation="vertical" />

        <UNavigationMenu :collapsed="collapsed" :items="links[1]" orientation="vertical" class="mt-auto" />
      </template>

      <template #footer="{ collapsed }">
        <UserMenu :collapsed="collapsed" />
        <UButton
          v-if="showSapCopyButton"
          :loading="isDuplicatingSapForm"
          :disabled="isDuplicatingSapForm"
          icon="i-lucide-copy"
          size="xs"
          variant="soft"
          @click="duplicateSapS4HanaForTesting"
        >
          🖨
        </UButton>
        <UButton size="xs" variant="soft" @click="copyAccessTokenToClipboard">📋</UButton>
      </template>
    </UDashboardSidebar>

    <slot />

    <NotificationsSlideover v-model="isNotificationsSlideoverOpen" />
  </UDashboardGroup>
</template>

<script setup lang="ts">
import { useNotificationStore } from '~~/stores/useNotificationStore'
import { useSeededSapS4HanaDuplicator } from '~/composables/testing/useSeededSapS4HanaDuplicator'

const { t: $t } = useI18n()

const links = [
  [
    {
      label: $t('common.general'),
      icon: 'i-lucide-user',
      to: '/settings',
      exact: true
    }
  ],
  [
    {
      label: $t('common.general'),
      icon: 'i-lucide-user',
      to: '/settings',
      exact: true
    }
  ]
]
const open = ref(false)
const logger = useLogger().withTag('layout')

const isNotificationsSlideoverOpen = ref(false)
const notificationStore = useNotificationStore()
const { hasUnread } = storeToRefs(notificationStore)

const {
  showButton: showSapCopyButton,
  isDuplicating: isDuplicatingSapForm,
  duplicateSapS4HanaForTesting
} = useSeededSapS4HanaDuplicator()

onMounted(async () => {
  await notificationStore.fetchUnreadCount()
  notificationStore.startPeriodicRefresh()
})

provide('notificationState', {
  isNotificationsSlideoverOpen,
  hasUnread
})

async function copyAccessTokenToClipboard() {
  const { session } = useUserSession()
  logger.debug('Access Token :', session.value?.jwt?.accessToken)
  const accessToken = session.value?.jwt?.accessToken
  if (accessToken) {
    navigator.clipboard.writeText(accessToken)
    logger.info('Access token copied to clipboard')
  } else {
    logger.warn('No access token found in session')
  }
}
</script>
