/**
 * Kramar Enhanced Reviews frontend script.
 *
 * Handles:
 *  - Helpful vote AJAX (Ja / Nee buttons)
 *  - Sort select: reloads the page with ?review_sort=<value>
 *
 * No jQuery. No inline scripts. All config via wp_localize_script (kramarEnhancedReviews).
 */
(function () {
	'use strict';

	var cfg = window.kramarEnhancedReviews || {};

	// -----------------------------------------------------------------
	// Helpful voting
	// -----------------------------------------------------------------

	function initVoting() {
		if (!cfg.votingEnabled) {
			return;
		}

		document.addEventListener('click', function (e) {
			var btn = e.target.closest('.kramar-helpful__btn');
			if (!btn) {
				return;
			}

			// Already voted — bail silently.
			if (btn.classList.contains('kramar-helpful__btn--voted')) {
				return;
			}

			var wrap      = btn.closest('.kramar-helpful');
			var commentId = wrap ? wrap.getAttribute('data-id') : null;
			var direction = btn.getAttribute('data-vote');

			if (!commentId || !direction) {
				return;
			}

			// Disable all buttons in this widget immediately.
			var btns = wrap.querySelectorAll('.kramar-helpful__btn');
			btns.forEach(function (b) {
				b.classList.add('kramar-helpful__btn--voted');
				b.disabled = true;
			});

			var body = new URLSearchParams();
			body.append('action', 'kramar_review_vote');
			body.append('nonce', cfg.nonce || '');
			body.append('comment_id', commentId);
			body.append('direction', direction);

			fetch(cfg.ajaxUrl || '', {
				method: 'POST',
				headers: { 'X-Requested-With': 'XMLHttpRequest' },
				body: body
			})
				.then(function (r) { return r.json(); })
				.then(function (d) {
					if (!d || !d.success) {
						// Already voted or error — show count as-is, leave disabled.
						return;
					}

					var up    = parseInt(d.data && d.data.up ? d.data.up : 0, 10);
					var down  = parseInt(d.data && d.data.down ? d.data.down : 0, 10);
					var total = up + down;
					var countEl = wrap.querySelector('.kramar-helpful__count');

					if (countEl && total > 0) {
						var pct = Math.round((up / total) * 100);
						// Replace ordered placeholders %1$d%% and %2$d from the PHP i18n string.
						var tpl = (cfg.i18nHelpful || '%1$d%% van %2$d bezoekers vond dit nuttig')
							.replace('%1$d%%', pct + '%')
							.replace('%2$d', total);
						countEl.textContent = tpl;
					}
				})
				.catch(function () {
					// Network error — leave buttons disabled.
				});
		});
	}

	// -----------------------------------------------------------------
	// Sort select
	// -----------------------------------------------------------------

	function initSort() {
		if (!cfg.sortEnabled) {
			return;
		}

		var select = document.getElementById('kramar-review-sort-select');
		if (!select) {
			return;
		}

		select.addEventListener('change', function () {
			var value = select.value;
			var url   = new URL(window.location.href);
			url.searchParams.set('review_sort', value);
			// Scroll to reviews section on reload.
			url.hash = '#reviews';
			window.location.href = url.toString();
		});
	}

	// -----------------------------------------------------------------
	// Init
	// -----------------------------------------------------------------

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function () {
			initVoting();
			initSort();
		});
	} else {
		initVoting();
		initSort();
	}
})();
