/**
 * Alsendo Connect - Package (Shipment) Templates management.
 *
 * @package Inspire_Labs\Alsendo_Connect
 */

var alsendoAddTemplateDialog;
var alsendoTrTemplate;
var alsendoTemplateFields = [
	'id', 'name', 'parcel_type', 'is_nstd',
	'package_length', 'package_width', 'package_height', 'package_weight',
	'package_contents', 'custom_text_content', 'declared_content',
	'shipping_method', 'pickup_hour_from', 'pickup_hour_to'
];

var alsendoSelectFields = ['parcel_type', 'is_nstd', 'package_contents', 'pickup_hour_from', 'pickup_hour_to'];
var alsendoRadioFields  = ['shipping_method'];

var alsendoIsSaving = false;

var alsendoAdditionalParcelsMax = 9;
var alsendoAdditionalParcelsCount = 0;

const alsendoIsApaczkaApi = function () {
	var $dlg = jQuery('#alsendoAddTemplateDialog');
	return ($dlg.data('api-type') || '') === 'apaczka';
};

const alsendoClearAdditionalParcels = function () {
	alsendoAdditionalParcelsCount = 0;
	jQuery('#alsendo_connect_additional_parcels_container').empty();
};

const alsendoApplyParcelTypeRules = function ($wrap) {
	var type = $wrap.find('select[data-field="parcel_type"]').val() || '';
	var $length = $wrap.find('input[data-field="package_length"]');
	var $width  = $wrap.find('input[data-field="package_width"]');
	var $height = $wrap.find('input[data-field="package_height"]');

	switch (type) {
		case 'europalette':
			$length.val(120).prop('readonly', true);
			$width.val(80).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_60x80':
			$length.val(80).prop('readonly', true);
			$width.val(60).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_120x100':
			$length.val(120).prop('readonly', true);
			$width.val(100).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_120x120':
			$length.val(120).prop('readonly', true);
			$width.val(120).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		default:
			$length.prop('readonly', false);
			$width.prop('readonly', false);
			$height.removeAttr('max').prop('readonly', false);
			break;
	}
};

const alsendoAddAdditionalParcel = function (values) {
	if (!alsendoIsApaczkaApi()) {
		return;
	}

	if (alsendoAdditionalParcelsCount >= alsendoAdditionalParcelsMax) {
		alert('Max 10 parcels can be added');
		return;
	}

	alsendoAdditionalParcelsCount++;
	var idx = alsendoAdditionalParcelsCount;
	values = values || {};

	var $container = jQuery('#alsendo_connect_additional_parcels_container');
	if (!$container.length) {
		return;
	}

	var $wrap = jQuery('<div>', { 'class': 'alsendo-additional-parcel-wrap', 'data-idx': idx });
	var $title = jQuery('<div>', { 'class': 'alsendo-additional-parcel-title' })
		.append(jQuery('<span>', { text: (alsendo_connect_templates.i18n_additional_parcel || 'Additional parcel') + ' #' + idx }))
		.append(jQuery('<button>', { type: 'button', 'class': 'button-link-delete alsendo_remove_template_parcel', text: alsendo_connect_templates.i18n_remove || 'Remove' }));

	$wrap.append($title);

	// Row: Parcel type + Non standard
	var $row1 = jQuery('<div>', { 'class': 'alsendo-tpl-row' });

	var $parcelTypeSelect = jQuery('#alsendo_connect_template_parcel_type').clone();
	$parcelTypeSelect
		.attr('id', 'alsendo_connect_template_additional_' + idx + '_parcel_type')
		.attr('name', 'template[additional_parcels][' + idx + '][parcel_type]')
		.attr('data-field', 'parcel_type')
		.val(values.parcel_type || $parcelTypeSelect.val() || '');

	var $isNstdSelect = jQuery('#alsendo_connect_template_is_nstd').clone();
	$isNstdSelect
		.attr('id', 'alsendo_connect_template_additional_' + idx + '_is_nstd')
		.attr('name', 'template[additional_parcels][' + idx + '][is_nstd]')
		.attr('data-field', 'is_nstd')
		.val(values.is_nstd || 'no');

	$row1
		.append(
			jQuery('<div>', { 'class': 'alsendo-tpl-field' })
				.append(jQuery('<label>', { 'for': $parcelTypeSelect.attr('id'), text: alsendo_connect_templates.i18n_parcel_type || 'Parcel type' }))
				.append($parcelTypeSelect)
		)
		.append(
			jQuery('<div>', { 'class': 'alsendo-tpl-field' })
				.append(jQuery('<label>', { 'for': $isNstdSelect.attr('id'), text: alsendo_connect_templates.i18n_non_standard_package || 'Non standard package' }))
				.append($isNstdSelect)
		);

	// Row: dimensions + weight
	var $row2 = jQuery('<div>', { 'class': 'alsendo-tpl-row' });

	function cloneNumberInput(baseId, field, labelText, step) {
		var $base = jQuery('#' + baseId).clone();
		var id = 'alsendo_connect_template_additional_' + idx + '_' + field;
		$base
			.attr('id', id)
			.attr('name', 'template[additional_parcels][' + idx + '][' + field + ']')
			.attr('data-field', field)
			.val(values[field] || '');
		if (step) {
			$base.attr('step', step);
		}
		return jQuery('<div>', { 'class': 'alsendo-tpl-field' })
			.append(jQuery('<label>', { 'for': id, text: labelText }))
			.append($base);
	}

	$row2
		.append(cloneNumberInput('alsendo_connect_template_package_length', 'package_length', alsendo_connect_templates.i18n_length_cm || 'Length [cm]', '1'))
		.append(cloneNumberInput('alsendo_connect_template_package_width', 'package_width', alsendo_connect_templates.i18n_width_cm || 'Width [cm]', '1'))
		.append(cloneNumberInput('alsendo_connect_template_package_height', 'package_height', alsendo_connect_templates.i18n_height_cm || 'Height [cm]', '1'))
		.append(cloneNumberInput('alsendo_connect_template_package_weight', 'package_weight', alsendo_connect_templates.i18n_weight_kg || 'Weight [kg]', 'any'));

	$wrap.append($row1).append($row2);
	$container.append($wrap);

	alsendoApplyParcelTypeRules($wrap);
};

const alsendoRenderAdditionalParcels = function (parcels) {
	if (!alsendoIsApaczkaApi()) {
		return;
	}
	alsendoClearAdditionalParcels();
	if (!Array.isArray(parcels)) {
		return;
	}
	parcels.forEach(function (p) {
		alsendoAddAdditionalParcel(p || {});
	});
};

const alsendoShowPageNotice = function (type, message) {
	jQuery('#wpbody .wp-header-end').after(
		'<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>'
	);
};

const alsendoShowDialogMessage = function (message, type) {
	type = type || 'error';
	var bgColor = type === 'success' ? '#ecf7ed' : '#fcf0f1';
	var borderColor = type === 'success' ? '#00a32a' : '#d63638';
	var textColor = type === 'success' ? '#00a32a' : '#d63638';

	var $msgBox = jQuery('#alsendo-tpl-dialog-message');
	if (!$msgBox.length) {
		jQuery('#alsendoTemplateFormFields').append(
			'<div id="alsendo-tpl-dialog-message"></div>'
		);
		$msgBox = jQuery('#alsendo-tpl-dialog-message');
	}
	$msgBox
		.css({
			'margin-top': '12px',
			'padding': '8px 12px',
			'background': bgColor,
			'border-left': '4px solid ' + borderColor,
			'color': textColor,
			'font-size': '13px'
		})
		.html(message).show();
};

const alsendoClearDialogMessages = function () {
	jQuery('#alsendo-tpl-dialog-message').hide().html('');
};

const alsendoSetSavingState = function (isSaving) {
	alsendoIsSaving = isSaving;
	var $saveBtn = alsendoAddTemplateDialog.closest('.ui-dialog').find('.ui-dialog-buttonpane button').first();

	if (isSaving) {
		$saveBtn.prop('disabled', true).css('opacity', '0.6');
		if (!$saveBtn.find('.alsendo-spinner').length) {
			$saveBtn.prepend('<span class="alsendo-spinner"></span>');
		}
	} else {
		$saveBtn.prop('disabled', false).css('opacity', '1');
		$saveBtn.find('.alsendo-spinner').remove();
	}
};

const alsendoSafeReload = function () {
	window.onbeforeunload = null;
	jQuery(window).off('beforeunload');
	window.location.reload();
};

const alsendoToggleCustomText = function () {
	var val = jQuery('#alsendo_connect_template_package_contents').val();
	if ('custom_text' === val) {
		jQuery('#alsendo_connect_custom_text_wrapper').show();
	} else {
		jQuery('#alsendo_connect_custom_text_wrapper').hide();
		jQuery('#alsendo_connect_template_custom_text_content').val('');
	}
};

const alsendoGetParcelType = function () {
	return jQuery('#alsendo_connect_template_parcel_type').val() || '';
};

const alsendoHasEcoletParcelUi = function () {
	return jQuery('#alsendo_connect_ecolet_parcel_type_mode').length > 0;
};

const alsendoToggleDimensionsForParcelType = function () {
	var type = alsendoGetParcelType();
	var isEnvelope = ('envelope' === type);
	var $row = jQuery('#alsendo_connect_dimensions_row');
	var $length = jQuery('#alsendo_connect_template_package_length');
	var $width = jQuery('#alsendo_connect_template_package_width');
	var $height = jQuery('#alsendo_connect_template_package_height');
	var $weight = jQuery('#alsendo_connect_template_package_weight');

	if (isEnvelope) {
		$row.hide();
		$length.val('').prop('readonly', false);
		$width.val('').prop('readonly', false);
		$height.val('').removeAttr('max').prop('readonly', false);
		$weight.val('');
		return;
	}

	$row.show();
};

const alsendoToggleNonStandardForEcolet = function () {
	var $wrapper = jQuery('#alsendo_connect_ecolet_nonstd_wrapper');
	if (!$wrapper.length) {
		$wrapper = jQuery('#alsendo_connect_nonstd_wrapper');
	}

	if (!alsendoHasEcoletParcelUi()) {
		$wrapper.show();
		return;
	}

	var type = alsendoGetParcelType();
	var showNonStandard = ('package' === type);

	if (showNonStandard) {
		$wrapper.show();
	} else {
		$wrapper.hide();
		jQuery('#alsendo_connect_template_is_nstd').val('no');
	}
};

const alsendoSyncEcoletParcelTypeUi = function () {
	if (!alsendoHasEcoletParcelUi()) {
		return;
	}

	var type = alsendoGetParcelType();
	var mode = 'package';
	var $paletteSelect = jQuery('#alsendo_connect_ecolet_palette_type');
	var paletteValues = $paletteSelect.find('option').map(function () {
		return jQuery(this).val();
	}).get();

	if ('envelope' === type) {
		mode = 'envelope';
	} else if ('package' === type) {
		mode = 'package';
	} else if (type) {
		mode = 'palette';
	}

	jQuery('input[name="template[parcel_type_mode]"]').prop('checked', false);
	jQuery('input[name="template[parcel_type_mode]"][value="' + mode + '"]').prop('checked', true);

	if ('palette' === mode) {
		if (paletteValues.indexOf(type) !== -1) {
			$paletteSelect.val(type);
		} else if ($paletteSelect.find('option').length > 0) {
			$paletteSelect.prop('selectedIndex', 0);
			jQuery('#alsendo_connect_template_parcel_type').val($paletteSelect.val() || '');
		}
		jQuery('#alsendo_connect_ecolet_palette_size_wrapper').show();
	} else {
		jQuery('#alsendo_connect_ecolet_palette_size_wrapper').hide();
	}
};

const alsendoUpdateParcelTypeFromEcoletUi = function () {
	if (!alsendoHasEcoletParcelUi()) {
		return;
	}

	var mode = jQuery('input[name="template[parcel_type_mode]"]:checked').val() || 'package';
	var $parcelType = jQuery('#alsendo_connect_template_parcel_type');
	var $paletteSelect = jQuery('#alsendo_connect_ecolet_palette_type');

	if ('palette' === mode) {
		var paletteType = $paletteSelect.val() || '';
		if (!paletteType && $paletteSelect.find('option').length > 0) {
			$paletteSelect.prop('selectedIndex', 0);
			paletteType = $paletteSelect.val() || '';
		}
		$parcelType.val(paletteType);
		jQuery('#alsendo_connect_ecolet_palette_size_wrapper').show();
	} else {
		$parcelType.val(mode);
		jQuery('#alsendo_connect_ecolet_palette_size_wrapper').hide();
	}

	alsendoOnParcelTypeChange();
	alsendoToggleDimensionsForParcelType();
	alsendoToggleNonStandardForEcolet();
};

const alsendoOnParcelTypeChange = function () {
	var type = alsendoGetParcelType();
	var $length = jQuery('#alsendo_connect_template_package_length');
	var $width  = jQuery('#alsendo_connect_template_package_width');
	var $height = jQuery('#alsendo_connect_template_package_height');

	switch (type) {
		case 'europalette':
			$length.val(120).prop('readonly', true);
			$width.val(80).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_60x80':
			$length.val(80).prop('readonly', true);
			$width.val(60).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_120x100':
			$length.val(120).prop('readonly', true);
			$width.val(100).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		case 'palette_120x120':
			$length.val(120).prop('readonly', true);
			$width.val(120).prop('readonly', true);
			if (parseInt($height.val(), 10) > 220) {
				$height.val(220);
			}
			$height.prop('max', 220).prop('readonly', false);
			break;
		default:
			$length.prop('readonly', false);
			$width.prop('readonly', false);
			$height.removeAttr('max').prop('readonly', false);
			break;
	}
};

const alsendoTogglePickupHours = function () {
	var val = jQuery('input[name="template[shipping_method]"]:checked').val() || '';
	if ('COURIER' === val) {
		jQuery('#alsendo_connect_pickup_hours_wrapper').show();
	} else {
		jQuery('#alsendo_connect_pickup_hours_wrapper').hide();
		jQuery('#alsendo_connect_template_pickup_hour_from').val('');
		jQuery('#alsendo_connect_template_pickup_hour_to').val('');
	}
};

const alsendoShowRowSpinner = function ($btn) {
	var $tr = $btn.closest('tr');
	$tr.find('.button').prop('disabled', true).css('opacity', '0.6');
	$btn.after('<span class="spinner is-active" style="float:none;margin:0 0 0 4px;"></span>');
};

const alsendoOnClickAddTemplate = function () {
	alsendoClearDialogMessages();
	alsendoAddTemplateDialog.dialog('option', 'title', alsendo_connect_templates.i18n_add_template);
	alsendoOpenTemplateDialog();
};

const alsendoOnClickEditTemplate = function () {
	alsendoClearDialogMessages();
	alsendoAddTemplateDialog.dialog('option', 'title', alsendo_connect_templates.i18n_edit_template);
	alsendoTrTemplate = jQuery(this).parentsUntil('tbody', 'tr').get(0);
	alsendoOpenTemplateDialog();
};

const alsendoOnClickDeleteTemplate = function () {
	alsendoTrTemplate = jQuery(this).parentsUntil('tbody', 'tr').get(0);
	if (undefined !== alsendoTrTemplate) {
		var template = jQuery(alsendoTrTemplate).data('template') || '';
		var id = template['id'] || 0;
		if (0 === id) {
			return;
		}

		if (true === alsendoIsSaving) {
			return;
		}
		alsendoIsSaving = true;

		var $deleteBtn = jQuery(this);
		alsendoShowRowSpinner($deleteBtn);

		var data = {
			action: 'alsendo_connect_shipment_template_delete',
			'template_delete': {
				_nonce: template._nonce,
				id: template.id,
				_legacy_slug: template._legacy_slug || ''
			}
		};

		console.log('[Alsendo Templates] Delete request:', data);

		jQuery.post({
			url: alsendo_connect_templates.ajax_url,
			dataType: 'json',
			data: data
		})
			.done(function () {
				console.log('[Alsendo Templates] Delete success');
				alsendoSafeReload();
			})
			.fail(function (xhr) {
				console.error('[Alsendo Templates] Delete failed:', xhr.status, xhr.responseText);
				alsendoShowPageNotice('error', alsendo_connect_templates.i18n_error_deleting + ' (HTTP ' + xhr.status + ')');
				var $tr = $deleteBtn.closest('tr');
				$tr.find('.spinner').remove();
				$tr.find('.button').prop('disabled', false).css('opacity', '1');
			})
			.always(function () {
				jQuery("html, body").scrollTop(0);
				alsendoIsSaving = false;
			});
	}
};

const alsendoOnClickSetDefault = function () {
	var $btn = jQuery(this);

	if ($btn.hasClass('is-default') || $btn.prop('disabled')) {
		return;
	}

	if (true === alsendoIsSaving) {
		return;
	}
	alsendoIsSaving = true;

	var slug = $btn.data('slug');
	alsendoShowRowSpinner($btn);

	jQuery.ajax({
		url: alsendo_connect_templates.ajax_url,
		type: 'POST',
		dataType: 'json',
		data: {
			action: 'alsendo_connect_shipment_template_set_default',
			_nonce: alsendo_connect_templates.set_default_nonce,
			template_slug: slug
		}
	})
		.done(function () {
			console.log('[Alsendo Templates] Default template updated to:', slug);
			alsendoSafeReload();
		})
		.fail(function (xhr) {
			console.error('[Alsendo Templates] Set default failed:', xhr.status, xhr.responseText);
			alsendoShowPageNotice('error', alsendo_connect_templates.i18n_error_setting_default + ' (HTTP ' + xhr.status + ')');
			var $tr = $btn.closest('tr');
			$tr.find('.spinner').remove();
			$tr.find('.button').prop('disabled', false).css('opacity', '1');
		})
		.always(function () {
			alsendoIsSaving = false;
		});
};

const alsendoOpenTemplateDialog = function () {
	var $checkbox = jQuery('#alsendo_connect_set_as_default');
	if ($checkbox.length) {
		$checkbox.prop('checked', false);
	}

	if (undefined !== alsendoTrTemplate) {
		var template = jQuery(alsendoTrTemplate).data('template') || '';

		jQuery.each(alsendoTemplateFields, function (i, el) {
			var $field = jQuery('#alsendo_connect_template_' + el);

			if (alsendoRadioFields.indexOf(el) !== -1) {
				jQuery('input[name="template[' + el + ']"]').prop('checked', false);
				if (template[el]) {
					jQuery('input[name="template[' + el + ']"][value="' + template[el] + '"]').prop('checked', true);
				}
			} else if (alsendoSelectFields.indexOf(el) !== -1) {
				$field.val(template[el] || '').change();
			} else {
				$field.val(template[el] || '');
			}
		});

		var legacySlug = template['_legacy_slug'] || '';
		jQuery('#alsendo_connect_template_legacy_slug').val(legacySlug);

		var templateSlug = template['template_slug'] || '';
		if (templateSlug && templateSlug === alsendo_connect_templates.default_slug) {
			if ($checkbox.length) {
				$checkbox.prop('checked', true);
			}
		}

		alsendoToggleCustomText();
		alsendoSyncEcoletParcelTypeUi();
		alsendoOnParcelTypeChange();
		alsendoToggleDimensionsForParcelType();
		alsendoToggleNonStandardForEcolet();
		alsendoTogglePickupHours();

		alsendoRenderAdditionalParcels(template.additional_parcels || []);
	} else {
		alsendoSyncEcoletParcelTypeUi();
		alsendoUpdateParcelTypeFromEcoletUi();
		alsendoToggleNonStandardForEcolet();
		alsendoClearAdditionalParcels();
	}
	alsendoAddTemplateDialog.dialog('open');
};

const alsendoResetForm = function () {
	alsendoTrTemplate = undefined;

	jQuery.each(alsendoTemplateFields, function (i, el) {
		var $field = jQuery('#alsendo_connect_template_' + el);

		if (alsendoRadioFields.indexOf(el) !== -1) {
			jQuery('input[name="template[' + el + ']"]').prop('checked', false);
		} else if (alsendoSelectFields.indexOf(el) !== -1) {
			if ($field.is('select')) {
				$field.prop('selectedIndex', 0).change();
			} else {
				$field.val('').change();
			}
		} else {
			$field.val('');
		}
	});

	jQuery('#alsendo_connect_template_legacy_slug').val('');

	var $checkbox = jQuery('#alsendo_connect_set_as_default');
	if ($checkbox.length) {
		$checkbox.prop('checked', false);
	}

	jQuery('#alsendo_connect_template_package_length, #alsendo_connect_template_package_width, #alsendo_connect_template_package_height')
		.prop('readonly', false);
	jQuery('#alsendo_connect_template_package_height').removeAttr('max');

	alsendoSyncEcoletParcelTypeUi();
	alsendoUpdateParcelTypeFromEcoletUi();
	alsendoToggleCustomText();
	alsendoToggleDimensionsForParcelType();
	alsendoToggleNonStandardForEcolet();
	alsendoTogglePickupHours();
	alsendoClearDialogMessages();
	alsendoClearAdditionalParcels();
};

const alsendoValidateForm = function () {
	var errors = [];

	var name = jQuery('#alsendo_connect_template_name').val().trim();
	if (!name) {
		errors.push(alsendo_connect_templates.i18n_field_template_name);
	}

	var isEnvelope = ('envelope' === alsendoGetParcelType());
	if (!isEnvelope) {
		var length = jQuery('#alsendo_connect_template_package_length').val();
		if (!length || parseFloat(length) <= 0) {
			errors.push(alsendo_connect_templates.i18n_field_length);
		}

		var width = jQuery('#alsendo_connect_template_package_width').val();
		if (!width || parseFloat(width) <= 0) {
			errors.push(alsendo_connect_templates.i18n_field_width);
		}

		var height = jQuery('#alsendo_connect_template_package_height').val();
		if (!height || parseFloat(height) <= 0) {
			errors.push(alsendo_connect_templates.i18n_field_height);
		}

		var weight = jQuery('#alsendo_connect_template_package_weight').val();
		if (!weight || parseFloat(weight) <= 0) {
			errors.push(alsendo_connect_templates.i18n_field_weight);
		}
	}

	var contents = jQuery('#alsendo_connect_template_package_contents').val();
	if ('custom_text' === contents) {
		var customText = jQuery('#alsendo_connect_template_custom_text_content').val().trim();
		if (!customText) {
			errors.push(alsendo_connect_templates.i18n_field_package_contents);
		}
	}

	var $radios = jQuery('input[name="template[shipping_method]"]');
	if ($radios.length > 0 && !$radios.is(':checked')) {
		errors.push(alsendo_connect_templates.i18n_field_shipping_method);
	}

	var shippingMethod = jQuery('input[name="template[shipping_method]"]:checked').val() || '';
	if ('COURIER' === shippingMethod) {
		if (!jQuery('#alsendo_connect_template_pickup_hour_from').val()) {
			errors.push(alsendo_connect_templates.i18n_field_pickup_hour_from);
		}
		if (!jQuery('#alsendo_connect_template_pickup_hour_to').val()) {
			errors.push(alsendo_connect_templates.i18n_field_pickup_hour_to);
		}
	}

	return errors;
};

const alsendoClampHeight = function () {
	var $height = jQuery('#alsendo_connect_template_package_height');
	var max = parseInt($height.attr('max'), 10);
	if (max && parseInt($height.val(), 10) > max) {
		$height.val(max);
	}
};

const alsendoSaveTemplate = function () {
	if (true === alsendoIsSaving) {
		console.log('[Alsendo Templates] Save blocked - already saving');
		return;
	}

	alsendoClearDialogMessages();

	var validationErrors = alsendoValidateForm();
	if (validationErrors.length > 0) {
		alsendoShowDialogMessage(
			alsendo_connect_templates.i18n_fill_required + ' <strong>' + validationErrors.join(', ') + '</strong>',
			'error'
		);
		return;
	}

	alsendoSetSavingState(true);

	var serializedData = jQuery('#alsendoAddTemplateDialog :input').serializeArray();

	var setAsDefault = jQuery('#alsendo_connect_set_as_default').is(':checked') ? '1' : '0';
	serializedData.push({ name: 'template[set_as_default]', value: setAsDefault });

	console.log('[Alsendo Templates] Save button clicked');
	console.log('[Alsendo Templates] AJAX URL:', alsendo_connect_templates.ajax_url);
	console.log('[Alsendo Templates] Serialized payload:', serializedData);

	var dataObj = {};
	jQuery.each(serializedData, function(i, field) {
		dataObj[field.name] = field.value;
	});
	console.log('[Alsendo Templates] Payload as object:', dataObj);

	jQuery.ajax({
		url: alsendo_connect_templates.ajax_url,
		type: 'POST',
		dataType: 'json',
		data: serializedData
	})
		.done(function (response, textStatus, xhr) {
			console.log('[Alsendo Templates] Save success:', xhr.status, response);
			alsendoSetSavingState(false);
			alsendoShowDialogMessage(alsendo_connect_templates.i18n_saved, 'success');

			setTimeout(function () {
				alsendoSafeReload();
			}, 300);
		})
		.fail(function (xhr) {
			console.error('[Alsendo Templates] Save failed:', xhr.status, xhr.statusText);
			console.error('[Alsendo Templates] Response body:', xhr.responseText);

			var errorMsg = '';

			if (xhr.responseJSON) {
				console.log('[Alsendo Templates] Response JSON:', xhr.responseJSON);
				if (Array.isArray(xhr.responseJSON)) {
					jQuery.each(xhr.responseJSON, function (index, element) {
						if ('string' === typeof element || element instanceof String) {
							errorMsg += element + '<br>';
						} else if (element.message) {
							errorMsg += element.message + '<br>';
						}
					});
				} else if (typeof xhr.responseJSON === 'object' && xhr.responseJSON.message) {
					errorMsg = xhr.responseJSON.message;
				}
			}

			if (!errorMsg) {
			if (xhr.responseText === '0') {
				errorMsg = alsendo_connect_templates.i18n_ajax_not_found;
			} else {
				errorMsg = alsendo_connect_templates.i18n_server_error + ' (HTTP ' + xhr.status + ')';
			}
			}

			alsendoShowDialogMessage(errorMsg, 'error');
			alsendoSetSavingState(false);
		});
};

jQuery(document).ready(function ($) {

	console.log('[Alsendo Templates] Initializing...');
	console.log('[Alsendo Templates] Config:', typeof alsendo_connect_templates !== 'undefined' ? alsendo_connect_templates : 'NOT LOADED');

	if (!$('#alsendoAddTemplateDialog').length) {
		console.warn('[Alsendo Templates] Dialog element #alsendoAddTemplateDialog not found');
		return;
	}

	var alsendoCSS = document.createElement('style');
	alsendoCSS.textContent =
		'@keyframes alsendo-spin { to { transform: rotate(360deg); } }' +
		'.alsendo-spinner {' +
		'  display:inline-block;width:14px;height:14px;' +
		'  border:2px solid #ccc;border-top-color:#0073aa;' +
		'  border-radius:50%;animation:alsendo-spin .6s linear infinite;' +
		'  margin-right:6px;vertical-align:middle;' +
		'}' +
		'.ui-dialog[aria-describedby="alsendoAddTemplateDialog"] .ui-dialog-titlebar-close {' +
		'  display:none !important;' +
		'}' +
		'.alsendo-tpl-default-checkbox-row {' +
		'  display:flex;align-items:center;gap:6px;' +
		'  padding:8px 16px 0;font-size:13px;' +
		'}' +
		'.alsendo-tpl-default-checkbox-row input[type="checkbox"] {' +
		'  margin:0;' +
		'}' +
		'.alsendo-tpl-default-checkbox-row label {' +
		'  cursor:pointer;user-select:none;' +
		'}';
	document.head.appendChild(alsendoCSS);

	alsendoAddTemplateDialog = $('#alsendoAddTemplateDialog').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 680,
		position: { my: 'center', at: 'center', of: window },
		buttons: {
			Save: {
				text: alsendo_connect_templates.i18n_save,
				click: alsendoSaveTemplate,
				class: 'button button-primary'
			},
			Cancel: {
				text: alsendo_connect_templates.i18n_cancel,
				click: function () {
					alsendoAddTemplateDialog.dialog("close");
				},
				class: 'button'
			}
		},
		open: function () {
			alsendoAddTemplateDialog.dialog('option', 'position', { my: 'center', at: 'center', of: window });
		},
		close: function () {
			alsendoResetForm();
		}
	});

	var $buttonPane = alsendoAddTemplateDialog.closest('.ui-dialog').find('.ui-dialog-buttonpane');
	if ($buttonPane.length) {
		$buttonPane.prepend(
			'<div class="alsendo-tpl-default-checkbox-row">' +
			'<input type="checkbox" id="alsendo_connect_set_as_default" value="1">' +
			'<label for="alsendo_connect_set_as_default">' + alsendo_connect_templates.i18n_set_as_default + '</label>' +
			'</div>'
		);
	}

	$('#alsendo_connect_template_package_contents').on('change', alsendoToggleCustomText);
	$('#alsendo_connect_template_parcel_type').on('change', function () {
		alsendoSyncEcoletParcelTypeUi();
		alsendoOnParcelTypeChange();
		alsendoToggleDimensionsForParcelType();
		alsendoToggleNonStandardForEcolet();
	});
	$('body').on('change', 'input[name="template[parcel_type_mode]"]', alsendoUpdateParcelTypeFromEcoletUi);
	$('#alsendo_connect_ecolet_palette_type').on('change', alsendoUpdateParcelTypeFromEcoletUi);
	$('#alsendo_connect_template_package_height').on('input change', alsendoClampHeight);
	$('body').on('change', 'input[name="template[shipping_method]"]', alsendoTogglePickupHours);

	$('body').on('click', '#alsendo_connect_add_template_parcel', function (e) {
		e.preventDefault();
		alsendoAddAdditionalParcel({});
	});

	$('body').on('click', '.alsendo_remove_template_parcel', function (e) {
		e.preventDefault();
		var $wrap = $(this).closest('.alsendo-additional-parcel-wrap');
		$wrap.remove();
		// Keep count in sync with DOM size.
		alsendoAdditionalParcelsCount = $('#alsendo_connect_additional_parcels_container .alsendo-additional-parcel-wrap').length;
	});

	$('body').on('change', '#alsendo_connect_additional_parcels_container select[data-field="parcel_type"]', function () {
		var $wrap = $(this).closest('.alsendo-additional-parcel-wrap');
		alsendoApplyParcelTypeRules($wrap);
	});

	alsendoSyncEcoletParcelTypeUi();
	alsendoUpdateParcelTypeFromEcoletUi();
	alsendoToggleNonStandardForEcolet();

	$('#alsendo_connect_add_template').on('click', alsendoOnClickAddTemplate);
	$('body').on('click', '.alsendo_connect_edit_template', alsendoOnClickEditTemplate);
	$('body').on('click', '.alsendo_connect_delete_template', alsendoOnClickDeleteTemplate);
	$('body').on('click', '.alsendo_connect_set_default_template:not(.is-default)', alsendoOnClickSetDefault);

	console.log('[Alsendo Templates] Ready.');
});
