<script setup>
import { toast } from 'bulma-toast'

const router = useRouter()
const activeSave = useActiveSave()
const tabs = useTabs()

defineProps({
  items: Array
})

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const openLink = (item) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    //router.push(item.link)
    openTab(item.link, item.text)
  }
}
</script>

<template>
  <nav aria-label="breadcrumb">
    <ol class="breadCrumb pl-0px">
      <template v-for="(item, index) in items" :key="index">
        <li v-if="item.active" class="breadCrumbItem active" aria-current="page"><span>{{ item.text }}</span></li>
        <li v-else-if="item.disabled" class="breadCrumbItem disabled"><span>{{ item.text }}</span></li>
        <li v-else class="breadCrumbItem"><a href="javascript:void(0);" @click.prevent="openLink(item)">{{ item.text }}</a></li>
      </template>
    </ol>
  </nav>
</template>