<script setup>
import useUserInfoStore from "@/stores/useUserInfoStore";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
const store = useUserInfoStore();

const user = ref("");
const open = ref(false);

function logout() {
  open.value = false;
  router.push("/logout");
}

function toggleOpen() {
  open.value = !open.value;
}

function close() {
  open.value = false;
}

// —— 點外面關閉 —— //
function onClickOutside(e) {
  // 只要點擊目標不在本元件根節點內，就關閉
  // 這裡用 closest('.dropdown') 判斷是否點在 dropdown 區塊內
  const target = e.target;
  if (!target.closest(".dropdown")) {
    close();
  }
}

// —— 鍵盤支援（Esc 關閉）—— //
function onKeydown(e) {
  if (e.key === "Escape") close();
}

onMounted(() => {
  const name = store.user?.user_name;
  if (name) user.value = name;

  document.addEventListener("click", onClickOutside, true);
  document.addEventListener("keydown", onKeydown);

  // 路由切換時關閉
  router.afterEach(() => close());
});

onBeforeUnmount(() => {
  document.removeEventListener("click", onClickOutside, true);
  document.removeEventListener("keydown", onKeydown);
});
</script>

<template>
  <!-- 用 open 狀態加上 dropdown-open，避免 focus 失效問題 -->
  <div class="dropdown dropdown-bottom dropdown-end" :class="{ 'dropdown-open': open }">
    <button
      type="button"
      class="flex flex-col justify-center items-center btn-group text-white text-center"
      aria-haspopup="menu"
      :aria-expanded="open ? 'true' : 'false'"
      @click="toggleOpen"
    >
      <font-awesome-icon :icon="['fas', 'user-circle']" class="text-lg lg:text-2xl mb-1" />
      <span class="text-xs lg:text-sm block">{{ user || "webUser" }}</span>
    </button>

    <ul
      class="dropdown-content translate-y-2 z-[100] menu py-3 shadow rounded w-32 bg-[#4c625e] border text-center"
      role="menu"
    >
      <li class="text-white" role="none">
        <button
          type="button"
          class="flex flex-col justify-center items-center"
          role="menuitem"
          @click="logout"
        >
          {{ $t('sign_out') }}
        </button>
      </li>
    </ul>
  </div>
</template>

