jQuery(function($){
	// Container FAQ
	var $container = $('#pixelio-cart-abandon-recovery-more-accordion');
	if (!$container.length) $container = $('.pixelio-cart-abandon-recovery-more-accordion');
	if (!$container.length) return console.warn('Container pixelio-cart-abandon-recovery-more-accordion introuvable.');

	// Texte localisé WP
	var texts = window.pixelioFaqData ? window.pixelioFaqData.texts || {} : {};
	var locale = (window.pixelioFaqData && pixelioFaqData.locale) ? pixelioFaqData.locale.split('_')[0] : 'en';
	var faqUrl = (window.pixelioFaqData ? pixelioFaqData.apiUrl : '') + 'faq?lang=' + encodeURIComponent(locale);
	var apiKey = window.pixelioFaqData ? pixelioFaqData.apiKey : '';

	function buildFaqItem(idx, item){
		var $q = $('<button/>', {
			class: 'pixelio-faq-question',
			type: 'button',
			'aria-expanded': 'false',
			text: item.title || texts.question || ('Question ' + (idx+1))
		});

		var $a = $('<div/>', {
			class: 'pixelio-faq-answer',
			html: item.description || ''
		}).hide();

		var $wrapper = $('<div/>', { class: 'pixelio-faq-item' })
			.append($q)
			.append($a)
			.removeClass('pixelio-cart-abandon-recovery-more-hide-it');

		$q.on('click', function(){
			var expanded = $(this).attr('aria-expanded') === 'true';
			$container.find('.pixelio-faq-question').attr('aria-expanded', 'false');
			$container.find('.pixelio-faq-answer').slideUp(150);

			if (!expanded) {
				$(this).attr('aria-expanded', 'true');
				$a.slideDown(150);
			}
		});

		return $wrapper;
	}

	var $loader = $('<div/>', { class: 'pixelio-faq-loader', text: texts.loading || pixelioFaqData.loadingFaq });
	$container.empty().append($loader);

	// Utilisation de jQuery.ajax pour WordPress
	$.ajax({
		url: faqUrl,
		method: 'GET',
		headers: { 'x-api-key': apiKey },
		dataType: 'json',
		success: function(data){
			$container.empty();
			if (!data || !data.success || !Array.isArray(data.faqs)) {
				$container.append($('<div/>', { class: 'pixelio-faq-empty', text: texts.noFaq || 'Aucune FAQ disponible.' }));
				return;
			}
			data.faqs.forEach(function(faqItem, i){
				var item = {
					title: faqItem.title || faqItem['title_'+locale] || '…',
					description: faqItem.description || faqItem['description_'+locale] || ''
				};
				var $el = buildFaqItem(i, item);
				$el.removeClass('pixelio-cart-abandon-recovery-more-hide-it');
				$container.append($el);
			});
		},
		error: function(xhr, status, err){
			console.error('Erreur FAQ:', err);
			$container.empty().append($('<div/>', { class: 'pixelio-faq-error', text: texts.errorFaq || pixelioFaqData.errorLoadingFaq }));
		}
	});

});
