<template>
  <div class="organization-layout min-h-screen text-white">
    <!-- Modular header with BaseHeader + Lego components -->
    <BaseHeader>
      <template #left>
        <HeaderLogo />
      </template>

      <template #center>
        <div class="font-semibold text-lg text-white tracking-wide">{{ orgDisplayName }} garázsa</div>
      </template>

      <template #right>
        <!-- Hamburger Menu (Company Settings) -->
        <div class="relative hamburger-container">
          <button
            @click.stop="isHamburgerOpen = !isHamburgerOpen"
            class="flex h-9 w-9 items-center justify-center rounded-lg text-white/60 hover:text-white hover:bg-white/10 transition-all duration-200 cursor-pointer"
            :aria-label="t('company.companyDataMenu')"
            :title="t('company.companyDataMenu')"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
            </svg>
          </button>

          <!-- Hamburger Dropdown -->
          <Transition
            enter-active-class="transition duration-150 ease-out"
            enter-from-class="scale-95 opacity-0 -translate-y-2"
            enter-to-class="scale-100 opacity-100 translate-y-0"
            leave-active-class="transition duration-100 ease-in"
            leave-from-class="scale-100 opacity-100 translate-y-0"
            leave-to-class="scale-95 opacity-0 -translate-y-2"
          >
            <div
              v-if="isHamburgerOpen"
              class="absolute right-0 top-full mt-2 w-56 z-50 rounded-xl border border-white/10 bg-[#04151F]/95 backdrop-blur-xl shadow-2xl shadow-black/40 overflow-hidden"
            >
              <div class="py-1">
                <button
                  @click="openCompanyData"
                  class="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-white/80 transition-all duration-150 hover:bg-white/5 hover:text-white"
                >
                  <svg class="w-4 h-4 text-white/40" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                  </svg>
                  {{ t('company.companyDataMenu') }}
                </button>
              </div>
            </div>
          </Transition>
        </div>

        <HeaderCompanySwitcher />
        <HeaderProfile />
      </template>
    </BaseHeader>

    <!-- Main content slot for child routes -->
    <main class="relative z-10">
      <router-view />
    </main>

    <!-- Company Data Modal -->
    <CompanyDataModal
      v-if="showCompanyDataModal"
      @close="showCompanyDataModal = false"
      @saved="showCompanyDataModal = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '../stores/auth'
import { useThemeStore } from '../stores/theme'
import BaseHeader from '../components/layout/BaseHeader.vue'
import HeaderLogo from '../components/header/HeaderLogo.vue'
import HeaderCompanySwitcher from '../components/header/HeaderCompanySwitcher.vue'
import HeaderProfile from '../components/header/HeaderProfile.vue'
import CompanyDataModal from '../components/organization/CompanyDataModal.vue'

const route = useRoute()
const { t } = useI18n()
const authStore = useAuthStore()
const themeStore = useThemeStore()

// ── Hamburger Menu State ──────────────────────────────────────────
const isHamburgerOpen = ref(false)
const showCompanyDataModal = ref(false)

// ── Resolve organization display name from route params ────────────
const orgDisplayName = computed(() => {
  const id = Number(route.params.id)
  if (!id) return t('organization.fallbackName')
  const org = authStore.myOrganizations.find((o) => o.organization_id === id)
  return org?.display_name || org?.name || t('organization.fallbackName')
})

// ── Resolve current organization object ────────────────────────────
const currentOrganization = computed(() => {
  const id = Number(route.params.id)
  if (!id) return null
  return authStore.myOrganizations.find((o) => o.organization_id === id) || null
})

// ── Hamburger Menu Handlers ───────────────────────────────────────
function openCompanyData() {
  isHamburgerOpen.value = false
  showCompanyDataModal.value = true
}

// ── Close hamburger on outside click ──────────────────────────────
function handleOutsideClick(e: MouseEvent) {
  const target = e.target as HTMLElement
  if (isHamburgerOpen.value && !target.closest('.hamburger-container')) {
    isHamburgerOpen.value = false
  }
}

// ── Apply theme when organization loads or changes ────────────────
function applyOrgTheme() {
  const org = currentOrganization.value
  if (org?.visual_settings) {
    themeStore.applyTheme(org.visual_settings)
  }
}

// Watch for organization changes (e.g. when switching orgs via switcher)
watch(
  () => route.params.id,
  () => {
    applyOrgTheme()
  },
)

// Apply theme on mount
onMounted(() => {
  applyOrgTheme()
  document.addEventListener('mousedown', handleOutsideClick)
})

// Reset theme when leaving the organization view
onUnmounted(() => {
  themeStore.resetTheme()
  document.removeEventListener('mousedown', handleOutsideClick)
})
</script>
