(function () {

	'use strict';

	let picker,
		calendars = {},
		settings = {
			selector: '.appointment-calendar',
			datesFilter: true,
			pastDates: false,
			layout: window.JetAPBData.layout,
			weekDays: window.JetAPBData.week_days,
			timeFormat: window.JetAPBData.time_format,
			weekStart: window.JetAPBData.start_of_week,
			scrollToDetails: window.JetAPBData.scroll_to_details,
			api: window.JetAPBData.api,
			multiBooking: window.JetAPBData.multi_booking,
			services: window.JetAPBData.services,
			providers: window.JetAPBData.providers,
			UTCOffset: parseFloat( window.JetAPBData.utc_offset ),
			namespace: '',
			accessibility_labels: window.JetAPBData.accessibility_labels,
		};

	if ( window.JetAPBData.months ) {
		settings.months = window.JetAPBData.months;
	}

	if ( window.JetAPBData.shortWeekday ) {
		settings.shortWeekday = window.JetAPBData.shortWeekday;
	}

	const getProviderCalculatedValue = function( value, $field ) {
		if ( ! $field || ! $field.length ) {
			return value;
		}

		const fieldNode = $field[ 0 ];
		// Handle classic select-based provider field.
		if ( fieldNode && 'SELECT' === fieldNode.nodeName && fieldNode.classList.contains( 'appointment-provider' ) ) {
			const selectedOption = fieldNode.options && fieldNode.options[ fieldNode.selectedIndex ]
				? fieldNode.options[ fieldNode.selectedIndex ]
				: null;
			const calculatedValue = selectedOption ? selectedOption.getAttribute( 'data-calculate' ) : null;
			if ( null !== calculatedValue && '' !== calculatedValue ) {
				return calculatedValue;
			}
			return value;
		}
		// Handle custom-template provider fields rendered as radio/checkbox inputs.
		if ( fieldNode ) {
			// If the field itself is an input, normalise to a collection; otherwise, search within it.
			var $providerInputs;
			if ( fieldNode.nodeName === 'INPUT' && fieldNode.classList.contains( 'appointment-provider' ) ) {
				$providerInputs = jQuery( fieldNode );
			} else {
				$providerInputs = jQuery( fieldNode ).find( 'input.appointment-provider[type="radio"], input.appointment-provider[type="checkbox"]' );
			}
			if ( $providerInputs && $providerInputs.length ) {
				var $checked = $providerInputs.filter( ':checked' ).first();
				if ( $checked && $checked.length ) {
					var calculatedValueInput = $checked.attr( 'data-calculate' );
					if ( null !== calculatedValueInput && '' !== calculatedValueInput ) {
						return calculatedValueInput;
					}
				}
			}
		}

		return value;
	};

	const calcFiledValue = function( value, $field ) {
				value = getProviderCalculatedValue( value, $field );

				if ( 'appointment' === $field.data( 'field' ) ) {
					let outputValue = 0,
						parseValue = value ? JSON.parse( value ) : 0;

				if( typeof parseValue === 'object' ){
					for ( const slot of parseValue ) {
						let price = parseFloat( slot.price );
						let count = slot.count || 1;

						outputValue += price * count;
					}

					value = outputValue;
				}
			}

			return value;
		},
		bookingFormIinit = function( e, $el ) {

			let $cal = $el.find( '.appointment-calendar' ),
			$form = $el.find( 'form' );

			if ( ! $cal.length || ! $form.length ) {
				return;
			}

			let formId = $form.data('form-id');

			if ( calendars[formId] && calendars[formId].destroy ) {
				calendars[formId].destroy();
			}

			settings.namespace = e.data.namespace;

			if ( window.JetPlugins ) {
				window.JetPlugins.hooks.applyFilters( 'jet-apb.calendar-settings', settings, e, $el );
			}

			settings.selector = `[data-form-id="${formId}"] .appointment-calendar`;
			calendars[formId] = new VanillaCalendar( settings );

			if( settings.namespace === "jet-form-builder" && window.JetFormBuilderMain ){
				JetFormBuilderMain.filters.addFilter( 'forms/calculated-field-value', calcFiledValue );
			} else {
				JetEngine.filters.addFilter( 'forms/calculated-field-value', calcFiledValue );
			}


		},

		afterBookingFormIinit = function (e, $el) {

			const $cal  = $el.find('.appointment-calendar');
			const $form = $el.find('form');

			if ( ! $cal.length || ! $form.length) {
				return;
			} 

			const formId    = $form.data('form-id');
			const inputName = $cal.data('args').inputName;

			const jfb = window.JetFormBuilder?.[formId];
			if ( ! jfb?.dataInputs?.[inputName] ) {
				return;
			} 

			const input = jfb.dataInputs[inputName];

			input.value.watch( function () {
				setTimeout( () => {
					input.reportOnBlur();
				}, 0 );
			} );
		};

	jQuery( document ).on( 'jet-engine/booking-form/init', { namespace: "jet-form" }, bookingFormIinit );
	jQuery( document ).on( 'jet-form-builder/init', { namespace: "jet-form-builder" }, bookingFormIinit );
	jQuery( document ).on( 'jet-form-builder/after-init', { namespace: "jet-form-builder" }, afterBookingFormIinit );

}());
