<template>
  <LayoutContainer>
    <v-row>
      <v-col
        cols="12"
        class="menu-container"
        :class="{ 'sticky-menu': isSticky }"
      >
        <div
          v-for="menu in menus"
          :key="menu.id"
          @click="navigate(menu)"
        >
          <v-chip
            v-if="activeMenu === menu.id"
            class="active-menu"
          >
            {{ menu.label }}
          </v-chip>
          <span v-else>{{ menu.label }}</span>
        </div>
      </v-col>
    </v-row>
  </LayoutContainer>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';

const props = defineProps({
  menus: Array
});

const isSticky = ref(false);
const activeMenu = ref('');

const scrollToElement = (element) => {
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};

const handleScroll = () => {
  const scrollPosition = window.scrollY;
  isSticky.value = scrollPosition > 800; 

  for (const menu of props.menus) {
    const { element } = menu;
    if (element && scrollPosition >= element.offsetTop && scrollPosition < element.offsetTop + element.offsetHeight) {
      activeMenu.value = menu.id;
      break;
    }
  }
};

onMounted(() => {
  props.menus.forEach(menu => {
    menu.element = document.getElementById(menu.id);
  });
  window.addEventListener('scroll', handleScroll);
});

watch(() => props.menus, (newMenus) => {
  newMenus.forEach(menu => {
    menu.element = document.getElementById(menu.id);
  });
}, { deep: true });

const navigate = (menu) => {
  activeMenu.value = menu.id;
  scrollToElement(menu.element);
};
</script>

<style scoped>

.sticky-menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: white;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
.menu-container {
  z-index: 3;
  display: flex;
  justify-content: space-around;
  background: white;
  color: #071b1f;
  font-family: "Barlow";
  font-size: 1rem;
  line-height: 19px;
  display: flex;
  align-items: center;
  text-align: center;
  letter-spacing: 0.18em;
  text-transform: uppercase;
  border-bottom: 0.1rem solid #eaeaea;
}
.v-chip.active-menu {
  background: var(--Vert-100, #091D20);;
  color: white;
}

.menu-container div:hover {
  cursor: pointer;
  text-decoration: underline;
  z-index: 15;
}
</style>

