import { __ } from '@wordpress/i18n';
import { useState, useMemo, useEffect } from '@wordpress/element';

export const RenderSitemapItem = (props) => {
	const { _props, pl_props, data } = props;
	const { attributes } = _props;
	const { atts } = data;
	const [allData, setAllData] = useState({});
	const [memoizationCache, setMemoizationCache] = useState({});

	useEffect(() => {

		const ajaxUrl = `${pagelayer_ajax_url}&action=${atts.sitemap_type == 'post_type' ? 'pagelayer_get_pages_list' : 'pagelayer_get_taxonomy_list'}`;
		
		// Skip for title attribute
		const cacheKey = JSON.stringify({
			...attributes,
			title: ''
		});
		
		if(memoizationCache[cacheKey]) {
			setAllData(memoizationCache[cacheKey]);
			return;
		}
		
		var data_type = "",
			post_order = "",
			order = "",
			hier = "",
			depth = "",
			empty = "";

		if (atts['sitemap_type'] == 'post_type') {
			data_type = atts['source_post'];
			post_order = atts['order_post'];
			order = atts['order'];
			hier = atts['hierarchical'];
			depth = atts['depth'];
		} else {
			data_type = atts['source_taxonomy'];
			post_order = atts['order_taxonomy'];
			order = atts['order'];
			hier = atts['hierarchical'];
			depth = atts['depth'];
			empty = atts['hide_empty'];
		}
		
		jQuery.ajax({
			type: 'POST',
			url: ajaxUrl,
			data: {
				type: data_type,
				post_order: post_order,
				order: order,
				hier: hier,
				depth: depth,
				empty: empty,
				pagelayer_nonce: pagelayer_ajax_nonce,
			},
			success: function (ajaxResponse) {
				setAllData(ajaxResponse);
				var newMemoizationCache = { ...memoizationCache };
				
				newMemoizationCache[cacheKey] = ajaxResponse;
				setMemoizationCache(newMemoizationCache);
			},
			error: function (error) {
				console.error("Error fetching data:-->", error);
			},
		});

		jQuery('.pagelayer-sitemap-div-holder[data-nofollow] .pagelayer-sitemap-list-item a').attr('rel', 'nofollow');
		
	}, [attributes]);

	return (
		<div className="pagelayer-sitemap-section">
			{allData.length > 0 && (
				<>
					<span>
					{ attributes['title'] ? (
						attributes.title
					) : (
						attributes.sitemap_type === 'post_type' ? __('Pages') : __('Categories')
					)}
					</span>
					<div dangerouslySetInnerHTML={{ __html: allData }} />
				</>
			)}
		</div >
	);
};
