<script setup lang="ts">
import AllProjects from "./AllProjects.vue";
import ProjectsFilter from "./ProjectsFilter.vue";
import { useCategorysQuery } from "~/queries/projects";

const { t } = useI18n();
const router = useRouter();
const { data: queryResult, isLoading, isPending, error } = useCategorysQuery(1);

// Only get services when query has data
const services = computed(() => queryResult.value?.data?.services || []);

// Check if services are ready (query is not loading and has services data)
const servicesReady = computed(() => {
  return (
    !isLoading.value && !isPending.value && queryResult.value?.data?.services
  );
});

// Only initialize tabs data when services are ready
const tapsData = computed(() => {
  if (!servicesReady.value) {
    return [];
  }

  return [
    {
      value: "all-projects",
      title: t("projectsButtons.allProjectTap"),
      component: AllProjects,
    },
    ...services.value.map((service) => ({
      value: service.key,
      title: service.title,
      component: ProjectsFilter,
      props: {
        serviceId: service.id,
      },
    })),
  ];
});

const handleTabChange = (newValue: string) => {
  if (newValue) {
    router.replace({ query: {} });
  }
};
</script>
<template>
  <GlobalLoader v-if="isPending" />
  <div>
    <!-- Show tabs only when services are ready -->
    <HorizontalTabsWithContent
      v-if="servicesReady && tapsData.length > 0"
      :tabs-data="tapsData"
      :centered-content="false"
      @update:modelValue="handleTabChange"
    />

    <!-- Show error state if query failed -->
    <div v-else-if="error" class="py-8 text-center text-red-500">
      {{ $t("errors.failedToLoadServices") }}
    </div>
  </div>
</template>

<style scoped></style>
