/**
 * Featured Carousel (Elementor widget + Gutenberg block) — Swiper initialization.
 *
 * Reads the Swiper config from the container's `data-swiper-config` attribute;
 * navigation/pagination are wired from child elements when present, so the
 * PHP side never has to emit per-instance selectors.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	/**
	 * Initialize a single carousel instance.
	 *
	 * @param {HTMLElement} el The .trx-ad-featured-carousel wrapper.
	 */
	function initCarousel(el) {
		if (typeof Swiper === 'undefined' || el.dataset.trxAdInit) {
			return;
		}
		el.dataset.trxAdInit = '1';

		var config = {};
		try {
			config = JSON.parse(el.dataset.swiperConfig || '{}');
		} catch (e) {
			config = {};
		}

		var next = el.querySelector('.swiper-button-next');
		var prev = el.querySelector('.swiper-button-prev');
		if (next && prev) {
			config.navigation = { nextEl: next, prevEl: prev };
		}

		var pagination = el.querySelector('.swiper-pagination');
		if (pagination) {
			config.pagination = { el: pagination, clickable: true };
		}

		new Swiper(el, config);
	}

	/**
	 * Initialize all featured carousels on the page.
	 */
	function initAll() {
		document.querySelectorAll('.trx-ad-featured-carousel:not([data-trx-ad-init])').forEach(initCarousel);
	}

	// DOM ready.
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', initAll);
	} else {
		initAll();
	}

	// Elementor editor support.
	if (typeof jQuery !== 'undefined') {
		jQuery(window).on('elementor/frontend/init', function () {
			if (typeof elementorFrontend !== 'undefined') {
				elementorFrontend.hooks.addAction(
					'frontend/element_ready/trx_ad_featured_carousel.default',
					function ($scope) {
						var el = $scope[0].querySelector('.trx-ad-featured-carousel');
						if (el) {
							delete el.dataset.trxAdInit;
							initCarousel(el);
						}
					}
				);
			}
		});
	}
})();
