// source --> https://www.estoublon.com/wp-content/plugins/chronopost/public/js/chronoprecise.plugin.js?ver=4.2.1 
;(function($) {

	$.chronoprecise = function(el, options) {

		// Reference to ChronopostPublic utilities
		var ChronopostPublic = window.ChronopostPublic;

		var defaults = {
			navHtml: '<header class="rdvCarouselheader" id="rdvCarouselheader"><nav><a href="#" class="carousel-control prev" rel="prev">%prev_week_txt%</a><a href="#" class="carousel-control next" rel="next">%next_week_txt%</a></nav></header>'
		}

		var plugin = this;

		plugin.settings = {}

		var init = function() {
			plugin.firstLoaded = false;
			plugin.selectRdv = false;
			plugin.settings = $.extend({}, defaults, options);
			plugin.el = el;
			plugin.currentScreen = 1;
			plugin.totalScreen = $(plugin.el).find('#rdvCarouselContent .slide').length;
			plugin.initNavigation();
			plugin.initEvents();
			plugin.initMobileEvents();
			plugin.firstLoaded = true;
		}

		plugin.reload = function() {
			plugin.el = el;
			plugin.firstLoaded = true;
			plugin.currentScreen = 1;
			plugin.totalScreen = $(plugin.el).find('#rdvCarouselContent .slide').length;
			plugin.initNavigation();
			plugin.initEvents();
			plugin.initMobileEvents();
		}

		plugin.initEvents = function() {
      plugin.resetEvents();

			$(document.body).on('updated_checkout', function () {
				plugin.current_shipping_method = ChronopostPublic.getShippingMethodValue('input[name="shipping_method[0]"]');
				plugin.isActive = $('.appointment-link').length ? true : false;

				if (plugin.getShipAddress() != plugin.currentAddress && !plugin.loadingRdv && plugin.isActive && ! plugin.selectRdv) {
					plugin.loadingRdv = true,
						shipping_method = $('.appointment-link').closest('li').find('input[name="shipping_method[0]"]').val();
					$.ajax({
						type: 'POST',
						dataType: 'json',
						url: Chronoprecise.ajaxurl,
						cache: false,
						data: {
							'action': 'load_chronoprecise_appointment',
							'method_id' : shipping_method,
							'chrono_nonce' : Chronoprecise.chrono_nonce
						}
					})
						.done(function(output) {
							$('#outer-container-method-chronoprecise').html($(output.data).filter('#outer-container-method-chronoprecise').html());
							plugin.loadingRdv = false;
							$('#outer-container-method-chronoprecise').data('chronoprecise').reload();
							$(document).trigger('chronoprecise:slot_loaded');
							plugin.getScreen(plugin.currentScreen);
						});
				}
				setTimeout(function () {
					plugin.selectRdv = false;
				}, 200);
			});

			$(document.body).on('click', '.appointment-link a', function() {
				if (typeof plugin.loadingRdv != 'undefined' && plugin.loadingRdv) {
					$(document).on('chronoprecise:slot_loaded', function() {
						plugin.showFancybox();
						$(document).off('chronoprecise:slot_loaded');
					});
				} else {
					plugin.showFancybox();
				}
			});

			$(document.body).on('click', '.shipping_method_chronopostprecise', function() {
				plugin.selectRdv = true;
				plugin.selectChronopostSrdvSlot(this);
			});

			$(document.body).on('click', '#container-method-chronoprecise .carousel-control', function(event) {
				event.preventDefault();
				if (!$(this).is('.inactive')) {
					plugin.currentScreen = $(this).is('.next') ? plugin.currentScreen + 1 : plugin.currentScreen - 1;
					plugin.getScreen(plugin.currentScreen);
				}
			});
		}

		plugin.showFancybox = function() {
			$.fancybox.open({
				src  : '#container-method-chronoprecise',
				type : 'inline',
				// Clicked on the slide
				clickSlide : false,
				// Clicked on the background (backdrop) element
				touch: false
			});
		}

		plugin.resetEvents = function() {
      console.log("Reset events");
			//$( document.body ).off( 'updated_checkout');
      $(document.body).off('click', '.shipping_method_chronopostprecise');
      $(document.body).off('click', '#rdvCarouselheader .carousel-control');
			$('#global-mobile').off('click', 'th');
		}


		plugin.initMobileEvents = function() {
			$('#global-mobile').on('click', 'th', function(event){
				event.preventDefault();
				var $this = $(this);

				$('#global-mobile th').removeClass('active');
				$this.addClass('active');

				$('#time-list ul').hide();
				var idUlHoraireDay = $this.attr('id').replace("th","ul");
				$('#'+idUlHoraireDay).show();
			});
			$('#global-mobile th').eq(0).click();
		}

		var dateLeadingZero = function(date){
			return ('0' + date).slice(-2);
		}

		plugin.initNavigation = function() {
			plugin.settings.navHtml = plugin.settings.navHtml.replace('%prev_week_txt%', Chronoprecise.prev_week_txt).replace('%next_week_txt%', Chronoprecise.next_week_txt);
			if (plugin.totalScreen > 1) {
				$(plugin.el).find('#rdvCarousel').before(plugin.settings.navHtml);
			}
			plugin.getScreen(plugin.currentScreen);
		}

		plugin.getScreen = function(nb) {

			$('#rdvCarouselContent .slide')
				.removeClass('slide-active')
				.eq(nb - 1)
				.addClass('slide-active');
			$('#rdvCarouselheader .carousel-control')
				.removeClass('inactive')
			if (nb == 1) {
				$('#rdvCarouselheader .carousel-control.prev')
					.addClass('inactive');
			} else if (nb == plugin.totalScreen) {
				$('#rdvCarouselheader .carousel-control.next')
					.addClass('inactive');
			}
		}

		plugin.selectChronopostSrdvSlot = function(element) {

			$('#container-method-chronoprecise').addClass('slot-selected');

			var slotValue = $(element).data('slotvaluejson');

			var d = new Date(slotValue.deliveryDate);

			var thID = '#th_'+dateLeadingZero(d.getDate());
			thID += '-'+dateLeadingZero((d.getMonth() + 1));
			thID += '-'+d.getFullYear();

			$("#rdvCarousel .active").removeClass("active");

			var td = $(element).closest("td");
			var tr = td.closest("tr");
			var th = tr.find('th');

			th.addClass("active");
			$(thID).addClass("active");


			$("#global-mobile ul li.active").removeClass("active");

			var li = $(element).closest("li");
			li.addClass("active");

      console.log('Trigger chronoprecise:appointment_changed')
			$('#chronopostprecise_creneaux_info').val(JSON.stringify(slotValue));
      jQuery( document.body ).trigger('chronoprecise:appointment_changed', [ { slot: slotValue } ]);
			setTimeout(function() {
				jQuery( document.body ).trigger( 'update_checkout', { update_shipping_method: true });
			}, 5);
		}

		plugin.getShipAddress = function() {
			var address_1			 = $( 'input#billing_address_1' ).val(),
				address_2		 = $( 'input#billing_address_2' ).val(),
				postcode		 = $( 'input#billing_postcode' ).val(),
				city		 = $( 'input#billing_city' ).val(),
				country      = $( '#billing_country' ).val();

			if ( $( '#ship-to-different-address' ).find( 'input' ).is( ':checked' ) ) {
				address_1		 = $( 'input#shipping_address_1' ).val();
				address_2		 = $( 'input#shipping_address_2' ).val();
				postcode		 = $( 'input#shipping_postcode' ).val();
				city		 = $( 'input#shipping_city' ).val();
				country      = $( '#shipping_country' ).val();
			}

			var ship_address = address_1;
			if (address_2 != '') {
				ship_address += ' ' + address_2;
			}

			return ship_address + ' ' + postcode + ' ' + city + ' ' + country;
		}

		init();
	}

	$.fn.chronoprecise = function (options) {
		return this.each(function() {
			if (undefined == $(this).data('chronoprecise')) {
				var plugin = new $.chronoprecise(this, options);
				$(this).data('chronoprecise', plugin);
				if(options && options.openRdv){
					plugin.showFancybox();
				}

			}
		});
	}

})(jQuery);
// source --> https://www.estoublon.com/wp-content/plugins/chronopost/public/js/chronopost-public.js?ver=4.2.1 
/**
 * Chronopost public utilities namespace
 */
window.ChronopostPublic = window.ChronopostPublic || {};

/**
 * Get value from shipping method input, handling both radio and hidden types
 * WooCommerce switches radio inputs to hidden inputs when only one shipping option is available.
 * This function handles both cases correctly.
 *
 * @param {string} selector - jQuery selector for the input element(s)
 * @return {string|null} The value of the input, or null if not found
 */
window.ChronopostPublic.getShippingMethodValue = function(selector) {
	let $input = jQuery(selector);
	if ($input.length === 0) return null;

	// For radio inputs, get the checked one
	if ($input.first().attr('type') === 'radio') {
		return $input.filter(':checked').val();
	}
	// For hidden inputs, just get the value
	return $input.val();
};

(function ($) {
	'use strict';

	$(document).ready(function () {
		// Function to reset modal states
		function resetModalStates() {
			loadingMap = false;
			loadingRdv = false;
			$('#container-method-chronorelay').remove();
			$('#outer-container-method-chronoprecise').remove();
		}

		// Function to detect if we're in Gutenberg block checkout mode
		function isGutenbergCheckout() {
			return $('.wc-block-checkout').length > 0 || (window.wp && window.wp.data);
		}

		// Classic WooCommerce checkout events
		$('body').on('updated_checkout', function () {
			if (!$('#saturday_shipping').length) {
				$('#saturday_shipping_field_enable').val('no');
			}
			// Only reset modal states in Gutenberg mode to prevent fancybox re-opening issues
			if (isGutenbergCheckout()) {
				resetModalStates();
			}
		});

		// Gutenberg blocks checkout - listen for shipping method changes
		if (isGutenbergCheckout()) {
			let previousShippingMethods = [];

			const unsubscribe = window.wp.data.subscribe(() => {
				try {
					const store = window.wp.data.select('wc/store/cart');
					if (store && store.getCartData) {
						const cartData = store.getCartData();
						const currentMethods = cartData.shippingRates ?
							cartData.shippingRates.flatMap(rateGroup =>
								rateGroup.shipping_rates ? rateGroup.shipping_rates.filter(rate => rate.selected).map(rate => rate.rate_id) : []
							) : [];

						// Compare with previous methods
						const methodsChanged = JSON.stringify(currentMethods) !== JSON.stringify(previousShippingMethods);

						if (methodsChanged) {
							console.log('Shipping methods changed in Gutenberg checkout, resetting modal states');
							resetModalStates();
							previousShippingMethods = currentMethods;
						}
					}
				} catch (error) {
					// Silently handle any errors accessing WooCommerce store
				}
			});
		}
		$(document.body).on('change', '#saturday_shipping', function () {
			if (!$('form.checkout #saturday_shipping_field_enable').length) {
				$('form.checkout').append('<input type="hidden" name="saturday_shipping_field_enable" id="saturday_shipping_field_enable">');
			}

			$('#saturday_shipping_field_enable').val($(this).prop('checked') ? 'yes' : 'no');

			$( document.body ).trigger( 'update_checkout', { update_shipping_method: true });
		});

		var loadingMap = false,
			loadingRdv = false,
			shipping_method;

		/**
		 * Legacy AJAX function for ChronoPrecise appointment loading
		 * @param {string} shipping_method - Shipping method ID
		 * @param {number} instance_id - Instance ID
		 * @param {string} blockTarget - jQuery selector for blocking target
		 */
		function loadChronoPreciseLegacy(shipping_method, instance_id, blockTarget) {
			$.ajax({
				type: 'POST',
				dataType: 'json',
				url: Chronomap.ajaxurl,
				cache: false,
				data: {
					'action': 'load_chronoprecise_appointment',
					'method_id': shipping_method,
					'instance_id': instance_id,
					'chrono_nonce': Chronomap.chrono_nonce
				},
				error: function(jqXHR, error, errorThrown) {
					if (jqXHR.status && jqXHR.status == 400) {
						alert(jqXHR.responseText);
					} else {
						alert(Chronoprecise.error_cant_reach_server);
					}
					loadingRdv = false;
					$(blockTarget).unblock();
				}
			})
			.done(function (output) {
				if (output.status === 'success') {
					// Create container for the appointment picker
					let inserted = false;

					if ($('#payment').length) {
						$(output.data).insertBefore('#payment');
						inserted = true;
					}

					// Initialize the appointment picker if container was successfully inserted
					if (inserted && $('#outer-container-method-chronoprecise').length) {
						$('#outer-container-method-chronoprecise').chronoprecise({openRdv: true});
					} else if (!inserted) {
						console.error('Could not find suitable DOM insertion point for appointment container');
						$('body').prepend('<div class="pickup-relay-error woocommerce-error">Error displaying appointment selector. Please try again.</div>');
					}
				} else {
					// Enhanced error display for both checkout types
					const errorContainer = $('form.checkout').length ? 'form.checkout' : '.wc-block-checkout, body';
					$(errorContainer).prepend('<div class="pickup-relay-error woocommerce-error">' + output.data + '</div>');

					// Scroll to error (if not in body)
					if (errorContainer !== 'body') {
						$('html, body').animate({
							scrollTop: ($(errorContainer).offset().top - 100)
						}, 1000);
					}
					$(document.body).trigger('checkout_error');
				}
				loadingRdv = false;
				$(blockTarget).unblock();
			});
		}

		if ($('.chronorelaismap').length) {
			$('.chronorelaismap').chronomap();
		}
		if ($('#outer-container-method-chronoprecise').length) {
			$('#outer-container-method-chronoprecise').chronoprecise();
		}

		$(document.body).on('click', '.appointment-link, .chronopost-precise-slot-picker button', function (event) {
			// (let chronoprecise.plugin.js handle fancybox opening for existing containers)
			if ($(event.target).is('a')
        && $(event.target).closest('.appointment-link').length
        && $('#outer-container-method-chronoprecise').length) {
				return;
			}
			if (!$('#outer-container-method-chronoprecise').length && !loadingRdv) {
        $('.pickup-relay-error').remove();
        loadingRdv = true;

        // Enhanced shipping method detection for Gutenberg + Classic compatibility
        let shipping_method = null;
        let instance_id = null;

        // Method 1: Check for data attribute (Gutenberg blocks)
        if ($(event.target).data('method-id')) {
          shipping_method = $(event.target).data('method-id');
          console.log('Using Gutenberg data attribute:', shipping_method);
        }

        // Method 2: Original DOM traversal (Classic checkout)
        if (!shipping_method) {
          shipping_method = $(event.target).closest('li').find('input[name="shipping_method[0]"]').val();
          console.log('Using classic DOM traversal:', shipping_method);
        }

        // Method 3: Fallback - find any selected shipping method
        if (!shipping_method) {
          shipping_method = window.ChronopostPublic.getShippingMethodValue('input[name="shipping_method[0]"]');
          console.log('Using fallback selected method:', shipping_method);
        }

        // Get instance ID from data attribute or closest appointment link
        instance_id = $(this).data('instance-id') || $('.appointment-link').data('instance-id');

        // If still no method found, show error
        if (!shipping_method) {
          console.error('No shipping method found for appointment selection');
          $('form.checkout, .wc-block-checkout').prepend('<div class="pickup-relay-error woocommerce-error">Unable to determine shipping method. Please try again.</div>');
          loadingRdv = false;
          return;
        }

        // Enhanced blocking for both checkout types
        const blockTarget = $('.woocommerce-checkout-review-order-table').length ?
          '.woocommerce-checkout-review-order-table' : '.chronopost-container';
        $(blockTarget).block({
          message: null,
          overlayCSS: {
            background: "#fff",
            opacity: .6
          }
        });

        // Try to use REST API client if available, otherwise fallback to legacy AJAX
        if (window.chronoPreciseEnhanced && typeof ChronoPreciseRest !== 'undefined' && ChronoPreciseRest.useRestApi) {
          console.log('ChronoPrecise: Using REST API approach');

          window.chronoPreciseEnhanced.loadAppointmentModal(instance_id, shipping_method)
            .then(() => {
              // Success - unblock UI
              $(blockTarget).unblock();
              loadingRdv = false;
              $('#outer-container-method-chronoprecise').remove();
            })
            .catch((error) => {
              console.error('ChronoPrecise: REST API failed, using legacy fallback:', error);
              // Fallback to legacy AJAX
              loadChronoPreciseLegacy(shipping_method, instance_id, blockTarget);
            });
        } else {
          console.log('ChronoPrecise: Using legacy AJAX approach');
          loadChronoPreciseLegacy(shipping_method, instance_id, blockTarget);
        }
        event.preventDefault();
      }
    });

		$(document.body).on('click', '.pickup-relay-link, .chronopost-button--pickup', function (event) {
			if (!$('#container-method-chronorelay').length && !loadingMap) {
				$('.pickup-relay-error').remove();
				loadingMap = true;

				// Enhanced shipping method detection for Gutenberg + Classic compatibility
				let shipping_method = null;

				// Method 1: Check for data attribute (Gutenberg blocks)
				if ($(event.target).data('method-id')) {
					shipping_method = $(event.target).data('method-id');
				}

				// Method 2: Original DOM traversal (Classic checkout)
				if (!shipping_method) {
					shipping_method = $(event.target).closest('li').find('input[name="shipping_method[0]"]').val();
					console.log('Using classic DOM traversal:', shipping_method);
				}

				// Method 3: Fallback - find any selected shipping method
				if (!shipping_method) {
					shipping_method = window.ChronopostPublic.getShippingMethodValue('input[name="shipping_method[0]"]');
					console.log('Using fallback selected method:', shipping_method);
				}

				// If still no method found, show error
				if (!shipping_method) {
					console.error('No shipping method found for pickup relay selection');
					$('form.checkout, .wc-block-checkout').prepend('<div class="pickup-relay-error woocommerce-error">Unable to determine shipping method. Please try again.</div>');
					loadingMap = false;
					$('#container-method-chronorelay').remove();
					return;
				}

				// Try to use REST API client if available, otherwise fallback to legacy AJAX
				if (window.chronoRelaisEnhanced && typeof ChronoRelaisRest !== 'undefined' && ChronoRelaisRest.useRestApi) {
					console.log('ChronoRelais: Using REST API approach');

					window.chronoRelaisEnhanced.loadPickupRelayMap(shipping_method)
						.then(() => {
							// Success - unblock UI
							loadingMap = false;
						})
						.catch((error) => {
							console.error('ChronoRelais: REST API failed, using legacy fallback:', error);
							// Fallback to legacy AJAX
							loadChronoRelaisLegacy(shipping_method);
						});
				} else {
					console.log('ChronoRelais: Using legacy AJAX approach');
					loadChronoRelaisLegacy(shipping_method);
				}
				event.preventDefault();
			}
		});

	});

	/**
	 * Legacy AJAX function for ChronoRelais map loading
	 * @param {string} shipping_method - Shipping method ID
	 */
	function loadChronoRelaisLegacy(shipping_method) {
    let loadingMap = false;
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: Chronomap.ajaxurl,
			cache: false,
			data: {
				'action': 'load_chronorelais_picker',
				'method_id': shipping_method,
				'chrono_nonce': Chronomap.chrono_nonce
			}
		})
		.done(function (output) {
			if (output.status == 'success') {
				// Enhanced DOM insertion for Gutenberg + Classic compatibility
				let inserted = false;

				// Method 1: Classic checkout - insert before #payment
				if ($('#payment').length) {
					$(output.data).insertBefore('#payment');
					inserted = true;
				}

				// Initialize the map if container was successfully inserted
				if (inserted && $('#container-method-chronorelay').length) {
					$('.chronorelaismap').chronomap({openMap: true});
				} else if (!inserted) {
					console.error('Could not find suitable DOM insertion point for pickup relay container');
					$('body').prepend('<div class="pickup-relay-error woocommerce-error">Error displaying pickup point selector. Please try again.</div>');
				}
			} else {
				// Enhanced error display for both checkout types
				const errorContainer = $('form.checkout').length ? 'form.checkout' : '.wc-block-checkout, body';
				$(errorContainer).prepend('<div class="pickup-relay-error woocommerce-error">' + output.data + '</div>');

				// Scroll to error (if not in body)
				if (errorContainer !== 'body') {
					$('html, body').animate({
						scrollTop: ($(errorContainer).offset().top - 100)
					}, 1000);
				}
				$(document.body).trigger('checkout_error');
			}
			loadingMap = false;
		});
	}

})(jQuery);