<template>
  <div class="min-h-screen flex flex-col bg-base-300">
    <!-- Home Page Hero Header (full screen, dark background, collapses on scroll) -->
    <template v-if="isHomePage">
      <div
        class="fixed top-0 left-0 right-0 z-40 flex flex-col justify-center transition-all duration-100 ease-out"
        :style="heroStyle"
      >
        <!-- Dark gradient background -->
        <div class="absolute inset-0 bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900" />
        <div class="absolute inset-0 bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-primary/20 via-transparent to-transparent" />

        <!-- Content wrapper (centers content in the hero area) -->
        <div class="relative z-10 flex flex-col items-center justify-center flex-1 px-4">
          <!-- Logo and nav at top when expanded -->
          <div
            class="absolute top-0 left-0 right-0 flex items-center justify-between px-4 lg:px-6 transition-opacity duration-200"
            :style="{ height: '100px', opacity: heroExpanded ? 1 : 0 }"
          >
            <!-- Left: Logo + Nav links -->
            <div class="flex items-center gap-6 pt-4">
              <NuxtLink :to="localePath('/')" class="flex items-center gap-2">
                <span class="font-bold text-xl text-white">Optovia</span>
              </NuxtLink>
              <nav class="flex items-center gap-1">
                <button
                  class="px-3 py-1 text-sm font-medium rounded-lg transition-colors text-white/70 hover:text-white hover:bg-white/10"
                  @click="setCatalogMode('explore')"
                >
                  {{ $t('catalog.modes.explore') }}
                </button>
                <button
                  class="px-3 py-1 text-sm font-medium rounded-lg transition-colors text-white/70 hover:text-white hover:bg-white/10"
                  @click="setCatalogMode('quote')"
                >
                  {{ $t('catalog.modes.quote') }}
                </button>
              </nav>
            </div>

            <!-- Right: Icons (when expanded) -->
            <div class="flex items-center gap-1 pt-4">
              <NuxtLink
                :to="localePath('/clientarea/ai')"
                class="w-8 h-8 rounded-full flex items-center justify-center text-white/70 hover:text-white hover:bg-white/10 transition-colors"
              >
                <Icon name="lucide:bot" size="18" />
              </NuxtLink>
              <div class="dropdown dropdown-end">
                <button
                  tabindex="0"
                  class="w-8 h-8 rounded-full flex items-center justify-center text-white/70 hover:text-white hover:bg-white/10 transition-colors"
                >
                  <Icon name="lucide:globe" size="18" />
                </button>
                <div tabindex="0" class="dropdown-content bg-base-100 rounded-box z-50 w-52 p-4 shadow-lg border border-base-300">
                  <div class="font-semibold mb-2">{{ $t('common.language') }}</div>
                  <div class="flex gap-2 mb-4">
                    <NuxtLink
                      v-for="loc in locales"
                      :key="loc.code"
                      :to="switchLocalePath(loc.code)"
                      class="btn btn-sm"
                      :class="locale === loc.code ? 'btn-primary' : 'btn-ghost'"
                    >
                      {{ loc.code.toUpperCase() }}
                    </NuxtLink>
                  </div>
                  <div class="font-semibold mb-2">{{ $t('common.theme') }}</div>
                  <button class="btn btn-sm btn-ghost w-full justify-start" @click="toggleTheme">
                    <Icon :name="theme === 'night' ? 'lucide:sun' : 'lucide:moon'" size="16" />
                    {{ theme === 'night' ? $t('common.theme_light') : $t('common.theme_dark') }}
                  </button>
                </div>
              </div>
              <template v-if="sessionChecked">
                <template v-if="isLoggedIn">
                  <div class="dropdown dropdown-end">
                    <div
                      tabindex="0"
                      role="button"
                      class="w-8 h-8 rounded-full overflow-hidden ring-2 ring-white/20 hover:ring-white/40 transition-all cursor-pointer"
                    >
                      <div v-if="userAvatarSvg" v-html="userAvatarSvg" class="w-full h-full" />
                      <div v-else class="w-full h-full flex items-center justify-center font-bold text-xs bg-white/20 text-white">
                        {{ userInitials }}
                      </div>
                    </div>
                    <ul tabindex="0" class="dropdown-content menu bg-base-100 rounded-box z-50 w-52 p-2 shadow-lg border border-base-300">
                      <li class="menu-title"><span>{{ userName }}</span></li>
                      <li>
                        <NuxtLink :to="localePath('/clientarea/profile')">
                          <Icon name="lucide:user" size="16" />
                          {{ $t('dashboard.profile') }}
                        </NuxtLink>
                      </li>
                      <div class="divider my-1"></div>
                      <li>
                        <a @click="onClickSignOut" class="text-error">
                          <Icon name="lucide:log-out" size="16" />
                          {{ $t('auth.logout') }}
                        </a>
                      </li>
                    </ul>
                  </div>
                </template>
                <template v-else>
                  <button
                    @click="signIn()"
                    class="px-4 py-1.5 rounded-full text-sm font-medium bg-white/20 text-white hover:bg-white/30 transition-colors"
                  >
                    {{ $t('auth.login') }}
                  </button>
                </template>
              </template>
            </div>
          </div>

          <!-- Centered search area -->
          <div class="w-full max-w-2xl" :class="{ 'mt-0': heroExpanded, '-mt-4': !heroExpanded }">
            <!-- Big title (only when expanded) -->
            <div
              class="text-center mb-8 transition-all duration-200"
              :style="{ opacity: heroExpanded ? 1 : 0, transform: heroExpanded ? 'translateY(0)' : 'translateY(-20px)' }"
            >
              <h1 class="text-4xl lg:text-5xl font-bold text-white mb-3">
                {{ $t('hero.title', 'Оптовая торговля') }}
              </h1>
              <p class="text-lg text-white/70">
                {{ $t('hero.subtitle', 'Найдите лучших поставщиков и товары') }}
              </p>
            </div>

            <!-- Search input (always visible, centered) -->
            <div
              class="flex items-center gap-3 w-full px-5 py-3 rounded-full border border-white/40 bg-white/90 backdrop-blur-md shadow-lg focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20 transition-all cursor-text"
              @click="focusHeroInput"
            >
              <Icon name="lucide:search" size="22" class="text-primary flex-shrink-0" />
              <input
                ref="heroInputRef"
                v-model="searchQuery"
                type="text"
                :placeholder="$t('catalog.search.placeholder')"
                class="flex-1 min-w-32 bg-transparent outline-none text-lg text-base-content placeholder:text-base-content/50"
                @keyup.enter="navigateToCatalog"
              />
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- Regular Fixed Header (for non-home pages) -->
    <template v-else>
      <div class="fixed top-0 left-0 right-0 z-40" :style="headerStyle">
        <MainNavigation
          :session-checked="sessionChecked"
          :logged-in="isLoggedIn"
          :user-avatar-svg="userAvatarSvg"
          :user-name="userName"
          :user-initials="userInitials"
          :theme="theme"
          :user-data="userData"
          :is-seller="isSeller"
          :active-tokens="activeTokens"
          :available-chips="availableChips"
          :select-mode="selectMode"
          :search-query="searchQuery"
          :catalog-mode="catalogMode"
          :product-label="productLabel ?? undefined"
          :hub-label="hubLabel ?? undefined"
          :quantity="quantity"
          :can-search="canSearch"
          :show-mode-toggle="true"
          :show-active-mode="isCatalogSection"
          :glass-style="isCatalogSection"
          @toggle-theme="toggleTheme"
          @set-catalog-mode="setCatalogMode"
          @sign-out="onClickSignOut"
          @sign-in="signIn()"
          @switch-team="switchToTeam"
          @start-select="startSelect"
          @cancel-select="cancelSelect"
          @edit-token="editFilter"
          @remove-token="removeFilter"
          @update:search-query="searchQuery = $event"
          @update-quantity="setQuantity"
          @search="onSearch"
        />

        <SubNavigation
          v-if="!isCatalogSection"
          :section="currentSection"
        />
      </div>
    </template>

    <!-- Page content - padding-top compensates for fixed header -->
    <main class="flex-1 flex flex-col min-h-0 px-3 lg:px-6" :style="mainStyle">
      <slot />
    </main>
  </div>
</template>

<script setup lang="ts">
const runtimeConfig = useRuntimeConfig()
const siteUrl = runtimeConfig.public.siteUrl || 'https://optovia.ru/'
const { signIn, signOut, loggedIn, fetch: fetchSession } = useAuth()
const route = useRoute()
const router = useRouter()
const localePath = useLocalePath()
const { locale, locales } = useI18n()
const switchLocalePath = useSwitchLocalePath()

// Catalog search state
const {
  selectMode,
  searchQuery,
  activeTokens,
  availableChips,
  startSelect,
  cancelSelect,
  removeFilter,
  editFilter,
  setQuantity,
  catalogMode,
  setCatalogMode,
  productLabel,
  hubLabel,
  quantity,
  canSearch
} = useCatalogSearch()

// Collapsible header for catalog pages
const { headerOffset, isCollapsed } = useScrollCollapse(100)

// Hero scroll for home page
const {
  heroHeight,
  collapseProgress,
  isCollapsed: heroIsCollapsed,
  collapsedHeight
} = useHeroScroll()

// Hero input ref
const heroInputRef = ref<HTMLInputElement>()
const focusHeroInput = () => {
  heroInputRef.value?.focus()
}

// Navigate to catalog on enter
const navigateToCatalog = () => {
  router.push(localePath('/catalog'))
}

// Hero expanded state (not fully collapsed)
const heroExpanded = computed(() => collapseProgress.value < 0.5)

// Theme state
const theme = useState<'cupcake' | 'night'>('theme', () => 'cupcake')

// User data state (shared across layouts)
const userData = useState<{
  id?: string
  firstName?: string
  lastName?: string
  avatarId?: string
  activeTeam?: { name?: string; teamType?: string; logtoOrgId?: string; selectedLocation?: any }
  activeTeamId?: string
  teams?: Array<{ id?: string; name?: string; logtoOrgId?: string }>
} | null>('me', () => null)

const sessionChecked = ref(false)
const userAvatarSvg = useState('user-avatar-svg', () => '')
const lastAvatarSeed = useState('user-avatar-seed', () => '')

const isSeller = computed(() => {
  return userData.value?.activeTeam?.teamType === 'SELLER'
})

const isLoggedIn = computed(() => loggedIn.value || !!userData.value?.id)

const userName = computed(() => {
  return userData.value?.firstName || 'User'
})

const userInitials = computed(() => {
  const first = userData.value?.firstName?.charAt(0) || ''
  const last = userData.value?.lastName?.charAt(0) || ''
  if (first || last) return (first + last).toUpperCase()
  return '?'
})

// Determine current section from route
const currentSection = computed(() => {
  const path = route.path
  if (path.startsWith('/catalog') || path === '/') return 'catalog'
  if (path.includes('/clientarea/offers')) return 'seller'
  if (path.includes('/clientarea/orders') || path.includes('/clientarea/addresses') || path.includes('/clientarea/billing')) return 'orders'
  if (path.includes('/clientarea')) return 'settings'
  return 'catalog'
})

// Home page detection
const isHomePage = computed(() => {
  return route.path === '/' || route.path === '/en' || route.path === '/ru'
})

// Catalog section detection (unified search, no SubNav needed)
const isCatalogSection = computed(() => {
  return route.path.startsWith('/catalog') ||
         route.path.startsWith('/en/catalog') ||
         route.path.startsWith('/ru/catalog')
})

// Collapsible header logic - only for pages with SubNav
const hasSubNav = computed(() => !isHomePage.value && !isCatalogSection.value)
const canCollapse = computed(() => hasSubNav.value)
const isHeaderCollapsed = computed(() => canCollapse.value && isCollapsed.value)

// Header style - transform for smooth slide animation (only when SubNav present)
const headerStyle = computed(() => {
  if (!hasSubNav.value) return {}
  return { transform: `translateY(${headerOffset.value}px)` }
})

// Hero style for home page - height changes on scroll
const heroStyle = computed(() => {
  return {
    height: `${heroHeight.value}px`,
    minHeight: `${collapsedHeight}px`
  }
})

// Main content padding-top to compensate for fixed header
// For catalog section: no padding - map extends behind header
// Home page: hero height (dynamic)
// 154px = MainNav + SubNav (orders, seller, settings)
const mainStyle = computed(() => {
  if (isCatalogSection.value) return { paddingTop: '0' }
  if (isHomePage.value) return { paddingTop: `${heroHeight.value}px` }
  return { paddingTop: '154px' }
})

// Provide collapsed state to child components (CatalogPage needs it for map positioning)
provide('headerCollapsed', isHeaderCollapsed)

// Avatar generation
const generateUserAvatar = async (seed: string) => {
  if (!seed) return
  try {
    const response = await fetch(`https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}&backgroundColor=b6e3f4,c0aede,d1d4f9`)
    if (response.ok) {
      userAvatarSvg.value = await response.text()
      lastAvatarSeed.value = seed
    }
  } catch (error) {
    console.error('Error generating avatar:', error)
  }
}

const { setActiveTeam } = useActiveTeam()
const { mutate } = useGraphQL()
const locationStore = useLocationStore()

const syncUserUi = async () => {
  if (!userData.value) {
    locationStore.clear()
    return
  }

  if (userData.value.activeTeamId && userData.value.activeTeam?.logtoOrgId) {
    setActiveTeam(userData.value.activeTeamId, userData.value.activeTeam.logtoOrgId)
  }

  const seed = userData.value.avatarId || userData.value.id || userData.value.firstName || 'default'

  if (!userAvatarSvg.value || lastAvatarSeed.value !== seed) {
    userAvatarSvg.value = ''
    await generateUserAvatar(seed)
  }

  locationStore.setFromUserData(userData.value.activeTeam?.selectedLocation)
}

watch(userData, () => {
  void syncUserUi()
}, { immediate: true })

// Check session
await fetchSession().catch(() => {})
sessionChecked.value = true

const switchToTeam = async (team: { id?: string; logtoOrgId?: string; name?: string }) => {
  if (!team?.id) return

  try {
    const { SwitchTeamDocument } = await import('~/composables/graphql/user/teams-generated')
    const result = await mutate(SwitchTeamDocument, { teamId: team.id }, 'user', 'teams')

    if (result.switchTeam?.user && userData.value) {
      userData.value.activeTeam = team as typeof userData.value.activeTeam
      userData.value.activeTeamId = team.id
      if (team.logtoOrgId) {
        setActiveTeam(team.id, team.logtoOrgId)
      }
    }
  } catch (err) {
    console.error('Failed to switch team:', err)
  }
}

const onClickSignOut = () => {
  signOut(siteUrl)
}

const applyTheme = (value: 'cupcake' | 'night') => {
  if (import.meta.client) {
    document.documentElement.setAttribute('data-theme', value)
    localStorage.setItem('theme', value)
  }
}

onMounted(() => {
  const stored = import.meta.client ? localStorage.getItem('theme') : null
  if (stored === 'night' || stored === 'cupcake') {
    theme.value = stored as 'cupcake' | 'night'
  }
  applyTheme(theme.value)
})

watch(theme, (value) => applyTheme(value))

const toggleTheme = () => {
  theme.value = theme.value === 'night' ? 'cupcake' : 'night'
}

// Search handler for Quote mode - triggers search via shared state
const searchTrigger = useState<number>('catalog-search-trigger', () => 0)
const onSearch = () => {
  // Navigate to catalog page if not there
  if (!route.path.includes('/catalog')) {
    router.push({ path: localePath('/catalog'), query: { ...route.query, mode: 'quote' } })
  }
  // Trigger search by incrementing the counter (page watches this)
  searchTrigger.value++
}
</script>
