<template>
  <nav class="header-nav">
    <div
      v-for="(n, i) in nav"
      :key="i"
      class="header-nav-item"
      :class="{ active: isRouteActive(n) }"
    >
      <template v-if="n.children && n.children.length">
        <span class="header-nav-title">{{ n.title }}</span>
        <ul class="header-nav-children">
          <li
            v-for="(nn, j) in n.children"
            :key="j"
            class="header-nav-child"
            :class="{ active: isRouteActive(nn) }"
          >
            <router-link
              class="header-nav-title header-nav-link"
              :to="nn.route"
              >{{ nn.title }}</router-link
            >
          </li>
        </ul>
      </template>
      <router-link
        v-else
        class="header-nav-title header-nav-link"
        :to="n.route"
        >{{ n.title }}</router-link
      >
    </div>
  </nav>
</template>
<script>
export default {
  name: 'HeaderNav',
  props: {
    nav: {
      type: Array,
      required: true,
    },
  },
  methods: {
    isRouteActive(nav) {
      const path = this.$route.path
      if (nav.route === path) return true
      if (nav.children?.length) {
        return nav.children.some((e) => e.route === path)
      }
    },
  },
}
</script>
<style lang="scss">
.header-nav {
  display: flex;
  height: 100%;
}

@mixin header-nav-item-active($x) {
  &::before,
  &::after {
    content: '';
    display: block;
    width: 50%;
    transform: scaleX($x);
    height: 4px;
    background-color: var(--primary-color);
    position: absolute;
    top: 0;
    transition: transform 0.3s;
  }

  &::before {
    left: 0;
    transform-origin: 100%;
  }

  &::after {
    right: 0;
    transform-origin: 0;
  }

  &:hover {
    &::before,
    &::after {
      transform: scaleX(1);
    }
  }
}

.header-nav-item {
  width: 120px;
  height: 100%;
  position: relative;

  &:hover {
    .header-nav-children {
      display: flex;
    }
  }

  &.active {
    & > .header-nav-title {
      @include header-nav-item-active(1);
      color: var(--primary-color);
    }
  }

  & > .header-nav-title {
    @include header-nav-item-active(0);
  }
}

.header-nav-children {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  margin: 0;
  padding: 0;
  display: none;
  flex-direction: column;
  background-color: #000;
  color: #fff;
}

.header-nav-child {
  width: 100%;
  height: 60px;
  margin: 0;
  padding: 0;
  list-style-type: none;

  &.active {
    color: var(--primary-color);
  }
}

.header-nav-title {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;

  &:hover {
    color: var(--primary-color);
  }
}

.header-nav-link {
  color: inherit;
  text-decoration: none;
  cursor: pointer;
  transition: 0.3s;
}
</style>
