(function ($) {
	'use strict';

	function initAdvanceMegaMenu() {
		$('.unlockafe-amm').each(function () {
			var $widget = $(this);
			if ($widget.data('unlockafe-amm-inited')) return;
			$widget.data('unlockafe-amm-inited', true);

			var trigger = $widget.hasClass('unlockafe-amm--trigger-click') ? 'click' : 'hover';

			// Blocks panel uses position: absolute and CSS top: calc(100% + 12px); do not set inline top.
			function setBlocksPanelTop($item) {}

			var hoverCloseTimer = null;
			var FEATURED_SLIDER_DELAY = 4000;

			function startFeaturedSlider($featured) {
				if (!$featured || !$featured.length) return;

				var existing = $featured.data('ammSlider');
				if (existing && existing.timer) {
					clearInterval(existing.timer);
				}

				var $slides = $featured.find('.unlockafe-amm-featured__media--slider .unlockafe-amm-featured__img');
				if (!$slides.length || $slides.length < 2) {
					$featured.removeData('ammSlider');
					$slides.removeClass('is-active').first().addClass('is-active');
					return;
				}

				var index = 0;
				$slides.removeClass('is-active').eq(index).addClass('is-active');

				var timer = setInterval(function () {
					if (!$slides.length) return;
					index = (index + 1) % $slides.length;
					$slides.removeClass('is-active').eq(index).addClass('is-active');
				}, FEATURED_SLIDER_DELAY);

				$featured.data('ammSlider', { timer: timer });
			}

			function clearHoverCloseTimer() {
				if (hoverCloseTimer) {
					clearTimeout(hoverCloseTimer);
					hoverCloseTimer = null;
				}
			}

			$widget.find('.unlockafe-amm-nav__item').each(function () {
				var $item = $(this);
				var $panel = $item.find('.unlockafe-amm-panel');
				var $dropdown = $item.find('.unlockafe-amm-dropdown');
				var $content = $panel.length ? $panel : $dropdown;
				if (!$content.length) return;

				function setActiveItem($activeItem) {
					$widget.find('.unlockafe-amm-nav__link').removeClass('is-active');
					if ($activeItem && $activeItem.length) {
						$activeItem.find('.unlockafe-amm-nav__link').addClass('is-active');
					}
				}

				function closeItem() {
					$item.removeClass('is-open');
					setActiveItem(null);
				}

				// Open/close (mega panel or simple dropdown)
				if (trigger === 'hover') {
					var HOVER_CLOSE_DELAY = 280;
					$item.on('mouseenter.unlockafeamm', function () {
						clearHoverCloseTimer();
						$widget.find('.unlockafe-amm-nav__item').removeClass('is-open');
						$item.addClass('is-open');
						setActiveItem($item);
						setBlocksPanelTop($item);
					});
					$item.on('mouseleave.unlockafeamm', function () {
						hoverCloseTimer = setTimeout(function () {
							hoverCloseTimer = null;
							closeItem();
						}, HOVER_CLOSE_DELAY);
					});
				} else {
					$item.find('.unlockafe-amm-nav__link').on('click.unlockafeamm', function (e) {
						e.preventDefault();
						var wasOpen = $item.hasClass('is-open');
						$widget.find('.unlockafe-amm-nav__item').removeClass('is-open');
						if (!wasOpen) {
							$item.addClass('is-open');
							setActiveItem($item);
						} else {
							setActiveItem(null);
						}
						setBlocksPanelTop($item);
					});
				}
				$content.on('mouseenter.unlockafeamm', function () {
					if (trigger === 'hover') {
						clearHoverCloseTimer();
						$item.addClass('is-open');
						setActiveItem($item);
					}
				});
				$content.on('mouseleave.unlockafeamm', function () {
					if (trigger === 'hover') {
						hoverCloseTimer = setTimeout(function () {
							hoverCloseTimer = null;
							closeItem();
						}, HOVER_CLOSE_DELAY);
					}
				});
			});

			// Mobile toggle button – use delegation so it works even if DOM is wrapped by theme
			$widget.on('click.unlockafeamm', '.unlockafe-amm-toggle', function (e) {
				e.preventDefault();
				e.stopPropagation();
				var $root = $(this).closest('.unlockafe-amm');
				var $tgl = $(this);
				if (!$root.length) return;
				var isOpen = $root.hasClass('unlockafe-amm--mobile-open');
				if (isOpen) {
					$root.removeClass('unlockafe-amm--mobile-open');
					$tgl.attr('aria-expanded', 'false');
				} else {
					$root.addClass('unlockafe-amm--mobile-open');
					$tgl.attr('aria-expanded', 'true');
				}
			});

			// Close when clicking outside
			$(document).on('click.unlockafeamm', function (e) {
				if ($(e.target).closest('.unlockafe-amm').length) return;
				$widget.find('.unlockafe-amm-nav__item').removeClass('is-open');
				$widget.find('.unlockafe-amm-nav__link').removeClass('is-active');
				$widget.removeClass('unlockafe-amm--mobile-open');
				$widget.find('.unlockafe-amm-toggle').attr('aria-expanded', 'false');
			});

			// Category tabs: filter items
			$widget.find('.unlockafe-amm-tabs').on('click.unlockafeamm', '.unlockafe-amm-tab', function () {
				var $tab = $(this);
				var category = $tab.attr('data-category') || '';
				var $panel = $tab.closest('.unlockafe-amm-panel');
				$panel.find('.unlockafe-amm-tab').removeClass('is-active');
				$tab.addClass('is-active');
				filterByCategory($panel, category);
			});

			// Layout 4 & 5: scroll buttons for posts/pages panel body
			$widget.find('.unlockafe-amm-panel__body-outer').each(function () {
				var $outer = $(this);
				var $body = $outer.find('.unlockafe-amm-panel__body');
				var $btnUp = $outer.find('.unlockafe-amm-scroll-btn--up');
				var $btnDown = $outer.find('.unlockafe-amm-scroll-btn--down');
				var step = 200;

				function updateScrollButtons() {
					var scrollTop = $body.scrollTop();
					var maxScroll = $body[0].scrollHeight - $body[0].clientHeight;
					$btnUp.toggleClass('is-disabled', scrollTop <= 0);
					$btnDown.toggleClass('is-disabled', maxScroll <= 0 || scrollTop >= maxScroll - 2);
				}

				$body.on('scroll.unlockafeamm', updateScrollButtons);
				$outer.on('mouseenter.unlockafeamm', updateScrollButtons);

				$btnUp.on('click.unlockafeamm', function () {
					$body[0].scrollTop = Math.max(0, $body[0].scrollTop - step);
					updateScrollButtons();
				});
				$btnDown.on('click.unlockafeamm', function () {
					var el = $body[0];
					el.scrollTop = Math.min(el.scrollHeight - el.clientHeight, el.scrollTop + step);
					updateScrollButtons();
				});

				updateScrollButtons();
			});

			// Layout 1 (Blocks): update right panel from left list item (shared by click and hover)
			function updateBlocksFeaturedFromItem($link) {
				var $item = $link.closest('.unlockafe-amm-item--row');
				var $panel = $link.closest('.unlockafe-amm-panel--blocks');
				var $featured = $panel.find('.unlockafe-amm-blocks__right .unlockafe-amm-featured');
				if (!$featured.length) return;

				$panel.find('.unlockafe-amm-item--row').removeClass('is-active');
				$item.addClass('is-active');

				var title = $item.data('title') || '';
				var desc = $item.data('desc') || '';
				var link = $item.data('link') || '#';
				var img = $item.data('img') || '';
				// Read featured video URL directly from attribute to avoid any jQuery data caching issues
				var featuredVideo = $item.attr('data-featured-video') || '';
				var fallback = $item.data('fallback') || '';
				var galleryStr = ($item.data('gallery') || '').toString();
				var gallery = galleryStr ? galleryStr.split('|').filter(function (v) { return v; }) : [];

				$featured.find('.unlockafe-amm-featured__title').text(title);
				$featured.find('.unlockafe-amm-featured__overlay-title').text(title);

				if (desc) {
					var $sub = $featured.find('.unlockafe-amm-featured__subtitle');
					if (!$sub.length) {
						$sub = $('<p class="unlockafe-amm-featured__subtitle" />').insertAfter($featured.find('.unlockafe-amm-featured__title'));
					}
					$sub.text(desc);
					$featured.find('.unlockafe-amm-featured__overlay-desc').text(desc);
				} else {
					$featured.find('.unlockafe-amm-featured__subtitle').remove();
					$featured.find('.unlockafe-amm-featured__overlay-desc').text('');
				}

				var sliderData = $featured.data('ammSlider');
				if (sliderData && sliderData.timer) {
					clearInterval(sliderData.timer);
					$featured.removeData('ammSlider');
				}

				var $card = $featured.find('.unlockafe-amm-featured__card');
				if ($card.length) {
					// Clear previous media so the new item's featured media (video/gallery/image) fully controls the preview
					$card.find('.unlockafe-amm-featured__media--slider').remove();
					$card.find('.unlockafe-amm-featured__media--video').remove();
					$card.find('> .unlockafe-amm-featured__img').remove();
				}

				var hasMultiple = gallery.length > 1;
				if (featuredVideo && $card.length) {
					var $mediaVideo = $('<div class="unlockafe-amm-featured__media unlockafe-amm-featured__media--video" />')
						.prependTo($card);
					var $videoEl = $('<video />')
						.attr('src', featuredVideo)
						.attr('autoplay', 'autoplay')
						.attr('muted', 'muted')
						.attr('playsinline', 'playsinline')
						.attr('loop', 'loop')
						.attr('preload', 'metadata');
					if (img) {
						$videoEl.attr('poster', img);
					}
					$mediaVideo.append($videoEl);
				} else if (hasMultiple && $card.length) {
					var $media = $('<div class="unlockafe-amm-featured__media unlockafe-amm-featured__media--slider" />')
						.prependTo($card);
					gallery.forEach(function (url, idx) {
						var $slide = $('<div class="unlockafe-amm-featured__img" />')
							.css('background-image', 'url(' + url + ')')
							.attr('data-src', url)
							.attr('data-fallback', fallback || '');
						if (idx === 0) $slide.addClass('is-active');
						$media.append($slide);
						if (fallback) {
							var testImg = new Image();
							testImg.onerror = function () {
								$slide[0].style.backgroundImage = 'url(' + fallback + ')';
							};
							testImg.src = url;
						}
					});
					startFeaturedSlider($featured);
				} else if (img && $card.length) {
					var $img = $card.find('> .unlockafe-amm-featured__img').first();
					if (!$img.length) {
						$img = $('<div class="unlockafe-amm-featured__img" />')
							.prependTo($card);
					}
					$img.removeClass('unlockafe-amm-featured__img--placeholder');
					$img.attr('data-src', img).attr('data-fallback', fallback || '');
					$img.css('background-image', 'url(' + img + ')');
					if (fallback) {
						var testSingle = new Image();
						testSingle.onerror = function () {
							$img[0].style.backgroundImage = 'url(' + fallback + ')';
						};
						testSingle.src = img;
					}
				}

				var $btn = $featured.find('.unlockafe-amm-featured__btn');
				if ($btn.length) {
					$btn.attr('href', link || '#');
				}

				if (typeof window !== 'undefined' && window.innerWidth <= 768) {
					var $rightBlock = $panel.find('.unlockafe-amm-blocks__right');
					var $scrollBody = $panel.find('.unlockafe-amm-panel__body');
					function scrollDetailIntoView() {
						if ($rightBlock.length && $rightBlock[0].scrollIntoView) {
							$rightBlock[0].scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
							return;
						}
						if (!$scrollBody.length) return;
						var bodyEl = $scrollBody[0];
						if ($rightBlock.length) void $rightBlock[0].offsetHeight;
						var maxScroll = bodyEl.scrollHeight - bodyEl.clientHeight;
						if (maxScroll <= 0) return;
						bodyEl.scrollTo({ top: maxScroll, behavior: 'smooth' });
					}
					setTimeout(function () { requestAnimationFrame(scrollDetailIntoView); }, 50);
					setTimeout(function () { requestAnimationFrame(scrollDetailIntoView); }, 250);
					setTimeout(function () { requestAnimationFrame(scrollDetailIntoView); }, 500);
				}
			}

			$widget.find('.unlockafe-amm-panel--blocks').on('click.unlockafeamm', '.unlockafe-amm-item--row .unlockafe-amm-item__link', function (e) {
				e.preventDefault();
				updateBlocksFeaturedFromItem($(this));
			});
			$widget.find('.unlockafe-amm-panel--blocks').on('mouseenter.unlockafeamm', '.unlockafe-amm-item--row .unlockafe-amm-item__link', function () {
				updateBlocksFeaturedFromItem($(this));
			});

			// Submenu image fallback: if thematic image fails, show placeholder (data-fallback)
			$widget.find('img[data-fallback]').on('error.unlockafeamm', function () {
				var fb = this.getAttribute('data-fallback');
				if (fb) this.src = fb;
			});
			$widget.find('[data-fallback][data-src]').each(function () {
				var el = this;
				var src = el.getAttribute('data-src');
				var fb = el.getAttribute('data-fallback');
				if (!src || !fb) return;
				var img = new Image();
				img.onerror = function () {
					el.style.backgroundImage = 'url(' + fb + ')';
				};
				img.src = src;
			});

			// Initialize sliders for any featured blocks that already have multiple images
			$widget.find('.unlockafe-amm-featured').each(function () {
				startFeaturedSlider($(this));
			});
		});
	}

	function filterByCategory($panel, category) {
		var $body = $panel.find('.unlockafe-amm-panel__body');
		$body.attr('data-filter', category);

		// Rows (blocks layout)
		$body.find('.unlockafe-amm-item[data-category]').each(function () {
			var itemCat = $(this).attr('data-category') || '';
			$(this).toggleClass('is-hidden', category !== '' && itemCat !== category);
		});
		// Features layout: hide whole row when category doesn't match (same category = same row)
		$body.find('.unlockafe-amm-features__row[data-category]').each(function () {
			var rowCat = $(this).attr('data-category') || '';
			$(this).toggleClass('is-hidden', category !== '' && rowCat !== category);
		});
		// Cards (features layout)
		$body.find('.unlockafe-amm-card[data-category]').each(function () {
			var itemCat = $(this).attr('data-category') || '';
			$(this).toggleClass('is-hidden', category !== '' && itemCat !== category);
		});
		// Solution cards
		$body.find('.unlockafe-amm-sol-card[data-category]').each(function () {
			var itemCat = $(this).attr('data-category') || '';
			$(this).toggleClass('is-hidden', category !== '' && itemCat !== category);
		});

		// Update header count text for Features/Solutions panels
		var $count = $panel.find('.unlockafe-amm-panel__count').first();
		if ($count.length) {
			var label = (function () {
				var txt = ($count.text() || '').trim();
				var m = txt.match(/Showing\s+\d+\s+of\s+\d+\s+(.+)$/i);
				return m && m[1] ? m[1] : '';
			})();

			var selector = '';
			if ($panel.hasClass('unlockafe-amm-panel--blocks')) {
				selector = '.unlockafe-amm-item[data-category]';
			} else if ($panel.hasClass('unlockafe-amm-panel--features')) {
				selector = '.unlockafe-amm-card[data-category]';
			} else if ($panel.hasClass('unlockafe-amm-panel--solutions')) {
				selector = '.unlockafe-amm-sol-card[data-category]';
			}

			if (selector) {
				var total = $body.find(selector).length;
				var shown = $body.find(selector).not('.is-hidden').length;
				$count.text('Showing ' + shown + ' of ' + total + (label ? ' ' + label : ''));
			}
		}
	}

	// Elementor frontend init (for editor + frontend)
	if (typeof elementorFrontend !== 'undefined') {
		$(window).on('elementor/frontend/init', function () {
			elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-advance-mega-menu.default', function () {
				initAdvanceMegaMenu();
			});
		});
	}

	// Fallback: plain DOM-ready init in case Elementor hook doesn't fire
	$(function () {
		initAdvanceMegaMenu();
	});

	// Extra safety: vanilla JS global click handler for mobile toggles (works if jQuery init missed)
	if (typeof window !== 'undefined') {
		document.addEventListener('click', function (e) {
			var btn = e.target.closest && e.target.closest('.unlockafe-amm-toggle');
			if (!btn) return;
			var navRoot = btn.closest('.unlockafe-amm');
			if (!navRoot) return;
			e.preventDefault();
			e.stopPropagation();
			var isOpen = navRoot.classList.contains('unlockafe-amm--mobile-open');
			if (isOpen) {
				navRoot.classList.remove('unlockafe-amm--mobile-open');
				btn.setAttribute('aria-expanded', 'false');
			} else {
				navRoot.classList.add('unlockafe-amm--mobile-open');
				btn.setAttribute('aria-expanded', 'true');
			}
		}, false);
	}
})(jQuery);
