const DynamicAssetsLoader = (() => {
	let loadedAssets = new Set();

	function loadScript(url, callback) {
		if (loadedAssets.has(url)) return callback?.();
		const script = document.createElement("script");
		script.src = url;
		script.async = false; // مهم للحفاظ على الترتيب
		script.onload = () => {
			loadedAssets.add(url);
			callback?.();
		};
		document.head.appendChild(script);
	}

	function loadScriptsSequential(urls = [], index = 0, finalCallback) {
		if (index >= urls.length) {
			if (typeof finalCallback === "function") finalCallback();
			return;
		}
		loadScript(urls[index], () => {
			loadScriptsSequential(urls, index + 1, finalCallback);
		});
	}

	function loadCSS(url) {
		if (loadedAssets.has(url)) return;
		const link = document.createElement("link");
		link.rel = "stylesheet";
		link.href = url;
		document.head.appendChild(link);
		loadedAssets.add(url);
	}

	function loadMultipleCSS(urls = []) {
		urls.forEach(url => {
			if (!loadedAssets.has(url)) {
				loadCSS(url);
			}
		});
	}

	function loadAssets({ js, css, callback }) {
		if (css) {
			if (Array.isArray(css)) loadMultipleCSS(css);
			else loadCSS(css);
		}
		if (js) {
			if (Array.isArray(js)) loadScriptsSequential(js, 0, callback);
			else loadScript(js, callback);
		}
	}

	function watchClass(selector, options) {
		const observer = new MutationObserver(() => {
			if (document.querySelector(selector)) {
				loadAssets(options);
				observer.disconnect();
			}
		});
		observer.observe(document.body, { childList: true, subtree: true });
	}

	function onUserInteraction(options) {
		const loadOnce = () => {
			loadAssets(options);
			window.removeEventListener("click", loadOnce);
			window.removeEventListener("touchstart", loadOnce);
			window.removeEventListener("focusin", loadOnce);
			window.removeEventListener("mouseover", loadOnce);
		};
		window.addEventListener("click", loadOnce, { once: true });
		window.addEventListener("touchstart", loadOnce, { once: true });
		window.addEventListener("focusin", loadOnce, { once: true });
		window.addEventListener("mouseover", loadOnce, { once: true });
	}

	function onElementInteraction(selector, eventTypes = ['click'], options) {
		const element = document.querySelector(selector);
		if (!element) return;

		const handler = () => {
			loadAssets(options);
			eventTypes.forEach(evt => element.removeEventListener(evt, handler));
		};

		eventTypes.forEach(evt => element.addEventListener(evt, handler));
	}

	function onElementVisible(selector, options) {
		const element = document.querySelector(selector);
		if (!element || typeof IntersectionObserver === "undefined") return;

		const observer = new IntersectionObserver((entries, obs) => {
			entries.forEach(entry => {
				if (entry.isIntersecting) {
					loadAssets(options);
					obs.disconnect();
				}
			});
		}, {
			threshold: 0.1
		});

		observer.observe(element);
	}

	return {
		loadScript,
		loadCSS,
		watchClass,
		onUserInteraction,
		onElementInteraction,
		onElementVisible,
	};
})();


// *************************************************************************************
//  أمثلة الاستخدام:
// 1. تحميل intl-tel-input عند ظهور .intl-phone:

DynamicAssetsLoader.watchClass(".intl-phone", {
	js: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/js/intlTelInput.min.js",
	],
	css: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/css/intlTelInput.min.css"
	],
	callback: () => {
		console.log("intl-tel-input loaded");
	}
});

//  تحميل مكتبة عند أول تفاعل حقيقي مع الصفحة:
DynamicAssetsLoader.onUserInteraction({
	js: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/js/intlTelInput.min.js",
	],
	callback: () => {
		console.log("Lazy JS Loaded");
	}
});

// عند التفاعل مع عنصر معيّن:
DynamicAssetsLoader.onElementInteraction("#videoTrigger", ['click'], {
	js: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/js/intlTelInput.min.js",
	],
	css: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/css/intlTelInput.min.css"
	],
	callback: () => console.log("Video Player Loaded")
});


// عند ظهور عنصر معيّن داخل الشاشة:
DynamicAssetsLoader.onElementVisible(".form-lazy", {
	js: [
		"https://cdn.jsdelivr.net/npm/intl-tel-input@25.3.1/build/js/intlTelInput.min.js",
	],
	callback: () => console.log("Form Enhancer Loaded")
});


// تحميل مباشر
DynamicAssetsLoader.loadScript(
  "https://cdn.jsdelivr.net/npm/sweetalert2@11", 
  () => {
    console.log("SweetAlert2 Loaded ✅");
    Swal.fire("تم تحميل السكريبت!");
  }
);
DynamicAssetsLoader.loadCSS(
  "https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css"
);