<?php

namespace ShopGlut\Showcases\MegaMenu;

class MegaMenu {

	private $custom_menus = [];

	public function __construct() {
		add_action( 'init', [ $this, 'init' ] );
		add_action( 'wp_ajax_save_mega_menu', [ $this, 'saveMegaMenu' ] );
		add_action( 'wp_ajax_get_mega_menu', [ $this, 'getMegaMenu' ] );
		add_action( 'wp_ajax_delete_mega_menu', [ $this, 'deleteMegaMenu' ] );
		add_action( 'wp_ajax_get_mega_menu_demo_content', [ $this, 'getMegaMenuDemoContent' ] );
		add_action( 'admin_post_create_mega_menu_layout', [ $this, 'handleCreateMegaMenuLayout' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueueScripts' ] );
		add_action( 'wp_nav_menu_item_custom_fields', [ $this, 'addMenuItemFields' ], 10, 4 );
		add_action( 'wp_update_nav_menu_item', [ $this, 'updateMenuItem' ], 10, 3 );
	}

	public function init() {
		$this->custom_menus = get_option( 'shopglut_custom_mega_menus', [] );
	}

	public function enqueueScripts() {
		wp_enqueue_style( 'shopglut-mega-menu', plugin_dir_url( __FILE__ ) . 'assets/mega-menu.css', [], '1.0.0' );
		wp_enqueue_script( 'shopglut-mega-menu', plugin_dir_url( __FILE__ ) . 'assets/mega-menu.js', [ 'jquery' ], '1.0.0', true );
	}

	public function render() {
		?>
		<div class="wrap">
			<h1><?php echo esc_html__( 'Mega Menu Templates', 'shopglut' ); ?></h1>
			<p class="subheading"><?php echo esc_html__( 'Choose from our prebuilt mega menu templates and customize them for your store', 'shopglut' ); ?></p>
			
			<div class="shopglut-mega-menu-admin">
				<?php $this->renderPrebuiltTemplates(); ?>
				<?php $this->renderMegaMenuEditor(); ?>
				<?php $this->renderCustomMenus(); ?>
			</div>
		</div>
		<?php $this->addScriptsAndNonces(); ?>
		<?php
	}

	private function getPrebuiltTemplates() {
		return array(
			'category_grid' => array(
				'name' => __( 'Category Grid', 'shopglut' ),
				'description' => __( 'Clean grid layout showcasing product categories with images', 'shopglut' ),
				'columns' => 4,
				'width' => 800,
				'bg_color' => '#ffffff',
				'text_color' => '#333333',
				'show_images' => true,
				'show_product_count' => true,
				'layout_type' => 'grid',
				'featured_style' => 'simple'
			),
			'fashion_showcase' => array(
				'name' => __( 'Fashion Showcase', 'shopglut' ),
				'description' => __( 'Perfect for fashion stores with featured products and trending categories', 'shopglut' ),
				'columns' => 3,
				'width' => 900,
				'bg_color' => '#f8f9fa',
				'text_color' => '#2c3e50',
				'show_images' => true,
				'show_product_count' => false,
				'layout_type' => 'featured',
				'featured_style' => 'fashion'
			),
			'electronics_menu' => array(
				'name' => __( 'Electronics Menu', 'shopglut' ),
				'description' => __( 'Tech-focused design with product specifications and brand highlights', 'shopglut' ),
				'columns' => 5,
				'width' => 1000,
				'bg_color' => '#1a1a1a',
				'text_color' => '#ffffff',
				'show_images' => true,
				'show_product_count' => true,
				'layout_type' => 'tech',
				'featured_style' => 'modern'
			),
			'minimal_clean' => array(
				'name' => __( 'Minimal Clean', 'shopglut' ),
				'description' => __( 'Simple and elegant design focusing on clean typography and spacing', 'shopglut' ),
				'columns' => 3,
				'width' => 700,
				'bg_color' => '#ffffff',
				'text_color' => '#555555',
				'show_images' => false,
				'show_product_count' => false,
				'layout_type' => 'minimal',
				'featured_style' => 'clean'
			),
			'colorful_modern' => array(
				'name' => __( 'Colorful Modern', 'shopglut' ),
				'description' => __( 'Vibrant and modern design with colorful accents and engaging visuals', 'shopglut' ),
				'columns' => 4,
				'width' => 850,
				'bg_color' => '#667eea',
				'text_color' => '#ffffff',
				'show_images' => true,
				'show_product_count' => true,
				'layout_type' => 'modern',
				'featured_style' => 'colorful'
			)
		);
	}

	private function renderPrebuiltTemplates() {
		$templates = $this->getPrebuiltTemplates();

		// Group templates by categories
		$tab_names = [
			'tab1' => [
				'name' => esc_html__("All Templates", 'shopglut'),
				'templates' => array_keys($templates)
			]
		];
		?>
		<div class="shopg-tab-container shopg-template-gallery">
			<ul class="shopg-tabs">
				<?php foreach ($tab_names as $tab_id => $tab): ?>
					<li class="shopg-tab" data-tab="<?php echo esc_attr($tab_id); ?>">
						<?php echo esc_html($tab['name']); ?>
					</li>
				<?php endforeach; ?>
			</ul>

			<?php foreach ($tab_names as $tab_id => $tab): ?>
				<div class="shopg-tab-content" id="<?php echo esc_attr($tab_id); ?>">
					<?php foreach ($tab['templates'] as $template_id): ?>
						<?php if (isset($templates[$template_id])): ?>
							<?php $template = $templates[$template_id]; ?>
							<div class="shopg-template-preview" data-template="<?php echo esc_attr($template_id); ?>">
								<div class="template-header">
									<h2><?php echo esc_html($template['name']); ?></h2>
								</div>

								<div class="template-content product-demo">
									<!-- HTML Demo Preview for Mega Menu -->
									<div class="template-html-container">
										<!-- Background: Scaled HTML Preview -->
										<div class="html-preview-background">
											<?php $this->renderImprovedTemplatePreview( $template ); ?>
										</div>

										<!-- Foreground: View Demo Button with Overlay -->
										<div class="html-preview-overlay">
											<button type="button" class="demo-view-btn" onclick="openMegaMenuDemoModal('<?php echo esc_attr($template_id); ?>')">
												<svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
													<path d="M1 12C1 12 5 4 12 4C19 4 23 12 23 12C23 12 19 20 12 20C5 20 1 12 1 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
													<circle cx="12" cy="12" r="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												</svg>
												<span>View Live Demo</span>
											</button>
										</div>
									</div>
								</div>

								<div class="template-footer">
									<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
										<input type="hidden" name="action" value="create_mega_menu_layout">
										<input type="hidden" name="layout_template" value="<?php echo esc_attr($template_id); ?>">
										<?php
										$cache_key = 'shopglut_max_mega_menu_id';
										$layout_id = wp_cache_get($cache_key);

										if (false === $layout_id) {
											global $wpdb;
											// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
											$table_name = $wpdb->prefix . 'shopglut_mega_menus';
											// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
											// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
											$layout_id = intval($wpdb->get_var("SELECT MAX(id) FROM `{$table_name}`")) + 1 ?: 1;
											wp_cache_set($cache_key, $layout_id, '', 300);
										}
										?>
										<input type="hidden" name="layout_id" value="<?php echo esc_attr($layout_id); ?>">
										<?php wp_nonce_field('create_mega_menu_layout_nonce', 'create_mega_menu_layout_nonce'); ?>
										<div class="template-info">
											<p class="template-description"><?php echo esc_html($template['description']); ?></p>
											<div class="template-features">
												<span class="feature-tag">
													<?php echo esc_html($template['columns']); ?> columns
												</span>
												<span class="feature-tag">
													<?php echo esc_html($template['width']); ?>px
												</span>
												<span class="feature-tag">
													<?php echo $template['show_images'] ? esc_html__('With Images', 'shopglut') : esc_html__('Text Only', 'shopglut'); ?>
												</span>
											</div>
										</div>
										<button type="submit" class="choose-template-btn">
											<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
												<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
												<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
											</svg>
											<?php esc_html_e("Choose & Customize", 'shopglut'); ?>
										</button>
									</form>
								</div>
							</div>
						<?php endif; ?>
					<?php endforeach; ?>
				</div>
			<?php endforeach; ?>
		</div>

		<!-- HTML Demo Modal -->
		<div id="megaMenuDemoModal" class="shopglut-template-modal-image-modal" style="display: none;">
			<div class="shopglut-template-modal-modal-content">
				<button class="shopglut-template-modal-close-modal" onclick="closeMegaMenuDemoModal()" aria-label="Close">
					<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
						<line x1="18" y1="6" x2="6" y2="18"></line>
						<line x1="6" y1="6" x2="18" y2="18"></line>
					</svg>
				</button>
				<div class="shopglut-template-modal-modal-body" id="megaMenuDemoContent">
					<!-- Demo content will be loaded here -->
				</div>
			</div>
		</div>

		<style>
		/* Modern Mega Menu Template Gallery Styles */
		.shopg-template-gallery .shopg-template-preview {
			border: 1px solid #e0e0e0;
			border-radius: 12px;
			margin: 15px;
			padding: 0;
			background: #fff;
			box-shadow: 0 2px 8px rgba(0,0,0,0.08);
			transition: all 0.3s ease;
			overflow: hidden;
		}

		.shopg-template-gallery .shopg-template-preview:hover {
			box-shadow: 0 8px 25px rgba(0,0,0,0.15);
			transform: translateY(-2px);
		}

		.shopg-template-gallery .template-header {
			padding: 20px 20px 15px 20px;
			border-bottom: 1px solid #f0f0f0;
			background: #2271b1;
			color: white;
		}

		.shopg-template-gallery .template-header h2 {
			margin: 0;
			font-size: 16px;
			font-weight: 600;
			text-align: center;
			color: white;
		}

		.shopg-template-gallery .template-content.product-demo {
			padding: 10px;
			background: #fafafa;
			height: 320px;
			position: relative;
			overflow: hidden !important;
		}

		/* HTML Demo Preview Styles */
		.shopg-template-gallery .template-html-container {
			position: relative;
			width: 100%;
			height: 100%;
		}

		.shopg-template-gallery .html-preview-background {
			width: 75%;
			height: 100%;
			overflow: hidden !important;
			position: relative !important;
		}

		.shopg-template-gallery .html-preview-overlay {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.7);
			display: flex !important;
			align-items: center !important;
			justify-content: center !important;
			opacity: 0;
			transition: all 0.3s ease;
			border-radius: 8px;
			text-align: center;
		}

		.shopg-template-gallery .template-content.product-demo:hover .html-preview-overlay {
			opacity: 1;
		}

		.shopg-template-gallery .demo-view-btn {
			display: flex !important;
			align-items: center !important;
			justify-content: center !important;
			gap: 10px;
			background: rgba(255, 255, 255, 0.95);
			color: #2271b1;
			border: 2px solid #2271b1;
			padding: 12px 20px;
			border-radius: 8px;
			font-weight: 600;
			font-size: 14px;
			cursor: pointer;
			transition: all 0.3s ease;
			backdrop-filter: blur(10px);
			text-decoration: none;
			margin: 0 auto;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			z-index: 100;
		}

		.shopg-template-gallery .demo-view-btn:hover {
			background: #2271b1;
			color: white;
			transform: translate(-50%, -50%) translateY(-2px);
			box-shadow: 0 4px 15px rgba(34, 113, 177, 0.3);
		}

		.shopg-template-gallery .template-footer {
			padding: 20px;
			background: #fff;
			border-top: 1px solid #f0f0f0;
		}

		.shopg-template-gallery .template-info {
			margin-bottom: 15px;
		}

		.shopg-template-gallery .template-description {
			margin: 0 0 12px 0;
			color: #666;
			font-size: 13px;
			line-height: 1.5;
		}

		.shopg-template-gallery .template-features {
			display: flex;
			gap: 8px;
			flex-wrap: wrap;
		}

		.shopg-template-gallery .feature-tag {
			background: #f1f5f9;
			color: #475569;
			padding: 4px 8px;
			border-radius: 4px;
			font-size: 11px;
			font-weight: 500;
		}

		.shopg-template-gallery .choose-template-btn {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 8px;
			padding: 12px 20px;
			background: #2271b1;
			color: white;
			border: none;
			border-radius: 0 0 12px 12px;
			cursor: pointer;
			font-weight: 600;
			font-size: 14px;
			transition: all 0.3s ease;
			text-transform: uppercase;
			letter-spacing: 0.5px;
		}

		.shopg-template-gallery .choose-template-btn:hover {
			background: #135e96;
			transform: translateY(-1px);
			box-shadow: 0 4px 12px rgba(34, 113, 177, 0.3);
		}

		/* Tab Styles */
		.shopg-tab-container {
			margin-bottom: 30px;
		}

		.shopg-tabs {
			display: flex;
			list-style: none;
			margin: 0;
			padding: 0;
			border-bottom: 2px solid #e0e0e0;
		}

		.shopg-tab {
			padding: 12px 24px;
			cursor: pointer;
			background: none;
			border: none;
			border-bottom: 2px solid transparent;
			color: #666;
			font-weight: 500;
			transition: all 0.3s ease;
		}

		.shopg-tab:hover {
			color: #2271b1;
			background: #f8f9fa;
		}

		.shopg-tab.active {
			color: #2271b1;
			border-bottom-color: #2271b1;
			background: #f8f9fa;
		}

		.shopg-tab-content {
			display: none;
		}

		.shopg-tab-content.active {
			display: block;
		}

		/* Modal Styles */
		.shopglut-template-modal-image-modal {
			position: fixed !important;
			top: 0 !important;
			left: 0 !important;
			width: 100% !important;
			height: 100% !important;
			background: rgba(0, 0, 0, 0.9) !important;
			z-index: 999999 !important;
			display: none !important;
			align-items: center !important;
			justify-content: center !important;
			text-align: center;
		}

		.shopglut-template-modal-modal-content {
			background: white !important;
			border-radius: 12px !important;
			max-width: 95% !important;
			max-height: 95% !important;
			position: relative !important;
			overflow: visible !important;
			box-shadow: 0 20px 60px rgba(0,0,0,0.5) !important;
			animation: modalSlideIn 0.3s ease-out !important;
			z-index: 1000000 !important;
		}

		@keyframes modalSlideIn {
			from {
				transform: scale(0.8) translateY(20px);
				opacity: 0;
			}
			to {
				transform: scale(1) translateY(0);
				opacity: 1;
			}
		}

		.shopglut-template-modal-close-modal {
			position: fixed !important;
			top: 15% !important;
			right: 13.5% !important;
			transform: translateY(-50%) !important;
			font-size: 0 !important;
			font-weight: bold !important;
			color: #555 !important;
			cursor: pointer !important;
			z-index: 1000001 !important;
			background: rgba(255, 255, 255, 0.95) !important;
			border-radius: 50% !important;
			width: 40px !important;
			height: 40px !important;
			display: none !important;
			align-items: center !important;
			justify-content: center !important;
			box-shadow: 0 4px 15px rgba(0,0,0,0.2) !important;
			transition: all 0.3s ease !important;
			backdrop-filter: blur(10px) !important;
			border: 2px solid #e5e7eb !important;
			padding: 0 !important;
		}

		.shopglut-template-modal-close-modal.content-loaded {
			display: flex !important;
		}

		.shopglut-template-modal-close-modal:hover {
			background: rgba(255, 255, 255, 1) !important;
			transform: scale(1.1) !important;
		}

		.shopglut-template-modal-modal-body {
			padding: 25px;
			max-height: 85vh;
			overflow: auto;
		}

		@media (max-width: 768px) {
			.shopg-template-gallery .template-content.product-demo {
				height: 250px;
			}

			.shopg-template-gallery .shopg-template-preview {
				margin: 10px;
			}

			.shopg-template-gallery .template-features {
				gap: 6px;
			}

			.shopg-template-gallery .feature-tag {
				font-size: 10px;
				padding: 3px 6px;
			}
		}

		@media (max-width: 480px) {
			.shopg-template-gallery .template-content.product-demo {
				height: 200px;
			}

			.shopg-template-gallery .template-header {
				padding: 15px;
			}

			.shopg-template-gallery .template-header h2 {
				font-size: 14px;
			}

			.shopg-tabs {
				flex-wrap: wrap;
			}

			.shopg-tab {
				padding: 8px 16px;
				font-size: 13px;
			}
		}
		</style>

		<script>
		// Tab functionality
		document.addEventListener('DOMContentLoaded', function() {
			const tabs = document.querySelectorAll('.shopg-tab');
			const tabContents = document.querySelectorAll('.shopg-tab-content');

			tabs.forEach(tab => {
				tab.addEventListener('click', function() {
					const targetTab = this.getAttribute('data-tab');

					// Remove active class from all tabs and contents
					tabs.forEach(t => t.classList.remove('active'));
					tabContents.forEach(tc => tc.classList.remove('active'));

					// Add active class to clicked tab and corresponding content
					this.classList.add('active');
					const targetContent = document.getElementById(targetTab);
					if (targetContent) {
						targetContent.classList.add('active');
					}
				});
			});

			// Activate first tab by default
			if (tabs.length > 0 && tabContents.length > 0) {
				tabs[0].click();
			}
		});

		// Demo modal functions
		function openMegaMenuDemoModal(templateId) {
			const modal = document.getElementById('megaMenuDemoModal');
			const content = document.getElementById('megaMenuDemoContent');

			if (!modal || !content) return;

			// Show loading state
			content.innerHTML = '<div style="text-align: center; padding: 50px;"><div style="font-size: 18px; color: #666;">Loading demo...</div></div>';
			modal.style.display = 'flex';

			// Load demo content via AJAX
			const formData = new FormData();
			formData.append('action', 'get_mega_menu_demo_content');
			formData.append('template_id', templateId);
			formData.append('nonce', '<?php echo wp_create_nonce("shopglut_mega_menu_nonce"); ?>');

			fetch(ajaxurl, {
				method: 'POST',
				body: formData
			})
			.then(response => response.text())
			.then(html => {
				content.innerHTML = html;
				// Show close button when content loads
				const closeButton = modal.querySelector('.shopglut-template-modal-close-modal');
				if (closeButton) {
					closeButton.classList.add('content-loaded');
				}
			})
			.catch(error => {
				console.error('Error loading demo:', error);
				content.innerHTML = '<div style="text-align: center; padding: 50px;"><div style="color: #e74c3c;">Error loading demo. Please try again.</div></div>';
			});
		}

		function closeMegaMenuDemoModal() {
			const modal = document.getElementById('megaMenuDemoModal');
			if (modal) {
				modal.style.display = 'none';
				// Hide close button
				const closeButton = modal.querySelector('.shopglut-template-modal-close-modal');
				if (closeButton) {
					closeButton.classList.remove('content-loaded');
				}
			}
		}

		// Close modal when clicking outside
		document.addEventListener('click', function(e) {
			const modal = document.getElementById('megaMenuDemoModal');
			if (e.target === modal) {
				closeMegaMenuDemoModal();
			}
		});

		// Close modal when pressing Escape
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape') {
				closeMegaMenuDemoModal();
			}
		});
		</script>
		<?php
	}

	private function renderImprovedTemplatePreview( $template ) {
		$text_color = $template['text_color'];
		$bg_color = $template['bg_color'];

		// Create a mini mega menu preview that scales properly
		?>
		<div class="mega-menu-preview-wrapper" style="
			transform: scale(0.4);
			transform-origin: center center;
			width: 250%;
			height: 250%;
			position: absolute;
			top: -75%;
			left: -75%;
			background: <?php echo esc_attr( $bg_color ); ?>;
			border-radius: 8px;
			box-shadow: 0 4px 12px rgba(0,0,0,0.1);
			overflow: hidden;
		">
			<div class="mega-menu-preview-grid" style="
				display: grid;
				grid-template-columns: repeat(<?php echo esc_attr( $template['columns'] ); ?>, 1fr);
				gap: 15px;
				padding: 20px;
				height: 100%;
				color: <?php echo esc_attr( $text_color ); ?>;
			">
				<?php
				$sample_categories = ['Fashion', 'Electronics', 'Home', 'Sports', 'Books', 'Toys', 'Beauty', 'Auto'];
				$category_count = min($template['columns'] * 2, 8);

				for ( $i = 0; $i < $category_count; $i++ ) :
					$category_name = $sample_categories[$i] ?? 'Category ' . ($i + 1);
				?>
					<div class="preview-category" style="text-align: center;">
						<?php if ( $template['show_images'] ) : ?>
							<div style="
								width: 40px;
								height: 40px;
								background: rgba(255,255,255,0.2);
								border-radius: 6px;
								margin: 0 auto 8px;
								display: flex;
								align-items: center;
								justify-content: center;
								font-size: 18px;
							">📦</div>
						<?php endif; ?>

						<h4 style="
							margin: 0 0 8px 0;
							font-size: 11px;
							font-weight: 600;
						"><?php echo esc_html( $category_name ); ?></h4>

						<div style="font-size: 9px; opacity: 0.8; line-height: 1.4;">
							<div>Subitem 1</div>
							<div>Subitem 2</div>
							<div>Subitem 3</div>
						</div>
					</div>
				<?php endfor; ?>
			</div>
		</div>
		<?php
	}

	private function renderTemplatePreview( $template ) {
		$bg_style = '';
		$text_color = $template['text_color'];

		// Create different visual styles based on template type
		switch ( $template['layout_type'] ) {
			case 'grid':
				?>
				<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; width: 80%; height: 80%; color: <?php echo esc_attr( $text_color ); ?>;">
					<?php for ( $i = 0; $i < 4; $i++ ) : ?>
						<div style="background: rgba(255,255,255,0.1); border-radius: 4px; padding: 8px; font-size: 10px; text-align: center; display: flex; align-items: center; justify-content: center;">
							<?php if ( $template['show_images'] ) : ?>
								<div style="width: 20px; height: 20px; background: rgba(255,255,255,0.2); border-radius: 2px; margin-bottom: 4px;"></div>
							<?php else : ?>
								Cat <?php echo esc_html( $i + 1 ); ?>
							<?php endif; ?>
						</div>
					<?php endfor; ?>
				</div>
				<?php
				break;

			case 'featured':
				?>
				<div style="color: <?php echo esc_attr( $text_color ); ?>; text-align: center; padding: 20px;">
					<div style="width: 60px; height: 40px; background: rgba(255,255,255,0.2); border-radius: 4px; margin: 0 auto 10px;"></div>
					<div style="font-size: 12px; font-weight: bold;">Featured</div>
					<div style="font-size: 8px; opacity: 0.8; margin-top: 5px;">Fashion • Beauty • Lifestyle</div>
				</div>
				<?php
				break;

			case 'tech':
				?>
				<div style="color: <?php echo esc_attr( $text_color ); ?>; font-family: monospace;">
					<div style="display: flex; justify-content: space-around; align-items: center; height: 100%; font-size: 10px;">
						<div>📱<br>Mobile</div>
						<div>💻<br>Laptop</div>
						<div>🎧<br>Audio</div>
						<div>📷<br>Camera</div>
					</div>
				</div>
				<?php
				break;

			case 'minimal':
				?>
				<div style="color: <?php echo esc_attr( $text_color ); ?>; text-align: center; font-family: serif;">
					<div style="font-size: 14px; margin-bottom: 15px;">Categories</div>
					<div style="font-size: 10px; line-height: 2;">
						Fashion<br>
						Electronics<br>
						Home & Garden<br>
						Sports
					</div>
				</div>
				<?php
				break;

			case 'modern':
				?>
				<div style="background: linear-gradient(45deg, rgba(255,255,255,0.1), rgba(255,255,255,0.3)); color: <?php echo esc_attr( $text_color ); ?>; border-radius: 8px; padding: 20px; margin: 20px; display: flex; align-items: center; justify-content: center;">
					<div style="text-align: center;">
						<div style="font-size: 16px; margin-bottom: 5px;">🛍️</div>
						<div style="font-size: 11px; font-weight: bold;">Modern Shop</div>
					</div>
				</div>
				<?php
				break;
		}
	}

	private function renderCustomMenus() {
		if ( empty( $this->custom_menus ) ) {
			return;
		}
		?>
		<h2><?php echo esc_html__( 'Your Custom Menus', 'shopglut' ); ?></h2>
		<div class="custom-menus-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
			<?php foreach ( $this->custom_menus as $menu_id => $menu ) : ?>
				<div class="custom-menu-card" data-menu-id="<?php echo esc_attr( $menu_id ); ?>" style="border: 2px solid #0073aa; border-radius: 8px; overflow: hidden; background: #fff;">
					<div class="menu-preview" style="background: <?php echo esc_attr( $menu['bg_color'] ?? '#f0f8ff' ); ?>; height: 120px; position: relative; display: flex; align-items: center; justify-content: center;">
						<i class="fas fa-th-large" style="color: <?php echo esc_attr( $menu['text_color'] ?? '#0073aa' ); ?>; font-size: 32px;"></i>
					</div>
					<div class="menu-info" style="padding: 15px;">
						<h4 style="margin: 0 0 8px 0; color: #333;"><?php echo esc_html( $menu['name'] ?? __( 'Custom Menu', 'shopglut' ) ); ?></h4>
						<div class="menu-actions" style="display: flex; gap: 10px;">
							<button type="button" class="button button-small edit-custom-menu" data-id="<?php echo esc_attr( $menu_id ); ?>">
								<i class="fas fa-edit"></i> <?php echo esc_html__( 'Edit', 'shopglut' ); ?>
							</button>
							<button type="button" class="button button-small delete-custom-menu" data-id="<?php echo esc_attr( $menu_id ); ?>">
								<i class="fas fa-trash"></i> <?php echo esc_html__( 'Delete', 'shopglut' ); ?>
							</button>
						</div>
					</div>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}

	private function renderMegaMenuEditor() {
		?>
		<!-- Mega Menu Editor Modal -->
		<div id="mega-menu-editor-modal" class="shopglut-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 999999; padding: 20px; box-sizing: border-box;">
			<div class="modal-content" style="max-width: 1400px; background: #fff; border-radius: 8px; width: 100%; max-height: 95vh; overflow: hidden; margin: 20px auto; position: relative;">
				<div class="modal-header" style="background: #f8f9fa; padding: 20px 25px; border-bottom: 1px solid #dee2e6; display: flex; justify-content: space-between; align-items: center;">
					<h2 id="editor-title" style="margin: 0; color: #333; font-size: 24px;"><?php echo esc_html__( 'Mega Menu Editor', 'shopglut' ); ?></h2>
					<button class="modal-close" style="background: none; border: none; font-size: 24px; color: #666; cursor: pointer; padding: 0; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">&times;</button>
				</div>
				<div class="modal-body" style="padding: 25px; max-height: calc(95vh - 100px); overflow-y: auto;">
					<?php $this->renderMenuEditor(); ?>
				</div>
			</div>
		</div>

		<!-- Mega Menu Preview Modal -->
		<div id="mega-menu-preview-modal" class="shopglut-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 1000000; padding: 20px; box-sizing: border-box;">
			<div class="modal-content" style="max-width: 1400px; background: #fff; border-radius: 8px; width: 100%; margin: 50px auto; position: relative;">
				<div class="modal-header" style="background: #f8f9fa; padding: 15px 20px; border-bottom: 1px solid #dee2e6; display: flex; justify-content: space-between; align-items: center;">
					<h3 style="margin: 0; color: #333; font-size: 20px;"><?php echo esc_html__( 'Mega Menu Preview', 'shopglut' ); ?></h3>
					<button class="modal-close" style="background: none; border: none; font-size: 24px; color: #666; cursor: pointer; padding: 0; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">&times;</button>
				</div>
				<div class="modal-body" style="padding: 30px;">
					<div id="mega-menu-preview-display">
						<!-- Preview content will be loaded here -->
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	private function renderMenuEditor() {
		?>
		<form id="mega-menu-editor-form">
			<input type="hidden" id="menu-id" name="menu_id" value="">
			
			<!-- Banner Settings - Organized in compact grid -->
			<div class="editor-controls">
				<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 20px;">
					<div>
						<h3><?php echo esc_html__( 'Menu Settings', 'shopglut' ); ?></h3>
						<p>
							<label><?php echo esc_html__( 'Menu Name:', 'shopglut' ); ?></label>
							<input type="text" id="menu-name" name="menu_name" class="widefat" placeholder="<?php echo esc_attr__( 'My Custom Mega Menu', 'shopglut' ); ?>">
						</p>
						<p>
							<label><?php echo esc_html__( 'Description:', 'shopglut' ); ?></label>
							<textarea id="menu-description" name="menu_description" class="widefat" rows="2" placeholder="<?php echo esc_attr__( 'Customized from template', 'shopglut' ); ?>"></textarea>
						</p>
						<p>
							<label><?php echo esc_html__( 'Columns:', 'shopglut' ); ?></label>
							<select id="menu-columns" name="menu_columns" class="widefat">
								<option value="2">2 <?php echo esc_html__( 'Columns', 'shopglut' ); ?></option>
								<option value="3">3 <?php echo esc_html__( 'Columns', 'shopglut' ); ?></option>
								<option value="4">4 <?php echo esc_html__( 'Columns', 'shopglut' ); ?></option>
								<option value="5">5 <?php echo esc_html__( 'Columns', 'shopglut' ); ?></option>
							</select>
						</p>
						<p>
							<label><?php echo esc_html__( 'Menu Width (px):', 'shopglut' ); ?></label>
							<input type="number" id="menu-width" name="menu_width" value="800" min="400" max="1200" class="widefat">
						</p>
					</div>

					<div>
						<h3><?php echo esc_html__( 'Design', 'shopglut' ); ?></h3>
						<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
							<p>
								<label><?php echo esc_html__( 'Background Color:', 'shopglut' ); ?></label>
								<input type="color" id="menu-bg-color" name="menu_bg_color" value="#ffffff">
							</p>
							<p>
								<label><?php echo esc_html__( 'Text Color:', 'shopglut' ); ?></label>
								<input type="color" id="menu-text-color" name="menu_text_color" value="#333333">
							</p>
						</div>
						<p>
							<label>
								<input type="checkbox" id="show-images" name="show_images" value="1">
								<?php echo esc_html__( 'Show Category Images', 'shopglut' ); ?>
							</label>
						</p>
						<p>
							<label>
								<input type="checkbox" id="show-product-count" name="show_product_count" value="1">
								<?php echo esc_html__( 'Show Product Count', 'shopglut' ); ?>
							</label>
						</p>
						<div id="menu-categories-section">
							<h4><?php echo esc_html__( 'Categories to Display', 'shopglut' ); ?></h4>
							<p><small><?php echo esc_html__( 'Select categories for your menu:', 'shopglut' ); ?></small></p>
							<div id="category-selector" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; border-radius: 4px;">
								<?php $this->renderCategorySelector(); ?>
							</div>
						</div>
					</div>
				</div>

				<p style="text-align: center; margin-top: 30px;">
					<button type="button" id="preview-mega-menu-btn" class="button button-secondary button-large" style="margin-right: 15px;">
						<i class="fas fa-eye"></i> <?php echo esc_html__( 'Preview', 'shopglut' ); ?>
					</button>
					<button type="submit" class="button button-primary button-large">
						<i class="fas fa-save"></i> <?php echo esc_html__( 'Save Menu', 'shopglut' ); ?>
					</button>
				</p>
			</div>
		</form>
		<?php
	}

	private function renderCategorySelector() {
		if ( ! function_exists( 'get_terms' ) ) {
			echo '<p>' . esc_html__( 'WooCommerce not detected. Category selection requires WooCommerce.', 'shopglut' ) . '</p>';
			return;
		}

		$categories = get_terms( array(
			'taxonomy' => 'product_cat',
			'hide_empty' => false,
			'parent' => 0, // Only top-level categories
		) );

		if ( is_wp_error( $categories ) || empty( $categories ) ) {
			echo '<p>' . esc_html__( 'No product categories found. Please create some categories first.', 'shopglut' ) . '</p>';
			return;
		}

		?>
		<div class="category-list" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
			<?php foreach ( $categories as $category ) : ?>
				<?php 
				$subcategories = get_terms( array(
					'taxonomy' => 'product_cat',
					'hide_empty' => false,
					'parent' => $category->term_id,
				) );
				?>
				<div class="category-item" style="border: 1px solid #ddd; border-radius: 8px; padding: 15px; background: #f9f9f9;">
					<div class="category-header" style="margin-bottom: 10px;">
						<label style="display: flex; align-items: center; font-weight: 600;">
							<input type="checkbox" class="category-checkbox" data-id="<?php echo esc_attr( $category->term_id ); ?>" style="margin-right: 8px;">
							<?php echo esc_html( $category->name ); ?>
							<span style="color: #666; font-size: 12px; margin-left: 5px;">(<?php echo esc_html( $category->count ); ?>)</span>
						</label>
					</div>
					<?php if ( ! empty( $subcategories ) ) : ?>
						<div class="subcategories" style="margin-left: 20px; font-size: 13px;">
							<?php foreach ( $subcategories as $subcategory ) : ?>
								<label style="display: block; margin-bottom: 5px;">
									<input type="checkbox" class="subcategory-checkbox" data-id="<?php echo esc_attr( $subcategory->term_id ); ?>" data-parent="<?php echo esc_attr( $category->term_id ); ?>" style="margin-right: 5px;">
									<?php echo esc_html( $subcategory->name ); ?>
									<span style="color: #666;">(<?php echo esc_html( $subcategory->count ); ?>)</span>
								</label>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}

	// AJAX Methods
	public function saveMegaMenu() {
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'shopglut_mega_menu_nonce' ) ) {
			wp_die( 'Security check failed' );
		}

		$menu_id = sanitize_text_field( wp_unslash( $_POST['menu_id'] ?? '' ) );
		$menu_data = array(
			'name' => sanitize_text_field( wp_unslash( $_POST['menu_name'] ?? '' ) ),
			'description' => sanitize_textarea_field( wp_unslash( $_POST['menu_description'] ?? '' ) ),
			'type' => sanitize_text_field( wp_unslash( $_POST['menu_type'] ?? 'categories' ) ),
			'columns' => intval( $_POST['menu_columns'] ?? 4 ),
			'width' => intval( $_POST['menu_width'] ?? 800 ),
			'bg_color' => sanitize_hex_color( wp_unslash( $_POST['menu_bg_color'] ?? '#ffffff' ) ),
			'text_color' => sanitize_hex_color( wp_unslash( $_POST['menu_text_color'] ?? '#333333' ) ),
			'show_images' => isset( $_POST['show_images'] ),
			'show_product_count' => isset( $_POST['show_product_count'] ),
			'categories' => array_map( 'intval', $_POST['selected_categories'] ?? [] ),
			'created_at' => current_time( 'mysql' ),
		);

		if ( empty( $menu_id ) ) {
			$menu_id = 'menu_' . time() . '_' . wp_rand( 1000, 9999 );
		}

		$this->custom_menus[ $menu_id ] = $menu_data;
		update_option( 'shopglut_custom_mega_menus', $this->custom_menus );

		wp_send_json_success( array( 'menu_id' => $menu_id, 'message' => __( 'Mega menu saved successfully!', 'shopglut' ) ) );
	}

	public function getMegaMenu() {
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'shopglut_mega_menu_nonce' ) ) {
			wp_die( 'Security check failed' );
		}

		$menu_id = sanitize_text_field( wp_unslash( $_POST['menu_id'] ?? '' ) );
		$menu = $this->custom_menus[ $menu_id ] ?? null;

		if ( $menu ) {
			wp_send_json_success( $menu );
		} else {
			wp_send_json_error( __( 'Mega menu not found', 'shopglut' ) );
		}
	}

	public function deleteMegaMenu() {
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'shopglut_mega_menu_nonce' ) ) {
			wp_die( 'Security check failed' );
		}

		$menu_id = sanitize_text_field( wp_unslash( $_POST['menu_id'] ?? '' ) );

		if ( isset( $this->custom_menus[ $menu_id ] ) ) {
			unset( $this->custom_menus[ $menu_id ] );
			update_option( 'shopglut_custom_mega_menus', $this->custom_menus );
			wp_send_json_success( __( 'Mega menu deleted successfully!', 'shopglut' ) );
		} else {
			wp_send_json_error( __( 'Mega menu not found', 'shopglut' ) );
		}
	}

	public function getMegaMenuDemoContent() {
		if ( ! current_user_can( 'manage_options' ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'shopglut_mega_menu_nonce' ) ) {
			wp_die( 'Security check failed' );
		}

		$template_id = sanitize_text_field( wp_unslash( $_POST['template_id'] ?? '' ) );
		$templates = $this->getPrebuiltTemplates();

		if ( ! isset( $templates[ $template_id ] ) ) {
			wp_die( 'Template not found' );
		}

		$template = $templates[ $template_id ];
		$this->renderFullDemoPreview( $template );
		wp_die();
	}

	public function handleCreateMegaMenuLayout() {
		if (
			!isset($_POST['create_mega_menu_layout_nonce']) ||
			!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['create_mega_menu_layout_nonce'])), 'create_mega_menu_layout_nonce') ||
			!current_user_can('manage_options')
		) {
			wp_die('Security check failed', 'Error', ['response' => 403]);
		}

		try {
			// Validate required POST data
			if (!isset($_POST['layout_id']) || !isset($_POST['layout_template'])) {
				wp_die('Missing required fields', 'Error', ['response' => 400]);
			}

			// Get template data
			$template_id = sanitize_text_field(wp_unslash($_POST['layout_template']));
			$templates = $this->getPrebuiltTemplates();

			if (!isset($templates[$template_id])) {
				wp_die('Invalid template', 'Error', ['response' => 400]);
			}

			$template = $templates[$template_id];

			// Prepare data for insertion
			$data = array(
				'id' => absint($_POST['layout_id']),
				'menu_name' => sanitize_text_field($template['name'] . ' (#' . absint($_POST['layout_id']) . ')'),
				'menu_template' => $template_id,
				'menu_settings' => wp_json_encode(array(
					'columns' => $template['columns'],
					'width' => $template['width'],
					'bg_color' => $template['bg_color'],
					'text_color' => $template['text_color'],
					'show_images' => $template['show_images'],
					'show_product_count' => $template['show_product_count'],
					'layout_type' => $template['layout_type'],
					'featured_style' => $template['featured_style'],
					'description' => $template['description']
				)),
				'created_at' => current_time('mysql')
			);

			// Format specifiers for wpdb
			$format = array(
				'%d',  // id
				'%s',  // menu_name
				'%s',  // menu_template
				'%s',  // menu_settings
				'%s'   // created_at
			);

			// Database insertion
			global $wpdb;
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$table_name = $wpdb->prefix . 'shopglut_mega_menus';

			// Create table if it doesn't exist
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->query("
				CREATE TABLE IF NOT EXISTS `{$table_name}` (
					`id` int(11) NOT NULL AUTO_INCREMENT,
					`menu_name` varchar(255) NOT NULL,
					`menu_template` varchar(50) NOT NULL,
					`menu_settings` longtext NOT NULL,
					`created_at` datetime DEFAULT NULL,
					PRIMARY KEY (`id`)
				) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
			");

			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$inserted = $wpdb->insert($table_name, $data, $format);

			if ($inserted === false) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
				wp_die('Database insertion failed: ' . esc_html($wpdb->last_error), 'Error', ['response' => 500]);
			}

			// Clear cache after successful insertion to ensure next MAX(id) query is accurate
			wp_cache_delete('shopglut_max_mega_menu_id');

			// Redirect on success to the editor page
			$redirect_url = add_query_arg(
				array(
					'page' => 'shopglut_showcases',
					'editor' => 'megamenu',
					'layout_id' => absint($_POST['layout_id'])
				),
				admin_url('admin.php')
			);

			wp_safe_redirect($redirect_url);
			exit;

		} catch (Exception $e) {
			wp_die('An error occurred: ' . esc_html($e->getMessage()), 'Error', ['response' => 500]);
		}
	}

	private function renderFullDemoPreview( $template ) {
		$text_color = $template['text_color'];
		$bg_color = $template['bg_color'];
		?>
		<div style="background: #f8f9fa; padding: 40px; border-radius: 12px;">
			<div style="text-align: center; margin-bottom: 30px;">
				<h3 style="color: #333; margin: 0 0 10px 0;"><?php echo esc_html( $template['name'] ); ?> - Live Demo</h3>
				<p style="color: #666; margin: 0;"><?php echo esc_html( $template['description'] ); ?></p>
			</div>

			<div class="shopglut-mega-menu-demo" style="
				background-color: <?php echo esc_attr( $bg_color ); ?>;
				color: <?php echo esc_attr( $text_color ); ?>;
				width: <?php echo esc_attr( $template['width'] ); ?>px;
				max-width: 100%;
				margin: 0 auto;
				padding: 30px;
				border-radius: 12px;
				box-shadow: 0 8px 25px rgba(0,0,0,0.15);
			">
				<div class="mega-menu-demo-grid" style="
					display: grid;
					grid-template-columns: repeat(<?php echo esc_attr( $template['columns'] ); ?>, 1fr);
					gap: 25px;
				">
					<?php
					$sample_categories = [
						['name' => 'Fashion', 'icon' => '👗', 'subcategories' => ['Dresses', 'Tops', 'Shoes', 'Accessories']],
						['name' => 'Electronics', 'icon' => '📱', 'subcategories' => ['Smartphones', 'Laptops', 'Tablets', 'Accessories']],
						['name' => 'Home & Garden', 'icon' => '🏠', 'subcategories' => ['Furniture', 'Decor', 'Kitchen', 'Garden']],
						['name' => 'Sports', 'icon' => '⚽', 'subcategories' => ['Fitness', 'Outdoor', 'Team Sports', 'Equipment']],
						['name' => 'Books', 'icon' => '📚', 'subcategories' => ['Fiction', 'Non-Fiction', 'Educational', 'E-books']],
						['name' => 'Toys & Games', 'icon' => '🎮', 'subcategories' => ['Action Figures', 'Board Games', 'Video Games', 'Outdoor Toys']],
						['name' => 'Beauty', 'icon' => '💄', 'subcategories' => ['Skincare', 'Makeup', 'Hair Care', 'Fragrance']],
						['name' => 'Automotive', 'icon' => '🚗', 'subcategories' => ['Parts', 'Accessories', 'Tools', 'Car Care']]
					];

					$category_count = min($template['columns'] * 2, 8);

					for ( $i = 0; $i < $category_count; $i++ ) :
						$category = $sample_categories[$i] ?? ['name' => 'Category ' . ($i + 1), 'icon' => '📦', 'subcategories' => ['Item 1', 'Item 2', 'Item 3']];
					?>
						<div class="demo-category">
							<?php if ( $template['show_images'] ) : ?>
								<div class="category-icon" style="
									width: 60px;
									height: 60px;
									background: rgba(255,255,255,0.2);
									border-radius: 8px;
									margin: 0 auto 15px;
									display: flex;
									align-items: center;
									justify-content: center;
									font-size: 28px;
								"><?php echo esc_html( $category['icon'] ); ?></div>
							<?php endif; ?>

							<h4 style="
								margin: 0 0 15px 0;
								font-size: 16px;
								font-weight: 600;
								text-align: center;
							">
								<a href="#" style="color: inherit; text-decoration: none;" onclick="return false;">
									<?php echo esc_html( $category['name'] ); ?>
									<?php if ( $template['show_product_count'] ) : ?>
										<span style="font-size: 12px; opacity: 0.7; margin-left: 5px;">(42)</span>
									<?php endif; ?>
								</a>
							</h4>

							<ul style="
								list-style: none;
								padding: 0;
								margin: 0;
								text-align: center;
								font-size: 13px;
								line-height: 1.8;
							">
								<?php foreach ( $category['subcategories'] as $subcategory ) : ?>
									<li style="margin-bottom: 5px;">
										<a href="#" style="color: inherit; text-decoration: none; opacity: 0.8; transition: opacity 0.3s ease;" onclick="return false;">
											<?php echo esc_html( $subcategory ); ?>
											<?php if ( $template['show_product_count'] ) : ?>
												<span style="font-size: 11px; opacity: 0.6;">(12)</span>
											<?php endif; ?>
										</a>
									</li>
								<?php endforeach; ?>
							</ul>
						</div>
					<?php endfor; ?>
				</div>
			</div>

			<div style="text-align: center; margin-top: 30px;">
				<p style="color: #666; font-size: 14px;">
					<strong>Template Features:</strong>
					<?php echo esc_html( $template['columns'] ); ?> columns •
					<?php echo esc_html( $template['width'] ); ?>px width •
					<?php echo $template['show_images'] ? esc_html__('Images enabled', 'shopglut') : esc_html__('Text only', 'shopglut'); ?> •
					<?php echo $template['show_product_count'] ? esc_html__('Product counts', 'shopglut') : esc_html__('No counts', 'shopglut'); ?>
				</p>
			</div>
		</div>

		<style>
		.demo-category {
			text-align: center;
		}

		.demo-category ul li a:hover {
			opacity: 1 !important;
		}

		/* Responsive adjustments */
		@media (max-width: 768px) {
			.shopglut-mega-menu-demo {
				padding: 20px !important;
			}

			.mega-menu-demo-grid {
				gap: 20px !important;
				grid-template-columns: repeat(2, 1fr) !important;
			}
		}

		@media (max-width: 480px) {
			.mega-menu-demo-grid {
				grid-template-columns: 1fr !important;
			}
		}
		</style>
		<?php
	}

	// WordPress Menu Integration
	public function addMenuItemFields( $item_id, $item, $depth, $args ) {
		?>
		<p class="field-shopglut-mega-menu description description-wide">
			<label for="edit-menu-item-shopglut-mega-menu-<?php echo esc_attr( $item_id ); ?>">
				<?php echo esc_html__( 'ShopGlut Mega Menu', 'shopglut' ); ?><br />
				<select id="edit-menu-item-shopglut-mega-menu-<?php echo esc_attr( $item_id ); ?>" name="menu-item-shopglut-mega-menu[<?php echo esc_attr( $item_id ); ?>]">
					<option value=""><?php echo esc_html__( 'None', 'shopglut' ); ?></option>
					<?php foreach ( $this->custom_menus as $menu_id => $menu ) : ?>
						<option value="<?php echo esc_attr( $menu_id ); ?>" <?php selected( $menu_id, get_post_meta( $item_id, '_menu_item_shopglut_mega_menu', true ) ); ?>>
							<?php echo esc_html( $menu['name'] ); ?>
						</option>
					<?php endforeach; ?>
				</select>
			</label>
		</p>
		<?php
	}

	public function updateMenuItem( $menu_id, $menu_item_db_id, $args ) {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress handles nonce verification for nav menu updates
		if ( isset( $_REQUEST['menu-item-shopglut-mega-menu'][ $menu_item_db_id ] ) ) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- WordPress nav menu data doesn't need wp_unslash in this context
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress handles nonce verification for nav menu updates
			$mega_menu_id = sanitize_text_field( wp_unslash( $_REQUEST['menu-item-shopglut-mega-menu'][ $menu_item_db_id ] ) );
			update_post_meta( $menu_item_db_id, '_menu_item_shopglut_mega_menu', $mega_menu_id );
		}
	}

	// Frontend Display
	public function displayMegaMenu( $menu_id ) {
		$menu = $this->custom_menus[ $menu_id ] ?? null;
		if ( ! $menu ) {
			return '';
		}

		$categories = array();
		foreach ( $menu['categories'] as $cat_id ) {
			$category = get_term( $cat_id, 'product_cat' );
			if ( $category && ! is_wp_error( $category ) ) {
				$categories[] = $category;
			}
		}

		ob_start();
		?>
		<div class="shopglut-mega-menu" style="
			background-color: <?php echo esc_attr( $menu['bg_color'] ); ?>;
			color: <?php echo esc_attr( $menu['text_color'] ); ?>;
			width: <?php echo esc_attr( $menu['width'] ); ?>px;
			padding: 20px;
			border-radius: 8px;
			box-shadow: 0 4px 12px rgba(0,0,0,0.1);
		">
			<div class="mega-menu-grid" style="
				display: grid;
				grid-template-columns: repeat(<?php echo esc_attr( $menu['columns'] ); ?>, 1fr);
				gap: 20px;
			">
				<?php foreach ( $categories as $category ) : ?>
					<div class="mega-menu-category">
						<?php if ( $menu['show_images'] ) : ?>
							<?php $thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true ); ?>
							<?php if ( $thumbnail_id ) : ?>
								<div class="category-image" style="margin-bottom: 10px;">
									<?php echo wp_get_attachment_image( $thumbnail_id, 'thumbnail', false, array( 'style' => 'border-radius: 4px;' ) ); ?>
								</div>
							<?php endif; ?>
						<?php endif; ?>
						
						<h4 style="margin: 0 0 10px 0;">
							<a href="<?php echo esc_url( get_term_link( $category ) ); ?>" style="color: inherit; text-decoration: none;">
								<?php echo esc_html( $category->name ); ?>
								<?php if ( $menu['show_product_count'] ) : ?>
									<span style="font-size: 12px; opacity: 0.7;">(<?php echo esc_html( $category->count ); ?>)</span>
								<?php endif; ?>
							</a>
						</h4>
						
						<?php
						$subcategories = get_terms( array(
							'taxonomy' => 'product_cat',
							'hide_empty' => false,
							'parent' => $category->term_id,
							'number' => 5, // Limit subcategories
						) );
						?>
						
						<?php if ( ! empty( $subcategories ) && ! is_wp_error( $subcategories ) ) : ?>
							<ul style="list-style: none; padding: 0; margin: 0; font-size: 13px;">
								<?php foreach ( $subcategories as $subcategory ) : ?>
									<li style="margin-bottom: 5px;">
										<a href="<?php echo esc_url( get_term_link( $subcategory ) ); ?>" style="color: inherit; text-decoration: none; opacity: 0.8;">
											<?php echo esc_html( $subcategory->name ); ?>
											<?php if ( $menu['show_product_count'] ) : ?>
												<span style="font-size: 11px; opacity: 0.6;">(<?php echo esc_html( $subcategory->count ); ?>)</span>
											<?php endif; ?>
										</a>
									</li>
								<?php endforeach; ?>
							</ul>
						<?php endif; ?>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	public function addScriptsAndNonces() {
		?>
		<script>
		jQuery(document).ready(function($) {
			console.log('Mega Menu script loaded');
			
			// Customize functionality now handled via form submission - no need for JavaScript here

			// Edit custom menu
			$(document).on('click', '.edit-custom-menu', function(e) {
				e.preventDefault();
				var menuId = $(this).data('id');
				loadMenuForEdit(menuId);
				$('#mega-menu-editor-modal').show();
			});

			// Modal handlers
			$(document).on('click', '.modal-close', function() {
				$(this).closest('.shopglut-modal').hide();
			});

			// Delete custom menu
			$(document).on('click', '.delete-custom-menu', function(e) {
				e.preventDefault();
				var menuId = $(this).data('id');
				if (confirm('<?php echo esc_js( __( 'Are you sure you want to delete this menu?', 'shopglut' ) ); ?>')) {
					deleteMenu(menuId);
				}
			});

			// Preview menu button
			$(document).on('click', '#preview-mega-menu-btn', function(e) {
				e.preventDefault();
				updatePreviewModal();
				$('#mega-menu-preview-modal').show();
			});
		});

		function loadTemplate(templateId) {
			var templates = <?php echo json_encode( $this->getPrebuiltTemplates() ); ?>;
			var template = templates[templateId];

			jQuery('#editor-title').text('<?php echo esc_js( __( 'Customize Mega Menu Template', 'shopglut' ) ); ?>');
			jQuery('#menu-id').val('');
			jQuery('#menu-name').val(template.name + ' - Custom');
			jQuery('#menu-description').val(template.description);
			jQuery('#menu-columns').val(template.columns);
			jQuery('#menu-width').val(template.width);
			jQuery('#menu-bg-color').val(template.bg_color);
			jQuery('#menu-text-color').val(template.text_color);
			jQuery('#show-images').prop('checked', template.show_images);
			jQuery('#show-product-count').prop('checked', template.show_product_count);

			// Reset category selections
			jQuery('.category-checkbox, .subcategory-checkbox').prop('checked', false);
		}

		function loadMenuForEdit(menuId) {
			// Load existing custom menu for editing
			jQuery.ajax({
				url: ajaxurl,
				type: 'POST',
				data: {
					action: 'get_mega_menu',
					menu_id: menuId,
					nonce: '<?php echo esc_js( wp_create_nonce( 'shopglut_mega_menu_nonce' ) ); ?>'
				},
				success: function(response) {
					if (response.success) {
						var menu = response.data;
						jQuery('#editor-title').text('<?php echo esc_js( __( 'Edit Menu', 'shopglut' ) ); ?>');
						jQuery('#menu-id').val(menu.id);
						jQuery('#menu-name').val(menu.name);
						jQuery('#menu-description').val(menu.description);
						jQuery('#menu-columns').val(menu.columns);
						jQuery('#menu-width').val(menu.width);
						jQuery('#menu-bg-color').val(menu.bg_color);
						jQuery('#menu-text-color').val(menu.text_color);
						jQuery('#show-images').prop('checked', menu.show_images);
						jQuery('#show-product-count').prop('checked', menu.show_product_count);
						
						// Set categories
						jQuery('.category-checkbox, .subcategory-checkbox').prop('checked', false);
						if (menu.categories) {
							menu.categories.forEach(function(catId) {
								jQuery('.category-checkbox[data-id="' + catId + '"], .subcategory-checkbox[data-id="' + catId + '"]').prop('checked', true);
							});
						}
					}
				}
			});
		}

		function deleteMenu(menuId) {
			jQuery.ajax({
				url: ajaxurl,
				type: 'POST',
				data: {
					action: 'delete_mega_menu',
					menu_id: menuId,
					nonce: '<?php echo esc_js( wp_create_nonce( 'shopglut_mega_menu_nonce' ) ); ?>'
				},
				success: function(response) {
					if (response.success) {
						location.reload();
					} else {
						alert('<?php echo esc_js( __( 'Error deleting menu', 'shopglut' ) ); ?>');
					}
				}
			});
		}

		function updatePreviewModal() {
			var columns = jQuery('#menu-columns').val() || 4;
			var bgColor = jQuery('#menu-bg-color').val() || '#ffffff';
			var textColor = jQuery('#menu-text-color').val() || '#333333';
			var width = jQuery('#menu-width').val() || 800;
			var showImages = jQuery('#show-images').is(':checked');
			var showCount = jQuery('#show-product-count').is(':checked');

			var previewHtml = '<div class="shopglut-mega-menu" style="' +
				'background-color: ' + bgColor + '; ' +
				'color: ' + textColor + '; ' +
				'width: ' + width + 'px; ' +
				'padding: 20px; ' +
				'border-radius: 8px; ' +
				'box-shadow: 0 4px 12px rgba(0,0,0,0.1); ' +
				'opacity: 1; ' +
				'visibility: visible; ' +
				'position: relative;' +
				'">';

			previewHtml += '<div class="mega-menu-grid" style="' +
				'display: grid; ' +
				'grid-template-columns: repeat(' + columns + ', 1fr); ' +
				'gap: 20px;' +
				'">';

			// Generate sample categories for preview
			for (var i = 0; i < Math.min(columns * 2, 8); i++) {
				previewHtml += '<div class="mega-menu-category">';
				
				if (showImages) {
					previewHtml += '<div class="category-image" style="margin-bottom: 10px; width: 60px; height: 60px; background: rgba(0,0,0,0.1); border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 24px; opacity: 0.5;">📷</div>';
				}
				
				previewHtml += '<h4 style="margin: 0 0 10px 0;">';
				previewHtml += 'Category ' + (i + 1);
				if (showCount) {
					previewHtml += ' <span style="font-size: 12px; opacity: 0.7;">(25)</span>';
				}
				previewHtml += '</h4>';
				
				previewHtml += '<ul style="list-style: none; padding: 0; margin: 0; font-size: 13px;">';
				previewHtml += '<li style="margin-bottom: 5px; opacity: 0.8;">Subcategory 1</li>';
				previewHtml += '<li style="margin-bottom: 5px; opacity: 0.8;">Subcategory 2</li>';
				previewHtml += '<li style="margin-bottom: 5px; opacity: 0.8;">Subcategory 3</li>';
				previewHtml += '</ul>';
				
				previewHtml += '</div>';
			}

			previewHtml += '</div></div>';

			jQuery('#mega-menu-preview-display').html(previewHtml);
		}

		// Update preview on input changes
		jQuery(document).ready(function($) {
			$('#mega-menu-editor-form input, #mega-menu-editor-form select, #mega-menu-editor-form textarea').on('input change', function() {
				if ($('#mega-menu-preview-modal').is(':visible')) {
					setTimeout(updatePreviewModal, 300);
				}
			});
			
			// Form submission
			$('#mega-menu-editor-form').on('submit', function(e) {
				e.preventDefault();
				
				var selectedCategories = [];
				$('.category-checkbox:checked, .subcategory-checkbox:checked').each(function() {
					selectedCategories.push($(this).data('id'));
				});

				if (!$('#menu-name').val().trim()) {
					alert('<?php echo esc_js( __( 'Please enter a menu name', 'shopglut' ) ); ?>');
					return;
				}

				if (selectedCategories.length === 0) {
					alert('<?php echo esc_js( __( 'Please select at least one category', 'shopglut' ) ); ?>');
					return;
				}

				$.ajax({
					url: ajaxurl,
					type: 'POST',
					data: {
						action: 'save_mega_menu',
						menu_id: $('#menu-id').val(),
						menu_name: $('#menu-name').val(),
						menu_description: $('#menu-description').val(),
						menu_columns: $('#menu-columns').val(),
						menu_width: $('#menu-width').val(),
						menu_bg_color: $('#menu-bg-color').val(),
						menu_text_color: $('#menu-text-color').val(),
						show_images: $('#show-images').is(':checked') ? 1 : 0,
						show_product_count: $('#show-product-count').is(':checked') ? 1 : 0,
						selected_categories: selectedCategories,
						nonce: '<?php echo esc_js( wp_create_nonce( 'shopglut_mega_menu_nonce' ) ); ?>'
					},
					success: function(response) {
						if (response.success) {
							alert('<?php echo esc_js( __( 'Menu saved successfully!', 'shopglut' ) ); ?>');
							location.reload();
						} else {
							alert(response.data || '<?php echo esc_js( __( 'Error saving menu', 'shopglut' ) ); ?>');
						}
					},
					error: function() {
						alert('<?php echo esc_js( __( 'Connection error. Please try again.', 'shopglut' ) ); ?>');
					}
				});
			});

			// Category selection logic
			$('.category-checkbox').change(function() {
				var categoryId = $(this).data('id');
				var isChecked = $(this).is(':checked');
				$('.subcategory-checkbox[data-parent="' + categoryId + '"]').prop('checked', isChecked);
			});

			$('.subcategory-checkbox').change(function() {
				var parentId = $(this).data('parent');
				var hasCheckedSubcategories = $('.subcategory-checkbox[data-parent="' + parentId + '"]:checked').length > 0;
				$('.category-checkbox[data-id="' + parentId + '"]').prop('checked', hasCheckedSubcategories);
			});
		});
		</script>
		<?php
	}
}