/*!
 * CartNinja Recovery - Admin JS
 * Source file included in this plugin package.
 * Not minified - this is the full source.
 */

(function ($) {
	'use strict';

	var modal = $('#cartninja-cart-modal');
	var modalContent = $('#cartninja-cart-modal-content');

	function updateSmsCount() {
		var template = $('#cartninja_sms_template').val() || '';
		$('#cartninja-char-count').text(template.length + ' / 160');
	}

	function closeCartModal() {
		if (!modal.length) {
			return;
		}
		modal.attr('hidden', true);
		$('body').removeClass('cartninja-modal-open');
	}

	function openCartModal(content) {
		if (!modal.length) {
			return;
		}
		modalContent.html(content);
		modal.removeAttr('hidden');
		$('body').addClass('cartninja-modal-open');
	}

	function toggleGatewayPanels() {
		var providerField = document.querySelector('[data-cartninja-gateway-provider]');
		if (!providerField) {
			return;
		}

		var provider = providerField.value;
		document.querySelectorAll('[data-cartninja-gateway-panel]').forEach(function (panel) {
			panel.style.display = panel.getAttribute('data-cartninja-gateway-panel') === provider ? '' : 'none';
		});
	}

	function toggleDashboardPeriodFields() {
		var periodField = document.querySelector('[data-cartninja-period-filter]');
		var dateField = document.querySelector('[data-cartninja-period-date]');
		var dateToField = document.querySelector('[data-cartninja-period-date-to]');

		if (!periodField || !dateField || !dateToField) {
			return;
		}

		var needsDate = ['equals', 'not_on', 'after', 'before', 'between'].indexOf(periodField.value) !== -1;
		dateField.style.display = needsDate ? '' : 'none';
		dateField.disabled = !needsDate;

		dateToField.style.display = periodField.value === 'between' ? '' : 'none';
		dateToField.disabled = periodField.value !== 'between';
	}

	function initRevenueChart() {
		var ctx = document.getElementById('cartninja-revenue-chart');
		var rows = window.cartninjaDashboardChartData || [];

		if (!ctx || !window.Chart || !Array.isArray(rows)) {
			return;
		}

		new window.Chart(ctx, {
			type: 'line',
			data: {
				labels: rows.map(function (row) { return row.day; }),
				datasets: [
					{ label: 'Abandoned', data: rows.map(function (row) { return Number(row.abandoned || 0); }), borderColor: '#0EA5A0', backgroundColor: 'rgba(14,165,160,0.12)', borderWidth: 3, pointRadius: 3, pointHoverRadius: 5, fill: false, tension: 0.3 },
					{ label: 'Recovered', data: rows.map(function (row) { return Number(row.recovered || 0); }), borderColor: '#10B981', backgroundColor: 'rgba(16,185,129,0.12)', borderWidth: 3, pointRadius: 3, pointHoverRadius: 5, fill: false, tension: 0.3 }
				]
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				interaction: {
					mode: 'index',
					intersect: false
				},
				scales: {
					y: {
						beginAtZero: true,
						ticks: {
							precision: 0
						}
					}
				}
			}
		});
	}

	function clearSequenceEditor() {
		$('#cartninja-sequence-id').val(0);
		$('#cartninja-sequence-name').val('');
		$('#cartninja-sequence-active').prop('checked', false);
		$('#cartninja-sequence-steps').empty();
	}

	function normalizeStepForForm(step) {
		var delayMinutes = Number(step.delay_minutes || 30);
		var delayValue = delayMinutes;
		var delayUnit = 'minutes';

		if (delayMinutes % 1440 === 0) {
			delayValue = delayMinutes / 1440;
			delayUnit = 'days';
		} else if (delayMinutes % 60 === 0) {
			delayValue = delayMinutes / 60;
			delayUnit = 'hours';
		}

		return {
			channel: step.channel || 'sms',
			delay_value: delayValue,
			delay_unit: step.delay_unit || delayUnit,
			message_template: step.message_template || '',
			include_coupon: Number(step.include_coupon || 0),
			coupon_discount: step.coupon_discount || 10,
			coupon_type: step.coupon_type || 'percent'
		};
	}

	function loadSequence(sequence) {
		clearSequenceEditor();
		if (!sequence) {
			addStep();
			return;
		}

		$('#cartninja-sequence-id').val(sequence.id || 0);
		$('#cartninja-sequence-name').val(sequence.name || '');
		$('#cartninja-sequence-active').prop('checked', !!Number(sequence.is_active || 0));

		if (Array.isArray(sequence.steps) && sequence.steps.length) {
			sequence.steps.forEach(function (step) {
				addStep(normalizeStepForForm(step));
			});
		} else {
			addStep();
		}
	}

	function serializeSteps() {
		var steps = [];
		$('#cartninja-sequence-steps .cartninja-sequence-step').each(function (index) {
			var step = $(this);
			steps.push({
				step_order: index + 1,
				channel: step.find('.cartninja-step-channel').val(),
				delay_value: step.find('.cartninja-step-delay-value').val(),
				delay_unit: step.find('.cartninja-step-delay-unit').val(),
				message_template: step.find('.cartninja-step-message').val(),
				include_coupon: step.find('.cartninja-step-include-coupon').is(':checked') ? 1 : 0,
				coupon_discount: step.find('.cartninja-step-coupon-discount').val(),
				coupon_type: step.find('.cartninja-step-coupon-type').val(),
				is_active: 1
			});
		});
		return steps;
	}

	function addStep(stepData) {
		var step = stepData || {};
		var channels = [
			{ value: 'sms', label: 'SMS' },
			{ value: 'email', label: 'Email' }
		];
		var channelOptions = '';

		if (window.cartninjaAdminPro && Array.isArray(window.cartninjaAdminPro.sequenceChannels)) {
			channels = channels.concat(window.cartninjaAdminPro.sequenceChannels);
		}

		channels.forEach(function (channel) {
			channelOptions += '<option value="' + channel.value + '">' + channel.label + '</option>';
		});

		var html = '' +
			'<li class="cartninja-sequence-step">' +
				'<div class="cartninja-sequence-step__head"><strong>' + cartninjaAdmin.strings.stepLabel + '</strong><button type="button" class="cartninja-action-link cartninja-action-link--delete cartninja-remove-step"><span class="dashicons dashicons-trash" aria-hidden="true"></span><span>Remove</span></button></div>' +
				'<p><select class="cartninja-step-channel">' + channelOptions + '</select></p>' +
				'<p><input type="number" min="1" class="cartninja-step-delay-value small-text" value="' + (step.delay_value || 30) + '" /> ' +
				'<select class="cartninja-step-delay-unit"><option value="minutes">Minutes</option><option value="hours">Hours</option><option value="days">Days</option></select></p>' +
				'<p><textarea class="large-text cartninja-step-message" rows="4"></textarea></p>' +
				'<p><label><input type="checkbox" class="cartninja-step-include-coupon" /> Include coupon</label></p>' +
				'<p><input type="number" class="small-text cartninja-step-coupon-discount" value="' + (step.coupon_discount || 10) + '" /> ' +
				'<select class="cartninja-step-coupon-type"><option value="percent">Percent</option><option value="fixed_cart">Fixed cart</option></select></p>' +
			'</li>';
		var node = $(html);
		node.find('.cartninja-step-channel').val(step.channel || 'sms');
		node.find('.cartninja-step-delay-unit').val(step.delay_unit || 'minutes');
		node.find('.cartninja-step-message').val(step.message_template || '');
		node.find('.cartninja-step-include-coupon').prop('checked', !!Number(step.include_coupon || 0));
		node.find('.cartninja-step-coupon-type').val(step.coupon_type || 'percent');
		$('#cartninja-sequence-steps').append(node);
	}

	$(document).on('input', '#cartninja_sms_template', updateSmsCount);

	$(document).on('click', '#cartninja-send-test-sms', function (event) {
		event.preventDefault();
		var phone = $('#cartninja_test_phone').val();
		var button = $(this);
		var result = $('#cartninja-test-result');
		button.prop('disabled', true);
		result.text('');
		$.post(cartninjaAdmin.ajaxUrl, { action: 'cartninja_send_test_sms', nonce: cartninjaAdmin.nonce, phone: phone })
			.done(function (response) {
				result.text(response.data.message).css('color', response.success ? '#10B981' : '#EF4444');
			})
			.fail(function (xhr) {
				var message = cartninjaAdmin.strings.testError;
				if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
					message = xhr.responseJSON.data.message;
				}
				result.text(message).css('color', '#EF4444');
			})
			.always(function () {
				button.prop('disabled', false);
			});
	});

	$(document).on('click', '#cartninja-send-test-email', function (event) {
		event.preventDefault();
		var button = $(this);
		var result = $('#cartninja-email-test-result');
		button.prop('disabled', true);
		result.text('Sending test email...').css('color', '#334155');
		$.post(cartninjaAdmin.ajaxUrl, {
			action: 'cartninja_send_test_email',
			nonce: cartninjaAdmin.nonce,
			email: $('#cartninja_test_email').val(),
			email_subject: $('#cartninja_email_subject').val(),
			email_heading: $('#cartninja_email_heading').val(),
			email_template: $('#cartninja_email_template').val(),
			email_button_text: $('#cartninja_email_button_text').val(),
			email_footer_text: $('#cartninja_email_footer_text').val()
		})
			.done(function (response) {
				result.text(response.data.message).css('color', response.success ? '#10B981' : '#EF4444');
			})
			.fail(function (xhr) {
				var message = cartninjaAdmin.strings.emailTestError;
				if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
					message = xhr.responseJSON.data.message;
				}
				result.text(message).css('color', '#EF4444');
			})
			.always(function () {
				button.prop('disabled', false);
			});
	});

	$(document).on('click', '.cartninja-view-cart', function (event) {
		var cartId = $(this).data('cart-id');
		if (!cartId) {
			return;
		}
		event.preventDefault();
		openCartModal('<div class="cartninja-cart-details cartninja-cart-details--drawer"><p>' + cartninjaAdmin.strings.loadingCart + '</p></div>');
		$.post(cartninjaAdmin.ajaxUrl, { action: 'cartninja_get_cart_details', nonce: cartninjaAdmin.nonce, cart_id: cartId })
			.done(function (response) {
				if (response.success && response.data && response.data.html) {
					openCartModal(response.data.html);
				} else {
					openCartModal('<div class="cartninja-cart-details cartninja-cart-details--drawer"><p>' + cartninjaAdmin.strings.cartLoadError + '</p></div>');
				}
			})
			.fail(function () {
				openCartModal('<div class="cartninja-cart-details cartninja-cart-details--drawer"><p>' + cartninjaAdmin.strings.cartLoadError + '</p></div>');
			});
	});

	$(document).on('click', '.cartninja-modal__close, .cartninja-modal__backdrop', function () {
		closeCartModal();
	});

	$(document).on('keydown', function (event) {
		if (event.key === 'Escape') {
			closeCartModal();
		}
	});

	$(document).on('click', '#cartninja-add-sequence-step', function () {
		addStep();
	});

	$(document).on('click', '#cartninja-new-sequence', function () {
		clearSequenceEditor();
		addStep();
	});

	$(document).on('click', '.cartninja-remove-step', function () {
		$(this).closest('.cartninja-sequence-step').remove();
	});

	$(document).on('click', '#cartninja-save-sequence', function () {
		var result = $('#cartninja-sequence-result');
		$.post(cartninjaAdmin.ajaxUrl, {
			action: 'cartninja_save_sequence',
			nonce: cartninjaAdmin.nonce,
			sequence: {
				id: Number($('#cartninja-sequence-id').val() || 0),
				name: $('#cartninja-sequence-name').val(),
				is_active: $('#cartninja-sequence-active').is(':checked') ? 1 : 0,
				set_active: $('#cartninja-sequence-active').is(':checked') ? 1 : 0
			},
			steps: JSON.stringify(serializeSteps())
		}).done(function (response) {
			result.text(response.data.message || cartninjaAdmin.strings.sequenceSaved).css('color', '#10B981');
			window.location = 'admin.php?page=cartninja-sequences&sequence_id=' + response.data.sequence_id;
		}).fail(function (xhr) {
			var message = cartninjaAdmin.strings.sequenceError;
			if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
				message = xhr.responseJSON.data.message;
			}
			result.text(message).css('color', '#EF4444');
		});
	});

	$(document).on('click', '.cartninja-use-sequence', function () {
		var sequenceId = Number($(this).data('sequence-id') || 0);
		if (!sequenceId) {
			return;
		}

		$.post(cartninjaAdmin.ajaxUrl, {
			action: 'cartninja_set_active_sequence',
			nonce: cartninjaAdmin.nonce,
			sequence_id: sequenceId
		}).done(function () {
			window.location = 'admin.php?page=cartninja-sequences&sequence_id=' + sequenceId;
		});
	});

	$(document).on('click', '.cartninja-delete-sequence', function () {
		var sequenceId = Number($(this).data('sequence-id') || 0);
		if (!sequenceId || !window.confirm('Delete this sequence?')) {
			return;
		}

		$.post(cartninjaAdmin.ajaxUrl, {
			action: 'cartninja_delete_sequence',
			nonce: cartninjaAdmin.nonce,
			sequence_id: sequenceId
		}).done(function () {
			window.location = 'admin.php?page=cartninja-sequences';
		});
	});

	$(function () {
		updateSmsCount();
		toggleGatewayPanels();
		toggleDashboardPeriodFields();
		initRevenueChart();
		document.addEventListener('change', function (event) {
			if (event.target && event.target.matches('[data-cartninja-gateway-provider]')) {
				toggleGatewayPanels();
			}

			if (event.target && event.target.matches('[data-cartninja-period-filter]')) {
				toggleDashboardPeriodFields();
			}
		});

		if ($('#cartninja-sequence-steps').length) {
			$('#cartninja-sequence-steps').sortable();
			try {
				loadSequence(JSON.parse($('#cartninja-sequence-builder').attr('data-current-sequence') || '{}'));
			} catch (error) {
				clearSequenceEditor();
				addStep();
			}
		}
	});
})(jQuery);
