<template>
  <nav class="navbar">
    <ul>
      <li v-for="item in menu" :key="item.name">
        <router-link :to="item.link" v-if="item.link">
          {{ item.name }}
        </router-link>
        <span v-if="!item.link">
          {{  item.name }}
        </span>
        <transition name="fade">
          <div v-if="item.submenu && item.submenu.length" class="dropdown-content">
            <router-link v-for="subitem in item.submenu" :key="subitem.name" :to="subitem.link">
              {{ subitem.name }}
            </router-link>
          </div>
        </transition>
      </li>
    </ul>
  </nav>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'NavbarComponent',
  computed: {
    ...mapState(['menuData']),
    menu() {
      return this.menuData.filter(item => {
        if (!item.showInMenu) {
          return false;
        }
        if (item.requiresAuth && !this.isLoggedIn) {
          return false;
        }
        if (item.submenu) {
          item.submenu = item.submenu.filter(subitem => subitem.showInMenu && (!subitem.requiresAuth || this.isLoggedIn));
        }
        return true;
      });
    },
    isLoggedIn() {
      return this.$store.getters.isLoggedIn;
    }
  }
};
</script>

<style scoped>
.navbar {
  background-color: #9400ff;
  overflow: visible;
  height: 47px;
  display: flex;
  width: 100%;
}

.navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
}

.navbar li {
  position: relative;
}

.navbar a,
.navbar li > span {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 20px;
  text-decoration: none;
  font-weight: bold;
}

.navbar a:hover {
  background-color: #7a00d1;
}

.menu-icon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}

.dropdown-content {
  position: absolute;
  background-color: #9400ff;
  min-width: 200px;
  z-index: 1;
  top: 100%;
  left: 0;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;
  box-shadow: 2px 2px 4px #666;
}

.dropdown-content a {
  color: white;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #7a00d1;
}

.navbar li:hover .dropdown-content {
  opacity: 1;
  visibility: visible;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s ease-in-out, visibility 0.2s ease-in-out;
}

.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity: 0;
  visibility: hidden;
}
</style>
