<script setup>
import { toast } from 'bulma-toast'
import menusLag from './assets/langs/menus.js'

// Use the centralized role menu composable
const { getMenuType } = useRoleMenu()

// Get the menu type immediately during setup
const defaultSideBarMenu = ref(getMenuType())

const props = defineProps({
  menus: Array
})

const router = useRouter()
const url = useRequestURL()

const sideBar = useSideBar()
const sideBarScroll = useSideBarScroll()
const tabs = useTabs()
const activeMenu = useActiveMenu()
const activeSubMenu = useActiveSubMenu()
const activeSubChildMenu = useActiveSubChildMenu()
const activeSave = useActiveSave()

const getMenus = ref([])
const lang = ref('en-US')
const getLang = ref(null)
onMounted(() => {
  if(document.documentElement.getAttribute('lang')) {
    lang.value = document.documentElement.getAttribute('lang')
    getLang.value = menusLag(lang.value)
    if(getLang.value) {
      getMenus.value = setMenus(getLang.value)
    }
  }
})

const setMenus = (menusLangArg) => {
  //console.log(menusLangArg)
  return props.menus.map(item => {
    item.translatedText = menusLangArg[item.value]
    if(item.link && item.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))) {
      item.active = item.link.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))
      if(item.child) {
        const childrenActive = item.children.map(i => {
          i.translatedText = menusLangArg[i.value]
          if(i.child) {
            const subChildredActive = i.children.map(it => {
              it.translatedText = menusLangArg[it.value]
              if(it.link && it.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))) {
                it.active = it.link.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))
              } else {
                it.active = false
              }
              return it
            })

            i.children = subChildredActive
            i.active = subChildredActive.filter(it => it.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))).length >= 1 ? true : false
          } else {
            if(i.link && i.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))) {
              i.active = i.link.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))
            } else {
              i.active = false
            }
          }
          return i
        })
        item.children = childrenActive

        item.active = childrenActive.filter(i => i.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))).length >= 1 ? true : false
      }
    } else {
      item.active = false
      if(item.child) {
        const newChildren = item.children.map(i => {
          i.translatedText = menusLangArg[i.value]
          if(i.child) {
            const subChildren = i.children.map(it => {
              it.translatedText = menusLangArg[it.value]
              return it
            })
            i.children = subChildren
          }
          return i
        })
        item.children = newChildren
      }
    }
    return item
  })
}

const openMenu = (e, menu) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    if(e.target.parentElement.classList.contains('active')) {
      e.target.parentElement.classList.remove('active')
    } else {
      e.target.parentElement.classList.add('active')
    }
    activeMenu.value = menu?.value || ''
    openMenuHandler(menu)
  }
}
const openSubMenu = (e, menu) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    if(e.target.classList.contains('active')) {
      e.target.classList.remove('active')
      /*if(e.target.parentElement.parentElement.classList.contains('active')) {
        e.target.parentElement.parentElement.classList.remove('active')
      }*/
      if(e.target.nextElementSibling.classList.contains('active') && e.target.nextElementSibling.nodeName === 'DIV') {
        e.target.nextElementSibling.classList.remove('active')
      }
    } else {
      e.target.classList.add('active')
      /*if(!e.target.parentElement.parentElement.classList.contains('active')) {
        e.target.parentElement.parentElement.classList.add('active')
      }*/
      if(!e.target.nextElementSibling.classList.contains('active') && e.target.nextElementSibling.nodeName === 'DIV') {
        e.target.nextElementSibling.classList.add('active')
      }
    }
    activeSubMenu.value = menu?.value || ''
    openMenuHandler(menu)
  }
}
const openSubChildMenu = (e, menu) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    if(e.target.classList.contains('active')) {
      e.target.classList.remove('active')
      /*if(e.target.parentElement.parentElement.classList.contains('active')) {
        e.target.parentElement.parentElement.classList.remove('active')

        if(e.target.parentElement.parentElement.parentElement.classList.contains('active')) {
          e.target.parentElement.parentElement.parentElement.classList.remove('active')
        }
      }*/
    } else {
      e.target.classList.add('active')
      /*if(!e.target.parentElement.parentElement.classList.contains('active')) {
        e.target.parentElement.parentElement.classList.add('active')

        if(!e.target.parentElement.parentElement.parentElement.classList.contains('active')) {
          e.target.parentElement.parentElement.parentElement.classList.add('active')
        }
      }*/
    }
    activeSubChildMenu.value = menu?.value || ''
    openMenuHandler(menu)
  }
}
const openMenuHandler = (menu) => {
  if(menu.child) {
    menu.active = !menu.active
  } 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
      router.push(menu.link)
      sideBar.value = false
    } else {
      tabs.value.push({link: menu.link, text: menu.text, active: true})
      localStorage.setItem('tabs', JSON.stringify(tabs.value))
      router.push(menu.link)
      sideBar.value = false
    }
  }
}

const showSideBar = () => {
  sideBar.value = !sideBar.value
}

const sideBarRef = ref(null)
const scrollEndSideBar = (e) => {
  sideBarScroll.value = e.target.scrollTop ?? e.target.clientHeight
  //console.log(e.target)
  //console.log(e.target.scrollTop)
  //console.log(e.target.scrollHeight)
  //console.log(e.target.clientHeight)
}
onMounted(() => {
  if(sideBarScroll.value && sideBarRef.value) {
    sideBarRef.value.scrollTo(0, sideBarScroll.value || 0)
    //console.log(sideBarScroll.value)
    //console.log(sideBarRef.value)
  }
})

const searchSideBar = ref('')
const searchSideBarMenu = ref(false)
const searchSideBarMenus = ref([])
const searchSideBarTimer = ref(undefined)
const throttleSideBarMenu = () => {
  clearTimeout(searchSideBarTimer.value)
  searchSideBarTimer.value = setTimeout(() => {
    if(searchSideBar.value !== '') {
      searchSideBarMenu.value = true
      searchSideBarMenus.value = props.menus.map(item => (item.children || [])).flat().map(item2 => {
        if(item2.child) {
          return item2.children
        } else {
          return item2
        }
      }).flat().filter(i => i.text?.toLowerCase()?.includes(searchSideBar.value?.toLowerCase()) || i.translatedText?.toLowerCase()?.includes(searchSideBar.value?.toLowerCase()))
    } else {
      searchSideBarMenu.value = false
    }
  }, 1000)
}
</script>

<template>
  <aside id="sidebar" :class="{active: sideBar}" ref="sideBarRef" @scrollend="$event => scrollEndSideBar($event)">
    <div class="logo">LogShip</div>
<!--    <div class="search">-->
<!--      <div class="picker" :class="{active: searchSideBarMenu}">-->
<!--        <div class="pickerBackdrop" @click.self="searchSideBarMenu = false"></div>-->
<!--        <div class="pickerWrap">-->
<!--          <div class="group w-100pct" :class="activeSave ? 'pointerEvents-none opacity-0.6' : ''">-->
<!--            <input type="search" v-model="searchSideBar" @input="throttleSideBarMenu" @keyup.enter="throttleSideBarMenu" class="input groupItem" placeholder="Search here..." />-->
<!--            <button type="button" class="button groupItem" @click="throttleSideBarMenu">-->
<!--              <i class="pointerEvents-none menu-icon tf-icons ti ti-search fg-hexfff"></i>-->
<!--            </button>-->
<!--          </div>-->
<!--          <div class="pickerContent" style="margin-top: 5px;margin-left: -5px;">-->
<!--            <div class="pickerBody" style="box-shadow: 0 3px 8px rgba(0,0,0,.24);">-->
<!--              <div class="list flush">-->
<!--                <div v-for="(srcMenu, srcIndex) in searchSideBarMenus" :key="srcIndex" @click.self="openMenuHandler(srcMenu)" class="listItem p-1 cursor-pointer">{{ srcMenu.translatedText }}</div>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
    <ul>
<!--      Info: {{defaultSideBarMenu}}-->
<!--      <span v-if="defaultSideBarMenu == 'a'">Admin Menu</span>-->
<!--      <span v-else-if="defaultSideBarMenu == 'b'">Fulfillment Admin Menu</span>-->
<!--      <span v-else-if="defaultSideBarMenu == 'c'">Fulfillment Customer Menu</span>-->
<!--      <span v-else>SideBarMenu - Unallocated</span>-->

      <template v-for="(menu, index) in getMenus" :key="index">
        <li v-if="menu.menu === false" class="menuTitle">
          <h5>{{ menu.translatedText }}</h5>
        </li>
        <li v-else :class="{active: menu.active || activeMenu === menu.value || menu.children.filter(i => i.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))).length >= 1 || menu.children.filter(item => (item?.children?.filter(i => i?.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, '')))?.length || 0) >= 1).length >= 1}">
          <a class="dropdown" href="javascript:void(0)" @click.self="openMenu($event, menu)">

              <div class="item">
                <i class="pointerEvents-none" :class="menu.icon"></i>

                <span>{{ menu.translatedText || menu.text }}</span>
              </div>

              <div v-if="menu.child" class="arrow">
                <svg class="pointerEvents-none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512">
                  <path
                    d="M285.5 273L91.1 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.7-22.7c-9.4-9.4-9.4-24.5 0-33.9L188.5 256 34.5 101.3c-9.3-9.4-9.3-24.5 0-33.9l22.7-22.7c9.4-9.4 24.6-9.4 33.9 0L285.5 239c9.4 9.4 9.4 24.6 0 33.9z" />
                </svg>
              </div>
          </a>

          <div v-if="menu.child" class="dropdown-container">
            <template v-for="(child, ind) in menu.children" :key="ind">
              <a href="javascript:void(0)" @click.self="openSubMenu($event, child)" :class="{active: child.active || activeSubMenu === child.value || (child?.children?.filter(i => i?.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, '')))?.length || 0) >= 1 || child.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))}">
                <div class="w-100pct d-flex justify-between fgInheritImportant pointerEvents-none">
                  <span class="fgInheritImportant pointerEvents-none">{{ child.text }}</span>
                  <span v-if="child.child" class="subArrow pointerEvents-none">
                    <svg class="pointerEvents-none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512">
                      <path
                        d="M285.5 273L91.1 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.7-22.7c-9.4-9.4-9.4-24.5 0-33.9L188.5 256 34.5 101.3c-9.3-9.4-9.3-24.5 0-33.9l22.7-22.7c9.4-9.4 24.6-9.4 33.9 0L285.5 239c9.4 9.4 9.4 24.6 0 33.9z" />
                    </svg>
                  </span>
                </div>
              </a>
              <div class="children-container" :class="{active: (child.active || activeSubMenu === child.value || (child?.children?.filter(i => i?.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, '')))?.length || 0) >= 1 || child.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))) && child.child}">
                <a v-for="(sub, inx) in child.children" :key="inx" href="javascript:void(0)" @click.self="openSubChildMenu($event, sub)" :class="{active: sub.active || activeSubChildMenu === sub.value || sub.link?.endsWith(url.pathname.replace(/\/create|\/add|\/\d+\/edit|\/\d+\/view|\/\d+\/print|\/\d+\/duplicate/g, ''))}" style="justify-content: flex-start;">
                  <span class="tf-icon ti ti-chevron-right ti-sm me-1 cursor-pointer"></span> {{ sub.translatedText }}
                </a>
              </div>
            </template>
          </div>
        </li>
      </template>
    </ul>

    <div id="close" @click="showSideBar">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512" class="pointerEvents-none">
        <path
          d="M242.7 256l100.1-100.1c12.3-12.3 12.3-32.2 0-44.5l-22.2-22.2c-12.3-12.3-32.2-12.3-44.5 0L176 189.3 75.9 89.2c-12.3-12.3-32.2-12.3-44.5 0L9.2 111.5c-12.3 12.3-12.3 32.2 0 44.5L109.3 256 9.2 356.1c-12.3 12.3-12.3 32.2 0 44.5l22.2 22.2c12.3 12.3 32.2 12.3 44.5 0L176 322.7l100.1 100.1c12.3 12.3 32.2 12.3 44.5 0l22.2-22.2c12.3-12.3 12.3-32.2 0-44.5L242.7 256z" />
      </svg>
    </div>
  </aside>
  <Teleport to="body">
    <div id="overlay" class="overlay" :class="{active: sideBar}" @click="showSideBar"></div>
  </Teleport>
</template>