/**
 * Header & Footer Builder - Elementor Editor Scripts
 *
 * Runs inside the Elementor editor preview iframe.
 * All it does is ensure the header/footer wrappers are positioned
 * correctly relative to the Elementor canvas — no links, no buttons.
 * @package Softech_Addons_for_Elementor
 * @since   1.2.0
 * @updated 1.2.3
 */

/* global elementorFrontend */
( function () {
	'use strict';

	/**
	 * Move the header wrapper before #elementor and the footer wrapper
	 * after #elementor so they appear outside the editable canvas area,
	 * just like they do on the real frontend.
	 *
	 * This is a cosmetic reposition only — it does not affect saved data.
	 */
	function positionHFWrappers() {
		var canvas = document.getElementById( 'elementor' );
		if ( ! canvas ) {
			return;
		}

		var header = document.querySelector( '.sits-hf-editor-wrapper[data-template-type="header"]' );
		var footer = document.querySelector( '.sits-hf-editor-wrapper[data-template-type="footer"]' );

		if ( header && canvas.parentNode && header.parentNode !== canvas.parentNode ) {
			canvas.parentNode.insertBefore( header, canvas );
		}

		if ( footer && canvas.parentNode && footer.parentNode !== canvas.parentNode ) {
			canvas.parentNode.insertBefore( footer, canvas.nextSibling );
		}
	}

	// Run on DOM ready.
	document.addEventListener( 'DOMContentLoaded', positionHFWrappers );

	// Re-run after Elementor frontend initialises (handles async iframe loads).
	if ( typeof elementorFrontend !== 'undefined' ) {
		elementorFrontend.hooks.addAction( 'frontend/element_ready/global', positionHFWrappers );
	}

// Force overlay link click to work inside Elementor iframe
	document.addEventListener( 'click', function( e ) {
		var wrapper = e.target.closest( '.sits-hf-editor-wrapper' );
		if ( wrapper && wrapper.dataset.editUrl ) {
			e.preventDefault();
			e.stopImmediatePropagation();
			window.open( wrapper.dataset.editUrl, '_blank' );
		}
	}, true );

} )();
