(function ($) {
	'use strict';

	var svgExpand   = '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="64px" height="64px" viewBox="-16 -16 64 64" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"><path d="M7.539,26.475l6.849,-6.971c0.58,-0.591 0.572,-1.541 -0.019,-2.121c-0.591,-0.58 -1.541,-0.572 -2.121,0.019l-6.737,6.856c-0.007,-0.079 -0.011,-0.159 -0.011,-0.24c0,-0 -0,-7.018 -0,-7.018c-0,-0.828 -0.672,-1.5 -1.5,-1.5c-0.828,0 -1.5,0.672 -1.5,1.5l0,7.018c0,3.037 2.462,5.5 5.5,5.5c3.112,-0 6.905,-0 6.905,-0c0.828,-0 1.5,-0.673 1.5,-1.5c0,-0.828 -0.672,-1.5 -1.5,-1.5l-6.905,-0c-0.157,-0 -0.311,-0.015 -0.461,-0.043Z"/><path d="M24.267,5.51l-7.056,7.181c-0.58,0.591 -0.571,1.541 0.019,2.122c0.591,0.58 1.541,0.571 2.121,-0.019l7.149,-7.277c0.031,0.156 0.047,0.318 0.047,0.483c-0,0 -0,6.977 -0,6.977c-0,0.828 0.672,1.5 1.5,1.5c0.828,0 1.5,-0.672 1.5,-1.5l-0,-6.977c-0,-3.038 -2.463,-5.5 -5.5,-5.5c-3.162,0 -7.047,0 -7.047,0c-0.828,0 -1.5,0.672 -1.5,1.5c0,0.828 0.672,1.5 1.5,1.5c0,0 3.885,0 7.047,0c0.074,-0 0.147,0.003 0.22,0.01Z"/></svg>';
	var svgCompress = '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="64px" height="64px" viewBox="-16 -16 64 64" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"><path d="M11.21,18.511l-8.284,8.433c-0.58,0.59 -0.572,1.541 0.019,2.121c0.59,0.58 1.541,0.572 2.121,-0.019l8.378,-8.527c0.03,0.156 0.046,0.317 0.046,0.482c0,0 0,6.977 0,6.977c0,0.828 0.672,1.5 1.5,1.5c0.828,0 1.5,-0.672 1.5,-1.5l0,-6.977c0,-3.037 -2.462,-5.5 -5.5,-5.5c-3.14,0 -6.984,0 -6.984,0c-0.828,0 -1.5,0.672 -1.5,1.5c-0,0.828 0.672,1.5 1.5,1.5l6.984,0c0.074,0 0.148,0.004 0.22,0.01Z"/><path d="M18.496,11.437c-0.012,-0.102 -0.019,-0.205 -0.019,-0.31c0,-0 0,-7.145 0,-7.145c0,-0.827 -0.672,-1.5 -1.5,-1.5c-0.828,0 -1.5,0.673 -1.5,1.5l0,7.145c0,3.038 2.463,5.5 5.5,5.5c3.139,0 6.981,0 6.981,0c0.828,0 1.5,-0.672 1.5,-1.5c-0,-0.828 -0.672,-1.5 -1.5,-1.5l-6.981,0c-0.135,0 -0.267,-0.011 -0.396,-0.031l8.421,-8.572c0.58,-0.591 0.572,-1.541 -0.019,-2.121c-0.59,-0.581 -1.541,-0.572 -2.121,0.018l-8.366,8.516Z"/></svg>';
	var svgClose    = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16"><path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"/></svg>';
	var svgBack     = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/></svg>';
	var svgServices = ` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
							<line x1="8" y1="6" x2="21" y2="6"></line>
							<line x1="8" y1="12" x2="21" y2="12"></line>
							<line x1="8" y1="18" x2="21" y2="18"></line>
							<circle cx="4" cy="6" r="1"></circle>
							<circle cx="4" cy="12" r="1"></circle>
							<circle cx="4" cy="18" r="1"></circle>
						</svg>`;
	var svgMinimize = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path d="M9.5 3.75a.75.75 0 0 1 .75.75v5.75H4.5a.75.75 0 0 1 0-1.5h3.19L3.97 5.03a.75.75 0 0 1 1.06-1.06l3.72 3.72V4.5a.75.75 0 0 1 .75-.75Zm4.25 10h5.75a.75.75 0 0 1 0 1.5h-3.19l3.72 3.72a.75.75 0 1 1-1.06 1.06l-3.72-3.72v3.19a.75.75 0 0 1-1.5 0v-5.75ZM19.5 8.75a.75.75 0 0 1 0 1.5h-5.75V4.5a.75.75 0 0 1 1.5 0v3.19l3.72-3.72a.75.75 0 1 1 1.06 1.06l-3.72 3.72h3.19ZM10.25 19.5a.75.75 0 0 1-1.5 0v-3.19l-3.72 3.72a.75.75 0 0 1-1.06-1.06l3.72-3.72H4.5a.75.75 0 0 1 0-1.5h5.75v5.75Z"/></svg>';
	var svgResizeSourceService = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" stroke-linecap="round" stroke-linejoin="round"/><path stroke-linecap="round" stroke-linejoin="round" d="M9 3v18M14 9l3 3-3 3"/></svg>'
	var svgCollapseSourceService = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" stroke-linecap="round" stroke-linejoin="round"/><path stroke-linecap="round" stroke-linejoin="round" d="M9 3v18M17 9l-3 3 3 3"/></svg>'
	var calendlyIsOpen    = false;
	var calendlyClosing   = false;
	var calendlyMinimized = false;
	var serviceCardsMode  = false;
	var panelMode         = 'services';
	var currentServiceUrl = '';
	var servicePanelView  = 'cards';
	var activeServiceLinks = null;
	var activeSvgIcon 	 = 'services';
	var dragInitialized   = false;
	var resetDragState    = function () {};

	function escapeHtml( value ) {
		if ( ! value ) {
			return '';
		}
		return String( value ).replace( /[&<>"']/g, function ( character ) {
			return {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			}[ character ];
		} );
	}

	function isMobile() {
		return window.matchMedia( '(max-width: 768px)' ).matches;
	}

	function centerChatWindow() {
    var container = document.getElementById('mindweco-container');
    if (!container) return;

    if (isMobile()) {
        container.style.position = '';
        container.style.right = '';
        container.style.bottom = '';
        container.style.margin = '';
        container.style.transform = '';
        return;
    }

    var rect = container.getBoundingClientRect();
    var w = rect.width || container.offsetWidth;
    var h = rect.height || container.offsetHeight;

    container.style.position  = 'fixed';
    container.style.transform = 'none';         
    container.style.margin    = '0';
    container.style.right     = '';
    container.style.bottom    = '';
}

	function resetChatWindowPosition() {
		var container = document.getElementById( 'mindweco-container' );
		if ( ! container ) {
			return;
		}

		container.style.position = '';
		container.style.right = '';
		container.style.bottom = '';
		container.style.margin = '';
		container.style.transform = '';
	}

	function setActivePanelIcon( iconName ) {
		$( '#mwc-panel-mode-services, #mwc-panel-mode-sources, #resize-panel-services-sources' ).removeClass( 'mwc-panel-btn-active' );
		if ( iconName === 'services' ) {
			$( '#mwc-panel-mode-services' ).addClass( 'mwc-panel-btn-active' );
		} else if ( iconName === 'sources' ) {
			$( '#mwc-panel-mode-sources' ).addClass( 'mwc-panel-btn-active' );
		} else if ( iconName === 'resize' ) {
			$( '#resize-panel-services-sources' ).addClass( 'mwc-panel-btn-active' );
		}
	}

	function mountWidgetAtBodyRoot() {
		var root       = document.getElementById( 'mindweb-mindweco-root' );
		var btnWrapper = document.getElementById( 'mindweco-btn-wrapper' );
		var popup      = document.getElementById( 'citation-popup' );

		[ btnWrapper, root, popup ].forEach( function ( element ) {
			if ( element && element.parentNode !== document.body ) {
				document.body.appendChild( element );
			}
		} );
	}

	function updateServicesButtonIcon() {
		var $btn = $( '#mindweco-calendly-btn' );
		var $closeBtnChat = $( '#mindweco-calendly-close' );
		if ( ! $btn.length ) {
			return;
		}

		if ( calendlyIsOpen && ! calendlyMinimized ) {
			$btn.html( svgCompress );
			$btn.attr( 'title', 'Minimize services' );
			$btn.attr( 'aria-label', 'Minimize services' );
			return;
		}

		$btn.html( svgServices );
		$btn.attr( 'title', 'Services & Options' );
		
		$btn.attr( 'aria-label', 'Services & Options' );
	}

	function showBackArrow( onBack ) {
		$( '.mindweco-close' )
			.html( svgBack )
			.off( 'click.mwcBack' )
			.on( 'click.mwcBack', function () {
				if ( typeof onBack === 'function' ) {
					onBack();
				} else {
					closeCalendly();
				}
			} )
			.css( 'visibility', 'visible' )
			.show();
	}

	function showCloseIcon() {
		$( '.mindweco-close' )
			.html( svgClose )
			.off( 'click.mwcBack' )
			.css( 'visibility', 'visible' )
			.show();
	}

	function setPanelHeaderAction( mode ) {
		var $btn = $( '#mindweco-calendly-close' );
		if ( ! $btn.length ) return;

		if ( mode === 'back' ) {
			$btn.html( svgBack );
			$btn.attr( 'aria-label', 'Back to services' );

			$btn.off('click.mwcHeader').on('click.mwcHeader', function () {
				renderServiceCards( getServiceLinks() );
				switchPanelToServiceCards();
			});

			return;
		}

		$btn.html( isMobile() ? svgBack : svgClose );
		$btn.attr( 'aria-label', 'Close' );

		$btn.off('click.mwcHeader').on('click.mwcHeader', function () {
			closeCalendly();
		});
	}

	function syncResizeBtn() {
		var $resizeBtn = $( '#resize-mindweco' );
		var $root      = $( '#mindweb-mindweco-root' );
		var $modeBtns  = $( '#mwc-panel-mode-services, #mwc-panel-mode-sources' );

		if ( ! $resizeBtn.length ) {
			return;
		}

		if ( hasServices() ) {
			$root.removeClass( 'mindweco-no-services' ).addClass( 'mindweco-has-services' );
			$resizeBtn[0].style.setProperty( 'display', 'none', 'important' );
			$modeBtns.each( function () {
				this.style.removeProperty( 'display' );
			} );
		} else {
			$root.removeClass( 'mindweco-has-services' ).addClass( 'mindweco-no-services' );
			$resizeBtn[0].style.removeProperty( 'display' );
			$modeBtns.each( function () {
				this.style.setProperty( 'display', 'none', 'important' );
			} );
		}
	}

	function setServicesSourcesResizeMode( enabled, activeIcon ) {
		var $panel     = $( '#mindweco-calendly-panel' );
		var $chatPanel = $( '#mindweco-container' );
		var $btn       = $( '#resize-panel-services-sources' );

		if ( enabled && isMobile() ) {
			enabled = false;
		}

		$panel.toggleClass( 'mwc-resize-panel-sources-services-width', enabled );
		$chatPanel.toggleClass( 'mwc-resize-panel-sources-services-remove-width', enabled );
		$btn
			.attr( 'aria-label', enabled ? 'Restore panel size' : 'Expand panel' )
			.attr( 'title', enabled ? 'Restore panel size' : 'Expand panel' );
		if ( activeIcon ) {
			setActivePanelIcon( activeIcon );
		}
	}


	function setServicesSourcesResizeIcon( icon ) {
		var $panel     = $( '#mindweco-calendly-panel' );
		if($panel.hasClass( 'mwc-resize-panel-sources-services-width' )) {
			$( '#resize-panel-services-sources' ).html( svgCollapseSourceService ).attr( 'aria-label', 'Restore panel size' ).attr( 'title', 'Restore panel size' );
		} else {
			$( '#resize-panel-services-sources' ).html( svgResizeSourceService ).attr( 'aria-label', 'Expand panel' ).attr( 'title', 'Expand panel' );
		}

	}

	function toggleServicesSourcesResizeMode() {
		var $panel = $( '#mindweco-calendly-panel' );

		if ( ! $panel.length || ! $panel.is( ':visible' ) ) {
			return;
		}

		setServicesSourcesResizeMode( ! $panel.hasClass( 'mwc-resize-panel-sources-services-width' ), 'resize' );
	}


	function swapContentServicesChat(){
		var $root = $( '#mindweb-mindweco-root' );
		var $chatPanel = $( '#mindweco-container' );
		var $servicesPanel = $( '#mindweco-calendly-panel' );

		if ( ! $root.hasClass( 'calendly-open' ) || ! $chatPanel.length || ! $servicesPanel.length || ! $servicesPanel.is( ':visible' ) ) {
			return;
		}

		$root.toggleClass( 'mwc-content-swapped' );
		$chatPanel.toggleClass( 'mwc-swap-content-active' );
		$servicesPanel.toggleClass( 'mwc-swap-content-active' );

	}

	function ensureServiceViewBar() {
		var $bar = $( '#mwc-service-view-bar' );
		if ( $bar.length ) {
			return $bar;
		}
		$( '#mindweco-calendly-panel .mindweco-calendly-panel-header' ).after(
			'<div id="mwc-service-view-bar" style="display:none;">' +
				'<button type="button" class="mwc-service-back-btn">' + svgBack + '<span>Back to services</span></button>' +
			'</div>'
		);
		return $( '#mwc-service-view-bar' );
	}

	function normalizeServiceLinks( services ) {
		if ( ! Array.isArray( services ) ) {
			return [];
		}

		return services.map( function ( service ) {
			if ( typeof service === 'string' ) {
				var url = service.trim();
				return url ? { title: '', description: '', url: url } : null;
			}

			if ( ! service || typeof service !== 'object' ) {
				return null;
			}

			var urlValue = service.url || service.link || service.service_url || service.serviceUrl || service.href || '';
			var urlText = String( urlValue || '' ).trim();
			if ( ! urlText ) {
				return null;
			}

			return {
				title: String( service.title || service.name || service.label || '' ).trim(),
				description: String( service.description || service.summary || service.text || '' ).trim(),
				url: urlText
			};
		} ).filter( function ( service ) {
			return service && service.url;
		} );
	}

	function getConfiguredServiceLinks() {
		var data = typeof mindwecoData !== 'undefined' ? mindwecoData : null;

		if ( ! data ) {
			return [];
		}

		var services = normalizeServiceLinks( data.service_links );
		if ( services.length > 0 ) {
			return services;
		}

		if ( data.calendly_url ) {
			var fallback = [ { title: '', description: '', url: data.calendly_url } ];
			return fallback;
		}

		return [];
	}

	function setActiveServiceLinks( services ) {
		var normalized = normalizeServiceLinks( services );
		activeServiceLinks = normalized.length > 0 ? normalized : null;
		return activeServiceLinks ? activeServiceLinks.slice() : getConfiguredServiceLinks();
	}

	function clearActiveServiceLinks() {
		activeServiceLinks = null;
	}

	function getServiceLinks() {
		if ( Array.isArray( activeServiceLinks ) && activeServiceLinks.length > 0 ) {
			return activeServiceLinks.slice();
		}

		return getConfiguredServiceLinks();
	}

	function hasServices() {
		return getServiceLinks().length > 0;
	}

	function ensureServicesBody() {
		var $body = $( '#mwc-services-body' );
		if ( $body.length ) {
			return $body;
		}
		$( '.mwc-cal-iframe-wrapper' ).prepend( '<div id="mwc-services-body" style="display:none;"></div>' );
		return $( '#mwc-services-body' );
	}

	function getEmbeddableUrl( serviceUrl ) {
    if ( ! serviceUrl ) {
        return '';
    }
    if ( serviceUrl.indexOf( 'calendly.com' ) === -1 ) {
        return serviceUrl;
    }
    var sep = serviceUrl.indexOf( '?' ) !== -1 ? '&' : '?';
    return serviceUrl
        + sep
        + 'utm_source=mindweco'
        + '&embed_domain=' + encodeURIComponent( window.location.hostname )
        + '&embed_type=Inline'
        + '&hide_gdpr_banner=1'
        + '&background_color=ffffff'
        + '&text_color=333333'
        + '&primary_color=3d6eff'
}

	function getIframeCss() {
		if ( typeof mindwecoConfig !== 'undefined' && mindwecoConfig && typeof mindwecoConfig.iframeCss === 'string' ) {
			return mindwecoConfig.iframeCss.trim();
		}

		if ( typeof mindwecoData !== 'undefined' && mindwecoData && typeof mindwecoData.iframeCss === 'string' ) {
			return mindwecoData.iframeCss.trim();
		}

		return '';
	}

	function injectIframeCss( iframeElement ) {
		var css = getIframeCss();
		var doc;
		var existing;
		var style;

		if ( ! css || ! iframeElement ) {
			return;
		}

		try {
			doc = iframeElement.contentDocument || iframeElement.contentWindow.document;
			if ( ! doc || ! doc.head ) {
				return;
			}

			existing = doc.querySelector( 'style[data-mindweco-iframe-css="1"]' );
			if ( existing ) {
				existing.remove();
			}

			style = doc.createElement( 'style' );
			style.type = 'text/css';
			style.setAttribute( 'data-mindweco-iframe-css', '1' );
			style.appendChild( doc.createTextNode( css ) );
			doc.head.appendChild( style );
		} catch ( error ) {
			// Cross-origin iframes cannot be styled directly; ignore and continue.
		}
	}

	function switchPanelToServiceCards() {
		var $panel          = $( '#mindweco-calendly-panel' );
		var $iframe         = $( '#mindweco-calendly-iframe' );
		var $loading        = $( '#mwc-cal-loading' );
		var $servicesBody   = ensureServicesBody();
		var $serviceViewBar = ensureServiceViewBar();

		serviceCardsMode  = true;
		servicePanelView  = 'cards';
		currentServiceUrl = '';
		panelMode         = 'services';

		$panel.addClass( 'mwc-panel-showing-services' ).removeClass( 'mwc-panel-showing-sources' );
		$panel.find( '.mindweco-calendly-panel-header .mwc-cal-title' ).text( 'Services & Options' );
		$panel.find( '.mindweco-calendly-panel-header .mwc-cal-sub' ).text( 'Choose what suits you best' );
		$( '#mwc-sources-body' ).hide();
		$panel.find( '.mwc-cal-iframe-wrapper' ).show();
		$loading.addClass( 'hidden' );
		$serviceViewBar.hide();
		$iframe.removeClass( 'loaded' ).attr( 'src', '' ).hide();
		$servicesBody.css({
			'display'        : 'flex',
			'flex-direction' : 'column',
			'overflow-y'     : 'auto',
			'max-height'     : '100%'
		});
		setPanelHeaderAction( 'close' );
	}

	function renderServiceCards( services ) {
		var $servicesBody = ensureServicesBody();
		var html = '';

		if ( services.length > 8 ) {
			html += '<input type="text" id="mwc-service-search" placeholder="Search services..." onclick="event.stopPropagation()" style="width:100%; padding:8px 12px; border:1px solid var(--mw-border-soft); border-radius:10px; background:var(--mw-bg-soft); color:var(--mw-text-primary); font-size:13px; box-sizing:border-box; outline:none; margin-bottom:8px; flex-shrink:0;" />';
		}

		services.forEach( function ( service, index ) {
			var title       = service.title || ( 'Service ' + ( index + 1 ) );
			var description = service.description || '';
			var host        = '';
			try {
				host = new URL( service.url ).hostname;
			} catch ( e ) {
				host = service.url;
			}

			var searchText = escapeHtml( ( title + ' ' + description + ' ' + host ).toLowerCase() );

			html += '<button type="button" class="mwc-service-card" data-service-url="' + escapeHtml( service.url ) + '" data-search-text="' + searchText + '">';
			html += '<span class="mwc-service-card-icon" aria-hidden="true">';
			html += `
				<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
					<line x1="8" y1="6" x2="21" y2="6"></line>
					<line x1="8" y1="12" x2="21" y2="12"></line>
					<line x1="8" y1="18" x2="21" y2="18"></line>
					<circle cx="4" cy="6" r="1"></circle>
					<circle cx="4" cy="12" r="1"></circle>
					<circle cx="4" cy="18" r="1"></circle>
				</svg>
				`;
			html += '</span>';
			html += '<span class="mwc-service-card-copy">';
			html += '<span class="mwc-service-card-title">' + escapeHtml( title ) + '</span>';
			html += '<span class="mwc-service-card-url">' + escapeHtml( host ) + '</span>';
			if ( description ) {
				html += '<span class="mwc-service-card-description">' + escapeHtml( description ) + '</span>';
			}
			html += '</span>';
			html += '<span class="mwc-service-card-arrow" aria-hidden="true">';
			html += '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"></path><path d="m13 5 7 7-7 7"></path></svg>';
			html += '</span>';
			html += '</button>';
		} );

		$servicesBody.html( html );

		if ( services.length > 8 ) {
			$( document ).off( 'input.mwcSearch' ).on( 'input.mwcSearch', '#mwc-service-search', function () {
				var val    = $( this ).val().toLowerCase().trim();
				var $cards = $servicesBody.find( '.mwc-service-card' );

				var visibleCount = 0;

				$cards.each( function () {
					var cardText = $( this ).data( 'search-text' ) || '';
					if ( cardText.includes( val ) ) {
						$( this ).show();
						visibleCount++;
					} else {
						$( this ).hide();
					}
				} );

				if ( visibleCount === 0 ) {
					if ( $servicesBody.find( '#mwc-no-results' ).length === 0 ) {
						$servicesBody.append(
							'<div id="mwc-no-results" style="padding:10px; text-align:center; color:#888;">No services found</div>'
						);
					}
				} else {
					$( '#mwc-no-results' ).remove();
				}
			} );
		}
	}

	function openCalendly( selectedUrl ) {
		if ( calendlyIsOpen || calendlyClosing ) {
			return;
		}

		var showCardsOnly = ( selectedUrl === '__service_cards__' );
		var services      = getServiceLinks();
		var calendlyUrl   = showCardsOnly ? '' : ( selectedUrl || ( services[0] && services[0].url ? services[0].url : '' ) );

		if ( ! showCardsOnly && ! calendlyUrl ) {
			return;
		}

		var $panel          = $( '#mindweco-calendly-panel' );
		var $iframe         = $( '#mindweco-calendly-iframe' );
		var $loading        = $( '#mwc-cal-loading' );
		var $root           = $( '#mindweb-mindweco-root' );
		var $chatPanel      = $( '#mindweco-container' );
		var $servicesBody   = ensureServicesBody();
		var $serviceViewBar = ensureServiceViewBar();

		calendlyIsOpen   = true;
		serviceCardsMode = false;
		panelMode        = 'services';

		updateServicesButtonIcon();
		setActivePanelIcon( 'services' );

		if ( window.MindwecoCitations && window.MindwecoCitations.switchToCalendly ) {
			window.MindwecoCitations.switchToCalendly();
		}

		if ( showCardsOnly ) {
			$iframe.removeClass( 'loaded' ).attr( 'src', '' ).hide();
			$loading.addClass( 'hidden' );
			$serviceViewBar.hide();
		} else {
			currentServiceUrl = calendlyUrl;
			servicePanelView  = 'iframe';
			$servicesBody.hide();
			$serviceViewBar.hide();
			$iframe.removeClass( 'loaded' ).attr( 'src', '' ).show();
			$loading.removeClass( 'hidden' );
		}

		$panel.css({ 'height': '', 'max-height': '', 'margin-top': '' });
		$root.addClass( 'calendly-open' );

		if ( ! isMobile() ) {
			$chatPanel.css( 'display', 'flex' );
			$( '.mindweco-close' ).hide();
			setPanelHeaderAction( 'close' );
		} else {
			$chatPanel.css( 'display', 'none' );
			$( '#mindweco-calendly-close' ).html( svgBack );
			setPanelHeaderAction( 'close' );
			$( '#mindweco-calendly-close' ).html( svgBack );
		}

		$panel
			.css( 'display', 'flex' )
			.removeClass( 'mwc-leaving mwc-resize-mode' )
			.addClass( 'mwc-entering' );

		$panel.one( 'animationend webkitAnimationEnd', function () {
			$panel.removeClass( 'mwc-entering' );
		} );

		if ( ! showCardsOnly && calendlyUrl ) {
			var fullUrl = getEmbeddableUrl( calendlyUrl );
			$iframe.attr( 'src', fullUrl );
			$iframe.off( 'load.mwc' ).on( 'load.mwc', function () {
				if ( ! $( this ).attr( 'src' ) ) {
					return;
				}
				injectIframeCss( this );
				$loading.addClass( 'hidden' );
				$iframe.addClass( 'loaded' );
			} );
		}

		setTimeout( function () {
			$( '#mindweco-calendly-close' ).focus();
		}, 420 );
	}

	function closeCalendly() {
		if ( ! calendlyIsOpen || calendlyClosing ) {
			return;
		}

		var $panel      = $( '#mindweco-calendly-panel' );
		var $iframe     = $( '#mindweco-calendly-iframe' );
		var $root       = $( '#mindweb-mindweco-root' );
		var $chatPanel  = $( '#mindweco-container' );
		var $btnWrapper = $( '#mindweco-btn-wrapper' );

		calendlyClosing = true;
		var finished    = false;

		$panel.removeClass( 'mwc-entering' ).addClass( 'mwc-leaving' );

		function finishClose() {
			if ( finished ) { return; }
			finished = true;

			$panel.css( 'display', 'none' ).removeClass( 'mwc-leaving' );
			$iframe.removeClass( 'loaded' ).attr( 'src', '' );
			ensureServicesBody().hide().empty();
			ensureServiceViewBar().hide();
			$( document ).off( 'input.mwcSearch' );
			$chatPanel.hide().removeClass( 'closing maximized minimized' );
			setServicesSourcesResizeMode( false );
			$root.removeClass( 'maximized-open calendly-open mwc-content-swapped' );
			$root.css({ 'padding': '', 'box-sizing': '', 'flex-direction': '' });

			if ( ! isMobile() ) {
				$btnWrapper.show();
			}

			if ( isMobile() ) {
				$chatPanel.css( 'display', 'flex' );
				$( '#mindweco-calendly-close' ).html( svgClose );
				showCloseIcon();
			} else {
				$( '.mindweco-close' ).show();
			}

			setPanelHeaderAction( 'close' );

			calendlyIsOpen    = false;
			calendlyClosing   = false;
			calendlyMinimized = false;
			serviceCardsMode  = false;
			panelMode         = 'services';
			currentServiceUrl = '';
			servicePanelView  = 'cards';
			clearActiveServiceLinks();
			$( '#mindweco-swap-content' )[0].style.setProperty( 'display', 'none', 'important' );
			updateServicesButtonIcon();
			syncResizeBtn();
		}

		$panel.one( 'animationend webkitAnimationEnd', finishClose );
		setTimeout( finishClose, 420 );
	}

	function minimizeCalendly() {
		var $panel     = $( '#mindweco-calendly-panel' );
		var $root      = $( '#mindweb-mindweco-root' );
		var $chatPanel = $( '#mindweco-container' );

		calendlyMinimized = true;
		updateServicesButtonIcon();

		$panel
			.removeClass( 'mwc-entering' )
			.addClass( 'mwc-leaving' );

		var finished = false;

		function finishMinimize() {
			if ( finished ) { return; }
			finished = true;

			$panel.css( 'display', 'none' ).removeClass( 'mwc-leaving' );
			setServicesSourcesResizeMode( false );
			$root.removeClass( 'calendly-open mwc-content-swapped' );
			resetDragState();

			if ( isMobile() ) {
				$chatPanel.css( 'display', 'flex' );
				showCloseIcon();
			} else {
				$( '.mindweco-close' ).show();
			}
		}

		$panel.one( 'animationend webkitAnimationEnd', finishMinimize );
		setTimeout( finishMinimize, 420 );
	}

	function restoreCalendly() {
		var $panel     = $( '#mindweco-calendly-panel' );
		var $root      = $( '#mindweb-mindweco-root' );
		var $chatPanel = $( '#mindweco-container' );

		calendlyMinimized = false;
		updateServicesButtonIcon();

		$root.addClass( 'calendly-open' );

		if ( ! isMobile() ) {
			$chatPanel.css( 'display', 'flex' );
			$( '.mindweco-close' ).hide();
		} else {
			$chatPanel.css( 'display', 'none' );
			showBackArrow( closeCalendly );
		}

		$panel
			.css( 'display', 'flex' )
			.removeClass( 'mwc-leaving mwc-resize-mode' )
			.addClass( 'mwc-entering' );

		$panel.one( 'animationend webkitAnimationEnd', function () {
			$panel.removeClass( 'mwc-entering' );
		} );

		setTimeout( function () {
			$( '#mindweco-calendly-close' ).focus();
		}, 420 );
	}

	function showServicesPanel() {
		var hasOverride = arguments.length > 0;
		var services = hasOverride ? setActiveServiceLinks( arguments[0] ) : getServiceLinks();

		if ( calendlyIsOpen && calendlyMinimized ) {
			restoreCalendly();
		}

		if ( services.length === 0 ) {
			showSourcesPanel();
			return;
		}

		if ( ! calendlyIsOpen ) {
			if ( services.length > 1 ) {
				renderServiceCards( services );
				openCalendly( '__service_cards__' );
				switchPanelToServiceCards();
			} else {
				openCalendly( services[0].url );
			}
			return;
		}

		panelMode = 'services';
		if ( window.MindwecoCitations && window.MindwecoCitations.switchToCalendly ) {
			window.MindwecoCitations.switchToCalendly();
		}

		if ( hasOverride ) {
			if ( services.length > 1 ) {
				renderServiceCards( services );
				switchPanelToServiceCards();
				setActivePanelIcon( 'services' );
				return;
			}

			var overrideServiceUrl = services[0] && services[0].url ? services[0].url : '';
			if ( ! overrideServiceUrl ) {
				showSourcesPanel();
				return;
			}

			var $overridePanel          = $( '#mindweco-calendly-panel' );
			var $overrideIframe         = $( '#mindweco-calendly-iframe' );
			var $overrideLoading        = $( '#mwc-cal-loading' );
			var $overrideServicesBody   = ensureServicesBody();
			var $overrideServiceViewBar = ensureServiceViewBar();

			serviceCardsMode  = false;
			currentServiceUrl = overrideServiceUrl;
			servicePanelView  = 'iframe';

			$overridePanel.addClass( 'mwc-panel-showing-services' ).removeClass( 'mwc-panel-showing-sources' );
			$overridePanel.find( '.mindweco-calendly-panel-header .mwc-cal-title' ).text( 'Services & Options' );
			$overridePanel.find( '.mindweco-calendly-panel-header .mwc-cal-sub' ).text( 'Choose what suits you best' );
			$( '#mwc-sources-body' ).hide();
			$overridePanel.find( '.mwc-cal-iframe-wrapper' ).show();
			$overrideServicesBody.hide();
			$overrideServiceViewBar.hide();
			$overrideIframe.off( 'load.mwc' ).removeClass( 'loaded' ).attr( 'src', '' ).show();
			$overrideLoading.removeClass( 'hidden' );
			setPanelHeaderAction( 'close' );

			$overrideIframe.on( 'load.mwc', function () {
				if ( ! $( this ).attr( 'src' ) ) {
					return;
				}
				injectIframeCss( this );
				$overrideLoading.addClass( 'hidden' );
				$overrideIframe.addClass( 'loaded' );
			} );

			setTimeout( function () {
				$overrideIframe.attr( 'src', getEmbeddableUrl( overrideServiceUrl ) );
			}, 80 );

			setActivePanelIcon( 'services' );
			return;
		}

		if ( services.length > 1 && ( servicePanelView === 'cards' || ! currentServiceUrl ) ) {
			renderServiceCards( services );
			switchPanelToServiceCards();
			setActivePanelIcon( 'services' );
			return;
		}

		var serviceUrl      = currentServiceUrl || services[0].url;
		var $panel          = $( '#mindweco-calendly-panel' );
		var $iframe         = $( '#mindweco-calendly-iframe' );
		var $loading        = $( '#mwc-cal-loading' );
		var $servicesBody   = ensureServicesBody();
		var $serviceViewBar = ensureServiceViewBar();

		serviceCardsMode = false;
		$panel.addClass( 'mwc-panel-showing-services' ).removeClass( 'mwc-panel-showing-sources' );
		$panel.find( '.mindweco-calendly-panel-header .mwc-cal-title' ).text( 'Services & Options' );
		$panel.find( '.mindweco-calendly-panel-header .mwc-cal-sub' ).text( 'Choose what suits you best' );
		$( '#mwc-sources-body' ).hide();
		$panel.find( '.mwc-cal-iframe-wrapper' ).show();
		$servicesBody.hide();
		$serviceViewBar.toggle( services.length > 1 );
		$iframe.off( 'load.mwc' ).removeClass( 'loaded' ).attr( 'src', '' ).show();
		$loading.removeClass( 'hidden' );
		setPanelHeaderAction( isMobile() && services.length > 1 ? 'back' : 'close' );

		$iframe.on( 'load.mwc', function () {
			if ( ! $( this ).attr( 'src' ) ) {
				return;
			}
			injectIframeCss( this );
			$loading.addClass( 'hidden' );
			$iframe.addClass( 'loaded' );
		} );

		setTimeout( function () {
			$iframe.attr( 'src', getEmbeddableUrl( serviceUrl ) );
		}, 80 );
		
		setActivePanelIcon( 'services' );
	}

	function showSourcesPanel() {
		if ( ! window.MindwecoCitations || ! window.MindwecoCitations.switchToSources ) {
			return;
		}

		if ( ! hasServices() && ! calendlyIsOpen ) {
			openSourcesOnlyPanel();
			return;
		}

		if ( ! calendlyIsOpen ) {
			openCalendly( '__service_cards__' );
		}

		serviceCardsMode = false;
		panelMode        = 'sources';
		ensureServicesBody().hide();
		ensureServiceViewBar().hide();
		window.MindwecoCitations.switchToSources();
		setActivePanelIcon( 'sources' );
		setPanelHeaderAction( 'close' );
	}

	function setSuggestedServices( services ) {
		setActiveServiceLinks( services );

		// Only refresh the visible panel; do not open it on response arrival.
		if ( calendlyIsOpen && ! calendlyMinimized ) {
			showServicesPanel( services );
		}
	}

	function openSourcesOnlyPanel() {
		if ( ! window.MindwecoCitations || ! window.MindwecoCitations.switchToSources ) {
			return;
		}

		var $panel     = $( '#mindweco-calendly-panel' );
		var $root      = $( '#mindweb-mindweco-root' );
		var $chatPanel = $( '#mindweco-container' );

		panelMode = 'sources';
		calendlyIsOpen    = true;
		calendlyMinimized = false;
		window.MindwecoCitations.switchToSources();
		setPanelHeaderAction( 'close' );
		syncResizeBtn();

		$root.addClass( 'calendly-open' );

		if ( ! isMobile() ) {
			$chatPanel.css( 'display', 'flex' );
			$( '.mindweco-close' ).hide();
		} else {
			$chatPanel.css( 'display', 'none' );
			$( '#mindweco-calendly-close' ).html( svgBack );
		}

		$panel
			.css({ 'display': 'flex', 'height': '', 'max-height': '', 'margin-top': '' })
			.removeClass( 'mwc-leaving mwc-resize-mode' )
			.addClass( 'mwc-entering' );

		$panel.one( 'animationend webkitAnimationEnd', function () {
			$panel.removeClass( 'mwc-entering' );
		} );
	}

	function init() {
		mountWidgetAtBodyRoot();
		initDrag();

		var $container   = $( '#mindweco-container' );
		var $btnWrapper  = $( '#mindweco-btn-wrapper' );
		var serviceLinks = getServiceLinks();

		var hasCalendly = serviceLinks.length > 0;
		syncResizeBtn();

		$( '#open-mindweco' ).on( 'click', function () {
			if ( window.MindwecoMessages && window.MindwecoMessages.connectSocket ) {
				window.MindwecoMessages.connectSocket();
			}

			if ( $container.is( ':visible' ) ) {
				$( '#mindweco-input' ).focus();
				return;
			}

			var savedTheme = localStorage.getItem( 'mindweco-theme-mode' ) || 'light';
			if ( window.MindwecoTheme ) {
				window.MindwecoTheme.updateIcon( savedTheme );
			}

			if ( $( '#mindweco-messages' ).find( '.default-welcome-message' ).length === 0 ) {
				if ( window.MindwecoMessages ) {
					window.MindwecoMessages.showDefault();
				}
			}

			var historyState = window.MindwecoHistory && window.MindwecoHistory.getState();
			if ( historyState && ! historyState.historyLoaded ) {
				if ( window.MindwecoCitations && window.MindwecoCitations.clearPanel ) {
					window.MindwecoCitations.clearPanel();
				}
				window.MindwecoHistory.load();
			}

			$container.css( 'display', 'flex' );
			resetDragState();
			centerChatWindow();
			$( '#mindweco-input' ).focus();
			$btnWrapper.hide();
		} );

		$( '#close-mindweco' ).on( 'click', function () {
			var $closeIconModal = $( '.mindweco-close' );
			if ( window.MindwecoMessages && window.MindwecoMessages.closeActiveSocket ) {
				window.MindwecoMessages.closeActiveSocket();
			}
			resetDragState();
			$container.addClass( 'closing' );
			setTimeout( function () {
				$container.hide().removeClass( 'closing maximized minimized' );
				resetChatWindowPosition();
				var $root = $( '#mindweb-mindweco-root' );
				setServicesSourcesResizeMode( false );
				$root.removeClass( 'maximized-open calendly-open mwc-content-swapped' );
				$root.css({ 'padding': '', 'box-sizing': '', 'flex-direction': '' });
				calendlyIsOpen    = false;
				calendlyMinimized = false;
				$( '#resize-mindweco' ).html( svgExpand );
				clearActiveServiceLinks();
				syncResizeBtn();
				$closeIconModal.show();
				$btnWrapper.show();
			}, 500 );
		} );


		$( document ).on( 'click', '#resize-panel-services-sources', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			setServicesSourcesResizeIcon();
			toggleServicesSourcesResizeMode();
		} );

		$( document ).on( 'click', '#mindweco-swap-content', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			swapContentServicesChat();
		} );

		$( '#resize-mindweco' ).on( 'click', function () {
			var $closeIconModal = $( '.mindweco-close' );
			var $btn            = $( this );
			var $root           = $( '#mindweb-mindweco-root' );
			var $sidepanel      = $( '#mindweco-calendly-panel' );

			if ( $container.hasClass( 'maximized' ) ) {
				$container.removeClass( 'maximized' ).addClass( 'minimized' );
				$( '#mindweco-swap-content' )[0].style.setProperty( 'display', 'none', 'important' );
				setServicesSourcesResizeMode( false );
				$root.removeClass( 'maximized-open calendly-open mwc-content-swapped' );
				$root.css({ 'padding': '', 'box-sizing': '', 'flex-direction': '' });
				calendlyIsOpen    = false;
				calendlyMinimized = false;

				$btn.html( svgExpand );
				syncResizeBtn();
				$closeIconModal.show();
				$btnWrapper.hide();

				$sidepanel
					.removeClass( 'mwc-resize-mode mwc-entering mwc-leaving' )
					.css({ 'height': '', 'max-height': '', 'margin-top': '' })
					.hide();

				if ( isMobile() ) {
					$container.css( 'display', 'flex' );
				}
			} else {
				$container.removeClass( 'minimized' ).addClass( 'maximized' );
				$( '#mindweco-swap-content' )[0].style.setProperty( 'display', 'flex', 'important' );
				calendlyIsOpen    = true;
				calendlyMinimized = false;
				$btn.html( svgCompress );
				$closeIconModal.hide();
				$btnWrapper.hide();

				$root.css({
					'padding'    : '0',
					'box-sizing' : 'border-box'
				});

				$root.addClass( 'maximized-open calendly-open' );

				if ( ! isMobile() ) {
					$container.css( 'display', 'flex' );
					$( '.mindweco-close' ).hide();
				} else {
					$container.css( 'display', 'none' );
					$( '#mindweco-calendly-close' ).html( svgBack );
				}

				if ( hasServices() ) {
					var svc = getServiceLinks();
					renderServiceCards( svc );
					switchPanelToServiceCards();
				} else {
					openSourcesOnlyPanel();
					return;
				}

				$sidepanel
					.css({ 'height': '', 'max-height': '', 'margin-top': '' })
					.removeClass( 'mwc-leaving mwc-resize-mode' )
					.addClass( 'mwc-entering' );

				$sidepanel.one( 'animationend webkitAnimationEnd', function () {
					$sidepanel.removeClass( 'mwc-entering' );
				} );
			}
		} );

		$( document ).on( 'click', '#mindweco-calendly-close', function () {
			var $closeIconModal = $( '.mindweco-close' );
			var $root           = $( '#mindweb-mindweco-root' );
			var $sidepanel      = $( '#mindweco-calendly-panel' );

			if ( hasCalendly ) {
				closeCalendly();
				return;
			}

			$sidepanel
				.removeClass( 'mwc-entering mwc-resize-mode' )
				.addClass( 'mwc-leaving' );

			var finished = false;

			function finishSidepanelClose() {
				if ( finished ) { return; }
				finished = true;

				if ( window.MindwecoMessages && window.MindwecoMessages.closeActiveSocket ) {
					window.MindwecoMessages.closeActiveSocket();
				}

				$sidepanel
					.css( 'display', 'none' )
					.removeClass( 'mwc-leaving' );

				setServicesSourcesResizeMode( false );
				$root.removeClass( 'maximized-open calendly-open mwc-content-swapped' );
				$root.css({
					'padding'        : '',
					'box-sizing'     : '',
					'flex-direction' : ''
				});

				$( '#mindweco-container' )
					.hide()
					.removeClass( 'maximized minimized closing' );

				calendlyIsOpen    = false;
				calendlyMinimized = false;
				$( '#resize-mindweco' ).html( svgExpand );
				clearActiveServiceLinks();
				syncResizeBtn();

				if ( isMobile() ) {
					$( '#mindweco-container' ).css( 'display', 'flex' );
					showCloseIcon();
				} else {
					$( '.mindweco-close' ).show();
				}

				if ( ! isMobile() ) {
					$( '#mindweco-btn-wrapper' ).show();
				}
			}

			$sidepanel.off( 'animationend.mwcClose webkitAnimationEnd.mwcClose' ).one( 'animationend.mwcClose webkitAnimationEnd.mwcClose', finishSidepanelClose );
			setTimeout( finishSidepanelClose, 420 );
		} );

		$( document ).on( 'click', '#mwc-panel-mode-sources', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			showSourcesPanel();
			setActivePanelIcon( 'sources' );
		} );

		$( document ).on( 'click', '#mwc-panel-mode-services', function ( e ) {
			e.preventDefault();
			e.stopPropagation();
			showServicesPanel();
			setActivePanelIcon( 'services' );
		} );

		$( document ).on( 'keydown.mwcCalendly', function ( e ) {
			if ( e.key === 'Escape' && calendlyIsOpen ) {
				closeCalendly();
			}
		} );

		$( document ).on( 'click.mwcOverlay', function ( e ) {
			if ( ! calendlyIsOpen || calendlyClosing ) {
				return;
			}
			var $t          = $( e.target );
			var insideChat  = $t.closest( '#mindweco-container' ).length > 0;
			var insidePanel = $t.closest( '#mindweco-calendly-panel' ).length > 0;
			var insideBtn   = $t.closest( '#mindweco-calendly-btn, .mindweco-open-calendly' ).length > 0;

			if ( ! insideChat && ! insidePanel && ! insideBtn ) {
				closeCalendly();
			}
		} );

		$( document ).on( 'click', '.mindweco-open-calendly', function ( e ) {
			e.stopPropagation();
			openCalendly();
		} );

		$( '#mindweco-calendly-btn' ).on( 'click', function ( e ) {
			e.stopPropagation();
			var services = getServiceLinks();
			if ( calendlyIsOpen && ! calendlyMinimized ) {
				minimizeCalendly();
			} else if ( calendlyIsOpen && calendlyMinimized ) {
				restoreCalendly();
			} else {
				if ( services.length > 1 ) {
					renderServiceCards( services );
					openCalendly( '__service_cards__' );
					switchPanelToServiceCards();
				} else {
					openCalendly();
				}
			}
		} );

		$( document ).on( 'click', '.mwc-service-card', function ( e ) {
			e.stopPropagation();
			var serviceUrl = $( this ).data( 'service-url' );
			if ( ! serviceUrl ) {
				return;
			}

			if ( ! calendlyIsOpen ) {
				openCalendly( serviceUrl );
				return;
			}

			var $iframe         = $( '#mindweco-calendly-iframe' );
			var $loading        = $( '#mwc-cal-loading' );
			var $serviceViewBar = ensureServiceViewBar();

			serviceCardsMode  = false;
			currentServiceUrl = serviceUrl;
			servicePanelView  = 'iframe';

			ensureServicesBody().hide();
			$serviceViewBar.css( 'display', 'flex' );

			$iframe.off( 'load.mwc' ).removeClass( 'loaded' ).attr( 'src', '' ).show();
			$loading.removeClass( 'hidden' );

			if ( isMobile() ) {
				setPanelHeaderAction( 'back' );
			} else {
				setPanelHeaderAction( 'close' );
			}

			$iframe.on( 'load.mwc', function () {
				var currentSrc = $( this ).attr( 'src' );
				if ( ! currentSrc || currentSrc === '' ) {
					return;
				}
				injectIframeCss( this );
				$loading.addClass( 'hidden' );
				$iframe.addClass( 'loaded' );
			} );

			setTimeout( function () {
				$iframe.attr( 'src', getEmbeddableUrl( serviceUrl ) );
			}, 80 );
		} );

		$( document ).on( 'click', '.mwc-service-back-btn', function () {
			currentServiceUrl = '';
			renderServiceCards( getServiceLinks() );
			switchPanelToServiceCards();
		} );

		$( document ).on( 'click', '#mwc-panel-mode-toggle', function ( e ) {
			e.preventDefault();
			e.stopPropagation();

			if ( panelMode === 'sources' ) {
				showServicesPanel();
			} else {
				showSourcesPanel();
			}
		} );
	}

	function initDrag() {
		if ( dragInitialized ) {
			return;
		}

		var topbar = document.querySelector( '#mindweco-container .mindweco-header' );
		var windowElement = document.getElementById( 'mindweco-container' );
		if ( ! topbar || ! windowElement ) {
			return;
		}

		dragInitialized = true;

		var isDragging = false;
		var startX;
		var startY;
		var startLeft;
		var startTop;
		var activePointerId = null;

		function isDragAvailable( target ) {
			return (
				! isMobile() &&
				( ! calendlyIsOpen || calendlyMinimized ) &&
				! windowElement.classList.contains( 'maximized' ) &&
				! target.closest( 'button, a, input, textarea, select, [role="button"]' )
			);
		}

		function clampPosition( left, top ) {
			var rect = windowElement.getBoundingClientRect();
			var margin = 8;
			var maxLeft = Math.max( margin, window.innerWidth - rect.width - margin );
			var maxTop = Math.max( margin, window.innerHeight - rect.height - margin );

			return {
				left: Math.min( Math.max( left, margin ), maxLeft ),
				top: Math.min( Math.max( top, margin ), maxTop )
			};
		}

		function startDrag( clientX, clientY, target ) {
			if ( ! isDragAvailable( target ) ) {
				return false;
			}

			if ( windowElement.style.transform && windowElement.style.transform !== 'none' ) {
				var transformedRect = windowElement.getBoundingClientRect();
				windowElement.style.transform = 'none';
				windowElement.style.right = 'auto';
				windowElement.style.bottom = 'auto';
				windowElement.style.margin = '0';
			}

			var rect = windowElement.getBoundingClientRect();
			isDragging = true;
			startX = clientX;
			startY = clientY;
			startLeft = rect.left;
			startTop = rect.top;
			windowElement.style.position = 'fixed';
			windowElement.style.right = 'auto';
			windowElement.style.bottom = 'auto';
			windowElement.style.margin = '0';
			windowElement.style.transform = 'none';
			topbar.classList.add( 'mindweco-header-dragging' );
			document.body.style.userSelect = 'none';
			return true;
		}

		function moveDrag( clientX, clientY ) {
			if ( ! isDragging ) {
				return;
			}

			var clamped = clampPosition(
				startLeft + ( clientX - startX ),
				startTop + ( clientY - startY )
			);
			windowElement.style.left = clamped.left + 'px';
			windowElement.style.top = clamped.top + 'px';
		}

		function stopDrag() {
			activePointerId = null;
			isDragging = false;
			topbar.classList.remove( 'mindweco-header-dragging' );
			document.body.style.userSelect = '';
		}

		resetDragState = stopDrag;

		topbar.addEventListener( 'pointerdown', function ( e ) {
			if ( startDrag( e.clientX, e.clientY, e.target ) ) {
				activePointerId = e.pointerId;
				if ( topbar.setPointerCapture ) {
					topbar.setPointerCapture( e.pointerId );
				}
				e.preventDefault();
				e.stopPropagation();
			}
		} );

		topbar.addEventListener('click', function (e) {
			if (!e.target.closest('button, a, input, textarea, select, [role="button"]')) {
				e.stopPropagation(); // prevent overlay-close handler from firing
			}
		});

		topbar.addEventListener( 'pointermove', function ( e ) {
			if ( activePointerId !== null && e.pointerId !== activePointerId ) {
				return;
			}

			moveDrag( e.clientX, e.clientY );
		} );

		topbar.addEventListener( 'pointerup', function ( e ) {
			if ( activePointerId !== null && e.pointerId !== activePointerId ) {
				return;
			}

			if ( topbar.releasePointerCapture ) {
				topbar.releasePointerCapture( e.pointerId );
			}
			stopDrag();
		} );

		topbar.addEventListener( 'pointercancel', stopDrag );
		topbar.addEventListener( 'dragstart', function ( e ) {
			e.preventDefault();
		} );
		window.addEventListener( 'blur', stopDrag );
	}

	window.MindwecoUI = {
		init             : init,
		openCalendly     : openCalendly,
		closeCalendly    : closeCalendly,
		minimizeCalendly : minimizeCalendly,
		restoreCalendly  : restoreCalendly,
		initDrag           : initDrag,
		showServicesPanel: showServicesPanel,
		showSourcesPanel : showSourcesPanel,
		setSuggestedServices : setSuggestedServices
	};

} )( jQuery );
