<?php

namespace Unlockafe_addons\Widgets;

use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Widget_Base;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Icons_Manager;

if (!defined('ABSPATH')) {
	exit;
}

class Mega_Menu extends Widget_Base
{
	protected $nav_menu_index = 1;

	private function get_demo_manual_items(string $layout): array
	{
		if ($layout === 'layout-2') {
			return [
				[
					'item_id' => 'demo',
					'parent_id' => '',
					'title' => 'Demo',
					'link' => ['url' => '#'],
				],
				[
					'item_id' => 'about',
					'parent_id' => '',
					'title' => 'About',
					'link' => ['url' => '#'],
				],
				[
					'item_id' => 'pages',
					'parent_id' => '',
					'title' => 'Pages',
					'link' => ['url' => '#'],
				],
				[
					'item_id' => 'blogs',
					'parent_id' => '',
					'title' => 'Blogs',
					'link' => ['url' => '#'],
				],
				[
					'item_id' => 'contact',
					'parent_id' => '',
					'title' => 'Contact',
					'link' => ['url' => '#'],
				],

				// Demo image cards (layout-2)
				['item_id' => 'demo_crm', 'parent_id' => 'demo', 'title' => 'CRM Software', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-1.png']],
				['item_id' => 'demo_finance', 'parent_id' => 'demo', 'title' => 'Finance Apps', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-2.png']],
				['item_id' => 'demo_chatbot', 'parent_id' => 'demo', 'title' => 'AI Chatbot', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-3.png']],
				['item_id' => 'demo_agency', 'parent_id' => 'demo', 'title' => 'AI Agency', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-4.png']],
				['item_id' => 'demo_generator', 'parent_id' => 'demo', 'title' => 'AI Image Generator', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-5.png']],
				['item_id' => 'demo_generator2', 'parent_id' => 'demo', 'title' => 'AI Image Generator 2', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-6.png']],
				['item_id' => 'demo_generator3', 'parent_id' => 'demo', 'title' => 'AI Image Generator 3', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-7.png']],
				['item_id' => 'demo_stock', 'parent_id' => 'demo', 'title' => 'Photostock', 'link' => ['url' => '#'], 'thumb' => ['url' => UNLOCKAFE_ASSETS . 'front-end/images/work/work-thumb-4-8.png']],
				[
					'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' => 'service_details',
					'parent_id' => 'pages_service',
					'title' => 'Service Details',
					'link' => ['url' => '#'],
				],
			];
		}

		// layout-1
		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' => '#'],
			],

			// Projects submenu + submenu of submenu (flyout on click)
			['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' => '#']],

			// Demo mega columns (headings)
			['item_id' => 'col_hlv_1', 'parent_id' => 'demo', 'title' => 'HOME LIGHT VERSION', 'link' => ['url' => '#']],
			['item_id' => 'col_hdv_1', 'parent_id' => 'demo', 'title' => 'HOME DARK VERSION', 'link' => ['url' => '#']],
			['item_id' => 'col_hlv_2', 'parent_id' => 'demo', 'title' => 'HOME LIGHT VERSION', 'link' => ['url' => '#']],
			['item_id' => 'col_hdv_2', 'parent_id' => 'demo', 'title' => 'HOME DARK VERSION', 'link' => ['url' => '#']],
			['item_id' => 'col_show_1', 'parent_id' => 'demo', 'title' => 'SHOWCASE', 'link' => ['url' => '#']],
			['item_id' => 'col_show_2', 'parent_id' => 'demo', 'title' => 'SHOWCASE', 'link' => ['url' => '#']],

			// Column lists
			['item_id' => 'hlv1_modern', 'parent_id' => 'col_hlv_1', 'title' => 'Modern Agency', 'link' => ['url' => '#']],
			['item_id' => 'hlv1_design', 'parent_id' => 'col_hlv_1', 'title' => 'Design Studio', 'link' => ['url' => '#']],
			['item_id' => 'hlv1_marketing', 'parent_id' => 'col_hlv_1', 'title' => 'Digital Marketing', 'link' => ['url' => '#']],
			['item_id' => 'hlv1_creative', 'parent_id' => 'col_hlv_1', 'title' => 'Creative Studio', 'link' => ['url' => '#']],
			['item_id' => 'hlv1_arch', 'parent_id' => 'col_hlv_1', 'title' => 'Architecture Hub', 'link' => ['url' => '#']],

			['item_id' => 'hdv1_modern', 'parent_id' => 'col_hdv_1', 'title' => 'Modern Agency', 'link' => ['url' => '#']],
			['item_id' => 'hdv1_design', 'parent_id' => 'col_hdv_1', 'title' => 'Design Studio', 'link' => ['url' => '#']],
			['item_id' => 'hdv1_marketing', 'parent_id' => 'col_hdv_1', 'title' => 'Digital Marketing', 'link' => ['url' => '#']],
			['item_id' => 'hdv1_creative', 'parent_id' => 'col_hdv_1', 'title' => 'Creative Studio', 'link' => ['url' => '#']],
			['item_id' => 'hdv1_arch', 'parent_id' => 'col_hdv_1', 'title' => 'Architecture Hub', 'link' => ['url' => '#']],

			['item_id' => 'hlv2_corp', 'parent_id' => 'col_hlv_2', 'title' => 'Corporate Agency', 'link' => ['url' => '#']],
			['item_id' => 'hlv2_mobile', 'parent_id' => 'col_hlv_2', 'title' => 'Mobile App', 'link' => ['url' => '#']],
			['item_id' => 'hlv2_it', 'parent_id' => 'col_hlv_2', 'title' => 'IT Solutions', 'link' => ['url' => '#']],
			['item_id' => 'hlv2_crypto', 'parent_id' => 'col_hlv_2', 'title' => 'Cryptocurrency', 'link' => ['url' => '#']],
			['item_id' => 'hlv2_startup', 'parent_id' => 'col_hlv_2', 'title' => 'Startup Agency', 'link' => ['url' => '#']],

			['item_id' => 'hdv2_corp', 'parent_id' => 'col_hdv_2', 'title' => 'Corporate Agency', 'link' => ['url' => '#']],
			['item_id' => 'hdv2_mobile', 'parent_id' => 'col_hdv_2', 'title' => 'Mobile App', 'link' => ['url' => '#']],
			['item_id' => 'hdv2_it', 'parent_id' => 'col_hdv_2', 'title' => 'IT Solutions', 'link' => ['url' => '#']],
			['item_id' => 'hdv2_crypto', 'parent_id' => 'col_hdv_2', 'title' => 'Cryptocurrency', 'link' => ['url' => '#']],
			['item_id' => 'hdv2_startup', 'parent_id' => 'col_hdv_2', 'title' => 'Startup Agency', 'link' => ['url' => '#']],

			['item_id' => 'show1_webgl', 'parent_id' => 'col_show_1', 'title' => 'Webgl Showcase', 'link' => ['url' => '#']],
			['item_id' => 'show1_coverflow', 'parent_id' => 'col_show_1', 'title' => 'Coverflow Slider', 'link' => ['url' => '#']],
			['item_id' => 'show1_thumb', 'parent_id' => 'col_show_1', 'title' => 'Creative Thumb Slider', 'link' => ['url' => '#']],
			['item_id' => 'show1_skew', 'parent_id' => 'col_show_1', 'title' => 'Creative Skew Slider', 'link' => ['url' => '#']],
			['item_id' => 'show1_text', 'parent_id' => 'col_show_1', 'title' => 'Creative Text Slider', 'link' => ['url' => '#']],

			['item_id' => 'show2_wrapper', 'parent_id' => 'col_show_2', 'title' => 'Wrapper Slider', 'link' => ['url' => '#']],
			['item_id' => 'show2_portfolio', 'parent_id' => 'col_show_2', 'title' => 'Portfolio Slider', 'link' => ['url' => '#']],
			['item_id' => 'show2_pshow', 'parent_id' => 'col_show_2', 'title' => 'Portfolio Showcase', 'link' => ['url' => '#']],
			['item_id' => 'show2_brand', 'parent_id' => 'col_show_2', 'title' => 'Brand Showcase', 'link' => ['url' => '#']],
			['item_id' => 'show2_interactive', 'parent_id' => 'col_show_2', 'title' => 'Interactive with Hover', 'link' => ['url' => '#']],
		];
	}

	private function build_manual_tree(array $items): array
	{
		$nodes = [];
		$children_map = [];

		foreach ($items as $item) {
			$id = isset($item['item_id']) ? trim((string) $item['item_id']) : '';
			if ($id === '') {
				continue;
			}
			$nodes[$id] = $item;
			$children_map[$id] = [];
		}

		$roots = [];
		foreach ($nodes as $id => $item) {
			$parent_id = isset($item['parent_id']) ? trim((string) $item['parent_id']) : '';
			if ($parent_id !== '' && isset($children_map[$parent_id])) {
				$children_map[$parent_id][] = $id;
			} else {
				$roots[] = $id;
			}
		}

		return [
			'roots' => $roots,
			'nodes' => $nodes,
			'children' => $children_map,
		];
	}

	private function render_manual_items(array $tree, array $ids, string $layout, int $depth = 0): string
	{
		if (empty($ids)) {
			return '';
		}

		$nodes = $tree['nodes'] ?? [];
		$children = $tree['children'] ?? [];

		$html = '';
		foreach ($ids as $id) {
			if (!isset($nodes[$id])) {
				continue;
			}

			$item = $nodes[$id];
			$title = isset($item['title']) ? (string) $item['title'] : '';
			$link = $item['link']['url'] ?? '';
			$is_external = !empty($item['link']['is_external']);
			$nofollow = !empty($item['link']['nofollow']);
			$thumb = ($layout === 'layout-2') ? ($item['thumb']['url'] ?? '') : '';

			$child_ids = $children[$id] ?? [];
			$has_children = !empty($child_ids);

			$li_classes = [];
			if ($depth === 0 && $id === 'demo') {
				$li_classes[] = 'unlockafe-mega-menu__mega-parent';
			}
			if (!empty($thumb)) {
				$li_classes[] = 'unlockafe-mega-menu__has-thumb';
			}
			if ($has_children) {
				$li_classes[] = 'unlockafe-mega-menu__has-children';
			}
			$li_attr = !empty($li_classes) ? ' class="' . esc_attr(implode(' ', $li_classes)) . '"' : '';

			$a_attrs = '';
			if (!empty($link)) {
				$a_attrs .= ' href="' . esc_url($link) . '"';
				if ($is_external) {
					$a_attrs .= ' target="_blank"';
				}
				$rels = [];
				if ($nofollow) {
					$rels[] = 'nofollow';
				}
				if ($is_external) {
					$rels[] = 'noopener';
					$rels[] = 'noreferrer';
				}
				if (!empty($rels)) {
					$a_attrs .= ' rel="' . esc_attr(implode(' ', array_unique($rels))) . '"';
				}
			} else {
				$a_attrs .= ' href="#"';
			}

			$html .= '<li' . $li_attr . '>';
			$html .= '<a' . $a_attrs . '>';
			if (!empty($thumb)) {
				$html .= '<span class="unlockafe-mega-menu__thumb"><img src="' . esc_url($thumb) . '" alt="" loading="lazy"></span>';
				$html .= '<span class="unlockafe-mega-menu__label">' . esc_html($title) . '</span>';
			} else {
				$html .= esc_html($title);
			}
			$html .= '</a>';

			if ($has_children) {
				$has_thumb_child = false;
				if ($layout === 'layout-2') {
					foreach ($child_ids as $cid) {
						if (!empty($nodes[$cid]['thumb']['url'])) {
							$has_thumb_child = true;
							break;
						}
					}
				}
				$submenu_class = 'unlockafe-mega-menu__submenu' . ($has_thumb_child ? ' unlockafe-mega-menu__submenu--cards' : '');
				$html .= '<ul class="' . esc_attr($submenu_class) . '">';
				$html .= $this->render_manual_items($tree, $child_ids, $layout, $depth + 1);
				$html .= '</ul>';
			}

			$html .= '</li>';
		}

		return $html;
	}

	/**
	 * Allowed SVG tags and attributes for wp_kses when outputting user SVG code.
	 *
	 * @return array<string, array<string>>
	 */
	private function mega_menu_allowed_svg_kses(): array
	{
		$allowed_attr = [
			'class' => true,
			'id' => true,
			'width' => true,
			'height' => true,
			'viewbox' => true,
			'viewBox' => true,
			'xmlns' => true,
			'fill' => true,
			'stroke' => true,
			'stroke-width' => true,
			'stroke-linecap' => true,
			'stroke-linejoin' => true,
			'd' => true,
			'transform' => true,
			'x' => true,
			'y' => true,
			'cx' => true,
			'cy' => true,
			'r' => true,
			'rx' => true,
			'ry' => true,
			'points' => true,
			'x1' => true,
			'y1' => true,
			'x2' => true,
			'y2' => true,
		];
		return [
			'svg' => $allowed_attr,
			'path' => $allowed_attr,
			'circle' => $allowed_attr,
			'rect' => $allowed_attr,
			'line' => $allowed_attr,
			'polyline' => $allowed_attr,
			'polygon' => $allowed_attr,
			'g' => $allowed_attr,
			'defs' => $allowed_attr,
			'use' => array_merge($allowed_attr, ['href' => true, 'xlink:href' => true]),
		];
	}

	private function render_grid_item(array $item, string $layout_type): string
	{
		if (empty($item['item_enable']) || $item['item_enable'] !== 'yes') {
			return '';
		}
		$title = isset($item['title']) ? (string) $item['title'] : '';
		$desc = isset($item['description']) ? (string) $item['description'] : '';
		$link = $item['link']['url'] ?? '';
		$is_external = !empty($item['link']['is_external']);
		$nofollow = !empty($item['link']['nofollow']);
		$media_type = $item['media_type'] ?? 'icon';
		$show_media = !empty($item['show_media']) && $item['show_media'] === 'yes';
		$svg_code = isset($item['item_svg_code']) ? trim((string) $item['item_svg_code']) : '';
		$visibility = $item['item_visibility'] ?? 'both';
		$vis_class = $visibility === 'desktop_only' ? 'unlockafe-mm-desktop-only' : ($visibility === 'mobile_only' ? 'unlockafe-mm-mobile-only' : '');

		$a_attrs = ' href="' . esc_url($link ?: '#') . '"';
		if ($is_external) {
			$a_attrs .= ' target="_blank"';
		}
		$rels = [];
		if ($nofollow) {
			$rels[] = 'nofollow';
		}
		if ($is_external) {
			$rels[] = 'noopener';
			$rels[] = 'noreferrer';
		}
		if (!empty($rels)) {
			$a_attrs .= ' rel="' . esc_attr(implode(' ', array_unique($rels))) . '"';
		}

		$category_id = isset($item['category_id']) ? trim((string) $item['category_id']) : '';
		$item_badge = isset($item['item_badge']) ? $item['item_badge'] : 'none';
		$item_classes = ['unlockafe-mm-item', 'elementor-repeater-item-' . ($item['_id'] ?? '')];
		if ($vis_class) {
			$item_classes[] = $vis_class;
		}
		if ($item_badge === 'new') {
			$item_classes[] = 'unlockafe-mm-item--has-badge';
		}
		if ($item_badge === 'new') {
			$item_classes[] = 'unlockafe-mm-item--has-badge';
		}
		$item_classes[] = 'unlockafe-mm-layout--' . esc_attr($layout_type);
		$data_category = $category_id !== '' ? ' data-category="' . esc_attr($category_id) . '"' : '';

		$media_html = '';
		if ($media_type === 'image' && $show_media && !empty($item['image']['url'])) {
			$media_html = '<span class="unlockafe-mm-item__media unlockafe-mm-item__media--image"><img src="' . esc_url($item['image']['url']) . '" alt="" loading="lazy"></span>';
		} elseif ($media_type === 'icon' && $show_media && !empty($item['selected_icon']['value'])) {
			ob_start();
			Icons_Manager::render_icon($item['selected_icon'], ['aria-hidden' => 'true']);
			$icon_html = ob_get_clean();
			$media_html = '<span class="unlockafe-mm-item__media unlockafe-mm-item__media--icon">' . $icon_html . '</span>';
		} elseif ($media_type === 'svg_code' && $svg_code !== '') {
			$sanitized = wp_kses($svg_code, $this->mega_menu_allowed_svg_kses());
			if ($sanitized !== '') {
				$media_html = '<span class="unlockafe-mm-item__media unlockafe-mm-item__media--svg">' . $sanitized . '</span>';
			}
		}

		$badge_html = ($item_badge === 'new') ? '<span class="unlockafe-mm-item__badge unlockafe-mm-item__badge--new">' . esc_html__('NEW', 'unlock-addons-for-elementor') . '</span>' : '';

		$html = '<div class="' . esc_attr(implode(' ', $item_classes)) . '"' . $data_category . '>';
		$html .= '<a class="unlockafe-mm-item__link" ' . $a_attrs . '>';
		if ($badge_html) {
			$html .= $badge_html;
		}
		if ($media_html) {
			$html .= $media_html;
		}
		$html .= '<span class="unlockafe-mm-item__title">' . esc_html($title) . '</span>';
		if ($desc !== '') {
			$html .= '<span class="unlockafe-mm-item__desc">' . esc_html($desc) . '</span>';
		}
		$html .= '</a></div>';
		return $html;
	}

	private function render_grid_panel(array $settings, string $widget_id): string
	{
		$rows = isset($settings['mega_menu_rows']) && is_array($settings['mega_menu_rows']) ? $settings['mega_menu_rows'] : [];
		$categories = isset($settings['mega_menu_categories']) && is_array($settings['mega_menu_categories']) ? $settings['mega_menu_categories'] : [];
		$layout_type = 'block';
		if (!empty($categories[0]['layout_type'])) {
			$layout_type = $categories[0]['layout_type'];
		}
		if ($layout_type === 'custom_template' && !empty($categories[0]['template_id']) && class_exists('\Elementor\Plugin')) {
			return \Elementor\Plugin::$instance->frontend->get_builder_content((int) $categories[0]['template_id'], true);
		}

		$total_items = 0;
		foreach ($rows as $row) {
			$cols = isset($row['row_columns']) && is_array($row['row_columns']) ? $row['row_columns'] : [];
			foreach ($cols as $col) {
				$items = isset($col['column_items']) && is_array($col['column_items']) ? $col['column_items'] : [];
				foreach ($items as $item) {
					if (!empty($item['item_enable']) && $item['item_enable'] === 'yes') {
						$total_items++;
					}
				}
			}
		}

		$panel_heading = isset($settings['panel_heading']) ? trim((string) $settings['panel_heading']) : '';
		if ($panel_heading === '' && !empty($categories[0]['label'])) {
			$panel_heading = $categories[0]['label'];
		}
		$show_item_count = !empty($settings['show_item_count']) && $settings['show_item_count'] === 'yes';
		$cta_show = !empty($settings['cta_show']) && $settings['cta_show'] === 'yes';
		$cta_text = isset($settings['cta_text']) ? (string) $settings['cta_text'] : '';
		$cta_button_text = isset($settings['cta_button_text']) ? (string) $settings['cta_button_text'] : '';
		$cta_link = isset($settings['cta_link']['url']) ? $settings['cta_link']['url'] : '';
		$cta_external = !empty($settings['cta_link']['is_external']);
		$cta_nofollow = !empty($settings['cta_link']['nofollow']);

		$show_category_tabs = in_array($layout_type, ['features', 'solutions'], true) && count($categories) > 1;
		$panel_style = isset($settings['panel_style']) ? $settings['panel_style'] : 'light';
		$panel_class = 'unlockafe-mega-menu__grid-panel unlockafe-mm-layout--' . esc_attr($layout_type);
		if ($panel_style === 'light') {
			$panel_class .= ' unlockafe-mm-panel--light';
		}
		$html = '<div class="' . $panel_class . '" data-layout="' . esc_attr($layout_type) . '">';

		if ($panel_heading !== '' || $show_item_count || $show_category_tabs) {
			$html .= '<div class="unlockafe-mm-panel-header">';
			if ($panel_heading !== '') {
				$html .= '<h3 class="unlockafe-mm-panel-title">' . esc_html($panel_heading) . '</h3>';
			}
			if ($show_item_count && $total_items > 0) {
				$count_label = $layout_type === 'solutions' ? esc_html__('solutions', 'unlock-addons-for-elementor') : ($layout_type === 'block' ? esc_html__('blocks', 'unlock-addons-for-elementor') : esc_html__('features', 'unlock-addons-for-elementor'));
				$html .= '<p class="unlockafe-mm-panel-count">' . esc_html(sprintf(/* translators: 1: number, 2: number, 3: label */ __('Showing %1$d of %2$d %3$s', 'unlock-addons-for-elementor'), $total_items, $total_items, $count_label)) . '</p>';
			}
			if ($show_category_tabs) {
				$html .= '<div class="unlockafe-mm-tabs" role="tablist">';
				$all_label = ($layout_type === 'solutions') ? esc_html__('All Solutions', 'unlock-addons-for-elementor') : esc_html__('All Blocks', 'unlock-addons-for-elementor');
				$html .= '<button type="button" class="unlockafe-mm-tab is-active" role="tab" data-category="">' . $all_label . '</button>';
				foreach ($categories as $cat) {
					$cid = isset($cat['category_id']) ? trim((string) $cat['category_id']) : '';
					$lab = isset($cat['label']) ? $cat['label'] : $cid;
					if ($cid !== '') {
						$html .= '<button type="button" class="unlockafe-mm-tab" role="tab" data-category="' . esc_attr($cid) . '">' . esc_html($lab) . '</button>';
					}
				}
				$html .= '</div>';
			}
			$html .= '</div>';
		} elseif ($show_category_tabs) {
			$html .= '<div class="unlockafe-mm-tabs" role="tablist">';
			$html .= '<button type="button" class="unlockafe-mm-tab is-active" role="tab" data-category="">' . esc_html__('All', 'unlock-addons-for-elementor') . '</button>';
			foreach ($categories as $cat) {
				$cid = isset($cat['category_id']) ? trim((string) $cat['category_id']) : '';
				$lab = isset($cat['label']) ? $cat['label'] : $cid;
				if ($cid !== '') {
					$html .= '<button type="button" class="unlockafe-mm-tab" role="tab" data-category="' . esc_attr($cid) . '">' . esc_html($lab) . '</button>';
				}
			}
			$html .= '</div>';
		}

		$html .= '<div class="unlockafe-mm-panel-body">';
		foreach ($rows as $row) {
			$cols = isset($row['row_columns']) && is_array($row['row_columns']) ? $row['row_columns'] : [];
			if (empty($cols)) {
				continue;
			}
			$grid_tracks = [];
			foreach ($cols as $col) {
				$w = $col['column_width'] ?? 'auto';
				$grid_tracks[] = $w === 'auto' ? '1fr' : (intval($w) . 'fr');
			}
			$html .= '<div class="unlockafe-mega-menu__grid-row" style="display:grid;grid-template-columns:' . esc_attr(implode(' ', $grid_tracks)) . ';gap:16px;">';
			foreach ($cols as $col) {
				$items = isset($col['column_items']) && is_array($col['column_items']) ? $col['column_items'] : [];
				$html .= '<div class="unlockafe-mega-menu__grid-col">';
				foreach ($items as $item) {
					$html .= $this->render_grid_item($item, $layout_type);
				}
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		$html .= '</div>';

		if ($cta_show && ($cta_text !== '' || $cta_button_text !== '' || !empty($settings['cta_subtext']))) {
			$cta_rel = [];
			if ($cta_external) {
				$cta_rel[] = 'noopener';
				$cta_rel[] = 'noreferrer';
			}
			if ($cta_nofollow) {
				$cta_rel[] = 'nofollow';
			}
			$cta_subtext = isset($settings['cta_subtext']) ? trim((string) $settings['cta_subtext']) : '';
			$html .= '<div class="unlockafe-mm-cta">';
			$html .= '<div class="unlockafe-mm-cta__inner">';
			if ($cta_text !== '') {
				$html .= '<p class="unlockafe-mm-cta__text">' . esc_html($cta_text) . '</p>';
			}
			if ($cta_subtext !== '') {
				$html .= '<p class="unlockafe-mm-cta__subtext">' . esc_html($cta_subtext) . '</p>';
			}
			if ($cta_button_text !== '' && $cta_link !== '') {
				$html .= '<a href="' . esc_url($cta_link) . '" class="unlockafe-mm-cta__btn"' . ($cta_external ? ' target="_blank"' : '') . (!empty($cta_rel) ? ' rel="' . esc_attr(implode(' ', $cta_rel)) . '"' : '') . '>' . esc_html($cta_button_text) . '</a>';
			}
			$html .= '</div></div>';
		}

		$html .= '</div>';
		return $html;
	}

	private function render_grid_menu(string $widget_id, array $settings): string
	{
		$label = !empty($settings['mega_parent_label']) ? $settings['mega_parent_label'] : esc_html__('Menu', 'unlock-addons-for-elementor');
		$panel = $this->render_grid_panel($settings, $widget_id);
		$list_id = 'unlockafe_mega_menu_' . $widget_id;
		$panel_style = isset($settings['panel_style']) ? $settings['panel_style'] : 'light';
		$submenu_class = 'unlockafe-mega-menu__submenu unlockafe-mega-menu__submenu--grid';
		if ($panel_style === 'light') {
			$submenu_class .= ' unlockafe-mm-dropdown--light';
		}
		$html = '<ul id="' . esc_attr($list_id) . '" class="unlockafe-mega-menu__list">';
		$html .= '<li class="unlockafe-mega-menu__has-children unlockafe-mega-menu__mega-parent unlockafe-mega-menu__mega-parent--grid">';
		$html .= '<a href="#" class="unlockafe-mega-menu__parent-link">' . esc_html($label) . '</a>';
		$html .= '<div class="' . esc_attr($submenu_class) . '">' . $panel . '</div>';
		$html .= '</li></ul>';
		return $html;
	}

	public function get_name()
	{
		return 'unlockafe-mega-menu';
	}

	public function get_title()
	{
		return __('Mega Menu', 'unlock-addons-for-elementor');
	}

	public function get_icon()
	{
		return 'eicon-menu-bar ulicon';
	}

	public function get_categories()
	{
		return ['unlockafe-addons'];
	}

	public function get_style_depends()
	{
		return ['unlockafe-global', 'unlockafe-mega-menu'];
	}

	public function get_script_depends()
	{
		return ['unlockafe-mega-menu'];
	}

	protected function get_nav_menu_index()
	{
		return $this->nav_menu_index++;
	}

	private function get_available_menus()
	{
		$menus = wp_get_nav_menus();
		$options = [];

		foreach ($menus as $menu) {
			$options[$menu->slug] = $menu->name;
		}

		return $options;
	}

	private function migrate_manual_items_to_grid(array $manual_items): array
	{
		if (empty($manual_items)) {
			return [];
		}
		$tree = $this->build_manual_tree($manual_items);
		$roots = $tree['roots'] ?? [];
		$nodes = $tree['nodes'] ?? [];
		$children = $tree['children'] ?? [];
		if (empty($roots)) {
			return [];
		}
		$columns = [];
		foreach ($roots as $root_id) {
			$child_ids = $children[$root_id] ?? [];
			$column_items = [];
			foreach ($child_ids as $cid) {
				$n = $nodes[$cid] ?? null;
				if (!$n) {
					continue;
				}
				$media_type = (!empty($n['thumb']['url'])) ? 'image' : 'none';
				$item = [
					'title' => isset($n['title']) ? (string) $n['title'] : '',
					'description' => '',
					'link' => isset($n['link']) && is_array($n['link']) ? $n['link'] : ['url' => '', 'is_external' => false, 'nofollow' => false],
					'media_type' => $media_type,
					'item_enable' => 'yes',
					'item_visibility' => 'both',
				];
				if ($media_type === 'image' && !empty($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';
				}
				$column_items[] = $item;
			}
			if (empty($column_items)) {
				$root_node = $nodes[$root_id] ?? null;
				$column_items[] = [
					'title' => $root_node && isset($root_node['title']) ? (string) $root_node['title'] : esc_html__('Item', 'unlock-addons-for-elementor'),
					'link' => $root_node && isset($root_node['link']) && is_array($root_node['link']) ? $root_node['link'] : ['url' => '#', 'is_external' => false, 'nofollow' => false],
					'item_enable' => 'yes',
					'item_visibility' => 'both',
					'media_type' => 'none',
				];
			}
			$columns[] = ['column_width' => 'auto', 'column_items' => $column_items];
		}
		return [['row_columns' => $columns]];
	}

	private function get_elementor_templates(): array
	{
		$options = ['' => esc_html__('— Select Template —', 'unlock-addons-for-elementor')];
		if (!class_exists('\Elementor\Plugin')) {
			return $options;
		}
		$posts = get_posts([
			'post_type' => 'elementor_library',
			'posts_per_page' => -1,
			'post_status' => 'publish',
			'meta_query' => [
				[
					'key' => '_elementor_template_type',
					'value' => ['page', 'section'],
					'compare' => 'IN',
				],
			],
		]);
		foreach ($posts as $post) {
			$options[(string) $post->ID] = $post->post_title;
		}
		return $options;
	}

	protected function register_controls()
	{
		$this->start_controls_section(
			'unlockafe_mega_menu_layout',
			[
				'label' => esc_html__('Layout', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_CONTENT,
			]
		);

		$this->add_control(
			'layout',
			[
				'label' => esc_html__('Select Layout', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'layout-1' => esc_html__('Layout 1', 'unlock-addons-for-elementor'),
					'layout-2' => esc_html__('Layout 2', 'unlock-addons-for-elementor'),
				],
				'default' => 'layout-1',
			]
		);

		$this->add_control(
			'trigger',
			[
				'label' => esc_html__('Trigger', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'hover' => esc_html__('Hover', 'unlock-addons-for-elementor'),
					'click' => esc_html__('Click', 'unlock-addons-for-elementor'),
				],
				'default' => 'hover',
			]
		);

		$this->add_control(
			'open_animation',
			[
				'label' => esc_html__('Open Animation', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'top-to-bottom' => esc_html__('Top to Bottom', 'unlock-addons-for-elementor'),
					'fade' => esc_html__('Fade', 'unlock-addons-for-elementor'),
					'scale' => esc_html__('Scale', 'unlock-addons-for-elementor'),
					'slide-left' => esc_html__('Slide Left', 'unlock-addons-for-elementor'),
					'slide-right' => esc_html__('Slide Right', 'unlock-addons-for-elementor'),
				],
				'default' => 'top-to-bottom',
			]
		);

		$this->add_control(
			'close_animation',
			[
				'label' => esc_html__('Close Animation', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'bottom-to-top' => esc_html__('Bottom to Top', 'unlock-addons-for-elementor'),
					'fade' => esc_html__('Fade', 'unlock-addons-for-elementor'),
					'scale' => esc_html__('Scale', 'unlock-addons-for-elementor'),
					'slide-left' => esc_html__('Slide Left', 'unlock-addons-for-elementor'),
					'slide-right' => esc_html__('Slide Right', 'unlock-addons-for-elementor'),
				],
				'default' => 'bottom-to-top',
			]
		);

		$this->add_control(
			'animation_duration',
			[
				'label' => esc_html__('Animation Duration (ms)', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::NUMBER,
				'min' => 0,
				'max' => 2000,
				'step' => 10,
				'default' => 250,
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'unlockafe_mega_menu_content',
			[
				'label' => esc_html__('Menu', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_CONTENT,
			]
		);

		$this->add_control(
			'menu_source',
			[
				'label' => esc_html__('Menu Source', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'wp_menu' => esc_html__('WordPress Menu', 'unlock-addons-for-elementor'),
					'manual' => esc_html__('Manual Builder', 'unlock-addons-for-elementor'),
				],
				'default' => 'wp_menu',
			]
		);

		$this->add_control(
			'manual_builder_type',
			[
				'label' => esc_html__('Builder Type', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'options' => [
					'legacy' => esc_html__('Legacy (Tree)', 'unlock-addons-for-elementor'),
					'grid' => esc_html__('Grid (Rows & Columns)', 'unlock-addons-for-elementor'),
				],
				'default' => 'legacy',
				'condition' => [
					'menu_source' => 'manual',
				],
			]
		);

		$menus = $this->get_available_menus();

		if (!empty($menus)) {
			$this->add_control(
				'menu',
				[
					'label' => __('Select Menu', 'unlock-addons-for-elementor'),
					'type' => Controls_Manager::SELECT,
					'options' => $menus,
					'default' => array_keys($menus)[0],
					'save_default' => true,
					'description' => sprintf(__('Manage your menus in the <a href="%s" target="_blank">WordPress Menus screen</a>.', 'unlock-addons-for-elementor'), admin_url('nav-menus.php')),
					'condition' => [
						'menu_source' => 'wp_menu',
					],
				]
			);
		} else {
			$this->add_control(
				'menu',
				[
					'type' => Controls_Manager::RAW_HTML,
					'raw' => sprintf(__('<strong>No menus found.</strong><br>Go to the <a href="%s" target="_blank">Menus screen</a> to create one.', 'unlock-addons-for-elementor'), admin_url('nav-menus.php?action=edit&menu=0')),
					'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
					'condition' => [
						'menu_source' => 'wp_menu',
					],
				]
			);
		}

		$repeater = new Repeater();
		$repeater->add_control(
			'item_id',
			[
				'label' => esc_html__('Item ID', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => '',
				'label_block' => true,
			]
		);
		$repeater->add_control(
			'parent_id',
			[
				'label' => esc_html__('Parent ID', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => '',
				'label_block' => true,
				'description' => esc_html__('Leave empty for top-level items. Use a parent Item ID to create submenu/submenu of submenu.', 'unlock-addons-for-elementor'),
			]
		);
		$repeater->add_control(
			'title',
			[
				'label' => esc_html__('Title', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => '',
				'label_block' => true,
			]
		);
		$repeater->add_control(
			'link',
			[
				'label' => esc_html__('Link', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::URL,
				'placeholder' => esc_html__('https://your-link.com', 'unlock-addons-for-elementor'),
				'show_external' => true,
				'default' => [
					'url' => '',
					'is_external' => false,
					'nofollow' => false,
				],
			]
		);
		$repeater->add_control(
			'thumb',
			[
				'label' => esc_html__('Thumbnail', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::MEDIA,
				'default' => [
					'url' => '',
				],
			]
		);

		$this->add_control(
			'manual_items',
			[
				'label' => esc_html__('Manual Items', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::REPEATER,
				'fields' => $repeater->get_controls(),
				'default' => $this->get_demo_manual_items('layout-1'),
				'title_field' => '{{{ title }}}',
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'legacy',
				],
			]
		);

		// ——— Categories (Grid builder) ———
		$cat_repeater = new Repeater();
		$cat_repeater->add_control('category_id', [
			'label' => esc_html__('Category ID', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => '',
			'label_block' => true,
			'description' => esc_html__('Unique key (e.g. features, solutions). Used for filtering and layout.', 'unlock-addons-for-elementor'),
		]);
		$cat_repeater->add_control('label', [
			'label' => esc_html__('Label', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => '',
			'label_block' => true,
		]);
		$cat_repeater->add_control('parent_id', [
			'label' => esc_html__('Parent Category ID', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => '',
			'label_block' => true,
			'description' => esc_html__('Leave empty for top-level category.', 'unlock-addons-for-elementor'),
		]);
		$cat_repeater->add_control('layout_type', [
			'label' => esc_html__('Layout Type', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'default' => 'block',
			'options' => [
				'block' => esc_html__('Block Layout', 'unlock-addons-for-elementor'),
				'widget_style' => esc_html__('Widget Style', 'unlock-addons-for-elementor'),
				'features' => esc_html__('Features Layout', 'unlock-addons-for-elementor'),
				'solutions' => esc_html__('Solutions Layout', 'unlock-addons-for-elementor'),
				'custom_template' => esc_html__('Custom Template', 'unlock-addons-for-elementor'),
			],
		]);
		$cat_repeater->add_control('template_id', [
			'label' => esc_html__('Elementor Template', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'options' => $this->get_elementor_templates(),
			'condition' => [
				'layout_type' => 'custom_template',
			],
		]);

		$this->add_control(
			'mega_menu_categories',
			[
				'label' => esc_html__('Categories', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::REPEATER,
				'fields' => $cat_repeater->get_controls(),
				'default' => [
					['category_id' => 'main', 'label' => esc_html__('Main', 'unlock-addons-for-elementor'), 'parent_id' => '', 'layout_type' => 'block'],
				],
				'title_field' => '{{{ label }}}',
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		// ——— Grid: Rows → Columns → Items ———
		$item_repeater = new Repeater();
		$item_repeater->add_control('title', [
			'label' => esc_html__('Title', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => '',
			'label_block' => true,
		]);
		$item_repeater->add_control('description', [
			'label' => esc_html__('Description', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXTAREA,
			'default' => '',
			'label_block' => true,
		]);
		$item_repeater->add_control('link', [
			'label' => esc_html__('Link', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::URL,
			'placeholder' => esc_html__('https://your-link.com', 'unlock-addons-for-elementor'),
			'show_external' => true,
			'default' => ['url' => '', 'is_external' => false, 'nofollow' => false],
		]);
		$item_repeater->add_control('media_type', [
			'label' => esc_html__('Media Type', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'default' => 'icon',
			'options' => [
				'none' => esc_html__('None', 'unlock-addons-for-elementor'),
				'icon' => esc_html__('Icon', 'unlock-addons-for-elementor'),
				'image' => esc_html__('Image', 'unlock-addons-for-elementor'),
				'svg_code' => esc_html__('SVG Code', 'unlock-addons-for-elementor'),
			],
		]);
		$item_repeater->add_control('image', [
			'label' => esc_html__('Image', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::MEDIA,
			'default' => ['url' => ''],
			'condition' => ['media_type' => 'image'],
		]);
		$item_repeater->add_control('selected_icon', [
			'label' => esc_html__('Icon', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::ICONS,
			'default' => ['value' => 'fas fa-star', 'library' => 'fa-solid'],
			'condition' => ['media_type' => 'icon'],
		]);
		$item_repeater->add_control('item_svg_code', [
			'label' => esc_html__('SVG Icon Code', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXTAREA,
			'default' => '',
			'placeholder' => esc_html__('Paste your SVG code here (e.g. <svg>...</svg>)', 'unlock-addons-for-elementor'),
			'condition' => ['media_type' => 'svg_code'],
			'description' => esc_html__('Paste raw SVG code. It will be shown beside this item in the menu list.', 'unlock-addons-for-elementor'),
			'rows' => 4,
		]);
		$item_repeater->add_control('show_media', [
			'label' => esc_html__('Show Image/Icon', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
			'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
			'return_value' => 'yes',
			'default' => 'yes',
			'condition' => ['media_type' => ['image', 'icon']],
		]);
		$item_repeater->add_control('category_id', [
			'label' => esc_html__('Category ID', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::TEXT,
			'default' => '',
			'description' => esc_html__('Must match a Category ID from Categories above.', 'unlock-addons-for-elementor'),
		]);
		$item_repeater->add_control('item_enable', [
			'label' => esc_html__('Enable', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SWITCHER,
			'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
			'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
			'return_value' => 'yes',
			'default' => 'yes',
		]);
		$item_repeater->add_control('item_visibility', [
			'label' => esc_html__('Visibility', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'default' => 'both',
			'options' => [
				'both' => esc_html__('Desktop & Mobile', 'unlock-addons-for-elementor'),
				'desktop_only' => esc_html__('Desktop only', 'unlock-addons-for-elementor'),
				'mobile_only' => esc_html__('Mobile only', 'unlock-addons-for-elementor'),
			],
		]);
		$item_repeater->add_control('item_badge', [
			'label' => esc_html__('Badge', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'default' => 'none',
			'options' => [
				'none' => esc_html__('None', 'unlock-addons-for-elementor'),
				'new' => esc_html__('NEW', 'unlock-addons-for-elementor'),
			],
		]);
		$item_repeater->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name' => 'item_typography',
				'selector' => '{{WRAPPER}} {{CURRENT_ITEM}} .unlockafe-mm-item__title',
				'condition' => ['item_enable' => 'yes'],
			]
		);
		$item_repeater->add_control('item_text_color', [
			'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'selectors' => ['{{WRAPPER}} {{CURRENT_ITEM}} .unlockafe-mm-item__title' => 'color: {{VALUE}};'],
			'condition' => ['item_enable' => 'yes'],
		]);
		$item_repeater->add_group_control(
			Group_Control_Background::get_type(),
			[
				'name' => 'item_background',
				'types' => ['classic', 'gradient'],
				'selector' => '{{WRAPPER}} {{CURRENT_ITEM}}.unlockafe-mm-item',
				'condition' => ['item_enable' => 'yes'],
			]
		);
		$item_repeater->add_control('item_hover_bg', [
			'label' => esc_html__('Hover Background', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::COLOR,
			'selectors' => ['{{WRAPPER}} {{CURRENT_ITEM}}.unlockafe-mm-item:hover' => 'background-color: {{VALUE}};'],
			'condition' => ['item_enable' => 'yes'],
		]);
		$item_repeater->add_control('item_padding', [
			'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::DIMENSIONS,
			'size_units' => ['px', 'em', '%'],
			'selectors' => ['{{WRAPPER}} {{CURRENT_ITEM}}.unlockafe-mm-item' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};'],
			'condition' => ['item_enable' => 'yes'],
		]);

		$col_repeater = new Repeater();
		$col_repeater->add_control('column_width', [
			'label' => esc_html__('Column Width', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::SELECT,
			'default' => 'auto',
			'options' => [
				'auto' => esc_html__('Auto', 'unlock-addons-for-elementor'),
				'1' => '1/12',
				'2' => '2/12',
				'3' => '3/12',
				'4' => '4/12',
				'5' => '5/12',
				'6' => '6/12',
				'7' => '7/12',
				'8' => '8/12',
				'9' => '9/12',
				'10' => '10/12',
				'11' => '11/12',
				'12' => '12/12',
			],
		]);
		$col_repeater->add_control('column_items', [
			'label' => esc_html__('Items', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::REPEATER,
			'fields' => $item_repeater->get_controls(),
			'default' => [
				['title' => esc_html__('Menu Item', 'unlock-addons-for-elementor'), 'item_enable' => 'yes', 'item_visibility' => 'both'],
			],
			'title_field' => '{{{ title }}}',
		]);

		$row_repeater = new Repeater();
		$row_repeater->add_control('row_columns', [
			'label' => esc_html__('Columns', 'unlock-addons-for-elementor'),
			'type' => Controls_Manager::REPEATER,
			'fields' => $col_repeater->get_controls(),
			'default' => [
				['column_width' => '6', 'column_items' => [['title' => esc_html__('Item 1', 'unlock-addons-for-elementor'), 'item_enable' => 'yes', 'item_visibility' => 'both']]],
				['column_width' => '6', 'column_items' => [['title' => esc_html__('Item 2', 'unlock-addons-for-elementor'), 'item_enable' => 'yes', 'item_visibility' => 'both']]],
			],
			'title_field' => esc_html__('Row', 'unlock-addons-for-elementor'),
		]);

		$this->add_control(
			'mega_menu_rows',
			[
				'label' => esc_html__('Mega Menu Rows', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::REPEATER,
				'fields' => $row_repeater->get_controls(),
				'default' => [],
				'title_field' => esc_html__('Row', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'mega_parent_label',
			[
				'label' => esc_html__('Mega Menu Parent Label', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => esc_html__('Menu', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'panel_heading',
			[
				'label' => esc_html__('Panel Heading', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => '',
				'placeholder' => esc_html__('e.g. Discover Our Features', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'panel_style',
			[
				'label' => esc_html__('Panel Style', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SELECT,
				'default' => 'light',
				'options' => [
					'light' => esc_html__('Light (white card)', 'unlock-addons-for-elementor'),
					'dark' => esc_html__('Dark', 'unlock-addons-for-elementor'),
				],
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'show_item_count',
			[
				'label' => esc_html__('Show Item Count', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SWITCHER,
				'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
				'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
				'return_value' => 'yes',
				'default' => 'yes',
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'cta_show',
			[
				'label' => esc_html__('Show CTA Banner', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SWITCHER,
				'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
				'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
				'return_value' => 'yes',
				'default' => '',
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
				],
			]
		);

		$this->add_control(
			'cta_text',
			[
				'label' => esc_html__('CTA Title', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => esc_html__('Ready to supercharge your website? Unlock all premium features today', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
					'cta_show' => 'yes',
				],
			]
		);

		$this->add_control(
			'cta_subtext',
			[
				'label' => esc_html__('CTA Subtext', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => '',
				'placeholder' => esc_html__('e.g. Get access to 41+ blocks', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
					'cta_show' => 'yes',
				],
			]
		);

		$this->add_control(
			'cta_button_text',
			[
				'label' => esc_html__('CTA Button Text', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::TEXT,
				'default' => esc_html__('Get Started Free', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
					'cta_show' => 'yes',
				],
			]
		);

		$this->add_control(
			'cta_link',
			[
				'label' => esc_html__('CTA Button Link', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::URL,
				'placeholder' => esc_html__('https://your-link.com', 'unlock-addons-for-elementor'),
				'condition' => [
					'menu_source' => 'manual',
					'manual_builder_type' => 'grid',
					'cta_show' => 'yes',
				],
			]
		);

		$this->add_responsive_control(
			'panel_max_height',
			[
				'label' => esc_html__('Panel Max Height', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::SLIDER,
				'size_units' => ['px', 'vh'],
				'range' => [
					'px' => ['min' => 100, 'max' => 1000],
					'vh' => ['min' => 10, 'max' => 100],
				],
				'default' => [
					'unit' => 'px',
					'size' => 420,
				],
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-maxh: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .unlockafe-mega-menu__submenu' => 'max-height: {{SIZE}}{{UNIT}}; overflow: auto;',
				],
			]
		);

		$this->add_control(
			'columns',
			[
				'label' => esc_html__('Columns (Layout 1)', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::NUMBER,
				'min' => 1,
				'max' => 6,
				'step' => 1,
				'default' => 6,
				'condition' => [
					'layout' => 'layout-1',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'unlockafe_mega_menu_style_menu',
			[
				'label' => esc_html__('Menu', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'menu_bg_color',
			[
				'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#000000',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-nav-bg: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'menu_text_color',
			[
				'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-menu-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'menu_hover_text_color',
			[
				'label' => esc_html__('Hover Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-menu-hover-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'unlockafe_mega_menu_style_submenu',
			[
				'label' => esc_html__('Submenu', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'submenu_bg_color',
			[
				'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#000000',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-submenu-bg: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'submenu_text_color',
			[
				'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-submenu-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'submenu_hover_bg_color',
			[
				'label' => esc_html__('Hover Background Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => 'rgba(255,255,255,0.08)',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-submenu-hover-bg: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'submenu_hover_text_color',
			[
				'label' => esc_html__('Hover Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-submenu-hover-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'unlockafe_mega_menu_style_subsubmenu',
			[
				'label' => esc_html__('Submenu of Submenu', 'unlock-addons-for-elementor'),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'subsubmenu_bg_color',
			[
				'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#000000',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-subsubmenu-bg: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'subsubmenu_text_color',
			[
				'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-subsubmenu-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'subsubmenu_hover_bg_color',
			[
				'label' => esc_html__('Hover Background Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => 'rgba(255,255,255,0.08)',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-subsubmenu-hover-bg: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'subsubmenu_hover_text_color',
			[
				'label' => esc_html__('Hover Text Color', 'unlock-addons-for-elementor'),
				'type' => Controls_Manager::COLOR,
				'default' => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .unlockafe-mega-menu' => '--unlockafe-mm-subsubmenu-hover-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();
	}

	protected function render()
	{
		$settings = $this->get_settings_for_display();

		$layout = !empty($settings['layout']) ? $settings['layout'] : 'layout-1';
		$trigger = !empty($settings['trigger']) ? $settings['trigger'] : 'hover';
		$columns = isset($settings['columns']) ? (int) $settings['columns'] : 6;
		$columns = max(1, min(6, $columns));

		$open_anim = !empty($settings['open_animation']) ? $settings['open_animation'] : 'top-to-bottom';
		$close_anim = !empty($settings['close_animation']) ? $settings['close_animation'] : 'bottom-to-top';
		$duration = isset($settings['animation_duration']) ? (int) $settings['animation_duration'] : 250;
		$duration = max(0, min(2000, $duration));

		$menu_source = $settings['menu_source'] ?? 'wp_menu';

		$widget_id = $this->get_id();

		$menu_html = '';
		if ($menu_source === 'manual') {
			$builder_type = $settings['manual_builder_type'] ?? 'legacy';
			if ($builder_type === 'grid') {
				$rows = isset($settings['mega_menu_rows']) && is_array($settings['mega_menu_rows']) ? $settings['mega_menu_rows'] : [];
				if (empty($rows)) {
					$legacy_items = isset($settings['manual_items']) && is_array($settings['manual_items']) ? $settings['manual_items'] : [];
					$rows = $this->migrate_manual_items_to_grid($legacy_items);
				}
				if (!empty($rows)) {
					$settings_for_grid = $settings;
					$settings_for_grid['mega_menu_rows'] = $rows;
					$menu_html = $this->render_grid_menu($widget_id, $settings_for_grid);
				} else {
					$menu_html = '<ul id="unlockafe_mega_menu_' . esc_attr($widget_id) . '" class="unlockafe-mega-menu__list"><li><a href="#">' . esc_html__('Add rows in Grid builder', 'unlock-addons-for-elementor') . '</a></li></ul>';
				}
			} else {
				$items = isset($settings['manual_items']) && is_array($settings['manual_items']) ? $settings['manual_items'] : [];
				if (empty($items)) {
					$items = $this->get_demo_manual_items($layout);
				}
				$tree = $this->build_manual_tree($items);
				$inner = $this->render_manual_items($tree, $tree['roots'] ?? [], $layout);
				if ($inner === '') {
					return;
				}
				$menu_html = '<ul id="unlockafe_mega_menu_' . esc_attr($widget_id) . '" class="unlockafe-mega-menu__list">' . $inner . '</ul>';
			}
		} else {
			$menu = $settings['menu'] ?? '';
			if (empty($menu)) {
				return;
			}

			$menu_args = [
				'echo' => false,
				'menu' => $menu,
				'menu_class' => 'unlockafe-mega-menu__list',
				'menu_id' => 'unlockafe_mega_menu_' . $widget_id,
				'fallback_cb' => 'wp_page_menu',
				'container' => false,
				'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
			];

			$menu_html = wp_nav_menu($menu_args);

			if (!empty($menu_html)) {
				$menu_html = str_replace('sub-menu', 'unlockafe-mega-menu__submenu', $menu_html);
				$menu_html = str_replace('children', 'unlockafe-mega-menu__submenu', $menu_html);
				$menu_html = str_replace('menu-item-has-children', 'unlockafe-mega-menu__has-children', $menu_html);
			}
		}

		$layout_type_attr = '';
		if ($menu_source === 'manual' && ($settings['manual_builder_type'] ?? '') === 'grid') {
			$cats = isset($settings['mega_menu_categories']) && is_array($settings['mega_menu_categories']) ? $settings['mega_menu_categories'] : [];
			if (!empty($cats[0]['layout_type'])) {
				$layout_type_attr = ' data-grid-layout="' . esc_attr($cats[0]['layout_type']) . '"';
			}
		}

		$wrapper_attrs = [
			'class' => 'unlockafe-mega-menu unlockafe-mega-menu--' . esc_attr($layout),
			'data-trigger' => esc_attr($trigger),
			'data-open-animation' => esc_attr($open_anim),
			'data-close-animation' => esc_attr($close_anim),
			'data-duration' => esc_attr((string) $duration),
			'data-columns' => esc_attr((string) $columns),
		];

		$attr_html = '';
		foreach ($wrapper_attrs as $k => $v) {
			$attr_html .= ' ' . $k . '="' . esc_attr($v) . '"';
		}

		echo '<nav' . $attr_html . $layout_type_attr . '>';
		echo '<button type="button" class="unlockafe-mega-menu__toggle" aria-controls="unlockafe_mega_menu_' . esc_attr($widget_id) . '" aria-expanded="false">';
		echo '<span class="unlockafe-mega-menu__toggle-icon" aria-hidden="true"></span>';
		echo '</button>';
		echo $menu_html;
		echo '<script>(function(){var nav=document.querySelector(".unlockafe-mega-menu button.unlockafe-mega-menu__toggle[aria-controls=\\"unlockafe_mega_menu_' . esc_js($widget_id) . '\\"]");if(!nav){return;}var root=nav.closest(".unlockafe-mega-menu");if(!root){return;}var list=root.querySelector("#unlockafe_mega_menu_' . esc_js($widget_id) . '");if(!list){return;}nav.addEventListener("click",function(e){e.preventDefault();var open=root.classList.toggle("is-mobile-open");nav.setAttribute("aria-expanded",open?"true":"false");if(window.matchMedia&&window.matchMedia("(max-width: 767px)").matches){list.style.display=open?"flex":"none";}});})();</script>';
		echo '</nav>';
	}
}
