import { useRef, useEffect, useState } from "react";

export const RenderPostsFolioBlock = (props) => {
	const { _props, tag, data } = props;
	const { className, attributes } = _props;
	const { id, atts } = data;
	
	const [cachedResponses, setCachedResponses] = useState([]);
	const [postHTML, setPostHTML] = useState([]);

	useEffect(() => {
		const post = {};
		
		post["pagelayer_nonce"] = pagelayer_ajax_nonce;
		if (atts["type"]) post["post_type"] = atts["type"];
		if (atts["filter_by"]) post["filter_by"] = atts["filter_by"];
		if (atts["count"]) post["posts_per_page"] = atts["count"];

		const stringifiedPost = JSON.stringify(post);

		// Check if the response is already cached
		const cachedResponse = cachedResponses.find(
			(cached) => JSON.stringify(cached.post) === stringifiedPost
		);
		
		if (cachedResponse) {
			setPostHTML(cachedResponse.data);
		} else {
			// If not cached, make the AJAX call
			jQuery.ajax({
				url: pagelayer_ajax_url + "action=pagelayer_fetch_posts",
				type: "post",
				data: post,
				success: function (data) {
					setPostHTML(data);
					
					// Cache the response for future use
					setCachedResponses((prevResponses) => [
						...prevResponses,
						{ post: post, data: data },
					]);
				},
			});
		}
	}, [attributes["type"], attributes["filter_by"], attributes["count"]]);

	useEffect(() => {
		pagelayer_post_folio(pagelayer_query(`.p-${id}`));
	}, [attributes["type"], attributes["filter_by"], attributes["count"], postHTML]);

	return (
		<div className="pagelayer-postfolio-section" dangerouslySetInnerHTML={{__html: postHTML}} />
	);
};

