document.addEventListener("DOMContentLoaded", function (){
let canBeLoaded=true;
const loadMoreBtn=document.getElementById("load-more-posts");
const postContainer=document.getElementById("post-container");
const container=document.getElementById("list-container-v2");
if(!loadMoreBtn||!postContainer) return;
const templatePart=container?.dataset.templatePart||"";
loadMoreBtn.addEventListener("click", function (){
if(!canBeLoaded) return;
if(parseInt(infiniteScroll.current_page) > parseInt(infiniteScroll.max_page)){
loadMoreBtn.textContent="Tidak Ada Lagi";
loadMoreBtn.disabled=true;
return;
}
canBeLoaded=false;
loadMoreBtn.textContent="Loading...";
const data=new URLSearchParams();
data.append("action", "load_more_posts");
data.append("page", infiniteScroll.current_page);
data.append("category", infiniteScroll.category_id);
data.append("tag", infiniteScroll.tag_id);
data.append("author", infiniteScroll.author_id);
data.append("archive_type", infiniteScroll.archive_type);
data.append("taxonomy", infiniteScroll.taxonomy);
data.append("term_id", infiniteScroll.term_id);
data.append("term_slug", infiniteScroll.term_slug);
data.append("is_cv_maker", infiniteScroll.is_cv_maker);
data.append("current_post", infiniteScroll.current_post||0);
data.append("single_category", infiniteScroll.single_category||0);
data.append("single_lokasi", infiniteScroll.single_lokasi||0);
data.append("single_type", infiniteScroll.single_type||0);
if(templatePart!==""){
data.append("template_part", templatePart);
}
fetch(infiniteScroll.ajax_url, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: data.toString()
})
.then((response)=> response.text())
.then((response)=> {
const trimmed=response.trim();
if(trimmed==="<p>Tidak ada lagi.</p>"){
loadMoreBtn.textContent="Tidak Ada Lagi";
loadMoreBtn.disabled=true;
return;
}
postContainer.insertAdjacentHTML("beforeend", trimmed);
document.dispatchEvent(new Event("postsLoaded"));
infiniteScroll.current_page++;
canBeLoaded=true;
if(parseInt(infiniteScroll.current_page) > parseInt(infiniteScroll.max_page)){
loadMoreBtn.disabled=true;
loadMoreBtn.textContent="Tidak Ada Lagi";
}else{
loadMoreBtn.textContent="Lihat Lebih Banyak";
}})
.catch((error)=> {
console.error("AJAX Error:", error);
canBeLoaded=true;
loadMoreBtn.textContent="Lihat Lebih Banyak";
});
});
});