<script>
    import Header from "$lib/ui/header.svelte";

    export let data;

    let endOfArticle = false;


    let { blog } = data;
    let returnSize = blog.total_articles;
    let offset = blog.articles.length;

    function loadMore() {
    if (offset >= returnSize) {
        endOfArticle = true;
    } else {
        fetch(`/getPosts?offset=${offset}`)
            .then(response => response.json())
            .then(newArticles => {
                if (newArticles.length > 0) {
                    blog.articles = [...blog.articles, ...newArticles];
                    offset += newArticles.length;
                    if(offset >= returnSize) endOfArticle = true;
                } else {
                    endOfArticle = true;
                }
            })
            .catch(error => console.error('Error loading more articles:', error));
    }
    }
</script>

<div>
    <Header
        title={blog?.site.title}
        subtitle={blog?.site.subtitle}
    />
    <div class="bg-gray-100 py-20">
        <div class="section-wrapper">
            <h2 class="text-2xl mb-8 font-bold">Latest articles</h2>

            <div class="flex flex-col gap-5">
                {#each blog?.articles || [] as article}
                    <a href="/{article.seo_slug}">
                        <div
                            class="bg-white rounded-3xl px-8 py-8 flex flex-row sm:flex-col"
                        >
                            <div>
                                <span
                                    class="text-sm text-gray-400 font-normal mb-8"
                                    >{new Date(
                                        article.created_at,
                                    ).toLocaleDateString("en-de", {
                                        day: "2-digit",
                                        month: "long",
                                        year: "numeric",
                                    })}</span
                                >
                                <h3 class="text-2xl font-semibold">
                                    {article.title}
                                </h3>
                            </div>
                        </div>
                    </a>
                {/each}

                {#if !endOfArticle}
                    <button on:click={loadMore} class="px-8 py-3 bg-gray-200 hover:bg-gray-300 cursor-pointer duration-150 text-gray-900 rounded-lg font-semibold mt-6 mx-auto">Load more</button>
                {/if}
            </div>
        </div>
    </div>
</div>
