/**
 * 360° View widget — drag-to-rotate frame sequence.
 *
 * Fully data-attribute driven: frames, auto-rotate flag, and rotate speed
 * come from the .trx-ad-view-360 container, so no per-instance inline
 * script is needed.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	/**
	 * Initialize a single 360 viewer instance.
	 *
	 * @param {HTMLElement} node The .trx-ad-view-360 wrapper.
	 */
	function initViewer(node) {
		if (node.dataset.inited) {
			return;
		}
		node.dataset.inited = '1';

		var frames = [];
		try {
			frames = JSON.parse(node.dataset.frames || '[]');
		} catch (e) {
			frames = [];
		}
		if (frames.length < 4) {
			return;
		}

		var img = node.querySelector('.trx-ad-view-360__frame');
		if (!img) {
			return;
		}

		var idx = 0;
		var dragging = false;
		var lastX = 0;
		var sensitivity = 8;

		function setFrame(i) {
			idx = ((i % frames.length) + frames.length) % frames.length;
			img.src = frames[idx];
		}

		node.addEventListener('mousedown', function (e) { dragging = true; lastX = e.clientX; img.style.cursor = 'grabbing'; });
		window.addEventListener('mouseup', function () { dragging = false; img.style.cursor = 'grab'; });
		window.addEventListener('mousemove', function (e) {
			if (!dragging) return;
			var dx = e.clientX - lastX;
			if (Math.abs(dx) >= sensitivity) {
				setFrame(idx + (dx > 0 ? 1 : -1));
				lastX = e.clientX;
			}
		});
		node.addEventListener('touchstart', function (e) { dragging = true; lastX = e.touches[0].clientX; }, { passive: true });
		node.addEventListener('touchend', function () { dragging = false; });
		node.addEventListener('touchmove', function (e) {
			if (!dragging) return;
			var dx = e.touches[0].clientX - lastX;
			if (Math.abs(dx) >= sensitivity) {
				setFrame(idx + (dx > 0 ? 1 : -1));
				lastX = e.touches[0].clientX;
			}
		}, { passive: true });

		if (node.dataset.autoRotate === '1') {
			setInterval(function () { setFrame(idx + 1); }, parseInt(node.dataset.rotateSpeed, 10) || 80);
		}
	}

	/**
	 * Initialize all 360 viewers on the page.
	 */
	function initAll() {
		document.querySelectorAll('.trx-ad-view-360:not([data-inited])').forEach(initViewer);
	}

	// 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_view_360.default',
					function ($scope) {
						var el = $scope[0].querySelector('.trx-ad-view-360');
						if (el) {
							delete el.dataset.inited;
							initViewer(el);
						}
					}
				);
			}
		});
	}
})();
