<script setup>
const router = useRouter()
const url = useRequestURL()
const tabs = useTabs()

onMounted(() => {
  const getTabs = localStorage.getItem('tabs')
  if(getTabs) {
    tabs.value = JSON.parse(getTabs)
    if(url.pathname) {
      tabs.value.map((item, ind) => {
        if((url.pathname.startsWith(item.link) && item.link != '/') || url.pathname == item.link) {
          item.active = true
        } else {
          item.active = false
        }
        return item
      })
      router.push(url.pathname)
    }
  }
})

const openTab = (menu) => {
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === menu.link).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === menu.link)
    tabs.value[tabIndex].active = true
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(menu.link)
  } else {
    tabs.value.push({link: menu.link, text: menu.text, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(menu.link)
  }
}

const closeTab = (active, index) => {
  if(active) {
    tabs.value.splice(index, 1)
    tabs.value.map((item, ind) => {
      if((Number(index) - 1) === Number(ind)) {
        item.active = true
      } else {
        item.active = false
      }
      return item
    })
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    const newLink = tabs.value.filter(i => i.active)
    if(newLink.length >= 1) {
      router.push(newLink[0].link)
    }
  } else {
    tabs.value.splice(index, 1)
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
  }
}
</script>

<template>
  <ul class="nav tab" style="padding-left: 0.75rem;padding-top: 0.75rem;">
    <li v-for="(tab, index) in tabs" :id="index" class="item" :class="{active: tab.active, disabled: tab.disabled}">
      <span @click="openTab(tab)" class="link" aria-current="page" :class="{'opacity-0.5': !tab.active}">
        {{ tab.text }}
        <i v-if="tab.link !== '/'" @click.stop="closeTab(tab.active, index)" class="menu-icon tf-icons ti ti-square-rounded-x-filled fg-hex999"></i>
        <i v-else class="menu-icon tf-icons ti ti-square-rounded-chevron-down-filled fg-hex999"></i>
      </span>
    </li>
  </ul>
</template>

<style scoped>
.item:not(.active) {
  color: inherit;
}
</style>