(function($){
	var feedbackStorageKey = 'pixelmole_followup_feedback_open';
	var previewTimer = null;

	function getPreviewBody() {
		if (window.tinymce) {
			var editor = tinymce.get('pixelmole_followup_body');
			if (editor) {
				return editor.getContent({format: 'raw'});
			}
		}
		return $('#pixelmole_followup_body').val() || '';
	}

	function renderPreview(html) {
		var iframe = document.getElementById('pixelmole-email-preview');
		if (!iframe) {
			return;
		}

		if ('srcdoc' in iframe) {
			iframe.srcdoc = html;
			return;
		}

		var doc = iframe.contentDocument || iframe.contentWindow.document;
		if (doc) {
			doc.open();
			doc.write(html);
			doc.close();
		}
	}

	function updatePreview() {
		if (typeof PixelMoleFollowup === 'undefined') {
			return;
		}

		if (!document.getElementById('pixelmole-email-preview')) {
			return;
		}

		var subject = $('input[name="pixelmole_followup_settings[subject]"]').val() || '';
		var body = getPreviewBody();

		$.post(PixelMoleFollowup.ajaxUrl, {
			action: 'pixelmole_render_preview_email',
			subject: subject,
			body: body,
			nonce: PixelMoleFollowup.nonce
		}).done(function(resp){
			if (resp && resp.success && resp.data && resp.data.html) {
				renderPreview(resp.data.html);
			}
		});
	}

	function schedulePreview() {
		if (previewTimer) {
			window.clearTimeout(previewTimer);
		}
		previewTimer = window.setTimeout(updatePreview, 300);
	}

	function initResizer() {
		var $layout = $('.pixelmole-settings-layout');
		var $resizer = $('.pixelmole-settings-resizer');
		var $form = $('.pixelmole-settings-form');
		var $side = $('.pixelmole-settings-side');

		if (!$layout.length || !$resizer.length || !$form.length || !$side.length) {
			return;
		}

		var dragging = false;

		function isSmallViewport() {
			return window.matchMedia && window.matchMedia('(max-width: 780px)').matches;
		}

		function resetInlineSizing() {
			$form.css('flex', '');
			$side.css('max-width', '');
		}

		$resizer.on('mousedown', function(e){
			if (isSmallViewport()) {
				return;
			}
			dragging = true;
			$('body').addClass('pixelmole-resizing');
			$layout.addClass('is-resizing');
			e.preventDefault();
		});

		$(document).on('mousemove', function(e){
			if (!dragging) {
				return;
			}

			var layoutOffset = $layout.offset().left;
			var layoutWidth = $layout.outerWidth();
			var resizerWidth = $resizer.outerWidth();
			var minForm = 420;
			var minPreview = 280;

			var newFormWidth = e.pageX - layoutOffset - (resizerWidth / 2);
			newFormWidth = Math.max(minForm, Math.min(newFormWidth, layoutWidth - minPreview - resizerWidth));

			$form.css('flex', '0 0 ' + newFormWidth + 'px');
			$side.css('max-width', (layoutWidth - newFormWidth - resizerWidth) + 'px');
		});

		$(document).on('mouseup', function(){
			if (!dragging) {
				return;
			}
			dragging = false;
			$('body').removeClass('pixelmole-resizing');
			$layout.removeClass('is-resizing');
		});

		$(window).on('resize', function(){
			if (isSmallViewport()) {
				resetInlineSizing();
			}
		});

		if (isSmallViewport()) {
			resetInlineSizing();
		}
	}


	function initFeedbackState(){
		var $feedback = $('.pixelmole-feedback');
		if (!$feedback.length || !window.localStorage) {
			return;
		}

		try {
			var stored = window.localStorage.getItem(feedbackStorageKey);
			if (stored === null || stored === '1') {
				$feedback.removeClass('is-collapsed');
			}
		} catch (err) {
			// Ignore storage errors.
		}
	}

	$(document).on('click', '#pixelmole-send-test', function(e){
		e.preventDefault();
		var $btn = $(this), $res = $('#pixelmole-test-result');
		var $input = $('#pixelmole-test-email');
		var to = $input.val();
		$res.removeClass('is-success is-error is-thinking').addClass('is-thinking').text('...');
		$btn.prop('disabled', true);
		$.post(PixelMoleFollowup.ajaxUrl, {
			action: 'pixelmole_send_test_email',
			to: to,
			nonce: PixelMoleFollowup.nonce
		}).done(function(resp){
			if(resp && resp.success){
				$res.text(resp.data.message).removeClass('is-thinking').addClass('is-success');
				$input.val('');
			}else{
				$res.text(resp && resp.data && resp.data.message ? resp.data.message : 'Error')
					.removeClass('is-thinking').addClass('is-error');
			}
		}).fail(function(){
			$res.text('Request failed').addClass('is-error');
		}).always(function(){
			$btn.prop('disabled', false);
		});
	});

	$(document).on('click', '.pixelmole-cancel-email', function(e){
		e.preventDefault();

		if (typeof PixelMoleFollowup === 'undefined') {
			return;
		}

		var i18n = PixelMoleFollowup.i18n || {};
		var confirmText = i18n.confirmCancel || 'Are you sure you want to cancel this email?';
		var successText = i18n.cancelSuccess || 'Scheduled email canceled.';
		var errorText = i18n.cancelError || 'Could not cancel the scheduled email.';

		if (!window.confirm(confirmText)) {
			return;
		}

		var $btn = $(this);
		var orderId = $btn.data('order-id');
		var timestamp = $btn.data('timestamp');
		var originalText = $btn.text();

		$btn.prop('disabled', true).text('...');

		$.post(PixelMoleFollowup.ajaxUrl, {
			action: 'pixelmole_cancel_followup_email',
			orderId: orderId,
			timestamp: timestamp,
			nonce: PixelMoleFollowup.nonce
		}).done(function(resp){
			if (resp && resp.success) {
				window.alert(successText);
				window.location.reload();
			} else {
				var message = resp && resp.data && resp.data.message ? resp.data.message : errorText;
				window.alert(message);
				$btn.prop('disabled', false).text(originalText);
			}
		}).fail(function(){
			window.alert(errorText);
			$btn.prop('disabled', false).text(originalText);
		});
	});

	$(document).on('click', '.pixelmole-feedback-close', function(e){
		e.preventDefault();
		var $feedback = $(this).closest('.pixelmole-feedback');
		$feedback.toggleClass('is-collapsed');

		if (!window.localStorage) {
			return;
		}

		try {
			var expanded = $feedback.hasClass('is-collapsed') ? '0' : '1';
			window.localStorage.setItem(feedbackStorageKey, expanded);
		} catch (err) {
			// Ignore storage errors.
		}
	});

	$(document).on('input', 'input[name="pixelmole_followup_settings[subject]"]', schedulePreview);
	$(document).on('input', '#pixelmole_followup_body', schedulePreview);

	$(document).on('tinymce-editor-init', function(event, editor) {
		if (editor && editor.id === 'pixelmole_followup_body') {
			editor.on('change keyup input SetContent', schedulePreview);
			schedulePreview();
		}
	});

	$(initFeedbackState);
	$(schedulePreview);
	$(initResizer);
})(jQuery);
