(function($){
	function openModal(modalId){
		var $m = $('#'+modalId);
		$m.addClass('active');
		// allow layout to apply before adding show for transition
		requestAnimationFrame(function(){
			$m.addClass('show');
		});
	}
	function closeModal($m){
		$m.removeClass('show');
		$m.one('transitionend webkitTransitionEnd oTransitionEnd', function(e){
			// Only act on the opacity transition of the container
			if (e.target === $m[0]) {
				$m.removeClass('active');
			}
		});
	}

	$(document).on('click', '.chcpl-inquiry-btn', function(){
		var $btn = $(this);
		var modalId = $btn.data('modal-id');
		var serviceId = $btn.data('service-id');
		var serviceName = $btn.data('service-name');
		var $modal = $('#'+modalId);
		$modal.find('input[name="service_id"]').val(serviceId);
		$modal.find('input[name="service_name"]').val(serviceName);
		$modal.find('.chcpl-service-name').text(serviceName);
		openModal(modalId);
	});

	$(document).on('click', '[data-show-panel]', function(){
		var panel = $(this).data('show-panel');
		var $card = $(this).closest('.chcpl-lock-card');
		$card.find('.chcpl-lock-main').toggle(panel === 'main');
		$card.find('.chcpl-lock-panel--form').toggle(panel === 'form');
		$card.find('.chcpl-lock-panel--pw').toggle(panel === 'pw');
	});

	$(document).on('click', '.chcpl-modal [data-close="true"]', function(){
		closeModal($(this).closest('.chcpl-modal'));
	});

	// Inquiry submit
	$(document).on('submit', '.chcpl-inquiry-form', function(e){
		e.preventDefault();
		var $form = $(this);
		var $status = $form.find('.chcpl-form-status');
		var $submitBtn = $form.find('button[type="submit"]');
		$status.text('');
		var data = $form.serialize();
		
		// Store original button text and add loading state
		var originalText = $submitBtn.html();
		if (!$submitBtn.data('original-text')) {
			$submitBtn.data('original-text', originalText);
		}
		$submitBtn.prop('disabled', true).addClass('chcpl-submit-loading');
		$submitBtn.html('<span class="chcpl-spinner"></span> ' + ($submitBtn.data('original-text') || originalText));
		
		var redirectUrl = $form.data('redirect-url') || '';
		$.post(CHCPL_Ajax.ajaxUrl, data)
			.done(function(resp){
				if (resp && resp.success) {
					if (redirectUrl && $form.hasClass('chcpl-access-form')) {
						window.location.href = redirectUrl;
						return;
					}
					$status.css('color','#16a34a').text(resp.data && resp.data.message ? resp.data.message : 'Envoyé.');
					$form[0].reset();
				} else {
					var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Erreur. Veuillez réessayer.';
					$status.css('color','#dc2626').text(msg);
				}
			})
			.fail(function(){
				$status.css('color','#dc2626').text('Erreur réseau.');
			})
			.always(function(){
				// Restore original button state
				var restoreText = $submitBtn.data('original-text') || originalText;
				$submitBtn.prop('disabled', false).removeClass('chcpl-submit-loading').html(restoreText);
			});
	});

    // Lock form submit (no cookies; replace content with unlocked HTML)
	$(document).on('submit', '.chcpl-lock-form', function(e){
		e.preventDefault();
		var $form = $(this);
		var $status = $form.find('.chcpl-form-status');
		var $submitBtn = $form.find('button[type="submit"]');
		$status.text('');
		var data = $form.serialize();
		
		// Store original button text and add loading state
		var originalText = $submitBtn.html();
		if (!$submitBtn.data('original-text')) {
			$submitBtn.data('original-text', originalText);
		}
		$submitBtn.prop('disabled', true).addClass('chcpl-submit-loading');
		$submitBtn.html('<span class="chcpl-spinner"></span> ' + ($submitBtn.data('original-text') || originalText));
		
		$.post(CHCPL_Ajax.ajaxUrl, data)
			.done(function(resp){
				if (resp && resp.success) {
					var $lockWrapper = $form.closest('.chcpl-lock');
					if (resp.data && resp.data.html && $lockWrapper.length) {
						// Replace the lock wrapper with the unlocked content
						var html = resp.data.html;
						if (typeof html === 'string' && html.trim().length > 0) {
							// Clean up the HTML and try to parse
							html = html.trim();
							var $newContent = $(html);
							if ($newContent.length > 0) {
								// Successfully parsed - replace the lock wrapper
								$lockWrapper.replaceWith($newContent);
								// Re-initialize any scripts that might be needed
								$(document).trigger('chcpl-list-unlocked');
							} else {
								// If jQuery parsing fails, try wrapping and replacing
								var $temp = $('<div>').html(html);
								if ($temp.children().length > 0) {
									$lockWrapper.replaceWith($temp.children());
								} else {
									// Last resort: replace inner HTML
									$lockWrapper.parent().html(html);
								}
							}
						} else {
							// Fallback: just show success message
							$status.css('color','#16a34a').text(resp.data && resp.data.message ? resp.data.message : 'Accès accordé.');
						}
					} else {
						// Fallback: just show success
						$status.css('color','#16a34a').text(resp.data && resp.data.message ? resp.data.message : 'Accès accordé.');
					}
				} else {
					// Error response - but check if HTML was provided anyway
					var $lockWrapper = $form.closest('.chcpl-lock');
					if (resp && resp.data && resp.data.html && typeof resp.data.html === 'string' && resp.data.html.trim().length > 0 && $lockWrapper.length) {
						// Try to use the HTML even if marked as error
						var html = resp.data.html.trim();
						var $newContent = $(html);
						if ($newContent.length > 0) {
							$lockWrapper.replaceWith($newContent);
							$(document).trigger('chcpl-list-unlocked');
							return; // Successfully replaced, exit early
						}
					}
					var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Mot de passe incorrect.';
					$status.css('color','#dc2626').text(msg);
					// Log for debugging
					if (resp && resp.data && resp.data.html) {
						console.log('CHCPL Unlock Error - HTML received:', resp.data.html.substring(0, 200));
					}
				}
			})
			.fail(function(xhr, status, error){
				console.error('CHCPL Unlock Error:', status, error, xhr.responseText);
				$status.css('color','#dc2626').text('Erreur réseau.');
			})
			.always(function(){
				// Restore original button state
				var restoreText = $submitBtn.data('original-text') || originalText;
				$submitBtn.prop('disabled', false).removeClass('chcpl-submit-loading').html(restoreText);
			});
	});

	// Hover Image Overlay - Disabled on mobile devices
	var isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || (window.innerWidth <= 1024 && 'ontouchstart' in window);
	
	if (!isMobileDevice) {
		var hoverOverlay = null;
		var hoverTimeout = null;

		function createHoverOverlay($service, imageUrl) {
			if (hoverOverlay) {
				hoverOverlay.remove();
			}
			hoverOverlay = $('<div class="chcpl-service-hover-overlay"><img src="' + imageUrl + '" alt="" /></div>');
			$('body').append(hoverOverlay);
			return hoverOverlay;
		}

		function positionHoverOverlay($service, $overlay) {
			var serviceOffset = $service.offset();
			var serviceWidth = $service.outerWidth();
			var serviceHeight = $service.outerHeight();
			var overlayWidth = $overlay.outerWidth();
			var overlayHeight = $overlay.outerHeight();
			var windowWidth = $(window).width();
			var windowHeight = $(window).height();
			var scrollTop = $(window).scrollTop();
			var scrollLeft = $(window).scrollLeft();

			// Default: position to the right of the service
			var left = serviceOffset.left + serviceWidth + 16;
			var top = serviceOffset.top;

			// If not enough space on right, position to the left
			if (left + overlayWidth > windowWidth + scrollLeft - 20) {
				left = serviceOffset.left - overlayWidth - 16;
			}

			// If not enough space on left either, position above
			if (left < scrollLeft + 20) {
				left = serviceOffset.left + (serviceWidth / 2) - (overlayWidth / 2);
				top = serviceOffset.top - overlayHeight - 16;
			}

			// If not enough space above, position below
			if (top < scrollTop + 20) {
				top = serviceOffset.top + serviceHeight + 16;
			}

			// Ensure it doesn't go below viewport
			if (top + overlayHeight > scrollTop + windowHeight - 20) {
				top = scrollTop + windowHeight - overlayHeight - 20;
			}

			// Ensure it doesn't go off left edge
			if (left < scrollLeft + 20) {
				left = scrollLeft + 20;
			}

			// Ensure it doesn't go off right edge
			if (left + overlayWidth > scrollLeft + windowWidth - 20) {
				left = scrollLeft + windowWidth - overlayWidth - 20;
			}

			$overlay.css({
				left: left + 'px',
				top: top + 'px'
			});
		}

		$(document).on('mouseenter', '.chcpl-service-has-image', function() {
			var $service = $(this);
			var imageUrl = $service.data('hover-image');
			if (!imageUrl) return;

			// Clear any existing timeout
			if (hoverTimeout) {
				clearTimeout(hoverTimeout);
				hoverTimeout = null;
			}

			// If overlay exists and has same image, just reposition it
			if (hoverOverlay && hoverOverlay.find('img').attr('src') === imageUrl) {
				positionHoverOverlay($service, hoverOverlay);
				hoverOverlay.addClass('active');
				return;
			}

			// Remove old overlay if exists
			if (hoverOverlay) {
				hoverOverlay.remove();
				hoverOverlay = null;
			}

			// Show overlay immediately
			var $overlay = createHoverOverlay($service, imageUrl);
			// Wait for image to load, then position
			$overlay.find('img').on('load', function() {
				positionHoverOverlay($service, $overlay);
				$overlay.addClass('active');
			});
			// If image already loaded
			if ($overlay.find('img')[0].complete) {
				positionHoverOverlay($service, $overlay);
				$overlay.addClass('active');
			}
		});

		$(document).on('mouseleave', '.chcpl-service-has-image', function(e) {
			if (hoverTimeout) {
				clearTimeout(hoverTimeout);
				hoverTimeout = null;
			}
			
			// Check if we're moving to another service with an image
			var relatedTarget = e.relatedTarget;
			var isMovingToService = false;
			
			if (relatedTarget) {
				var $related = $(relatedTarget);
				isMovingToService = $related.closest('.chcpl-service-has-image').length > 0;
			}
			
			// Also check if mouse is still over any service with image
			setTimeout(function() {
				var $hoveredService = $('.chcpl-service-has-image:hover');
				if ($hoveredService.length === 0 && hoverOverlay) {
					hoverOverlay.removeClass('active');
					setTimeout(function() {
						if (hoverOverlay) {
							hoverOverlay.remove();
							hoverOverlay = null;
						}
					}, 200);
				}
			}, 50);
		});

		// Reposition on scroll/resize
		$(window).on('scroll resize', function() {
			if (hoverOverlay && hoverOverlay.hasClass('active')) {
				var $service = $('.chcpl-service-has-image:hover');
				if ($service.length) {
					positionHoverOverlay($service, hoverOverlay);
				}
			}
		});
	}
})(jQuery);
