<template>
  <!-- 寬度：256px -->
  <div
    :class="[
      ' text-white h-full flex flex-col transition-all whitespace-nowrap overflow-x-hidden  ',
      collapsed ? 'w-16 ' : 'w-64 z-50',
    ]"
    style="background: linear-gradient(to bottom, #9DBCD9, #9DBCD9);"
    @mouseenter="collapsed = false"
    @mouseleave="collapsed = true"
  >
    <!-- 高度：80px -->
    <div class="relative pl-2 py-1 h-20 w-full overflow-hidden">
      <!-- MARK：縮回時顯示，展開時漸隱 -->
      <router-link :to="`/`">
        <img
          src= "@images/IDA_mark.png"
          class="h-full object-contain transition-opacity  "
          :class="{ 'opacity-0': showLogo, 'opacity-100': !showLogo }"
          alt="IDA Mark"
        />

        <!-- LOGO：展開時顯示，縮回時漸隱 -->
        <img
          src= "@images/IDA_logo.png"
          class="absolute top-[10px] h-[81px] w-auto object-cover transition-opacity  "
          :class="{ 'opacity-100': showLogo, 'opacity-0': !showLogo }"
          alt="IDA Logo"
        />
      </router-link>
    </div>

    
    <hr class=" border mx-2 my-1">
    <ul class="flex-1 overflow-y relative">
      <li
        v-for="(item, index) in rawMenu"
        :key="index"
        class="group relative"
        @mouseenter="collapsed && (hoverMenus[index] = true)"
        @mouseleave="collapsed && (hoverMenus[index] = false)"
      >
        <div class="pt-1">
          <!-- 主選單 -->
          <component
            :is="item.children ? 'div' : RouterLink"
            :to="!item.children ? item.to : undefined"
            @click="item.children && toggleSubmenu(index)"
            :class="[
              'flex items-center mx-2 p-2 cursor-pointer justify-between transition duration-200 rounded-xl',
              !item.children && isActive(item.to) ? ' bg-slate-400 text-white' : ''
            ]"
            :title="collapsed ? item.title : ''"
          >
          <span class="flex items-center">
            <component
              v-if="typeof item.icon === 'function'"
              :is="item.icon"
              class="w-8 h-8 mr-3 shrink-0"
            />
            <img
              v-else-if="typeof item.icon === 'string'"
              :src="item.icon"
              alt="icon"
              class="w-7 h-7 mr-3 shrink-0 object-contain"
            />
            <span class="font-bold" v-show="!collapsed">{{ item.title }}</span>
          </span>

            <template v-if="item.children && !collapsed">
              <ChevronDownIcon class="w-4 h-4" v-if="openMenus[index]" />
              <ChevronRightIcon class="w-4 h-4" v-else />
            </template>
          </component>
          
          <!-- 子選單（有子項時） -->
          <transition name="fade-slide">
            <component
              :is="collapsed ? 'div' : 'ul'"
              v-if="shouldShowSubmenu(index, item) || shouldShowTooltip(index, item)"
              :class="[collapsed
                ? 'fixed left-[4rem] bg-gray-700 rounded shadow-lg z-50 w-44 py-2 px-3'
                : 'pl-10']"
              :style="collapsed ? `top: ${index * 4.5 + 6}rem` : ''"
            >
              <!-- 無論是否有 children，都顯示主項 title（作為浮出提示或 submenu 標題） -->
              <div
                v-if="collapsed"
                class="text-gray-300 font-bold"
                :class="{ 'pb-1 mb-1 border-b border-gray-600': item.children }"
              >
                {{ item.title }}
              </div>

              <!-- 子選項（只有有 children 時才顯示） -->
              <template v-if="item.children">
                <li v-for="(child, i) in item.children" :key="i">
                  <RouterLink
                    :to="child.to"
                    class="block p-2 whitespace-nowrap rounded transition duration-200"
                    :class="[
                      isActive(child.to)
                        ? 'bg-gray-700 text-white'
                        : 'hover:bg-gray-600 text-gray-300'
                    ]"
                  >
                    {{ child.title }}
                  </RouterLink>
                </li>
              </template>
            </component>
          </transition>
        </div>
        
        <!-- <div v-if="index !== rawMenu.length - 1" class="border-b border-gray-600 mx-4"></div> -->
      </li>
    </ul>

    <!-- Collapse button -->
    <div class="relative p-3 ">
      <div class="flex items-center justify-start w-full">
        <!-- <div
          class="h-8 w-8 rounded-full flex items-center justify-center text-white font-bold text-sm flex-shrink-0"
        >
          <a
          
            :href="`${ASSET_URL}/logout`"
            title="登出"
          >
            <ArrowRightStartOnRectangleIcon class="w-8 h-8" />
          </a>
        </div>
        <div
          :class="[
            'ml-2 text-base font-serif whitespace-nowrap overflow-hidden transition-all duration-300',
            collapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'
          ]"
        >
          <span class="block">返回智慧化<br>管理技術平台</span>
        </div> -->
        <div class="w-full">
          <a
            :href="`${ASSET_URL}/logout`"
            title="登出"
            class="flex items-center justify-start w-full no-underline text-inherit"
          >
            <div class="h-8 w-8 rounded-full flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
              <ArrowRightStartOnRectangleIcon class="w-8 h-8" />
            </div>
            <div
              :class="[
                'ml-2 text-base font-serif whitespace-nowrap overflow-hidden transition-all duration-300',
                collapsed ? 'w-0 opacity-0' : 'w-auto opacity-100'
              ]"
            >
              <span class="block">返回智慧化<br>管理技術平台</span>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { 
  ArrowRightStartOnRectangleIcon, ChevronDownIcon, ChevronRightIcon, ChevronLeftIcon, 
  HomeIcon, Cog6ToothIcon, RectangleGroupIcon, InformationCircleIcon, 
} from '@heroicons/vue/24/solid'
import { onMounted, reactive, ref ,watch } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { api } from "@/global/axios"

const collapsed = ref(true)
const openMenus = reactive({})
const hoverMenus = reactive({})
const route = useRoute()

const showLogo = ref(false)

watch(collapsed, (val) => {
  if (!val) {
    showLogo.value = true
  } else {
    showLogo.value = false
  }
})

const isActive = (to) => {
  return route.path === to  // 簡單比對路徑(顯示高光)
  // return route.path.startsWith(to || '') 
}

const toggleSubmenu = (index) => {
  openMenus[index] = !openMenus[index]
}

const shouldShowSubmenu = (index, item) => {
  return item.children && (
    (!collapsed.value && openMenus[index]) ||
    (collapsed.value && hoverMenus[index])
  )
}

const shouldShowTooltip = (index, item) => {
  return collapsed.value && !item.children && hoverMenus[index]
}

const ASSET_URL = import.meta.env.VITE_ASSET_URL
const menu = [
  { 
    title: '概要', 
    icon: ASSET_URL + '/images/menu_icon.png',
    to: '/',
    permission: 'admin'
  },
  {
    title: '廠區管理',
    icon: ASSET_URL + '/images/factory_icon.png',
    to: '/Factory/Index',
    permission: 'admin',
  },
  {
    title: '設備管理',
    icon: ASSET_URL + '/images/equipment_icon.png',
    to: '/Equipment/Index',
    permission: 'admin' ,
  },
  {
    title: '檢核表單',
    icon: ASSET_URL + '/images/banks_icon.png',
    to: '/BankList/Index',
    permission: 'admin'
  },
  {
    title: '派工表單',
    icon: ASSET_URL + '/images/dispatch_icon.png',
    to: '/Dispatch/Index',
    permission: 'admin'
  },
  {
    title: '巡檢紀錄',
    icon: ASSET_URL + '/images/checks_icon.png',
    to: '/CheckList/Index',
    permission: 'admin' 
  },
  {
    title: '每日巡檢',
    icon: ASSET_URL + '/images/daily_icon.png',
    to: '/Daily/Index',
    permission: 'admin'
  },
  {
    title: '檢核分析',
    icon: ASSET_URL + '/images/analysis_icon.png',
    to: '/analysis',
    permission: 'admin'
  },
  { 
    title: '操作說明', 
    icon: InformationCircleIcon,
    to: '/maintain'
  },
]

const userData = ref({
  name:'',
  role: '',
})
const rawMenu = ref([...menu])

const getuser = async() => {
  const res = await api.get("/api/getuser")
  userData.value = res.data

  //權限可見功能
  if(userData.value.role === 'company'){
    rawMenu.value = [...menu]
  }else{
    const excludedFeature = ['廠區管理', '設備管理', '檢核表單', '派工表單']
    rawMenu.value = menu.filter(item => !excludedFeature.includes(item.title))
  }
}

onMounted(getuser)

</script>
