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


const router = useRouter()
const url = useRequestURL()
const tabs = useTabs()
const activeMenu = useActiveMenu()
const activeSubMenu = useActiveSubMenu()
const activeSubChildMenu = useActiveSubChildMenu()
const activeSave = useActiveSave()
const sideBarScroll = useSideBarScroll()

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
      })
      // Keep the query string + hash: this is a redundant self-navigation to the
      // current URL, but pushing url.pathname alone strips ?refType=order&refId=…
      // off pages opened with prefill params (e.g. the ticket wizard from an
      // order), silently dropping the reference. The full URL makes it a no-op.
      router.push(url.pathname + url.search + url.hash)
      activeMenu.value = ''
      activeSubMenu.value = ''
      activeSubChildMenu.value = ''
      sideBarScroll.value = 0
    }
  }
})

const openTab = (menu) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    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)
    }
    activeMenu.value = ''
    activeSubMenu.value = ''
    activeSubChildMenu.value = ''
    sideBarScroll.value = 0
  }
}

const closeTab = (active, index) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    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)
        activeMenu.value = ''
        activeSubMenu.value = ''
        activeSubChildMenu.value = ''
        sideBarScroll.value = 0
      }
    } else {
      tabs.value.splice(index, 1)
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
    }
  }
}

const contextMenu = ref(false)
const contextMenuX = ref(0)
const contextMenuY = ref(0)
const contextMenuTab = ref({})
const contextMenuIndex = ref(0)
const contextMenuHandler = (e, tab, index) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    contextMenuX.value = e.pageX
    contextMenuY.value = e.pageY
    contextMenu.value = true
    contextMenuTab.value = tab
    contextMenuIndex.value = index
  }
}

const contextMenuCloseTab = () => {
  contextMenu.value = false
  closeTab(contextMenuTab.value?.active || false, contextMenuIndex.value)
}

const contextMenuCloseAll = () => {
  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  contextMenu.value = false
  contextMenuTab.value = {}
  contextMenuIndex.value = 0
  router.push('/')
  activeMenu.value = ''
  activeSubMenu.value = ''
  activeSubChildMenu.value = ''
  sideBarScroll.value = 0
}

const contextMenuCloseInactive = () => {
  tabs.value = tabs.value.filter(i => i.active === true || i.link === '/');
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  contextMenu.value = false
  contextMenuTab.value = {}
  contextMenuIndex.value = 0
  activeMenu.value = ''
  activeSubMenu.value = ''
  activeSubChildMenu.value = ''
  sideBarScroll.value = 0
}

const contextMenuCloseOpen = () => {
  openTab(contextMenuTab.value)
  contextMenuCloseInactive()
}
</script>

<template>
  <div class="tab-bar-wrapper">
    <div class="tabs is-boxed">
      <ul class="px-1.5rem">
        <li v-for="(tab, index) in tabs" :id="index" :class="{'is-active': tab.active}">
          <a :title="tab.text" @click="openTab(tab)" @contextmenu.prevent="contextMenuHandler($event, tab, index)">
            <span class="tab-text" :class="{'tab-inactive': !tab.active}">{{ tab.text }}</span>
            <button v-if="tab.link !== '/'" class="delete ml-2" @click.stop="closeTab(tab.active, index)"></button>
            <i v-else class="menu-icon tf-icons ti ti-square-rounded-chevron-down-filled tab-icon ml-2"></i>
          </a>
        </li>
      </ul>
    </div>
  </div>
  <teleport to="body">
    <div v-if="contextMenu" class="contextMenu" @click.self="contextMenu = false">
      <div class="contextMenuContent" :style="{left: contextMenuX + 'px', top: contextMenuY + 'px'}">
        <div v-if="Number(contextMenuIndex) !== 0" class="contextMenuItem" @click="contextMenuCloseTab">Close Tab</div>
        <div class="contextMenuItem" @click="contextMenuCloseAll">Close All Tabs</div>
        <div class="contextMenuItem" @click="contextMenuCloseInactive">Close All Inactive Tabs</div>
        <div class="contextMenuItem" @click="contextMenuCloseOpen">Open &amp; Close Other Tabs</div>
      </div>
    </div>
  </teleport>
</template>

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

/* Tab Bar Theming */
.tab-bar-wrapper {
  background-color: var(--theme-surface);
  overflow-x: auto;
  border-bottom: 1px solid var(--theme-border);
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.tabs.is-boxed {
  background-color: var(--theme-surface);
}

.tabs.is-boxed ul {
  border-bottom-color: var(--theme-border);
}

.tabs.is-boxed li a {
  background-color: var(--theme-bg-tertiary);
  border-color: var(--theme-border);
  color: var(--theme-text-primary);
  transition: all 0.2s ease;
}

/* Cap tab width: long titles (e.g. product names) truncate with an ellipsis
   instead of blowing the tab up; the full text shows on hover via title. */
.tab-text {
  display: inline-block;
  max-width: 220px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.tabs.is-boxed li a:hover {
  background-color: var(--theme-bg-hover);
  border-bottom-color: var(--theme-border);
}

.tabs.is-boxed li.is-active a {
  background-color: var(--theme-surface) !important;
  border-color: var(--theme-border) !important;
  border-bottom-color: var(--theme-surface) !important;
  color: var(--theme-text-primary) !important;
  font-weight: bold;
}

.tab-inactive {
  color: var(--theme-text-muted);
}

.tab-icon {
  color: var(--theme-text-muted);
}

/* Context Menu Theming */
.contextMenu {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
}

.contextMenuContent {
  position: absolute;
  background-color: var(--theme-surface);
  border: 1px solid var(--theme-border);
  border-radius: 0.5rem;
  box-shadow: 0 4px 12px var(--theme-shadow-lg);
  min-width: 180px;
  padding: 0.5rem 0;
}

.contextMenuItem {
  padding: 0.5rem 1rem;
  cursor: pointer;
  color: var(--theme-text-primary);
  font-size: 0.875rem;
  transition: background-color 0.15s ease;
}

.contextMenuItem:hover {
  background-color: var(--theme-bg-hover);
}

/* Dark mode specific */
.dark .tab-bar-wrapper,
[data-mode="dark"] .tab-bar-wrapper {
  background-color: var(--theme-surface);
  border-bottom-color: var(--theme-border);
}

.dark .tabs.is-boxed,
[data-mode="dark"] .tabs.is-boxed {
  background-color: var(--theme-surface);
}

.dark .tabs.is-boxed li a,
[data-mode="dark"] .tabs.is-boxed li a {
  background-color: var(--theme-bg-tertiary);
  border-color: var(--theme-border);
  color: var(--theme-text-secondary);
}

.dark .tabs.is-boxed li a:hover,
[data-mode="dark"] .tabs.is-boxed li a:hover {
  background-color: var(--theme-bg-hover);
}

.dark .tabs.is-boxed li.is-active a,
[data-mode="dark"] .tabs.is-boxed li.is-active a {
  background-color: var(--theme-surface) !important;
  color: var(--theme-text-primary) !important;
}

.dark .contextMenuContent,
[data-mode="dark"] .contextMenuContent {
  background-color: var(--theme-surface);
  border-color: var(--theme-border);
}

.dark .contextMenuItem,
[data-mode="dark"] .contextMenuItem {
  color: var(--theme-text-primary);
}

.dark .contextMenuItem:hover,
[data-mode="dark"] .contextMenuItem:hover {
  background-color: var(--theme-bg-hover);
}
</style>