// src/components/Header.vue
<template>
  <header
      v-if="appStore.headerData"
      :style="`background-image: url('${appStore.imageBaseUrl}${appStore.headerData.header_background.url}'); background-size: cover; background-position: center;`"
      class="relative z-10"
  >
    <nav class="navbar p-2 md:p-4 shadow-md" :style="{ backgroundColor: appStore.headerData.mainColor }">
      <div class="container mx-auto flex items-center justify-between w-full">

        <div class="navbar-start w-auto flex-shrink-0">
          <router-link to="/home" class="flex flex-col items-start leading-tight">
            <span class="text-white text-lg font-bold">{{ appStore.checkLang.isTh ? 'ฮิวแมนเทคไทยแลนด์' : 'HumanTech' }}</span>
            <span class="text-white text-xs opacity-80">{{ appStore.checkLang.isTh ? 'HumanTech' : 'ฮิวแมนเทคไทยแลนด์' }}</span>
          </router-link>
        </div>

        <div class="navbar-end hidden md:flex flex-1 items-center justify-end space-x-2 lg:space-x-4">
          <ul class="menu menu-horizontal px-1 flex-nowrap">
            <li v-for="menu in orderedMainMenus" :key="menu.id">
              <template v-if="menu.sub_menus && menu.sub_menus.length > 0">
                <details :open="activeMenuId === menu.id" @toggle="handleDetailsToggle(menu.id, $event)">
                  <summary class="text-white font-semibold text-base hover:bg-gray-700 hover:text-white">
                    {{ appStore.checkLang.isTh ? menu.main_menu : menu.main_menu_en }}
                  </summary>
                  <ul class="p-2 bg-base-100 rounded-box w-52 text-black">
                    <li v-for="subMenu in (appStore.checkLang.isTh ? orderedSubMenus(menu.sub_menus) : orderedSubMenusEng(menu.sub_menus))" :key="subMenu.id">
                      <router-link :to="subMenu.link" class="hover:bg-gray-200 hover:text-black">
                        {{ appStore.checkLang.isTh ? subMenu.title_th : subMenu.title_en }}
                      </router-link>
                    </li>
                  </ul>
                </details>
              </template>
              <template v-else>
                <router-link
                    :to="menu.link"
                    class="text-white font-semibold text-base hover:bg-gray-700 hover:text-white"
                    @click="activeMenuId = null" >
                  {{ appStore.checkLang.isTh ? menu.main_menu : menu.main_menu_en }}
                </router-link>
              </template>
            </li>
          </ul>

          <div class="dropdown dropdown-end">
            <div tabindex="0" role="button" class="btn btn-ghost normal-case text-base text-white hover:bg-gray-700 hover:text-white">
              {{ appStore.checkLang.isTh ? 'ภาษาไทย' : 'English' }}
            </div>
            <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-30 text-black">
              <li><a @click="switchLanguageToThai" class="hover:bg-gray-200 hover:text-black">ภาษาไทย</a></li>
              <li><a @click="switchLanguageToEnglish" class="hover:bg-gray-200 hover:text-black">English</a></li>
            </ul>
          </div>
        </div>

        <div class="navbar-end md:hidden">
          <div class="dropdown dropdown-end">
            <div tabindex="0" role="button" class="btn btn-ghost lg:hidden text-white hover:bg-gray-700 hover:text-white">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h8m-8 6h16" /></svg>
            </div>
            <ul tabindex="0" class="menu menu-sm dropdown-content mt-3 z-[1] p-2 shadow bg-base-100 rounded-box w-52 text-black">
              <li v-for="menu in orderedMainMenus" :key="menu.id">
                <template v-if="menu.sub_menus && menu.sub_menus.length > 0">
                  <details :open="activeMobileMenuId === menu.id" @toggle="handleMobileDetailsToggle(menu.id, $event)">
                    <summary class="hover:bg-gray-200 hover:text-black">{{ appStore.checkLang.isTh ? menu.main_menu : menu.main_menu_en }}</summary>
                    <ul class="p-2 bg-base-200">
                      <li v-for="subMenu in (appStore.checkLang.isTh ? orderedSubMenus(menu.sub_menus) : orderedSubMenusEng(menu.sub_menus))" :key="subMenu.id">
                        <router-link :to="subMenu.link" class="hover:bg-gray-200 hover:text-black">{{ appStore.checkLang.isTh ? subMenu.title_th : subMenu.title_en }}</router-link>
                      </li>
                    </ul>
                  </details>
                </template>
                <template v-else>
                  <router-link :to="menu.link" class="hover:bg-gray-200 hover:text-black">
                    {{ appStore.checkLang.isTh ? menu.main_menu : menu.main_menu_en }}
                  </router-link>
                </template>
              </li>
              <li>
                <details :open="activeMobileMenuId === 'language'" @toggle="handleMobileDetailsToggle('language', $event)">
                  <summary class="hover:bg-gray-200 hover:text-black">{{ appStore.checkLang.isTh ? 'ภาษา' : 'Language' }}</summary>
                  <ul class="p-2 bg-base-200">
                    <li><a @click="switchLanguageToThai" class="hover:bg-gray-200 hover:text-black">ภาษาไทย</a></li>
                    <li><a @click="switchLanguageToEnglish" class="hover:bg-gray-200 hover:text-black">English</a></li>
                  </ul>
                </details>
              </li>
            </ul>
          </div>
        </div>

      </div>
    </nav>

  </header>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAppStore } from '@/stores/app';
import { RouterLink } from 'vue-router';
import _ from 'lodash';

const appStore = useAppStore();

// --- State to manage open menus ---
const activeMenuId = ref(null); // For desktop dropdowns
const activeMobileMenuId = ref(null); // For mobile dropdowns

// --- Handlers for desktop details toggles ---
const handleDetailsToggle = (menuId, event) => {
  if (event.target.open) {
    // If this details is being opened, set it as the active one
    activeMenuId.value = menuId;
  } else if (activeMenuId.value === menuId) {
    // If this details is being closed, clear the active one
    activeMenuId.value = null;
  }
};

// --- Handlers for mobile details toggles ---
const handleMobileDetailsToggle = (menuId, event) => {
  if (event.target.open) {
    activeMobileMenuId.value = menuId;
  } else if (activeMobileMenuId.value === menuId) {
    activeMobileMenuId.value = null;
  }
};

// --- Existing logic for menu ordering and language switching ---
const orderedMainMenus = computed(() => {
  if (!appStore.allMainMenus) return [];
  const activeMenus = appStore.allMainMenus.filter(menu =>
      appStore.checkLang.isTh ? menu.active : menu.active_en
  );
  const homeMenu = activeMenus.find(menu => menu.id === 1);
  const otherMenus = activeMenus.filter(menu => menu.id !== 1);
  return homeMenu ? [homeMenu, ..._.orderBy(otherMenus, 'order')] : _.orderBy(activeMenus, 'order');
});

const orderedSubMenus = (subMenus) => {
  if (!subMenus) return [];
  const activeItems = subMenus.filter(f => f.active === true);
  return _.orderBy(activeItems, 'order');
};

const orderedSubMenusEng = (subMenus) => {
  if (!subMenus) return [];
  const activeItems = subMenus.filter(f => f.active_en === true);
  return _.orderBy(activeItems, 'order');
};

const switchLanguageToThai = () => {
  appStore.toggleLanguage();
  // Close mobile language dropdown after selection
  activeMobileMenuId.value = null;
};

const switchLanguageToEnglish = () => {
  appStore.toggleLanguage();
  // Close mobile language dropdown after selection
  activeMobileMenuId.value = null;
};

onMounted(() => {
  const savedLang = localStorage.getItem('lang');
  if (savedLang === 'en') {
    appStore.isTh = false;
  } else {
    appStore.isTh = true;
  }
});
</script>

<style scoped>
/* No specific styles needed, using Tailwind/DaisyUI as before */
</style>