<script setup>
import SvgIcon from '@/components/SvgIcon.vue';
import { applyLayerSetting } from '@/components/viewer/utils/aps-viewer';

const store = useStore();
const { $getdata, $deleteapi } = useNuxtApp();
const layerSettings = ref([]);

async function fetchLayerSettings() {
  layerSettings.value = await $getdata("layersetting", { user: store.login.id });
}

async function deleteLayerSetting(id) {
  try {
    const result = await $deleteapi("layersetting", id);
    if (result && !result.error) {
      if (store.layersetting?.id === id) {
        store.commit('layersetting', undefined);
      }
      fetchLayerSettings();
    } else {
      throw new Error(result.error || "Xóa thiết lập layer không thành công.");
    }
  } catch (error) {
    console.error("Lỗi khi xóa thiết lập layer:", error);
    alert("Đã xảy ra lỗi khi xóa thiết lập layer. Vui lòng thử lại.");
  } 
}

onMounted(fetchLayerSettings);
</script>
<template>
  <ul v-if="layerSettings.length > 0">
    <li 
      v-for="layersetting in layerSettings"
      :key="layersetting.id"
      :class="[
        'border-bottom px-2 py-0 is-flex is-justify-content-space-between is-align-items-center is-clickable hoverable',
        store.layersetting?.id === layersetting.id && 'has-text-weight-bold has-background-white-ter'
      ]"
      @click="applyLayerSetting(layersetting, store)"
    >
      <span>{{ layersetting.name }}</span>
      <button class="delBtn" @click.stop="deleteLayerSetting(layersetting.id)">
        <SvgIcon v-bind="{ name: 'bin1.svg', type: 'primary', size: 18 }" />
      </button>
    </li>
  </ul>
  <p v-else>
    Bạn chưa tạo thiết lập layer nào.
  </p>
</template>
<style scoped>
.hoverable:hover {
  background-color: var(--bulma-primary-95);
}

.delBtn {
  border-radius: 4px;
  padding: 0.5rem;

  &:hover {
    background-color: hsla(0, 0%, 0%, 0.05);
  }
}
</style>