/**
 * Advance Mega Sidebar – editor: "Select Advance Mega Menu on this page" populates AMM widget ID.
 */
(function () {
	'use strict';

	function findAMMContainers(container) {
		var out = [];
		if (!container) return out;
		var model = container.model;
		if (model && model.get) {
			var widgetType = model.get('widgetType');
			if (widgetType === 'unlockafe-advance-mega-menu') {
				var id = model.get('id');
				var settings = model.get('settings') || {};
				var items = settings.menu_items || [];
				var label = id;
				if (items.length && items[0] && items[0].menu_label) {
					label = items[0].menu_label + ' (ID: ' + id + ')';
				} else {
					label = 'Advance Mega Menu (ID: ' + id + ')';
				}
				out.push({ id: id, label: label });
			}
		}
		var children = container.children;
		if (children && children.length) {
			for (var i = 0; i < children.length; i++) {
				out = out.concat(findAMMContainers(children[i]));
			}
		}
		return out;
	}

	function findAMMContainersByDOM() {
		var out = [];
		if (typeof elementor === 'undefined' || !elementor.getContainer) return out;
		var nodes = document.querySelectorAll('.elementor-element[data-id]');
		for (var i = 0; i < nodes.length; i++) {
			var id = nodes[i].getAttribute('data-id');
			if (!id) continue;
			try {
				var c = elementor.getContainer(id);
				if (c && c.model && c.model.get && c.model.get('widgetType') === 'unlockafe-advance-mega-menu') {
					var settings = c.model.get('settings') || {};
					var items = settings.menu_items || [];
					var label = items.length && items[0] && items[0].menu_label
						? items[0].menu_label + ' (ID: ' + id + ')'
						: 'Advance Mega Menu (ID: ' + id + ')';
					out.push({ id: id, label: label });
				}
			} catch (err) {}
		}
		return out;
	}

	function getDocumentContainer() {
		try {
			if (typeof elementor !== 'undefined' && elementor.documents && elementor.documents.getCurrent) {
				var doc = elementor.documents.getCurrent();
				if (doc && doc.container) return doc.container;
			}
		} catch (e) {}
		return null;
	}

	function runPickAMM(clickedButton) {
		// Use the same document as the button (panel may be in iframe)
		var doc = (clickedButton && clickedButton.ownerDocument) ? clickedButton.ownerDocument : document;
		// Find the help paragraph (next to the button) – use button's parent so we always show in the right place
		var helpEl = doc.querySelector('.unlockafe-ams-pick-help');
		if (!helpEl && clickedButton) {
			var wrap = clickedButton.closest('.elementor-control-amm_widget_id_picker');
			if (wrap) helpEl = wrap.querySelector('.unlockafe-ams-pick-help');
		}
		if (!helpEl) helpEl = doc.querySelector('.unlockafe-ams-pick-help');
		if (helpEl) {
			helpEl.style.display = 'block';
			helpEl.innerHTML = '';
		}

		// Get list of Advance Mega Menu widgets (DOM method works without document container)
		var list = findAMMContainersByDOM();
		if (list.length === 0) {
			var docContainer = getDocumentContainer();
			if (docContainer) list = findAMMContainers(docContainer);
		}

		if (list.length === 0) {
			if (helpEl) {
				helpEl.textContent = 'No Advance Mega Menu widget found on this page. Add an "Advance Mega Menu" widget to this template first, then use this button again.';
			}
			if (typeof elementor !== 'undefined' && elementor.notifications && elementor.notifications.showToast) {
				elementor.notifications.showToast({ message: 'No Advance Mega Menu widget found. Add one to this page first.' });
			}
			return;
		}

		var select = document.createElement('select');
		select.className = 'unlockafe-ams-pick-select';
		select.style.cssText = 'width:100%; margin-top:8px; padding:6px 8px;';
		var opt0 = document.createElement('option');
		opt0.value = '';
		opt0.textContent = '— Select one —';
		select.appendChild(opt0);
		list.forEach(function (item) {
			var opt = document.createElement('option');
			opt.value = item.id;
			opt.textContent = item.label;
			select.appendChild(opt);
		});

		// Apply selection by updating the Widget ID input in the panel (works without sidebar container)
		function applySelection(id) {
			var input = doc.querySelector('.elementor-control-amm_widget_id input[data-setting="amm_widget_id"]') ||
				doc.querySelector('input[data-setting="amm_widget_id"]');
			if (input) {
				input.value = id || '';
				input.dispatchEvent(new Event('input', { bubbles: true }));
				input.dispatchEvent(new Event('change', { bubbles: true }));
			}
			// Also try Elementor API if we have container
			try {
				if (typeof elementor !== 'undefined' && elementor.getCurrentElement) {
					var container = elementor.getCurrentElement();
					if (container && container.model && container.model.get && container.model.get('widgetType') === 'unlockafe-advance-mega-sidebar') {
						if (container.model.setSetting) container.model.setSetting('amm_widget_id', id || '');
						if (typeof $e !== 'undefined' && $e.run) {
							$e.run('document/elements/settings', { container: container, settings: { amm_widget_id: id || '' } });
						}
					}
				}
			} catch (err) {}
			if (typeof elementor !== 'undefined' && elementor.notifications && elementor.notifications.showToast) {
				elementor.notifications.showToast({ message: id ? 'Advance Mega Menu linked.' : 'Selection cleared.' });
			}
		}

		// Current value from the input if present
		var input = doc.querySelector('.elementor-control-amm_widget_id input[data-setting="amm_widget_id"]') ||
			doc.querySelector('input[data-setting="amm_widget_id"]');
		var currentId = (input && input.value) ? input.value.trim() : '';
		select.value = currentId;
		select.addEventListener('change', function () {
			applySelection(select.value);
		});

		if (helpEl) {
			helpEl.appendChild(document.createTextNode('Choose which Advance Mega Menu to use:'));
			helpEl.appendChild(select);
		}
	}

	function init() {
		document.addEventListener('click', function (e) {
			var btn = e.target && e.target.closest && e.target.closest('.unlockafe-ams-pick-amm');
			if (!btn) return;
			e.preventDefault();
			runPickAMM(btn);
		}, true);
	}

	if (typeof elementor !== 'undefined') {
		init();
	} else {
		jQuery(window).on('elementor:init', init);
	}
})();
