jQuery(document).ready(function ($) {
	var checkLibraries = setInterval(function () {
		if (
			typeof persianDate !== 'undefined' &&
			typeof $.fn.persianDatepicker !== 'undefined'
		) {
			clearInterval(checkLibraries);
			initDatepickers();
		}
	}, 100);

	function initDatepickers() {
		var $dateInputs = $('#dobare_birth_date, #dobare_marriage_date');

		if ($dateInputs.length === 0) {
			return;
		}

		$dateInputs.each(function () {
			var $currentInput = $(this);

			$currentInput.persianDatepicker({
				initialValue: false,
				format: 'YYYY/MM/DD',
				autoClose: true,
				persianDigit: false,
				viewMode: 'day',
				minDate: new Date(1300, 1, 1),
				maxDate: new Date(),
				calendar: {
					persian: {
						locale: 'fa',
					},
				},
				navigator: {
					enabled: true,
				},
				toolbox: {
					enabled: true,
					calendarSwitch: {
						enabled: false,
					},
					todayButton: {
						enabled: true,
						text: {
							fa: 'امروز',
						},
					},
				},
				timePicker: {
					enabled: false,
				},
				onSelect: function (unix) {
					var selectedDate = new Date(unix);
					var pd = new persianDate(selectedDate);
					var persianValue = pd.format('YYYY/MM/DD');
					var gregorianDate =
						selectedDate.getFullYear() +
						'-' +
						String(selectedDate.getMonth() + 1).padStart(2, '0') +
						'-' +
						String(selectedDate.getDate()).padStart(2, '0');

					$currentInput.val(persianValue);
					$currentInput.attr('data-gregorian-value', gregorianDate);
					$currentInput.data('original-gregorian', gregorianDate);
				},
			});
		});

		$dateInputs.each(function () {
			var $input = $(this);
			var gregorianValue = $input.attr('data-gregorian-value');

			if (gregorianValue && gregorianValue !== '') {
				try {
					var parts = gregorianValue.split('-');
					if (parts.length === 3) {
						var gDate = new Date(
							parseInt(parts[0]),
							parseInt(parts[1]) - 1,
							parseInt(parts[2]),
						);
						var pd = new persianDate(gDate);
						var persianValue = pd.format('YYYY/MM/DD');
						$input.val(persianValue);
						$input.data('original-gregorian', gregorianValue);
					}
				} catch (e) {
					// Silent fail
				}
			}
		});
	}

	$('form.woocommerce-EditAccountForm').on('submit', function (e) {
		$('#dobare_birth_date, #dobare_marriage_date').each(function () {
			var $input = $(this);
			var inputName = $input.attr('name');
			var persianValue = $input.val();
			var gregorianValue = $input.attr('data-gregorian-value');

			if (!gregorianValue || gregorianValue === '') {
				gregorianValue = $input.data('original-gregorian');
			}

			if (
				(!gregorianValue || gregorianValue === '') &&
				persianValue &&
				persianValue !== ''
			) {
				try {
					var normalizedValue = persianValue
						.replace(/۰/g, '0')
						.replace(/۱/g, '1')
						.replace(/۲/g, '2')
						.replace(/۳/g, '3')
						.replace(/۴/g, '4')
						.replace(/۵/g, '5')
						.replace(/۶/g, '6')
						.replace(/۷/g, '7')
						.replace(/۸/g, '8')
						.replace(/۹/g, '9');

					var parts = normalizedValue.split('/');
					if (parts.length === 3) {
						var pd = new persianDate([
							parseInt(parts[0]),
							parseInt(parts[1]),
							parseInt(parts[2]),
						]);
						gregorianValue = pd
							.toCalendar('gregorian')
							.format('YYYY-MM-DD');
					}
				} catch (e) {
					// Silent fail
				}
			}

			if (gregorianValue && gregorianValue !== '') {
				$('input[name="' + inputName + '_gregorian"]').remove();

				$input.after(
					'<input type="hidden" name="' +
						inputName +
						'" value="' +
						gregorianValue +
						'">',
				);

				$input.removeAttr('name');
			}
		});
	});
});
