<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { fetchNodeArticle, fetchNodeArticleInRange } from "../utils/fetch_data";

type Article = {
    title?: string;
    body?: {
        value?: string;
    };
};

const itemsPerPage = 3;
const currentPage = ref(1);
const totalItems = ref(0);
const articles = ref<Article[]>([]);
const isLoading = ref(false);
const errorMessage = ref("");

const totalPages = computed(() => Math.max(1, Math.ceil(totalItems.value / itemsPerPage)));

const normalizeArticles = (data: unknown): Article[] => {
    const list = Array.isArray(data) ? data : (data != null ? [data] : []);

    for (const item of list) {
        if (item?.body && typeof item.body.value === "string") {
            const parser = new DOMParser();
            const doc = parser.parseFromString(item.body.value, "text/html");
            let textContent = doc.body.textContent || "";
            if (textContent.length > 200) {
                textContent = `${textContent.slice(0, 200)}…`;
            }
            item.body.value = textContent;
        }
    }

    return list as Article[];
};

const loadTotalItems = async () => {
    const data = await fetchNodeArticle();
    totalItems.value = normalizeArticles(data).length;
};

const loadPage = async (page: number) => {
    isLoading.value = true;
    errorMessage.value = "";

    try {
        const from = ((page - 1) * itemsPerPage) + 1;
        const to = Math.min(page * itemsPerPage, totalItems.value || page * itemsPerPage);
        const data = await fetchNodeArticleInRange(from, to);
        articles.value = normalizeArticles(data);
    } catch (error) {
        console.error("[article-paginated] Failed to fetch paginated articles", error);
        articles.value = [];
        errorMessage.value = "Unable to load articles right now.";
    } finally {
        isLoading.value = false;
    }
};

onMounted(async () => {
    try {
        await loadTotalItems();
        await loadPage(currentPage.value);
    } catch (error) {
        console.error("[article-paginated] Failed to initialize pagination", error);
        articles.value = [];
        errorMessage.value = "Unable to initialize article pagination.";
    }
});

watch(currentPage, async (page) => {
    await loadPage(page);
});
</script>

<template>
    <div class="space-y-5">
        <UPageCard
            v-if="errorMessage"
            title="Something went wrong"
            :description="errorMessage"
            icon="i-lucide-circle-alert"
            :ui="{ root: 'w-full' }"
        />

        <UPageCard
            v-else-if="!isLoading && articles.length === 0"
            title="No Content found"
            description="Pending to load content from Drupal API"
            icon="i-lucide-lightbulb"
            spotlight
            spotlight-color="primary"
            :ui="{ root: 'w-full' }"
        />

        <template v-else>
            <UPageCard
                v-for="(article, index) in articles"
                :key="`${currentPage}-${index}`"
                :title="article.title || 'Untitled article'"
                icon="i-lucide-lightbulb"
                spotlight
                spotlight-color="primary"
                :ui="{ root: 'w-full' }"
            >
                <template v-if="article.body?.value">
                    <p>{{ article.body.value }}</p>
                </template>
            </UPageCard>

            <div class="flex justify-center pt-2">
                <UPagination
                    v-model:page="currentPage"
                    :items-per-page="itemsPerPage"
                    :total="totalItems"
                    :show-edges="true"
                />
            </div>
        </template>
    </div>
</template>
