<template>
  <!-- 头部 -->
  <header>
    <div class="inner">
      <div class="logo">厦门市文化遗产保护中心</div>
      <!-- 导航 -->
      <nav class="main-nav" :class="{ show: isMenuOpen }">
        <div class="container">
          <ul class="nav-list">
            <li v-for="item in navItems.content.value" :key="item.url" class="nav-item" :class="{ active: isActive(item.url) }">
              <a v-if="item.type === 'link'" :href="item.outlink" target="_blank">{{ item.name }}</a>
              <router-link v-else :to="item.url">{{ item.name }}</router-link>
            </li>
          </ul>
        </div>
      </nav>
      <div class="d-flex flex-row align-items-center">
        <button class="mobile-menu-toggle" @click="toggleMenu"><Icon name="material-symbols:menu" /></button>
        <div class="search-bar">
          <button @click="toggleSearch"><Icon name="material-symbols:search-rounded" /></button>
          <input type="text" placeholder="搜索..." v-model="keyword" @blur="hideSearch" @keydown.enter="goSearch" :class="{ show: isSearchOpen }">
        </div>
      </div>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { useSSrSimpleDataLoader } from '~/composeable/SimpleDataLoader';

const route = useRoute();

const navItems = await useSSrSimpleDataLoader('navItems', async () => {
  const data = (await $fetch('/api/channel/nav')).data || [];

  const specialPages = [] as any[];
  // 政策法规 特殊页
  const lawsPage = data.find(item => item.name === '政策法规');
  if (lawsPage) {
    lawsPage.url = '/channel/laws/?id=' + lawsPage.id;
  }
  const contactPage = data.find(item => item.name === '联系我们');
  if (contactPage) {
    contactPage.url = '/about';
  }
  specialPages.push(lawsPage, contactPage);

  return data.map(item => {
    const isSpeical = (specialPages.includes(item));
    return {
      ...item,
      url: isSpeical ? item.url : 
        (item.type === 'list' ? `/channel/${item.id}` : item.outlink),
    }
  });
});
const isMenuOpen = ref(false);
const isSearchOpen = ref(false);
const keyword = ref('');

function isActive(url: string): boolean {
  return route.path.startsWith(url);
}
function toggleMenu() {
  isMenuOpen.value = !isMenuOpen.value;
}
function toggleSearch() {
  isSearchOpen.value = !isSearchOpen.value;
}
function hideSearch() {
  isSearchOpen.value = false;
}
function goSearch() {
  if (keyword.value.trim()) {
    window.location.href = `/search/?keyword=${encodeURIComponent(keyword.value.trim())}`;
  }
}
</script>