/**
 * Waitlytics — Frontend JavaScript
 *
 * Handles subscription form AJAX and variable product
 * variation detection.
 *
 * @package Waitlytics
 */
(function($) {
	'use strict';

	var WTLY_Public = {

		init: function() {
			this.bindEvents();
			this.handleVariations();
		},

		bindEvents: function() {
			$(document).on('click', '.wtly-notify-button', this.handleSubscribe);
		},

		/**
		 * Handle WooCommerce variable product variation changes.
		 */
		handleVariations: function() {
			// When a variation is selected. Wrappers flagged with
			// data-wtly-overlay opt out of variation show/hide handling.
			$(document).on('found_variation', '.variations_form', function(e, variation) {
				var $wrapper = $(this).closest('.product, .single-product').find('.wtly-notify-form-wrapper').not('[data-wtly-overlay]');

				if (!$wrapper.length) {
					$wrapper = $('.wtly-notify-form-wrapper').not('[data-wtly-overlay]');
				}

				if (!variation.is_in_stock) {
					$wrapper.attr('data-variation-id', variation.variation_id).show();
				} else {
					$wrapper.hide();
				}
			});

			// When variation selection is reset.
			$(document).on('reset_data', '.variations_form', function() {
				var $wrapper = $(this).closest('.product, .single-product').find('.wtly-notify-form-wrapper').not('[data-wtly-overlay]');

				if (!$wrapper.length) {
					$wrapper = $('.wtly-notify-form-wrapper').not('[data-wtly-overlay]');
				}

				$wrapper.attr('data-variation-id', 0);

				if ($wrapper.data('parent-oos') === '1' || $wrapper.data('parent-oos') === 1) {
					$wrapper.show();
				} else {
					$wrapper.hide();
				}
			});
		},

		/**
		 * Handle subscription form submit.
		 */
		handleSubscribe: function(e) {
			e.preventDefault();

			var $btn = $(this);
			var $wrapper = $btn.closest('.wtly-notify-form-wrapper');
			var $input = $wrapper.find('.wtly-email-input');
			var $message = $wrapper.find('.wtly-form-message');
			var email = $input.val().trim();

			// Validate email.
			if (!email || !WTLY_Public.isValidEmail(email)) {
				$message.text(wtlyPublicData.i18n.invalidEmail)
						.removeClass('wtly-success').addClass('wtly-error').show();
				return;
			}

			// Disable button during request.
			$btn.prop('disabled', true);
			$message.hide();

			$.ajax({
				url: wtlyPublicData.restUrl + 'wtly/v1/subscribe',
				type: 'POST',
				contentType: 'application/json',
				beforeSend: function(xhr) {
					xhr.setRequestHeader('X-WP-Nonce', wtlyPublicData.nonce);
				},
				data: JSON.stringify({
					email: email,
					product_id: parseInt($wrapper.attr('data-product-id'), 10),
					variation_id: parseInt($wrapper.attr('data-variation-id'), 10) || 0
				}),
				success: function(response) {
					$message.text(response.message)
							.removeClass('wtly-error').addClass('wtly-success').show();
					$input.val('');
				},
				error: function(xhr) {
					var msg = wtlyPublicData.i18n.error;
					if (xhr.responseJSON && xhr.responseJSON.message) {
						msg = xhr.responseJSON.message;
					}
					$message.text(msg)
							.removeClass('wtly-success').addClass('wtly-error').show();
				},
				complete: function() {
					$btn.prop('disabled', false);
				}
			});
		},

		/**
		 * Validate email format.
		 *
		 * @param {string} email Email address to validate.
		 * @return {boolean} True if valid.
		 */
		isValidEmail: function(email) {
			return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
		}
	};

	$(function() {
		WTLY_Public.init();
	});

})(jQuery);
