<script setup>
import { onMounted, watch } from "vue";
import useBuildingStore from "@/stores/useBuildingStore";
import { useRouter } from "vue-router";

const store = useBuildingStore();
const router = useRouter();
const selectBuilding = (bui) => {
  store.selectedBuilding = bui; // 改變 selectedBuilding，watch 會自動更新資料

  if (bui.is_headquarter == true) {
    router.replace({ path: "/headquarters" });
  } else {
    router.replace({ path: "/dashboard" });
  }
};

onMounted(() => {
  store.initialize(); // 初始化資料
});
</script>

<template>
  <template v-if="store.buildings.length > 1">
    <div class="dropdown dropdown-bottom">
      <div
        tabindex="0"
        role="button"
        class="text-white ml-8 text-lg font-semiLight"
      >
        {{ store.selectedBuilding?.full_name }}
        <font-awesome-icon :icon="['fas', 'angle-down']" class="ml-1" />
      </div>
      <ul
        tabindex="0"
        class="dropdown-content w-56 left-8 translate-y-2 z-[1] menu py-3 shadow rounded bg-[#4c625e] border text-center"
      >
        <li
          class="text-white my-1 text-base cursor-pointer flex flex-row justify-between items-center"
          v-for="bui in store.buildings"
          :key="bui.building_tag"
          @click="selectBuilding(bui)"
        >
          <span class="w-full flex justify-between"
            >{{ bui.full_name }}
            <font-awesome-icon
              v-if="bui.is_headquarter"
              :icon="['fas', 'synagogue']"
              class="text-xs"
            />
            <font-awesome-icon
              v-else
              :icon="['fas', 'warehouse']"
              class="text-xs"
            />
          </span>
        </li>
      </ul>
    </div>
  </template>
  <template v-else>
    <div class="text-white ml-8 text-lg font-semiLight">
      {{ store.selectedBuilding?.full_name }}
    </div>
  </template>
</template>
<style lang="scss" scoped></style>
