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

	/***********************************************************
    // Start Create Edit Form Page Tooltip && FullScreen View //

	// Helper: create tooltip
	function createTooltip($col, message, positionClass, alignCenter = false) {
		const $tooltip = $('<div class="wordform-tooltip ' + positionClass + '">' + message + '</div>');
		$('body').append($tooltip);

		function positionTooltip() {
			const offset = $col.offset();
			const tooltipHeight = $tooltip.outerHeight();
			const tooltipWidth = $tooltip.outerWidth();
			let leftPos = offset.left;

			// Center horizontally if requested
			if (alignCenter) {
			leftPos = offset.left + ($col.outerWidth() / 2) - (tooltipWidth / 2);
			}

			$tooltip.css({
			top: offset.top - tooltipHeight - 10, // 10px above
			left: leftPos
			});
		}

		positionTooltip();
		$tooltip.addClass('show');

		// Reposition on scroll/resize for responsiveness
		jQuery(window).on('scroll resize', positionTooltip);

		return $tooltip;
	}

	// Only run if wrappers exist
	jQuery(function($) {
		const $leftCol = $('.wordform-draggable-elements-div-wrapper');
		const $middleCol = $('.wordform-builder-div-wrapper');
		const $rightCol = $('.wordform-builder-form-options-div-wrapper');

		const $fullscreenBtn = $('.wordform-fullscreen-btn');
  		const fullscreenWrapper = document.querySelector('.wordform-fullscreen-wrapper');  // WordPress admin container		  		

		if ($leftCol.length) {
			createTooltip(
			$leftCol,
			'Drag to DropZone or click to add',
			'wordform-tooltip-left'
			);
		}

		if ($middleCol.length) {
			createTooltip(
			$middleCol,
			'DropZone — Drag elements here',
			'wordform-tooltip-middle',
			true // center horizontally
			);
		}

		if ($rightCol.length) {
			createTooltip(
			$rightCol,
			'Customize form fields',
			'wordform-tooltip-right'
			);
		}		

		// Full Screen View

		// Rendering Full Screen CSS elements
		let originalStyles = {};
		function applyFullscreenStyles(el) {
			// Save original styles only once
			if (!originalStyles.width) {
				originalStyles = {
					width: el.style.width || '',
					height: el.style.height || '',
					overflowY: el.style.overflowY || '',
					overflowX: el.style.overflowX || '',
					padding: el.style.padding || '',
					background: el.style.background || ''
				};
			}
			// Apply fullscreen styles
			el.style.width = '100vw';
			el.style.height = '100vh';
			el.style.overflowY = 'auto';
			el.style.overflowX = 'hidden';
			el.style.padding = '20px';
			el.style.background = '#f1f1f1';
		}

		// Restore original styles
		function restoreOriginalStyles(el) {
			for (let prop in originalStyles) {
				el.style[prop] = originalStyles[prop];
			}
		}

		// Toggle Full Screen View
		function toggleFullScreen() {
			if (!document.fullscreenElement) {
				// Apply styles before entering fullscreen
				applyFullscreenStyles(fullscreenWrapper);

				// Enter fullscreen
				fullscreenWrapper.requestFullscreen?.();

				$fullscreenBtn.find('i').removeClass('fa-expand').addClass('fa-compress');
				$fullscreenBtn.contents().last()[0].textContent = ' Exit Full Screen';
			} else {
				// Exit fullscreen
				document.exitFullscreen?.();
				$fullscreenBtn.find('i').removeClass('fa-compress').addClass('fa-expand');
				$fullscreenBtn.contents().last()[0].textContent = ' Full Screen';
			}
		}

		// Click Full Screen Button
		$fullscreenBtn.on('click', toggleFullScreen);
		// On Change FullScreen
		document.addEventListener('fullscreenchange', function() {
			if (!document.fullscreenElement) {
				// Restore original styles when exiting fullscreen
				restoreOriginalStyles(fullscreenWrapper);				

				$fullscreenBtn.find('i').removeClass('fa-compress').addClass('fa-expand');
				$fullscreenBtn.contents().last()[0].textContent = ' Full Screen';
			}
		});
		
	}); // jQuery(function($)
	
	// End Tooltip && FullScreen View //
	**************************************************************************************/

	// Start Create Edit Form Page Tooltip && FullScreen View //

	// Helper: create tooltip
	function createTooltip($col, message, positionClass, alignCenter = false, appendTarget = 'body') {
		const $tooltip = $('<div class="wordform-tooltip ' + positionClass + '">' + message + '</div>');
		$(appendTarget).append($tooltip);

		function positionTooltip() {
			const offset = $col.offset();
			if (!offset) return; // safety check if element not in DOM
			const tooltipHeight = $tooltip.outerHeight();
			const tooltipWidth = $tooltip.outerWidth();
			let leftPos = offset.left;

			// Center horizontally if requested
			if (alignCenter) {
				leftPos = offset.left + ($col.outerWidth() / 2) - (tooltipWidth / 2);
			}

			$tooltip.css({
				top: offset.top - tooltipHeight - 10, // 10px above
				left: leftPos
			});
		}

		positionTooltip();
		$tooltip.addClass('show');

		// Reposition on scroll/resize for responsiveness
		jQuery(window).on('scroll resize', positionTooltip);

		return $tooltip;
	}

	// Only run if wrappers exist
	jQuery(function($) {
		const $leftCol = $('.wordform-draggable-elements-div-wrapper');
		const $middleCol = $('.wordform-builder-div-wrapper');
		const $rightCol = $('.wordform-builder-form-options-div-wrapper');

		const $fullscreenBtn = $('.wordform-fullscreen-btn');
		const fullscreenWrapper = document.querySelector('.wordform-fullscreen-wrapper');  // WordPress admin container		  
		let appendTarget = 'body'; // default append target

		// Init tooltips (normal mode)
		function initTooltips() {
			// Remove old tooltips
			$('.wordform-tooltip').remove();

			if ($leftCol.length) {
				createTooltip($leftCol, 'Drag to DropZone or click to add', 'wordform-tooltip-left', false, appendTarget);
			}

			if ($middleCol.length) {
				createTooltip($middleCol, 'DropZone — Drag elements here', 'wordform-tooltip-middle', true, appendTarget);
			}

			if ($rightCol.length) {
				createTooltip($rightCol, 'Customize form fields', 'wordform-tooltip-right', true, appendTarget);
			}
		}

		// Full Screen View

		// Rendering Full Screen CSS elements
		let originalStyles = {};
		function applyFullscreenStyles(el) {
			if (!originalStyles.width) {
				originalStyles = {
					width: el.style.width || '',
					height: el.style.height || '',
					overflowY: el.style.overflowY || '',
					overflowX: el.style.overflowX || '',
					padding: el.style.padding || '',
					background: el.style.background || ''
				};
			}
			el.style.width = '100vw';
			el.style.height = '100vh';
			el.style.overflowY = 'auto';
			el.style.overflowX = 'hidden';
			el.style.padding = '20px';
			el.style.background = '#f1f1f1';
		}

		function restoreOriginalStyles(el) {
			for (let prop in originalStyles) {
				el.style[prop] = originalStyles[prop];
			}
		}

		// Toggle Full Screen View
		function toggleFullScreen() {
			if (!document.fullscreenElement) {
				applyFullscreenStyles(fullscreenWrapper);
				fullscreenWrapper.requestFullscreen?.();

				$fullscreenBtn.find('i').removeClass('fa-expand').addClass('fa-compress');
				$fullscreenBtn.contents().last()[0].textContent = ' Exit Full Screen';
			} else {
				document.exitFullscreen?.();
				$fullscreenBtn.find('i').removeClass('fa-compress').addClass('fa-expand');
				$fullscreenBtn.contents().last()[0].textContent = ' Full Screen';
			}
		}

		// Click Full Screen Button
		$fullscreenBtn.on('click', toggleFullScreen);

		// On Change FullScreen
		document.addEventListener('fullscreenchange', function() {
			if (document.fullscreenElement === fullscreenWrapper) {
				// In fullscreen mode, append tooltips inside fullscreen wrapper
				appendTarget = fullscreenWrapper;
				initTooltips();
			} else {
				// Restore original styles + reset tooltips back to body
				restoreOriginalStyles(fullscreenWrapper);
				appendTarget = 'body';
				initTooltips();
				
				// Update button state for normal mode
				$fullscreenBtn.find('i').removeClass('fa-compress').addClass('fa-expand');
				$fullscreenBtn.contents().last()[0].textContent = ' Full Screen';				
			}
		});

		// Initialize tooltips on load
		initTooltips();

	}); // jQuery(function($)

	// End Tooltip && FullScreen View //




	// Start Connector Arrow Line Between Elements //
	
	(function ($) {
	// Ensure jQuery present
	if (typeof $ === 'undefined') return;

	// Create SVG once on DOM ready
	$(function () {
		if ($('#wordform-connector-svg').length === 0) {
		const svgHtml = `
			<svg id="wordform-connector-svg" class="wordform-connector-svg" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
			<defs>
				<!-- small lightweight arrowhead (updated) -->
				<marker id="wordform-arrowhead" markerUnits="strokeWidth"
						markerWidth="8" markerHeight="8" refX="6" refY="4" orient="auto">
				<path d="M0,0 L8,4 L0,8 z" fill="#0a66d1" opacity="0.92" />
				</marker>
			</defs>
			<path id="wordform-connector-path" stroke="#0a66d1" stroke-width="2" fill="none" marker-end="url(#wordform-arrowhead)"></path>
			</svg>
		`;
		$('body').append(svgHtml);
		}

		// Ensure SVG appended to body (avoid stacking issues)
		const $svg = $('#wordform-connector-svg').appendTo(document.body);
		const $path = $('#wordform-connector-path');
		let rafId = null;
		let activeEl = null;

		// ... your connector creation code that appends #wordform-connector-svg ...
		// Immediately after that:
		const stopFs = enableFullscreenSvgReconcile();
		// store stopFs if you need to disable later:
		window.__stopFsReconcile = stopFs;
		

		// Geometry helpers
		function getMidRight($el) {
		const rect = $el[0].getBoundingClientRect();
		return { x: rect.right, y: rect.top + rect.height / 2 };
		}
		function getMidLeft($el) {
		const rect = $el[0].getBoundingClientRect();
		return { x: rect.left, y: rect.top + rect.height / 2 };
		}
		function getTopLeftPanelAnchor($el) {
		const rect = $el[0].getBoundingClientRect();
		return {
			x: rect.left + 12,
			y: rect.top + 28
		};
		}

		// Smooth cubic bezier
		function makeBezierPath(start, end) {
		const dx = Math.max(32, Math.abs(end.x - start.x) * 0.4);
		const sx = start.x + dx;
		const ex = end.x - dx;
		return `M ${start.x} ${start.y} C ${sx} ${start.y} ${ex} ${end.y} ${end.x} ${end.y}`;
		}

		// Update connector path coordinates
		function updateConnector() {
		if (!activeEl) return;
		const $src = $(activeEl);
		const $panel = $('.wordform-builder-form-options-div-wrapper');

		if ($src.length === 0 || $panel.length === 0) {
			hideConnectorImmediate();
			return;
		}

		const start = getMidRight($src);
		const end = getTopLeftPanelAnchor($panel);
		const d = makeBezierPath(start, end);

		$path.attr('d', d);
		$path.attr('stroke', '#0a66d1');
		$path.attr('marker-end', 'url(#wordform-arrowhead)');
		}

		// RAF loop control
		function startUpdating() {
		if (rafId) return;
		(function loop() {
			updateConnector();
			rafId = requestAnimationFrame(loop);
		})();
		}
		function stopUpdating() {
		if (rafId) cancelAnimationFrame(rafId);
		rafId = null;
		}

		// Immediate hide (no fade)
		function hideConnectorImmediate() {
		stopUpdating();
		activeEl = null;
		$svg.removeClass('visible fading-out');
		$path.attr('d', '');
		$('.wordform-input-element-div-wrapper').removeClass('wordform-input-element-div-wrapper-show-arrow');
		$('.wordform-builder-form-options-div-wrapper').removeClass('active-for-connector');
		}

		// Public: show connector for given element (jQuery element)
		window.showWordformConnector = function ($element) {
		if (!($element && $element.length)) return;

		// ensure SVG exists and is appended to body
		$svg.appendTo(document.body);

		// after connector exists:
		const stopFs = enableFullscreenSvgReconcile();
		// to stop/remove listeners later:
		stopFs();


		// remove fading, make visible
		$svg.removeClass('fading-out').addClass('visible');

		// highlight element and panel
		$('.wordform-builder-form-options-div-wrapper').addClass('active-for-connector');
		$element.addClass('wordform-input-element-div-wrapper-show-arrow');

		// set active element and begin updating
		activeEl = $element.get(0);
		updateConnector(); // one immediate update
		startUpdating();
		};

		// Public: hide connector (returns Promise resolved after fade completes)
		window.hideWordformConnector = function () {
		return new Promise(function (resolve) {
			// remove highlight classes immediately
			$('.wordform-input-element-div-wrapper').removeClass('wordform-input-element-div-wrapper-show-arrow');
			$('.wordform-builder-form-options-div-wrapper').removeClass('active-for-connector');

			// if SVG not present, resolve immediately
			if ($svg.length === 0) {
			resolve();
			return;
			}

			// stop updates
			stopUpdating();
			activeEl = null;

			// start fade out via class
			$svg.addClass('fading-out');

			// Listen for transitionend on opacity, fallback timeout
			let handled = false;
			function done() {
			if (handled) return;
			handled = true;
			$svg.removeClass('visible fading-out');
			$path.attr('d', '');
			resolve();
			}

			// Use transitionend if available, watch for opacity property
			$svg.one('transitionend', function (e) {
			if (e && e.originalEvent && e.originalEvent.propertyName && e.originalEvent.propertyName.indexOf('opacity') === -1) {
				return;
			}
			done();
			});

			// Fallback timeout (match your CSS duration + small buffer)
			setTimeout(done, 420);
		});
		};

		// Window events: update on resize/scroll to avoid mispositioning
		$(window).on('resize scroll', function () {
		if (activeEl) updateConnector();
		});

		// Optional: hide on Esc
		$(document).on('keydown', function (e) {
		if (e.key === 'Escape' || e.keyCode === 27) {
			// call but ignore the returned promise here
			window.hideWordformConnector();
		}
		});

		// Make SVG visible if you want initial ready state removed; keep hidden by default
		// Force reflow then ensure class for correct stacking/visibility handling
		if ($svg.length) {
		void $svg[0].offsetWidth;
		$svg.removeClass('fading-out'); // keep hidden until showWordformConnector called
		}

		// If any element already has the selected class when the page loads, show connector		
		// Delay slightly to ensure layout/paint finished (helps accurate getBoundingClientRect)
		setTimeout(function () {
			var $preselected = $('.wordform-input-element-div-wrapper.wordform-input-element-div-wrapper-show-arrow').first();
			if ($preselected && $preselected.length) {
			// If connector currently fading-out, ensure we hide fully first, then show
			// hideWordformConnector returns a Promise in the updated code
			if (typeof window.hideWordformConnector === 'function') {
				window.hideWordformConnector().then(function () {
				if (typeof window.showWordformConnector === 'function') {
					window.showWordformConnector($preselected);
				}
				});
			} else {
				// Fallback: call show directly
				if (typeof window.showWordformConnector === 'function') {
				window.showWordformConnector($preselected);
				}
			}
			}
		}, 60); // small timeout for layout stabilization; increase to 120ms if needed		


		/* ===========================
		Usage examples and placement
		===========================
		1) If you initialize connector on DOM ready:

		$(function () {
		// ... your connector creation code that appends #wordform-connector-svg ...
		// Immediately after that:
		const stopFs = enableFullscreenSvgReconcile();
		// store stopFs if you need to disable later:
		window.__stopFsReconcile = stopFs;
		});

		2) If connector created elsewhere and you want to enable later:

		// after connector exists:
		const stopFs = enableFullscreenSvgReconcile();
		// to stop/remove listeners later:
		stopFs();

		Place the call after the SVG is present in DOM (after your connector init). Do not call before SVG exists.
		*/

		// Call this after your connector SVG is created and appended.
		// Returns a cleanup function that removes event listeners and observers.
		function enableFullscreenSvgReconcile(opts) {
		opts = opts || {};
		const svgSelector = opts.svgSelector || '#wordform-connector-svg';
		const wrapperSelector = opts.wrapperSelector || '.wordform-fullscreen-wrapper';
		const $svg = document.querySelector(svgSelector);
		if (!$svg) {
			console.warn('enableFullscreenSvgReconcile: SVG not found:', svgSelector);
			return function noop() {};
		}

		// Ensure wrapper can be used as positioning container
		function ensureWrapperPositioned(el) {
			if (!el) return;
			const cs = getComputedStyle(el);
			if (cs.position === 'static' || !cs.position) {
			el.style.position = 'relative';
			}
		}

		// Cross-browser current fullscreen element getter
		function getFullscreenElement() {
			return document.fullscreenElement
			|| document.webkitFullscreenElement
			|| document.mozFullScreenElement
			|| document.msFullscreenElement
			|| null;
		}

		// Move the SVG into a container and set absolute sizing
		function moveSvgToContainer(container) {
			if (!container || !container.appendChild) return;
			if ($svg.parentNode !== container) {
			container.appendChild($svg);
			}
			ensureWrapperPositioned(container);
			// Use absolute inside fullscreen container
			Object.assign($svg.style, {
			position: 'absolute',
			top: '0',
			left: '0',
			width: '100%',
			height: '100%',
			pointerEvents: 'none',
			zIndex: '2147483647'
			});
		}

		// Move back to body and use fixed sizing
		function moveSvgToBody() {
			if ($svg.parentNode !== document.body) {
			document.body.appendChild($svg);
			}
			Object.assign($svg.style, {
			position: 'fixed',
			top: '0',
			left: '0',
			width: '100vw',
			height: '100vh',
			pointerEvents: 'none',
			zIndex: '2147483647'
			});
		}

		// Called on fullscreen change or manual checks
		function reconcileSvgForFullscreen() {
			const fsEl = getFullscreenElement();
			if (fsEl) {
			// prefer an ancestor matching the wrapper selector, otherwise the fullscreen element itself
			const wrapper = fsEl.closest ? fsEl.closest(wrapperSelector) : null;
			const target = wrapper || (fsEl.matches && fsEl.matches(wrapperSelector) ? fsEl : null) || fsEl;
			moveSvgToContainer(target);
			} else {
			moveSvgToBody();
			}

			// If you have a global update function exposed, call it to recalc path
			// (updateConnector defined inside your connector code scope or global)
			if (typeof window.updateConnector === 'function') {
			try { window.updateConnector(); } catch (e) { /* ignore */ }
			} else if (typeof window.showWordformConnector === 'function') {
			// trigger one immediate update by re-showing active (safe no-op if not selected)
			// Note: avoid calling showWordformConnector repeatedly if you rely on its side effects
			try { /* noop */ } catch (e) {}
			}
		}

		// Event listeners for fullscreen changes (standard + vendors)
		function onFsChange() { reconcileSvgForFullscreen(); }
		document.addEventListener('fullscreenchange', onFsChange);
		document.addEventListener('webkitfullscreenchange', onFsChange);
		document.addEventListener('mozfullscreenchange', onFsChange);
		document.addEventListener('MSFullscreenChange', onFsChange);

		// Also watch for wrapper class/style changes if wrapper exists and may be toggled without Fullscreen API
		let mo = null;
		const wrapperEl = document.querySelector(wrapperSelector);
		if (wrapperEl && window.MutationObserver) {
			mo = new MutationObserver(reconcileSvgForFullscreen);
			mo.observe(wrapperEl, { attributes: true, attributeFilter: ['class', 'style'] });
		}

		// Initial reconcile (in case page already in fullscreen)
		// delay slightly so layout stabilizes if called immediately after DOM ready
		setTimeout(reconcileSvgForFullscreen, 30);

		// Return cleanup function
		return function disableFullscreenSvgReconcile() {
			document.removeEventListener('fullscreenchange', onFsChange);
			document.removeEventListener('webkitfullscreenchange', onFsChange);
			document.removeEventListener('mozfullscreenchange', onFsChange);
			document.removeEventListener('MSFullscreenChange', onFsChange);
			if (mo) {
			mo.disconnect();
			mo = null;
			}
			// restore svg to body on cleanup
			moveSvgToBody();
		};
		}




	});

	})(jQuery);

	// End Connector Arrow Line Between Elements //    

}); // jQuery(document).ready(function($)
