(function($){
	'use strict';

	var reordering = false;
	var enhanceTimer = null;
	var currentWidgetId = null;

	function getDemoItems(){
		return [
			{ item_id: 'demo', parent_id: '', title: 'Demo', link: { url: '#' } },
			{ item_id: 'home', parent_id: '', title: 'Home', link: { url: '#' } },
			{ item_id: 'pages', parent_id: '', title: 'Pages', link: { url: '#' } },
			{ item_id: 'projects', parent_id: '', title: 'Projects', link: { url: '#' } },
			{ item_id: 'blog', parent_id: '', title: 'Blog', link: { url: '#' } },
			{ item_id: 'shop', parent_id: '', title: 'Shop', link: { url: '#' } },
			{ item_id: 'pages_features', parent_id: 'pages', title: 'Features', link: { url: '#' } },
			{ item_id: 'pages_service', parent_id: 'pages', title: 'Service', link: { url: '#' } },
			{ item_id: 'pages_team', parent_id: 'pages', title: 'Team', link: { url: '#' } },
			{ item_id: 'pages_pricing', parent_id: 'pages', title: 'Pricing', link: { url: '#' } },
			{ item_id: 'pages_faq', parent_id: 'pages', title: 'FAQ', link: { url: '#' } },
			{ item_id: 'projects_portfolio', parent_id: 'projects', title: 'Portfolio', link: { url: '#' } },
			{ item_id: 'projects_case_studies', parent_id: 'projects', title: 'Case Studies', link: { url: '#' } },
			{ item_id: 'projects_gallery', parent_id: 'projects', title: 'Gallery', link: { url: '#' } },
			{ item_id: 'portfolio_grid', parent_id: 'projects_portfolio', title: 'Grid Layout', link: { url: '#' } },
			{ item_id: 'portfolio_masonry', parent_id: 'projects_portfolio', title: 'Masonry Layout', link: { url: '#' } },
			{ item_id: 'portfolio_slider', parent_id: 'projects_portfolio', title: 'Slider Layout', link: { url: '#' } },
			{ item_id: 'portfolio_single', parent_id: 'projects_portfolio', title: 'Single Project', link: { url: '#' } }
		];
	}

	function seedIfEmpty(){
		if (!currentWidgetId || typeof elementor === 'undefined' || !elementor.getContainer) {
			return;
		}
		var container = elementor.getContainer(currentWidgetId);
		if (!container || !container.settings) {
			return;
		}
		var menuSource = container.settings.get('menu_source');
		var builderType = container.settings.get('manual_builder_type');
		if (menuSource === 'manual' && builderType === 'legacy') {
			var current = container.settings.get('manual_items');
			if (Array.isArray(current) && current.length > 0) {
				return;
			}
			container.settings.setExternalChange('manual_items', getDemoItems());
		}
		if (menuSource === 'manual' && builderType === 'grid') {
			var rows = container.settings.get('mega_menu_rows');
			if (Array.isArray(rows) && rows.length > 0) {
				return;
			}
			var manualItems = container.settings.get('manual_items');
			if (Array.isArray(manualItems) && manualItems.length > 0) {
				var migrated = migrateManualItemsToGrid(manualItems);
				if (migrated && migrated.length > 0) {
					container.settings.setExternalChange('mega_menu_rows', migrated);
					return;
				}
			}
			container.settings.setExternalChange('mega_menu_rows', [
				{
					row_columns: [
						{ column_width: '6', column_items: [{ title: 'Item 1', item_enable: 'yes', item_visibility: 'both', media_type: 'none' }] },
						{ column_width: '6', column_items: [{ title: 'Item 2', item_enable: 'yes', item_visibility: 'both', media_type: 'none' }] }
					]
				}
			]);
		}
	}

	function migrateManualItemsToGrid(manualItems) {
		var nodes = {};
		var children = {};
		manualItems.forEach(function (item) {
			var id = (item.item_id || '').toString().trim() || ('id_' + Math.random().toString(36).slice(2, 9));
			nodes[id] = item;
			children[id] = [];
		});
		manualItems.forEach(function (item) {
			var id = (item.item_id || '').toString().trim();
			if (!id) { return; }
			var parentId = (item.parent_id || '').toString().trim();
			if (parentId && children[parentId]) {
				children[parentId].push(id);
			}
		});
		var roots = [];
		manualItems.forEach(function (item) {
			var id = (item.item_id || '').toString().trim();
			if (!id) { return; }
			var parentId = (item.parent_id || '').toString().trim();
			if (!parentId || !nodes[parentId]) {
				roots.push(id);
			}
		});
		if (roots.length === 0) { return null; }
		var columns = roots.map(function (rootId) {
			var childIds = children[rootId] || [];
			var columnItems = childIds.map(function (cid) {
				var n = nodes[cid];
				if (!n) { return { title: 'Item', item_enable: 'yes', item_visibility: 'both', media_type: 'none' }; }
				var mediaType = (n.thumb && n.thumb.url) ? 'image' : 'none';
				var item = {
					title: n.title || 'Item',
					description: '',
					link: n.link || { url: '', is_external: false, nofollow: false },
					media_type: mediaType,
					item_enable: 'yes',
					item_visibility: 'both'
				};
				if (mediaType === 'image' && n.thumb) {
					item.image = n.thumb;
					item.show_media = 'yes';
				} else {
					item.selected_icon = { value: 'fas fa-star', library: 'fa-solid' };
					item.show_media = 'yes';
				}
				return item;
			});
			if (columnItems.length === 0) {
				var rootNode = nodes[rootId];
				columnItems = [{
					title: rootNode && rootNode.title ? rootNode.title : 'Item',
					link: rootNode && rootNode.link ? rootNode.link : { url: '#', is_external: false, nofollow: false },
					item_enable: 'yes',
					item_visibility: 'both',
					media_type: 'none'
				}];
			}
			return { column_width: 'auto', column_items: columnItems };
		});
		return [{ row_columns: columns }];
	}

	function ensureStyles(){
		if (document.getElementById('unlockafe-mega-menu-editor-style')) {
			return;
		}
		var style = document.createElement('style');
		style.id = 'unlockafe-mega-menu-editor-style';
		style.textContent = '' +
			'.unlockafe-mm-repeater-row .elementor-repeater-row-title{display:flex;align-items:center;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-1 .elementor-repeater-row-title{padding-left:14px;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-2 .elementor-repeater-row-title{padding-left:28px;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-3 .elementor-repeater-row-title{padding-left:42px;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-4 .elementor-repeater-row-title{padding-left:56px;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-5 .elementor-repeater-row-title{padding-left:70px;}' +
			'.unlockafe-mm-repeater-row.unlockafe-mm-depth-6 .elementor-repeater-row-title{padding-left:84px;}';
		document.head.appendChild(style);
	}

	function readValue($row, settingName){
		var $field = $row.find('[data-setting="' + settingName + '"]');
		if ($field.length === 0) {
			return '';
		}
		var $input = $field.find('input, textarea, select').first();
		return ($input.val() || '').toString().trim();
	}

	function buildOrder(rows){
		var nodes = {};
		var children = {};
		var insertionOrder = [];

		rows.forEach(function($row){
			var id = readValue($row, 'item_id');
			if (!id) {
				id = 'row_' + $row.attr('data-id');
			}
			if (!children[id]) {
				children[id] = [];
			}
			nodes[id] = {
				id: id,
				parentId: readValue($row, 'parent_id'),
				$row: $row
			};
			insertionOrder.push(id);
		});

		insertionOrder.forEach(function(id){
			var node = nodes[id];
			var parentId = node.parentId;
			if (parentId && nodes[parentId]) {
				if (!children[parentId]) {
					children[parentId] = [];
				}
				children[parentId].push(id);
			}
		});

		var roots = [];
		insertionOrder.forEach(function(id){
			var node = nodes[id];
			var parentId = node.parentId;
			if (!parentId || !nodes[parentId]) {
				roots.push(id);
			}
		});

		var ordered = [];
		var depths = {};
		var visiting = {};

		function dfs(id, depth){
			if (!nodes[id]) {
				return;
			}
			if (visiting[id]) {
				return;
			}
			visiting[id] = true;
			depths[id] = depth;
			ordered.push(id);
			(children[id] || []).forEach(function(cid){
				dfs(cid, depth + 1);
			});
			visiting[id] = false;
		}

		roots.forEach(function(id){
			dfs(id, 0);
		});

		insertionOrder.forEach(function(id){
			if (ordered.indexOf(id) === -1) {
				dfs(id, 0);
			}
		});

		return { ordered: ordered, depths: depths, nodes: nodes };
	}

	function enhanceMegaMenuRepeater(){
		if (reordering) {
			return;
		}

		var $panel = $('#elementor-panel');
		if ($panel.length === 0) {
			return;
		}

		var $widget = $panel.find('[data-widget_type="unlockafe-mega-menu"]');
		if ($widget.length === 0) {
			return;
		}

		var $menuSource = $panel.find('[data-setting="menu_source"] select').first();
		if ($menuSource.length && $menuSource.val() !== 'manual') {
			return;
		}

		var builderType = ($panel.find('[data-setting="manual_builder_type"] select').first().val() || 'legacy').toString();
		if (builderType === 'grid') {
			seedIfEmpty();
			return;
		}

		var layout = ($panel.find('[data-setting="layout"] select').first().val() || 'layout-1').toString();

		var $manualItemsControl = $panel.find('.elementor-control-manual_items').first();
		if ($manualItemsControl.length === 0) {
			$manualItemsControl = $panel.find('[data-setting="manual_items"]').closest('.elementor-control').first();
		}
		if ($manualItemsControl.length === 0) {
			return;
		}

		// Elementor renders repeater row fields lazily (on row expand). Always toggle within the whole panel
		// so newly injected controls also get the correct visibility.
		$panel
			.find('.elementor-control [data-setting="thumb"], [data-setting="thumb"]')
			.closest('.elementor-control')
			.css('display', layout === 'layout-2' ? '' : 'none');

		var $rowsWrap = $manualItemsControl.find('.elementor-repeater-fields, .elementor-repeater-rows').first();
		if ($rowsWrap.length === 0) {
			return;
		}

		var $rows = $rowsWrap.children('.elementor-repeater-row');
		if ($rows.length === 0) {
			$rows = $rowsWrap.find('> .elementor-repeater-row');
		}
		if ($rows.length === 0) {
			seedIfEmpty();
			return;
		}

		ensureStyles();

		var rows = [];
		$rows.each(function(){
			rows.push($(this));
		});

		var tree = buildOrder(rows);

		reordering = true;
		try {
			tree.ordered.forEach(function(id){
				var node = tree.nodes[id];
				if (!node) {
					return;
				}
				node.$row.appendTo($rowsWrap);
			});

			Object.keys(tree.nodes).forEach(function(id){
				var node = tree.nodes[id];
				var depth = tree.depths[id] || 0;
				node.$row.addClass('unlockafe-mm-repeater-row');
				for (var i = 0; i <= 8; i++) {
					node.$row.removeClass('unlockafe-mm-depth-' + i);
				}
				node.$row.addClass('unlockafe-mm-depth-' + Math.min(depth, 6));
			});
		} finally {
			reordering = false;
		}
	}

	function scheduleEnhance(){
		clearTimeout(enhanceTimer);
		enhanceTimer = setTimeout(enhanceMegaMenuRepeater, 60);
	}

	$(window).on('elementor:init', function(){
		if (typeof elementor === 'undefined' || !elementor.channels || !elementor.channels.editor) {
			return;
		}

		elementor.channels.editor.on('section:activated', function(sectionName, editor){
			try {
				var view = editor && editor.getOption ? editor.getOption('editedElementView') : null;
				var widgetType = view && view.model ? view.model.get('widgetType') : null;
				if (widgetType !== 'unlockafe-mega-menu') {
					currentWidgetId = null;
					return;
				}
				currentWidgetId = view && view.model ? view.model.id : null;
				scheduleEnhance();
			} catch (e) {
				return;
			}
		});

		$(document).on('input change', '.elementor-control-manual_items [data-setting="item_id"] input, .elementor-control-manual_items [data-setting="parent_id"] input', scheduleEnhance);
		$(document).on('click', '.elementor-control-manual_items .elementor-repeater-add, .elementor-control-manual_items .elementor-repeater-remove', scheduleEnhance);
		$(document).on('change', '#elementor-panel [data-setting="manual_builder_type"] select', scheduleEnhance);

		if (typeof MutationObserver !== 'undefined') {
			var obs = new MutationObserver(function(){
				scheduleEnhance();
			});
			var panel = document.getElementById('elementor-panel');
			if (panel) {
				obs.observe(panel, { childList: true, subtree: true });
			}
		}
	});

	$(document).ready(function(){
		scheduleEnhance();
	});

	// Re-apply toggle when user changes layout or expands a repeater row (fields are injected on demand)
	$(document).on('change', '#elementor-panel [data-setting="layout"] select', scheduleEnhance);
	$(document).on('click', '#elementor-panel .elementor-repeater-row-item-title, #elementor-panel .elementor-repeater-row-tools', scheduleEnhance);
})(jQuery);
