(function () {
	var cfg = window.neurogenesisThemeRatingNotice || {};

	function postAction(ratingAction) {
		if (cfg.debug || !cfg.ajaxUrl || !cfg.nonce) {
			return Promise.resolve();
		}

		var body = new URLSearchParams();
		body.append('action', 'neurogenesis_theme_rating_notice');
		body.append('nonce', cfg.nonce);
		body.append('rating_action', ratingAction);

		return fetch(cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body: body.toString(),
		}).catch(function () {
			return null;
		});
	}

	function hideNotice(notice) {
		if (!notice) {
			return;
		}

		notice.classList.add('is-dismissed');
		notice.style.display = 'none';
	}

	function dismissPermanent(notice, serverAction) {
		postAction(serverAction || 'dismiss').finally(function () {
			hideNotice(notice);
		});
	}

	function remindLater(notice) {
		postAction('remind').finally(function () {
			hideNotice(notice);
		});
	}

	function snoozeWithoutRating(notice) {
		postAction('snooze').finally(function () {
			hideNotice(notice);
		});
	}

	function showPanel(notice, state) {
		var panels = notice.querySelectorAll('[data-rating-state]');

		Array.prototype.forEach.call(panels, function (panel) {
			panel.hidden = panel.getAttribute('data-rating-state') !== state;
		});
	}

	function setStarHighlight(starsWrap, value) {
		var stars = starsWrap.querySelectorAll('[data-rating-star]');

		Array.prototype.forEach.call(stars, function (star) {
			var starValue = parseInt(star.getAttribute('data-rating-star'), 10);
			star.classList.toggle('is-active', starValue <= value);
		});
	}

	function bindStars(notice) {
		var starsWrap = notice.querySelector('.neurogenesis-theme-rating-notice__stars');

		if (!starsWrap) {
			return;
		}

		var stars = starsWrap.querySelectorAll('[data-rating-star]');

		Array.prototype.forEach.call(stars, function (star) {
			star.addEventListener('mouseenter', function () {
				starsWrap.classList.add('is-hovering');
				setStarHighlight(starsWrap, parseInt(star.getAttribute('data-rating-star'), 10));
			});

			star.addEventListener('focus', function () {
				starsWrap.classList.add('is-hovering');
				setStarHighlight(starsWrap, parseInt(star.getAttribute('data-rating-star'), 10));
			});

			star.addEventListener('click', function () {
				var rating = parseInt(star.getAttribute('data-rating-star'), 10);
				starsWrap.classList.add('is-rated');
				setStarHighlight(starsWrap, rating);
				handleRating(notice, rating);
			});
		});

		starsWrap.addEventListener('mouseleave', function () {
			if (starsWrap.classList.contains('is-rated')) {
				return;
			}

			starsWrap.classList.remove('is-hovering');
			setStarHighlight(starsWrap, 0);
		});
	}

	function handleRating(notice, rating) {
		if (rating >= 4) {
			var headline = notice.querySelector('[data-rating-high-headline]');
			var i18n = cfg.i18n || {};
			var reviewUrl = cfg.reviewUrl || '';

			if (headline && i18n.highRatingHeadline) {
				headline.innerHTML = i18n.highRatingHeadline.replace('%d', String(rating));
			}

			if (reviewUrl) {
				window.open(reviewUrl, '_blank', 'noopener,noreferrer');
			}

			postAction('rated_high');
			showPanel(notice, 'thanks-high');
			return;
		}

		postAction('rated_low');
		showPanel(notice, 'thanks-low');
	}

	function dismissForActiveState(notice) {
		var activePanel = notice.querySelector('[data-rating-state]:not([hidden])');
		var state = activePanel ? activePanel.getAttribute('data-rating-state') : 'issues';

		if (state === 'thanks-low' || state === 'thanks-high') {
			dismissPermanent(notice, 'dismiss');
			return;
		}

		if (state === 'rate') {
			remindLater(notice);
			return;
		}

		snoozeWithoutRating(notice);
	}

	function bindActions(notice) {
		notice.addEventListener('click', function (event) {
			var dismiss = event.target.closest('.notice-dismiss');

			if (dismiss && notice.contains(dismiss)) {
				dismissForActiveState(notice);
				return;
			}

			var action = event.target.closest('[data-rating-action]');

			if (!action) {
				return;
			}

			var actionName = action.getAttribute('data-rating-action');

			if (actionName === 'no-issues') {
				event.preventDefault();
				showPanel(notice, 'rate');
				return;
			}

			if (actionName === 'remind') {
				event.preventDefault();
				remindLater(notice);
				return;
			}

			if (actionName === 'already-reviewed' || actionName === 'not-for-me') {
				event.preventDefault();
				dismissPermanent(notice, actionName === 'not-for-me' ? 'not_for_me' : 'already_reviewed');
				return;
			}

			if (actionName === 'need-help') {
				dismissPermanent(notice, 'need_help');
				return;
			}

			if (actionName === 'dismiss-permanent') {
				event.preventDefault();
				var activePanel = notice.querySelector('[data-rating-state]:not([hidden])');
				var state = activePanel ? activePanel.getAttribute('data-rating-state') : '';
				var serverAction = state === 'thanks-high' ? 'rated_high' : 'rated_low';
				dismissPermanent(notice, serverAction);
			}
		});
	}

	function init() {
		var notice = document.querySelector('[data-neurogenesis-theme-rating]');

		if (!notice) {
			return;
		}

		bindStars(notice);
		bindActions(notice);
	}

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