document.addEventListener("DOMContentLoaded", function () {
	const block = document.querySelector(
		".wp-block-carhop-blocks-dbmob-archives",
	);
	if (!block) return;

	const toolbar = block.querySelector(".notices-toolbar");
	if (!toolbar) return;

	const searchInput = toolbar.querySelector("input[name='search']");
	const sortBySelect = toolbar.querySelector("select[name='sort_by']");
	const loadMoreButton = block.querySelector(".load-more-button");

	// Évite les courses: annule les requêtes précédentes et ignore les réponses obsolètes
	let currentAbortController = null;
	let lastRequestId = 0;

	function updatePostCount(count) {
		const el = block.querySelector(".post-count__count");
		if (el != null && count != null) {
			el.textContent = String(count);
		}
	}

	// Debounce simple pour la recherche
	function debounce(fn, waitMs) {
		let timeoutId;
		return (...args) => {
			if (timeoutId) window.clearTimeout(timeoutId);
			timeoutId = window.setTimeout(() => fn(...args), waitMs);
		};
	}

	async function hydratePosts() {
		const searchValue = searchInput?.value ?? "";
		const offset = 0;
		const postsPerPage = -1;
		const sortBy = sortBySelect?.value ?? "date_desc";

		const params = new URLSearchParams({
			sort_by: sortBy,
			recherche: searchValue,
			post_type: "dbmob",
			offset: String(offset),
			posts_per_page: String(postsPerPage),
		});

		const url = `/wp-json/carhop-datas/v1/build/posts?${params.toString()}`;

		if (currentAbortController) currentAbortController.abort();
		currentAbortController = new AbortController();
		const requestId = ++lastRequestId;

		try {
			const response = await fetch(url, {
				signal: currentAbortController.signal,
			});
			if (!response.ok) throw new Error(`HTTP ${response.status}`);
			const data = await response.json();

			if (requestId !== lastRequestId) return;

			const articlesContainer = block.querySelector(".dbmob-grid");
			if (!articlesContainer) return;
			articlesContainer.innerHTML = data.html_template;

			updatePostCount(data.post_count);
		} catch (error) {
			if (error?.name === "AbortError") return;
			console.error("Erreur lors de la récupération des articles:", error);
		}
	}

	const hydratePostsDebounced = debounce(hydratePosts, 150);

	if (sortBySelect) {
		sortBySelect.addEventListener("change", (value) => {
			const sortByValue = value.target.value;
			hydratePosts(sortByValue);
		});
	}
	if (searchInput) {
		searchInput.addEventListener("input", () => {
			hydratePostsDebounced();
		});
	}
	if (loadMoreButton) {
		loadMoreButton.addEventListener("click", () => {
			const offset = loadMoreButton.dataset.offset;
			const postsPerPage = loadMoreButton.dataset.postsPerPage;
			hydratePosts(postsPerPage);
		});
	}
});
