---
import Logo from './Logo.astro';
import Navbar from './Navbar.astro';
import MobileMenu from './MobileMenu.astro';
import Search from './Search.astro';
import { pb } from '@lib/pocketbase';

interface NavItem {
  id: string;
  title: string;
  url: string;
  is_visible: boolean;
  order: number;
}

// Уникальный ключ 'header_nav' предотвращает отмену
const navItems: NavItem[] = await pb.collection('nav_items').getFullList({
  filter: 'is_visible = true',
  sort: 'order',
  requestKey: 'header_nav'
});

const { pathname } = Astro.url;
const currentPath = pathname.replace(/\/$/, '') || '/';
---

<header id="header" class="sticky top-0 z-50 w-full h-20 transition-[height] duration-300">
  <div id="header-container" class="relative h-full max-w-7xl px-4 mx-auto transition-all duration-300 border-transparent">
    <div class="flex items-center justify-between h-full select-none">
      <Logo />
      <nav class="flex items-center gap-x-6">
        <div class="hidden lg:flex items-center pr-6">
          <Navbar items={navItems} currentPath={currentPath} />
        </div>
        <Search />
        <div class="lg:hidden ml-2">
          <MobileMenu items={navItems} currentPath={currentPath} />
        </div>
      </nav>
    </div>
  </div>
</header>

<script>
  const headerElement = document.getElementById("header");
  const headerContainerElement = document.getElementById("header-container");

  function evaluateHeaderPosition() {
    if (window.scrollY > 20) {
      if (headerContainerElement) {
        headerContainerElement.classList.add("dark:border-neutral-800", "border-x", "border-b", "dark:bg-neutral-900/80", "backdrop-blur-xl", "rounded-b-xl");
        headerContainerElement.classList.remove("border-transparent");
      }
      if (headerElement) {
        headerElement.classList.add("h-16");
        headerElement.classList.remove("h-20");
      }
    } else {
      if (headerContainerElement) {
        headerContainerElement.classList.remove("dark:border-neutral-800", "border-x", "border-b", "dark:bg-neutral-900/80", "backdrop-blur-xl", "rounded-b-xl");
        headerContainerElement.classList.add("border-transparent");
      }
      if (headerElement) {
        headerElement.classList.remove("h-16");
        headerElement.classList.add("h-20");
      }
    }
  }
  window.addEventListener("scroll", evaluateHeaderPosition, { passive: true });
</script>