<script setup>
import { h, onMounted, ref, watch } from 'vue'
import { NMenu, NButton, NDrawer, NIcon } from 'naive-ui'
import MenuIcon from '@/components/Navbar/MenuIcon.vue'
import { RouterLink, useRoute } from 'vue-router'

const showMobileMenu = ref(false)

const route = useRoute()
const activeKey = ref('collection')

const menuOptions = [
  { label: 'Collection', key: 'collection' },
  { label: 'Charts', key: 'charts' },
  { label: 'Parsers', key: 'parsers' },
  { label: 'Personal', key: 'personal' },
  { label: 'Login', key: 'login' },
]


const windowWidth = ref(window.innerWidth)

onMounted(() => {
  const handleResize = () => {
    windowWidth.value = window.innerWidth
  }
  window.addEventListener('resize', handleResize)
  return () => window.removeEventListener('resize', handleResize)
})


watch(() => route.name, (newName) => {
  activeKey.value = newName
})

const renderLabel = (option) => {
  return h(
      RouterLink,
      {
        to: { name: option.key },
        class: 'nav-link',
        style: 'text-decoration: none; color: inherit;'
      },
      { default: () => option.label }
    )
}
</script>

<template>
  <header class="navbar">
    <div class="logo">Merch tracker</div>

    <n-menu
      class="menu-desktop"
      :options="menuOptions"
      mode="horizontal"
      :collapsed="false"
      :value="activeKey"
      @update:value="activeKey = $event"
      v-if="windowWidth > 768"
      :render-label="renderLabel"
    />

    <n-button
      class="menu-mobile-button"
      @click="showMobileMenu = !showMobileMenu"
    >
      <n-icon :size="34">
        <MenuIcon />
      </n-icon>
    </n-button>

    <n-drawer v-model:show="showMobileMenu" placement="right">
      <n-menu
        :options="menuOptions"
        mode="vertical"
        :value="activeKey"
        @update:value="activeKey = $event; showMobileMenu = false"
        :render-label="renderLabel"
      />
    </n-drawer>
  </header>
</template>

<style>
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: relative;
  z-index: 10;
}

.logo {
  font-weight: bold;
  font-size: 1.2rem;

  flex-shrink: 0;
}

.menu-desktop {
  display: flex;
}

.menu-mobile-button {
  display: none;
  width: 34px;
  height: 34px;
  padding: 0;
  margin: 0;
  border-radius: 8px;
  background: transparent;
  align-items: center;
  justify-content: flex-start;
  flex-shrink: 0;
}

@media (max-width: 768px) {
  .menu-mobile-button {
    display: inline-flex;
  }
}
</style>
