<script setup>
import { toast } from 'bulma-toast'
import navsLag from './assets/langs/navs.js'

const props = defineProps({
  showLanguageMenu: {
    type: Boolean,
    default: true
  },
  showUserMenu: {
    type: Boolean,
    default: true
  }
})

const activeSave = useActiveSave()
const tabs = useTabs()
const user = useCookie('logship_user')
const { getMenuType } = useRoleMenu()
const isFulfillmentCustomer = computed(() => getMenuType() === 'c')

const orgId = useCookie('logship_organization_id')

const unpaidInvoiceCount = ref(0)

// Cache key is scoped per organization (and versioned with _v3) so switching orgs
// never surfaces a stale count from another org, and the server-side filter change
// invalidates any pre-existing cache instead of lingering for up to 24h.
// (v2 caches hold a poisoned 0 from the over-tightened AD_Org_ID filter.)
const CACHE_KEY = computed(() => `logship_unpaid_invoices_v3_${orgId.value ?? 'none'}`)
const CACHE_TS_KEY = computed(() => `logship_unpaid_invoices_v3_ts_${orgId.value ?? 'none'}`)
const CACHE_TTL = 24 * 60 * 60 * 1000 // 24 hours

const fetchUnpaidInvoiceCount = async () => {
  if (!isFulfillmentCustomer.value) return

  // Check localStorage cache
  try {
    const cached = localStorage.getItem(CACHE_KEY.value)
    const cachedTs = localStorage.getItem(CACHE_TS_KEY.value)
    if (cached !== null && cachedTs) {
      const age = Date.now() - Number(cachedTs)
      if (age < CACHE_TTL) {
        unpaidInvoiceCount.value = Number(cached)
        return
      }
    }
  } catch (e) {
    // localStorage not available
  }

  // Fetch from server
  try {
    const res = await $fetch('/api/invoices/ffn-unpaid-count', {
      headers: useRequestHeaders(['cookie'])
    })
    const count = res?.count || 0
    unpaidInvoiceCount.value = count

    try {
      localStorage.setItem(CACHE_KEY.value, String(count))
      localStorage.setItem(CACHE_TS_KEY.value, String(Date.now()))
    } catch (e) {
      // localStorage not available
    }
  } catch (err) {
    console.warn('Could not fetch unpaid invoice count:', err)
  }
}

const lang = ref('en-US')
const langs = ref([
  {
    code: 'en-US',
    name: 'English',
    flag: '🇺🇸'
  },
  {
    code: 'de-DE',
    name: 'German',
    flag: '🇩🇪'
  },
  {
    code: 'es-ES',
    name: 'Español',
    flag: '🇪🇸'
  },
  {
    code: 'ne-NP',
    name: 'नेपाली',
    flag: '🇳🇵'
  }
])

onMounted(() => {
  if(document.documentElement.getAttribute('lang')) {
    lang.value = document.documentElement.getAttribute('lang')
  }

  fetchUnpaidInvoiceCount()

  // Close dropdowns when clicking outside
  const handleClickOutside = (e) => {
    const dropdowns = document.querySelectorAll('.nav-dropdown-wrapper')
    dropdowns.forEach(dropdown => {
      if (!dropdown.contains(e.target)) {
        dropdown.classList.remove('active')
      }
    })
  }

  document.addEventListener('click', handleClickOutside)

  onBeforeUnmount(() => {
    document.removeEventListener('click', handleClickOutside)
  })
})

const getLang = computed(() => {
  return navsLag(lang.value)
})

const getLangName = computed(() => {
  return langs.value.filter(i => i.code === lang.value)?.[0]?.name ?? 'English'
})

const getLangFlag = computed(() => {
  return langs.value.filter(i => i.code === lang.value)?.[0]?.flag ?? '🇺🇸'
})

const setLocale = (langCode) => {
  // Close the dropdown
  document.querySelectorAll('.nav-dropdown-wrapper.active').forEach(w => {
    w.classList.remove('active')
  })
  localStorage.setItem('logship_lang', langCode)
  location.reload()
}

const dropDownHandler = (e) => {
  e.stopPropagation()
  if(activeSave.value) {
    toast({
      message: getLang.value?.['save_warning'] || 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    const wrapper = e.target.closest('.nav-dropdown-wrapper')
    if (wrapper) {
      // Close all other dropdowns
      document.querySelectorAll('.nav-dropdown-wrapper.active').forEach(w => {
        if (w !== wrapper) w.classList.remove('active')
      })
      // Toggle this dropdown
      wrapper.classList.toggle('active')
    }
  }
}

const logout = async () => {
  await $fetch('/api/idempiere-auth/logout', {
    method: 'POST',
    headers: useRequestHeaders(['cookie'])
  })

  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  // Clear every unpaid-invoice cache variant (all orgs + legacy unversioned keys),
  // since the org cookie may already be gone by the time logout runs.
  try {
    Object.keys(localStorage)
      .filter(k => k.startsWith('logship_unpaid_invoices'))
      .forEach(k => localStorage.removeItem(k))
  } catch (e) {
    // localStorage not available
  }
  location.href = '/signin'
}

const goToInvoices = async () => {
  if(activeSave.value) {
    toast({
      message: getLang.value?.['save_warning'] || 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  try {
    tabs.value = tabs.value.map(item => ({
      ...item,
      active: false
    }))

    const normalizedPath = '/fulfillment/invoices'
    const existingTab = tabs.value.find(i => i.link === normalizedPath)

    if(existingTab) {
      existingTab.active = true
    } else {
      tabs.value.push({link: normalizedPath, text: 'Rechnungen', active: true})
    }

    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    await navigateTo('/fulfillment/invoices')
  } catch (error) {
    console.error('Navigation error:', error)
  }
}

const goToProfile = async () => {
  if(activeSave.value) {
    toast({
      message: getLang.value?.['save_warning'] || 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  try {
    tabs.value = tabs.value.map(item => ({
      ...item,
      active: false
    }))

    const normalizedPath = '/users/profile'
    const existingTab = tabs.value.find(i => i.link === normalizedPath)

    if(existingTab) {
      existingTab.active = true
    } else {
      tabs.value.push({link: normalizedPath, text: getLang.value?.['user_profile'] || 'User Profile', active: true})
    }

    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    await navigateTo('/users/profile')
  } catch (error) {
    console.error('Navigation error:', error)
  }
}
</script>

<template>
  <div class="user-menu-bar">
    <!-- Staff live-chat (isolated module): renders nothing unless enabled
         + non-limited role. Error-boundaried so it can never break the bar. -->
    <ClientOnly>
      <NuxtErrorBoundary>
        <ChatBadge />
        <template #error="{ error }">
          <span style="display:none">{{ error }}</span>
        </template>
      </NuxtErrorBoundary>
    </ClientOnly>

    <!-- Theme Toggle -->
    <ThemeToggle />

    <!-- Language Selector -->
    <div class="nav-dropdown-wrapper">
      <button class="nav-dropdown-trigger" @click="dropDownHandler($event)">
        <span class="flag-icon">{{ getLangFlag }}</span>
      </button>
      <div class="nav-dropdown-menu language-menu">
        <button
          v-for="(item, index) in langs"
          :key="index"
          v-show="item.code !== lang"
          class="nav-dropdown-item"
          @click="setLocale(item.code)"
        >
          <span class="flag-icon">{{ item.flag }}</span>
          <span>{{ item.name }}</span>
        </button>
      </div>
    </div>

    <!-- User Menu -->
    <div class="nav-dropdown-wrapper">
      <button class="nav-dropdown-trigger" @click="dropDownHandler($event)">
        <span class="user-icon-wrapper">
          <UIcon name="i-heroicons-user-circle" class="w-5 h-5" />
          <span v-if="unpaidInvoiceCount > 0" class="unpaid-badge-trigger">{{ unpaidInvoiceCount }}</span>
        </span>
        <span class="nav-dropdown-label">{{ user?.Name || getLang['guest'] || 'Guest' }}</span>
        <UIcon name="i-heroicons-chevron-down" class="w-4 h-4 transition-transform" />
      </button>
      <div class="nav-dropdown-menu user-menu">
        <button v-if="isFulfillmentCustomer" class="nav-dropdown-item" @click="goToInvoices()">
          <UIcon name="i-heroicons-document-text" class="w-4 h-4" />
          <span>Rechnungen</span>
          <span v-if="unpaidInvoiceCount > 0" class="unpaid-badge-menu">{{ unpaidInvoiceCount }}</span>
        </button>
        <button class="nav-dropdown-item" @click="goToProfile()">
          <UIcon name="i-heroicons-user" class="w-4 h-4" />
          <span>{{ getLang['account'] || 'Account' }}</span>
        </button>
        <button class="nav-dropdown-item" @click="logout()">
          <UIcon name="i-heroicons-arrow-right-on-rectangle" class="w-4 h-4" />
          <span>{{ getLang['log_out'] || 'Logout' }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-menu-bar {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* Dropdown structure styling */
.nav-dropdown-wrapper {
  position: relative;
  display: inline-block;
}

.nav-dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  border: 1px solid var(--theme-border);
  border-radius: 0.5rem;
  background: var(--theme-surface);
  color: var(--theme-text-primary);
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.nav-dropdown-trigger:hover {
  background-color: var(--theme-bg-hover);
  border-color: var(--theme-border-dark);
}

.nav-dropdown-label {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nav-dropdown-menu {
  display: none;
  position: absolute;
  top: calc(100% + 0.5rem);
  right: 0;
  background: var(--theme-surface);
  border: 1px solid var(--theme-border);
  border-radius: 0.5rem;
  box-shadow: 0 10px 15px -3px var(--theme-shadow-lg), 0 4px 6px -2px var(--theme-shadow);
  z-index: 1100;
  width: max-content;
  min-width: auto;
  overflow: hidden;
}

.nav-dropdown-wrapper.active .nav-dropdown-menu {
  display: block;
  animation: slideDown 0.2s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.nav-dropdown-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 0.875rem;
  width: 100%;
  border: none;
  background: none;
  color: var(--theme-text-primary);
  font-size: 0.875rem;
  text-align: left;
  cursor: pointer;
  transition: background-color 0.15s ease;
  white-space: nowrap;
}

.nav-dropdown-item:hover {
  background-color: var(--theme-bg-hover);
}

.nav-dropdown-item.font-semibold {
  font-weight: 600;
}

/* Language menu specific */
.language-menu {
  min-width: auto;
  width: max-content;
  padding: 0.5rem;
}

.nav-dropdown-wrapper.active .language-menu {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

/* User menu specific */
.user-menu {
  width: max-content;
  min-width: auto;
}

@media (max-width: 1024px) {
  .nav-dropdown-label {
    display: none;
  }

  .nav-dropdown-trigger {
    padding: 0.5rem;
    min-width: 2.5rem;
    justify-content: center;
  }

  .user-menu-bar {
    gap: 0.5rem;
    margin-right: 0.5rem;
  }
}

@media (max-width: 768px) {
  .nav-dropdown-trigger {
    padding: 0.375rem;
    min-width: 2.25rem;
  }

  .user-menu-bar {
    gap: 0.25rem;
    margin-right: 0.375rem;
  }
}

.flag-icon {
  font-size: 1.25rem;
  line-height: 1;
}

/* Unpaid invoice badge on the user icon */
.user-icon-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.unpaid-badge-trigger {
  position: absolute;
  top: -0.5rem;
  right: -0.5rem;
  min-width: 1.125rem;
  height: 1.125rem;
  padding: 0 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ef4444;
  color: white;
  font-size: 0.625rem;
  font-weight: 700;
  border-radius: 9999px;
  line-height: 1;
  pointer-events: none;
}

/* Unpaid invoice badge inside the dropdown menu item */
.unpaid-badge-menu {
  margin-left: auto;
  min-width: 1.25rem;
  height: 1.25rem;
  padding: 0 0.375rem;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #ef4444;
  color: white;
  font-size: 0.6875rem;
  font-weight: 700;
  border-radius: 9999px;
  line-height: 1;
}
</style>
