<template>
  <LayoutContainer>
    <v-row >
      <v-col
        cols="12"
        class="menu-container"
        :class="{ 'sticky-menu': isSticky }"
      >
        <div
          v-for="menu in menus"
          :key="menu.label"
          @click="navigate(menu)"
        >
          <v-chip
            v-if="activeMenu === menu.label"
            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, onUnmounted, reactive } from 'vue';

const refs = reactive({
  Presentation: null,
  Avantages: null,
  Fonctionnalites: null,
  Comparatif: null,
  contact: null,
  Temoignages: null,
  formations: null,
  Aide: null
});

const isSticky = ref(false);

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

  if (scrollPosition > 800) { 
    isSticky.value = true;
  } else {
    isSticky.value = false;
  }

  // Mettez à jour le menu actif en fonction de la position du défilement
  for (const key of Object.keys(refs)) {
    const element = refs[key];
    if (element) {
      const top = element.offsetTop;
      const bottom = top + element.offsetHeight;
      if (scrollPosition >= top && scrollPosition < bottom) {
        activeMenu.value = key;
        break;
      }
    }
  }
};

onMounted(() => {
  Object.keys(refs).forEach(key => {
    refs[key] = document.getElementById(key);
  });

  window.addEventListener('scroll', handleScroll);
});

onMounted(() => {
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
const menus = [
  { label: "Presentation" },
  { label: "Avantages" },
  { label: "Fonctionnalites" },
  { label: "Comparatif" },
  { label: "contact" },
  { label: "formations" },
  { label: "Temoignages" },
  { label: "Aide" },
];

const activeMenu = ref(menus[0].label);

const navigate = (menu) => {
  activeMenu.value = menu.label;
  const element = document.getElementById(menu.label);
  if (element) {
    element.scrollIntoView({ behavior: "smooth" });
  }
};
</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: 1000;
  display: flex;
  justify-content: space-around;
  padding: 1rem 10rem;
  background: white;
  color: #bbb8b8;
  font-family: "Barlow";
  font-size: 12px;
  line-height: 16px;
  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: black;
  color: white;
}

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