<script setup lang="ts">
import { useInfiniteScroll } from "@vueuse/core";
import { useCategorysQuery } from "~/queries/projects";
import { useRoute, useRouter } from "vue-router";
import type { Project, ProjectsResponse } from "~/types/projects";

const route = useRoute();
const router = useRouter();
const initialPage = Number(route.query.page) || 1;
const scrollTarget = ref<HTMLElement | null>(null);
const allProjects = ref<Project[]>([]);
const currentPage = ref(initialPage);
const isLoadingMore = ref(false);
const hasMorePages = ref(true);
const hasInitiallyLoaded = ref(false);
const fetchedPages = useFetchedPagesState();

const { locale, t } = useI18n();
const baseUrl = "https://webstdy.com";


const {
  data: initialData,
  isLoading,
  isPending,
  refetch,
} = useCategorysQuery(initialPage);

// SSR-safe fetch for direct navigation
if (import.meta.server && initialPage > 1) {
  await refetch();
}

watch(
  initialData,
  (newData) => {
    if (newData?.data?.projects) {
      const { data: projects, last_page, current_page } = newData.data.projects;
      allProjects.value = projects;
      currentPage.value = current_page;
      hasMorePages.value = current_page < last_page;
      hasInitiallyLoaded.value = true;
    }
  },
  { immediate: true },
);

// Infinite scroll loader
const loadMore = async () => {
  if (isLoadingMore.value || !hasMorePages.value) return;
  const nextPage = currentPage.value + 1;
  if (fetchedPages.value.has(nextPage)) return;
  fetchedPages.value.add(nextPage);
  isLoadingMore.value = true;

  try {
    const { get } = useApi();
    const response = await get<ProjectsResponse>(`projects`, {
      params: { page: nextPage },
    });

    const projectsData = response.data?.data.projects;
    if (projectsData?.data?.length) {
      allProjects.value.push(...projectsData.data);
      currentPage.value = projectsData.current_page;
      hasMorePages.value = projectsData.current_page < projectsData.last_page;

      // Update the URL silently (no reload)
      if (import.meta.client) {
        window.history.replaceState(null, "", `?page=${currentPage.value}`);
      }
    } else {
      hasMorePages.value = false;
    }
  } catch (err) {
    console.error("Error loading more projects:", err);
    hasMorePages.value = false;
  } finally {
    isLoadingMore.value = false;
  }
};

// Infinite scroll setup
if (import.meta.client) {
  useInfiniteScroll(scrollTarget, loadMore, {
    distance: 300,
    canLoadMore: () => hasMorePages.value && !isLoadingMore.value,
  });
}


const seoTitle = computed(() => {
  return currentPage.value > 1
    ? `${t("projectsSeo.title")} ${t("projectsSeo.page")} ${currentPage.value}`
    : t("projectsSeo.title");
});

const seoDescription = computed(() => {
  return currentPage.value > 1
    ? `${t("projectsSeo.description")} ${t("projectsSeo.page")} ${currentPage.value}`
    : t("projectsSeo.description");
});




// Add only page-specific SEO tags (no alternates/og)
useHead(() => {
  const pageParam = currentPage.value > 1 ? `?page=${currentPage.value}` : "";
  const canonicalHref = `${baseUrl}${
    locale.value === "en" ? "/en" : ""
  }/our-projects${pageParam}`;

  const linkTags: any[] = [{ rel: "canonical", href: canonicalHref }];

  if (currentPage.value > 1) {
    linkTags.push({
      rel: "prev",
      href:
        currentPage.value === 2
          ? `${baseUrl}${locale.value === "en" ? "/en" : ""}/our-projects`
          : `${baseUrl}${locale.value === "en" ? "/en" : ""}/our-projects?page=${
              currentPage.value - 1
            }`,
    });
  }

  if (hasMorePages.value) {
    linkTags.push({
      rel: "next",
      href: `${baseUrl}${
        locale.value === "en" ? "/en" : ""
      }/our-projects?page=${currentPage.value + 1}`,
    });
  }

  return {
    title: seoTitle.value,
    meta: [
      { name: "description", content: seoDescription.value },
      { property: "og:title", content: seoTitle.value },
      { property: "og:description", content: seoDescription.value },
      { property: "og:url", content: canonicalHref },
    ],
    link: linkTags,
  };
});


onUnmounted(() => {
  fetchedPages.value.clear();
});
</script>


<template>
  <!-- Empty state when no projects and not loading -->
  <section
    v-if="hasInitiallyLoaded && !isLoading && !allProjects.length"
    class="py-narrow-section"
  >
    <div class="container mx-auto px-4">
      <EmptyState class="mx-auto" />
    </div>
  </section>

  <section v-else-if="allProjects.length || isLoading" id="allProjects">
    <!-- Loading state for initial load -->
    <div v-if="isLoading || isPending" class="py-narrow-section">
      <div class="container mx-auto px-4">
        <div class="flex flex-col items-center gap-[30px]">
          <Skeleton class="mx-auto h-8 w-1/3 rounded" />
          <Skeleton
            class="h-[350px] w-full rounded-xl sm:h-[572px] xl:w-[950px]"
          />
          <div class="flex w-full flex-col gap-4 px-8 xl:w-[950px]">
            <Skeleton class="mx-auto h-4 w-3/4 rounded" />
            <Skeleton class="mx-auto h-4 w-1/2 rounded" />
          </div>
          <Skeleton class="mx-auto h-10 w-28 rounded-md" />
        </div>
      </div>
    </div>

    <!-- Projects list -->
    <div v-for="(project, index) in allProjects" :key="project.id">
      <ProjectsProjectSection
        :project-info="project"
        :section-bg="index % 2 === 0 ? 'bg-gradient-odd' : 'bg-gradient-even'"
      />
    </div>

    <div
      v-if="isLoadingMore"
      class="py-section"
      :class="
        allProjects.length % 2 === 0 ? 'bg-gradient-odd' : 'bg-gradient-even'
      "
    >
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-center pb-4">
          <div class="max-w-60">
            <ClientOnly>
              <Lottie name="loading" />
            </ClientOnly>
          </div>
        </div>
        <div class="flex flex-col items-center gap-[30px]">
          <Skeleton class="mx-auto h-8 w-1/3 rounded" />
          <Skeleton
            class="h-[350px] w-full rounded-xl sm:h-[572px] xl:w-[950px]"
          />
          <div class="flex w-full flex-col gap-4 px-8 xl:w-[950px]">
            <Skeleton class="mx-auto h-4 w-3/4 rounded" />
            <Skeleton class="mx-auto h-4 w-1/2 rounded" />
          </div>
          <Skeleton class="mx-auto h-10 w-28 rounded-md" />
        </div>
      </div>
    </div>

    <section
      ref="scrollTarget"
      class="py-section px-4"
      :class="
        allProjects.length % 2 === 0 ? 'bg-gradient-odd' : 'bg-gradient-even'
      "
    >
      <nav class="pagination invisible flex justify-center gap-4">
        <NuxtLinkLocale v-if="currentPage == 2" :to="`/our-projects`">
          Previous
        </NuxtLinkLocale>
        <NuxtLinkLocale
          v-else-if="currentPage > 2"
          :to="`/our-projects?page=${currentPage - 1}`"
        >
          Previous
        </NuxtLinkLocale>
        <NuxtLinkLocale
          v-if="hasMorePages"
          :to="`/our-projects?page=${currentPage + 1}`"
        >
          Next
        </NuxtLinkLocale>
      </nav>
      <SubscribeSection />
    </section>
  </section>
</template>
<style scoped></style>
