document.addEventListener('DOMContentLoaded', () => {
	const toggle = document.querySelector('.toggle-pass');
	const input = document.getElementById('password');
	const languageSelect = document.querySelector('#site-language');
	const languageIcon = document.querySelector('.language-flag img');
	const languageToggle = document.querySelector('.language-select__toggle');

	if (languageSelect) {
		const updateLanguageIcon = () => {
			if (!languageIcon) {
				return;
			}
			const selectedOption = languageSelect.options[languageSelect.selectedIndex];
			if (!selectedOption) {
				return;
			}
			const iconPath = selectedOption.getAttribute('data-icon');
			if (iconPath) {
				languageIcon.src = iconPath;
				languageIcon.alt = selectedOption.textContent.trim();
			}
		};

		updateLanguageIcon();
		languageSelect.addEventListener('change', updateLanguageIcon);

		if (languageToggle) {
			languageToggle.addEventListener('click', (event) => {
				event.preventDefault();
				event.stopPropagation();
				try {
					languageSelect.focus({ preventScroll: true });
				} catch (error) {
					languageSelect.focus();
				}

				if (typeof languageSelect.showPicker === 'function') {
					languageSelect.showPicker();
				} else {
					try {
						languageSelect.click();
					} catch (error) {
						const mouseEvent = new MouseEvent('mousedown', {
							bubbles: true,
							cancelable: true,
							view: window
						});
						languageSelect.dispatchEvent(mouseEvent);
					}
				}
			});
		}
	}

	if (toggle && input) {
		const showLabel = toggle.dataset.showLabel || 'Show password';
		const hideLabel = toggle.dataset.hideLabel || 'Hide password';

		const applyLabel = () => {
			const isVisible = input.getAttribute('type') === 'text';
			const label = isVisible ? hideLabel : showLabel;
			toggle.setAttribute('aria-label', label);
			toggle.setAttribute('title', label);
			const srText = toggle.querySelector('.visually-hidden');
			if (srText) {
				srText.textContent = label;
			}
		};

		toggle.addEventListener('click', () => {
			const isHidden = input.getAttribute('type') === 'password';
			input.setAttribute('type', isHidden ? 'text' : 'password');
			toggle.dataset.state = isHidden ? 'visible' : 'hidden';
			applyLabel();
		});

		applyLabel();
	}

	const menuToggle = document.querySelector('.topbar-menu');
	const dashboardBody = document.querySelector('.dashboard-body');

	if (menuToggle && dashboardBody) {
		const expandedLabel = menuToggle.dataset.expandedLabel || (window.__MESSAGES__ && window.__MESSAGES__['control_header_toggle_collapse']) ? window.__MESSAGES__['control_header_toggle_collapse'] : 'Thu gọn menu';
		const collapsedLabel = menuToggle.dataset.collapsedLabel || (window.__MESSAGES__ && window.__MESSAGES__['control_header_toggle_expand']) ? window.__MESSAGES__['control_header_toggle_expand'] : 'Mở menu';
		const mediaQuery = window.matchMedia('(max-width: 1200px)');
		const isMobileView = () => mediaQuery.matches;

		const applyState = () => {
			const mobile = isMobileView();
			const isMenuOpen = mobile
				? dashboardBody.classList.contains('menu-visible')
				: !dashboardBody.classList.contains('menu-collapsed');

			menuToggle.setAttribute('aria-expanded', isMenuOpen.toString());
			const pressedState = mobile ? isMenuOpen : (!isMenuOpen);
			menuToggle.setAttribute('aria-pressed', pressedState.toString());
			const label = isMenuOpen ? expandedLabel : collapsedLabel;
			menuToggle.setAttribute('aria-label', label);
			menuToggle.title = label;
		};

		const syncResponsiveState = () => {
			if (isMobileView()) {
				dashboardBody.classList.remove('menu-collapsed');
			} else {
				dashboardBody.classList.remove('menu-visible');
			}
			applyState();
		};

		menuToggle.addEventListener('click', () => {
			// Close all submenus before toggling menu
			closeAllSubmenus();
			closeDeclarationSubmenu();
			closeOperationsSubmenu();
			
			if (isMobileView()) {
				dashboardBody.classList.toggle('menu-visible');
			} else {
				dashboardBody.classList.toggle('menu-collapsed');
			}
			applyState();
		});

		if (typeof mediaQuery.addEventListener === 'function') {
			mediaQuery.addEventListener('change', syncResponsiveState);
		} else if (typeof mediaQuery.addListener === 'function') {
			mediaQuery.addListener(syncResponsiveState);
		}

		syncResponsiveState();
	}

	const allTopLevelItems = document.querySelectorAll('.sidebar-nav > ul > li, .sidebar-footer li');
	const primaryItems = document.querySelectorAll('.sidebar-nav > ul > li:not(.has-submenu), .sidebar-footer li');
	const submenuParents = document.querySelectorAll('.sidebar-nav li.has-submenu');
	const submenuTriggers = document.querySelectorAll('.sidebar-nav li.has-submenu .submenu-trigger');
	const submenuLinks = document.querySelectorAll('.sidebar-nav li.has-submenu .submenu-link');
	
	// Handle nested submenus (submenu within submenu)
	const nestedSubmenuParents = document.querySelectorAll('.submenu li.has-submenu');
	const nestedSubmenuTriggers = document.querySelectorAll('.submenu li.has-submenu .submenu-trigger');

	// Declaration and operations elements
	const declarationTriggers = document.querySelectorAll('.declaration-trigger');
	const declarationSubmenu = document.getElementById('declaration-submenu');
	const operationsTriggers = document.querySelectorAll('.operations-trigger');
	const operationsSubmenu = document.getElementById('operations-submenu');
	

	// Function to close all regular submenus
	const closeAllSubmenus = () => {
		submenuParents.forEach((parent) => {
			parent.classList.remove('submenu-open');
			const trigger = parent.querySelector('.submenu-trigger');
			if (trigger) {
				trigger.setAttribute('aria-expanded', 'false');
			}
		});
		// Also close nested submenus
		nestedSubmenuParents.forEach((parent) => {
			parent.classList.remove('submenu-open');
			const trigger = parent.querySelector('.submenu-trigger');
			if (trigger) {
				trigger.setAttribute('aria-expanded', 'false');
			}
		});
		// Don't close declaration submenu here - let it handle its own closing
	};

	// Function to close declaration submenu
	const closeDeclarationSubmenu = () => {
		if (declarationSubmenu) {
			declarationSubmenu.classList.remove('show');
		}
		// Remove selected state from declaration trigger(s)
		if (declarationTriggers && declarationTriggers.length) {
			declarationTriggers.forEach((t) => t.classList.remove('is-selected'));
		}
	};

	// Function to close operations submenu
	const closeOperationsSubmenu = () => {
		if (operationsSubmenu) {
			operationsSubmenu.classList.remove('show');
		}
		if (operationsTriggers && operationsTriggers.length) {
			operationsTriggers.forEach((t) => t.classList.remove('is-selected'));
		}
	};

	// Function to update positions of all open submenus
	const updateSubmenuPositions = () => {
		// Update regular submenus
		submenuParents.forEach((parent) => {
			if (parent.classList.contains('submenu-open')) {
				const trigger = parent.querySelector('.submenu-trigger');
				const submenu = parent.querySelector('.submenu');
				if (trigger && submenu) {
					const rect = trigger.getBoundingClientRect();
					const isCollapsed = document.body.classList.contains('menu-collapsed') || 
									   document.body.classList.contains('menu-visible');
					const marginLeft = isCollapsed ? 8 : 12;
					
					submenu.style.top = `${rect.top}px`;
					submenu.style.left = `${rect.right + marginLeft}px`;
				}
			}
		});

		// Update declaration submenu
		const declarationSubmenu = document.getElementById('declaration-submenu');
		if (declarationSubmenu && declarationSubmenu.classList.contains('show')) {
			const activeTrigger = document.querySelector('.declaration-trigger.is-selected');
			if (activeTrigger) {
				const rect = activeTrigger.getBoundingClientRect();
				const isCollapsed = document.body.classList.contains('menu-collapsed') || 
									document.body.classList.contains('menu-visible');
				const isMobile = window.innerWidth <= 1200;
				
				if (isMobile) {
					// Mobile: position static, hiển thị như nested menu trong sidebar
					declarationSubmenu.style.position = 'static';
					declarationSubmenu.style.top = '';
					declarationSubmenu.style.left = '';
					declarationSubmenu.style.margin = '8px 0';
					declarationSubmenu.style.width = '100%';
					declarationSubmenu.style.display = 'block';
				} else {
					// Desktop: position fixed như cũ
					const marginLeft = isCollapsed ? 8 : 12;
					declarationSubmenu.style.position = 'fixed';
					declarationSubmenu.style.top = `${rect.top}px`;
					declarationSubmenu.style.left = `${rect.right + marginLeft}px`;
					declarationSubmenu.style.margin = '';
					declarationSubmenu.style.width = '';
				}
			}
		}

		// Update operations submenu
		const operationsSubmenu = document.getElementById('operations-submenu');
		if (operationsSubmenu && operationsSubmenu.classList.contains('show')) {
			const activeTrigger = document.querySelector('.operations-trigger.is-selected');
			if (activeTrigger) {
				const rect = activeTrigger.getBoundingClientRect();
				const isCollapsed = document.body.classList.contains('menu-collapsed') || 
									document.body.classList.contains('menu-visible');
				const isMobile = window.innerWidth <= 1200;
				
				if (isMobile) {
					// Mobile: position static, hiển thị như nested menu trong sidebar
					operationsSubmenu.style.position = 'static';
					operationsSubmenu.style.top = '';
					operationsSubmenu.style.left = '';
					operationsSubmenu.style.margin = '8px 0';
					operationsSubmenu.style.width = '100%';
					operationsSubmenu.style.display = 'block';
				} else {
					// Desktop: position fixed như cũ
					const marginLeft = isCollapsed ? 8 : 12;
					operationsSubmenu.style.position = 'fixed';
					operationsSubmenu.style.top = `${rect.top}px`;
					operationsSubmenu.style.left = `${rect.right + marginLeft}px`;
					operationsSubmenu.style.margin = '';
					operationsSubmenu.style.width = '';
				}
			}
		}
	};

	// Throttle function for performance
	const throttle = (func, limit) => {
		let inThrottle;
		return function() {
			const args = arguments;
			const context = this;
			if (!inThrottle) {
				func.apply(context, args);
				inThrottle = true;
				setTimeout(() => inThrottle = false, limit);
			}
		}
	};

	// Add scroll listener to sidebar with throttling
	const sidebar = document.querySelector('.dashboard-sidebar');
	if (sidebar) {
		sidebar.addEventListener('scroll', throttle(updateSubmenuPositions, 16)); // ~60fps
	}

	// Add resize listener to update positions on window resize with throttling
	window.addEventListener('resize', throttle(updateSubmenuPositions, 100));

	const clearActiveItems = () => {
		allTopLevelItems.forEach((item) => item.classList.remove('active'));
	};

	const clearSubmenuSelection = () => {
		submenuLinks.forEach((link) => link.classList.remove('is-selected'));
	};

	primaryItems.forEach((item) => {
		item.addEventListener('click', () => {
			clearActiveItems();
			clearSubmenuSelection();
			closeAllSubmenus();
			item.classList.add('active');
		});
	});

	submenuTriggers.forEach((trigger) => {
		const parent = trigger.closest('.has-submenu');
		if (!parent) {
			return;
		}

		const positionSubmenu = () => {
			const submenu = parent.querySelector('.submenu');
			if (!submenu) return;
			
			const rect = trigger.getBoundingClientRect();
			const isCollapsed = document.body.classList.contains('menu-collapsed') || 
							   document.body.classList.contains('menu-visible');
			const marginLeft = isCollapsed ? 8 : 12;
			
			submenu.style.top = `${rect.top}px`;
			submenu.style.left = `${rect.right + marginLeft}px`;
		};

		const toggleSubmenu = () => {
			const isOpen = parent.classList.contains('submenu-open');
			clearSubmenuSelection();
			if (isOpen) {
				parent.classList.remove('submenu-open', 'active');
				trigger.setAttribute('aria-expanded', 'false');
			} else {
				clearActiveItems();
				closeAllSubmenus();
				parent.classList.add('active', 'submenu-open');
				trigger.setAttribute('aria-expanded', 'true');
				positionSubmenu();
			}
		};

		trigger.addEventListener('click', (event) => {
			event.preventDefault();
			event.stopPropagation();
			toggleSubmenu();
		});

		trigger.addEventListener('keydown', (event) => {
			if (event.key === 'Enter' || event.key === ' ') {
				event.preventDefault();
				toggleSubmenu();
			}
		});
	});

    submenuLinks.forEach((link) => {
		link.addEventListener('click', (event) => {
			// Skip if this is a declaration trigger or admin-declaration trigger
            if (link.classList.contains('declaration-trigger') || 
                link.classList.contains('operations-trigger') ||
                link.classList.contains('admin-declaration-trigger')) {
				return;
			}
			
			event.preventDefault();
			const parentItem = link.closest('.has-submenu');
			if (!parentItem) {
				return;
			}

			clearActiveItems();
			clearSubmenuSelection();
            closeAllSubmenus();
            // Also ensure declaration submenu is closed and its trigger unselected
            closeDeclarationSubmenu();
			parentItem.classList.add('active', 'submenu-open');
			link.classList.add('is-selected');
			const trigger = parentItem.querySelector('.submenu-trigger');
			if (trigger) {
				trigger.setAttribute('aria-expanded', 'true');
			}
		});
	});

	// Handle declaration submenu
    // Re-query to make sure elements exist
	const requeriedDeclarationTriggers = document.querySelectorAll('.declaration-trigger');
	const requeriedDeclarationSubmenu = document.getElementById('declaration-submenu');
	
	
	
	// Simple test - add visible border to triggers for debugging
	requeriedDeclarationTriggers.forEach(trigger => {
		// Remove debug styling
	});
	
	if (requeriedDeclarationSubmenu) {
		// Remove debug styling
	}

    // Add click listeners to declaration triggers
	if (requeriedDeclarationTriggers.length > 0) {
        requeriedDeclarationTriggers.forEach((trigger, index) => {
			const positionDeclarationSubmenu = () => {
				if (!requeriedDeclarationSubmenu) return;
				const rect = trigger.getBoundingClientRect();
				const isCollapsed = document.body.classList.contains('menu-collapsed') || 
									document.body.classList.contains('menu-visible');
				const isMobile = window.innerWidth <= 1200;
				
				if (isMobile) {
					// Mobile: position static, hiển thị như nested menu trong sidebar
					requeriedDeclarationSubmenu.style.position = 'static';
					requeriedDeclarationSubmenu.style.top = '';
					requeriedDeclarationSubmenu.style.left = '';
					requeriedDeclarationSubmenu.style.margin = '8px 0';
					requeriedDeclarationSubmenu.style.width = '100%';
					requeriedDeclarationSubmenu.style.zIndex = 'auto';
					requeriedDeclarationSubmenu.style.display = 'block';
				} else {
					// Desktop: position fixed như cũ
					const marginLeft = isCollapsed ? 8 : 12;
					requeriedDeclarationSubmenu.style.position = 'fixed';
					requeriedDeclarationSubmenu.style.zIndex = '10000';
					requeriedDeclarationSubmenu.style.top = `${rect.top}px`;
					requeriedDeclarationSubmenu.style.left = `${rect.right + marginLeft}px`;
					requeriedDeclarationSubmenu.style.margin = '';
					requeriedDeclarationSubmenu.style.width = '';
				}
				
				// Reset any debug styles
				requeriedDeclarationSubmenu.style.background = '';
				requeriedDeclarationSubmenu.style.height = '';
				requeriedDeclarationSubmenu.style.border = '';
				requeriedDeclarationSubmenu.style.padding = '';
				requeriedDeclarationSubmenu.style.cssText = requeriedDeclarationSubmenu.style.cssText.replace(/background:[^;]*;?/gi, '').replace(/height:[^;]*;?/gi, '').replace(/border:[^;]*;?/gi, '').replace(/padding:[^;]*;?/gi, '');
			};

			trigger.addEventListener('click', (event) => {
				event.preventDefault();
				event.stopPropagation();
				
				// Toggle declaration submenu
                if (requeriedDeclarationSubmenu) {
					const isVisible = requeriedDeclarationSubmenu.classList.contains('show');
					
                    if (isVisible) {
                        requeriedDeclarationSubmenu.classList.remove('show');
                        trigger.classList.remove('is-selected');
                        trigger.setAttribute('aria-expanded', 'false');
                        const parentLi = trigger.closest('li');
                        if (parentLi) parentLi.classList.remove('submenu-open');
					} else {
						// Clear any previous selection on other submenu links
						clearSubmenuSelection();
						
                        // Close Operations submenu if open
						const opsSub = document.getElementById('operations-submenu');
						if (opsSub) {
							opsSub.classList.remove('show');
						}
						const opsTriggers = document.querySelectorAll('.operations-trigger');
						if (opsTriggers && opsTriggers.length) {
							opsTriggers.forEach((t)=>{
								t.classList.remove('is-selected');
								t.setAttribute('aria-expanded','false');
								const li = t.closest('li');
								if (li) li.classList.remove('submenu-open');
							});
						}
						
						requeriedDeclarationSubmenu.classList.add('show');
						positionDeclarationSubmenu();
						
						// Force immediate positioning (no transition delay) - chỉ cho desktop
						const isMobile = window.innerWidth <= 1200;
						if (!isMobile) {
							const rect = trigger.getBoundingClientRect();
							const isCollapsed = document.body.classList.contains('menu-collapsed') || 
												document.body.classList.contains('menu-visible');
							const marginLeft = isCollapsed ? 8 : 12;
							
							requeriedDeclarationSubmenu.style.transition = 'none';
							requestAnimationFrame(() => {
								requeriedDeclarationSubmenu.style.top = `${rect.top}px`;
								requeriedDeclarationSubmenu.style.left = `${rect.right + marginLeft}px`;
								requestAnimationFrame(() => {
									requeriedDeclarationSubmenu.style.transition = '';
								});
							});
						}
						
                        // Mark the trigger as selected to keep active style
                        trigger.classList.add('is-selected');
                        trigger.setAttribute('aria-expanded', 'true');
                        const parentLi = trigger.closest('li');
                        if (parentLi) parentLi.classList.add('submenu-open', 'active');
					}
				}
			});
		});
	}

    // Add click listeners to declaration submenu items
    const declarationSubmenuItems = document.querySelectorAll('.declaration-submenu-item');
    declarationSubmenuItems.forEach((item) => {
        item.addEventListener('click', (event) => {
            const href = item.getAttribute('href');
            // If it's a real navigation link, allow default navigation
            if (href && href !== '#') {
                // optional: close submenu before navigate
                closeDeclarationSubmenu();
                return; // allow navigation
            }
            // Otherwise, treat as non-navigation item
            event.preventDefault();
            event.stopPropagation();
        });
    });

	// Close declaration submenu when clicking outside
	document.addEventListener('click', (event) => {
		if (declarationSubmenu && 
			!declarationSubmenu.contains(event.target) && 
			!event.target.closest('.declaration-trigger') && 
			!event.target.closest('.declaration-submenu') &&
			!event.target.closest('.submenu-trigger')) {
			closeDeclarationSubmenu();
		}
	});

    // Operations submenu (mirrors declaration behavior)
    // Re-query to make sure elements exist
	const requeriedOperationsTriggers = document.querySelectorAll('.operations-trigger');
	const requeriedOperationsSubmenu = document.getElementById('operations-submenu');
	
	
    
    // Simple test - add visible border to triggers for debugging
	requeriedOperationsTriggers.forEach(trigger => {
		// Remove debug styling
	});
	
	if (requeriedOperationsSubmenu) {
		// Remove debug styling
	}
    
    if (requeriedOperationsTriggers.length > 0) {
        requeriedOperationsTriggers.forEach((trigger) => {
            trigger.addEventListener('click', (event) => {
                event.preventDefault();
                event.stopPropagation();
                
                if (requeriedOperationsSubmenu) {
                    const isVisible = requeriedOperationsSubmenu.classList.contains('show');
                    if (isVisible) {
                        requeriedOperationsSubmenu.classList.remove('show');
                        trigger.classList.remove('is-selected');
                        trigger.setAttribute('aria-expanded', 'false');
                        const parentLi = trigger.closest('li');
                        if (parentLi) parentLi.classList.remove('submenu-open');
                    } else {
                        clearSubmenuSelection();
                        // Close Declaration submenu if open
                        const declSub = document.getElementById('declaration-submenu');
                        if (declSub) {
                            declSub.classList.remove('show');
                        }
                        const declTriggers = document.querySelectorAll('.declaration-trigger');
                        if (declTriggers && declTriggers.length) {
                            declTriggers.forEach((t)=>{
                                t.classList.remove('is-selected');
                                t.setAttribute('aria-expanded','false');
                                const li = t.closest('li');
                                if (li) li.classList.remove('submenu-open');
                            });
                        }
                        // Keep parent submenu open and mark active
                        const parentLi = trigger.closest('li');
                        if (parentLi) parentLi.classList.add('submenu-open','active');
                        requeriedOperationsSubmenu.classList.add('show');
						
						// Position submenu next to THIS specific clicked trigger
						const rect = trigger.getBoundingClientRect();
					const isCollapsed = document.body.classList.contains('menu-collapsed') || 
										document.body.classList.contains('menu-visible');
					const isMobile = window.innerWidth <= 1200;
					const marginLeft = isCollapsed ? 8 : 12;
					
					if (isMobile) {
						// Mobile: position static, hiển thị như nested menu trong sidebar
						requeriedOperationsSubmenu.style.position = 'static';
						requeriedOperationsSubmenu.style.top = '';
						requeriedOperationsSubmenu.style.left = '';
						requeriedOperationsSubmenu.style.margin = '8px 0';
						requeriedOperationsSubmenu.style.width = '100%';
						requeriedOperationsSubmenu.style.zIndex = 'auto';
						requeriedOperationsSubmenu.style.display = 'block';
					} else {
						// Desktop: position fixed như cũ
						requeriedOperationsSubmenu.style.position = 'fixed';
						requeriedOperationsSubmenu.style.zIndex = '10000';
						requeriedOperationsSubmenu.style.top = `${rect.top}px`;
						requeriedOperationsSubmenu.style.left = `${rect.right + marginLeft}px`;
						requeriedOperationsSubmenu.style.margin = '';
						requeriedOperationsSubmenu.style.width = '';
					}
					
					// Force immediate positioning (no transition delay)
					requeriedOperationsSubmenu.style.transition = 'none';
					requestAnimationFrame(() => {
						if (!isMobile) {
							requeriedOperationsSubmenu.style.top = `${rect.top}px`;
							requeriedOperationsSubmenu.style.left = `${rect.right + marginLeft}px`;
						}
						requestAnimationFrame(() => {
							requeriedOperationsSubmenu.style.transition = '';
						});
					});
						
                        trigger.classList.add('is-selected');
                        trigger.setAttribute('aria-expanded', 'true');
                        // Announce to assistive tech
                        try { trigger.focus({preventScroll:true}); } catch(_) {}
                    }
                }
            });
        });
    }

    const operationsSubmenuItems = document.querySelectorAll('#operations-submenu .declaration-submenu-item');
    operationsSubmenuItems.forEach((item) => {
        item.addEventListener('click', (event) => {
            const href = item.getAttribute('href');
            if (href && href !== '#') {
                closeOperationsSubmenu();
                return;
            }
            event.preventDefault();
            event.stopPropagation();
        });
    });

    document.addEventListener('click', (event) => {
        if (operationsSubmenu &&
            !operationsSubmenu.contains(event.target) &&
            !event.target.closest('.operations-trigger') &&
            !event.target.closest('#operations-submenu') &&
            !event.target.closest('.submenu-trigger')) {
            closeOperationsSubmenu();
        }
    });

	// Handle nested submenu triggers
	nestedSubmenuTriggers.forEach((trigger) => {
		const parent = trigger.closest('.has-submenu');
		if (!parent) {
			return;
		}

		const toggleNestedSubmenu = () => {
			const isOpen = parent.classList.contains('submenu-open');
			if (isOpen) {
				parent.classList.remove('submenu-open');
				trigger.setAttribute('aria-expanded', 'false');
			} else {
				// Close other nested submenus in the same level
				const siblingNestedSubmenus = parent.parentElement.querySelectorAll('.has-submenu');
				siblingNestedSubmenus.forEach((sibling) => {
					if (sibling !== parent) {
						sibling.classList.remove('submenu-open');
						const siblingTrigger = sibling.querySelector('.submenu-trigger');
						if (siblingTrigger) {
							siblingTrigger.setAttribute('aria-expanded', 'false');
						}
					}
				});
				parent.classList.add('submenu-open');
				trigger.setAttribute('aria-expanded', 'true');
			}
		};

		trigger.addEventListener('click', (event) => {
			event.preventDefault();
			event.stopPropagation();
			toggleNestedSubmenu();
		});

		trigger.addEventListener('keydown', (event) => {
			if (event.key === 'Enter' || event.key === ' ') {
				event.preventDefault();
				event.stopPropagation();
				toggleNestedSubmenu();
			}
		});
	});

	const fields = document.querySelectorAll('.field');
	fields.forEach((el, idx) => {
		el.animate([
			{ opacity: 0, transform: 'translateY(8px)' },
			{ opacity: 1, transform: 'translateY(0)' }
		], { duration: 350, delay: 80 * idx, easing: 'cubic-bezier(.2,.6,.2,1)', fill: 'both' });
	});
});

// Global Toast/Popup system
(function () {
    const containerId = 'toast-container';

    function ensureContainer() {
        let el = document.getElementById(containerId);
        if (!el) {
            el = document.createElement('div');
            el.id = containerId;
            document.body.appendChild(el);
        }
        return el;
    }

    function createToast(type, message, timeout) {
        const container = ensureContainer();
        const toast = document.createElement('div');
        toast.className = 'toast toast-' + (type || 'info');

        const content = document.createElement('div');
        content.className = 'toast-content';
        content.innerHTML = String(message || '');

        const close = document.createElement('button');
        close.className = 'toast-close';
        close.setAttribute('aria-label', 'Close');
        close.innerHTML = '\u00D7';
        close.onclick = function () { dismissToast(toast); };

        toast.appendChild(content);
        toast.appendChild(close);
        container.appendChild(toast);

        requestAnimationFrame(() => toast.classList.add('show'));

        const life = Math.max(2000, Math.min(timeout || 3500, 20000));
        let timer = setTimeout(() => dismissToast(toast), life);
        toast.addEventListener('mouseenter', () => { clearTimeout(timer); timer = null; });
        toast.addEventListener('mouseleave', () => { if (!timer) timer = setTimeout(() => dismissToast(toast), 1200); });
        return toast;
    }

    function dismissToast(toast) {
        if (!toast) return;
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 180);
    }

    window.showToast = function (type, message, timeout) { return createToast(type, message, timeout); };

    window.addEventListener('DOMContentLoaded', function () {
        try {
            // Skip if on Zalo page (it handles its own flash messages)
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.has('zalo')) {
                return; // Zalo page handles flash messages itself
            }
            
            const flash = window.__FLASH__ || {};
            if (flash.success) { 
                // Add success header for messages that don't have it yet
                const successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                let successMsg = flash.success;
                // Only add header if not already present
                if (successMsg.indexOf('<div class="error-header">') === -1 && successMsg.indexOf('<div class="success-header">') === -1) {
                    successMsg = '<div class="success-header">' + successTitle + '</div>' + successMsg;
                }
                createToast('success', successMsg); 
            }
            if (flash.error) { 
                // Add error header to all error messages
                const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                const errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + flash.error;
                createToast('error', errorWithHeader, 6000); 
            }
            if (Array.isArray(flash.infos)) { flash.infos.forEach(msg => createToast('info', msg)); }
        } catch (_) {}
    });
})();

// Reusable confirmation modal (replaces window.confirm)
(function(){
    function buildConfirm(message){
        var backdrop = document.createElement('div');
        backdrop.className = 'modal-backdrop show';
        var modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = '<div class="confirm-message"></div>'+
            '<div class="form-actions confirm-actions">'+
            '<button type="button" class="btn btn-secondary" data-cancel>Hủy</button>'+ 
            '<button type="button" class="btn btn-danger" data-ok>OK</button>'+ 
            '</div>';
        var msgEl = modal.querySelector('.confirm-message');
        if (msgEl) { msgEl.textContent = String(message || ''); }
        backdrop.appendChild(modal);
        return backdrop;
    }

    function confirmDialog(message){
        return new Promise(function(resolve){
            var view = buildConfirm(message);
            document.body.appendChild(view);
            function close(){ view.remove(); }
            view.addEventListener('click', function(e){
                if (e.target.matches('[data-modal-close],[data-cancel]')) { close(); resolve(false); }
                if (e.target.matches('[data-ok]')) { close(); resolve(true); }
            }, true);
        });
    }

    // Hook forms with class .needs-confirm
    window.addEventListener('submit', function(e){
        var form = e.target;
        if (form && form.classList && form.classList.contains('needs-confirm')){
            var btn = form.querySelector('[type="submit"][data-confirm-message]');
            var msg = btn ? btn.getAttribute('data-confirm-message') : 'Confirm?';
            e.preventDefault();
            confirmDialog(msg).then(function(ok){ if (ok) form.submit(); });
        }
    }, true);
})();

// ============================================
// ADMIN-LIKE SUBMENUS HANDLER (Zalo, Máy chấm công)
// ============================================
(function() {
	const adminDeclTriggers = document.querySelectorAll('.admin-declaration-trigger');
	if (adminDeclTriggers.length === 0) return;

	const getSubmenuForTrigger = (trigger) => {
		const li = trigger.closest('li');
		if (!li) return null;
		return li.querySelector('.admin-declaration-submenu');
	};

	const closeAllAdminLikeSubmenus = () => {
		document.querySelectorAll('.admin-declaration-submenu').forEach((sm) => sm.classList.remove('show'));
		adminDeclTriggers.forEach((trigger) => {
			trigger.classList.remove('is-selected');
			trigger.setAttribute('aria-expanded', 'false');
			const parentLi = trigger.closest('li.admin-declaration-parent');
			if (parentLi) parentLi.classList.remove('submenu-open');
		});
	};

	const positionAdminLikeSubmenu = (trigger, submenu) => {
		if (!submenu) return;
		const rect = trigger.getBoundingClientRect();
		const isCollapsed = document.body.classList.contains('menu-collapsed') || document.body.classList.contains('menu-visible');
		const isMobile = window.innerWidth <= 1200;
		if (isMobile) {
			submenu.style.position = 'static';
			submenu.style.top = '';
			submenu.style.left = '';
			submenu.style.margin = '8px 0';
			submenu.style.width = '100%';
			submenu.style.zIndex = 'auto';
			submenu.style.display = 'block';
		} else {
			const marginLeft = isCollapsed ? 8 : 12;
			submenu.style.position = 'fixed';
			submenu.style.zIndex = '10000';
			submenu.style.top = `${rect.top}px`;
			submenu.style.left = `${rect.right + marginLeft}px`;
			submenu.style.margin = '';
			submenu.style.width = '';
		}
	};

	adminDeclTriggers.forEach((trigger) => {
		const submenu = getSubmenuForTrigger(trigger);
		if (!submenu) return;
		trigger.addEventListener('click', (event) => {
			event.preventDefault();
			event.stopPropagation();
			const isVisible = submenu.classList.contains('show');
			if (isVisible) {
				submenu.classList.remove('show');
				trigger.classList.remove('is-selected');
				trigger.setAttribute('aria-expanded', 'false');
				const parentLi = trigger.closest('li');
				if (parentLi) parentLi.classList.remove('submenu-open');
			} else {
				// Close other nested submenus (declaration and operations)
				const declSubmenu = document.getElementById('declaration-submenu');
				if (declSubmenu) declSubmenu.classList.remove('show');
				const opsSubmenu = document.getElementById('operations-submenu');
				if (opsSubmenu) opsSubmenu.classList.remove('show');
				// Close other admin-like submenus
				document.querySelectorAll('.admin-declaration-submenu.show').forEach((sm)=>{ if (sm!==submenu) sm.classList.remove('show'); });
				document.querySelectorAll('.admin-declaration-trigger.is-selected').forEach((t)=>{ if (t!==trigger) { t.classList.remove('is-selected'); t.setAttribute('aria-expanded','false'); const li=t.closest('li'); if(li) li.classList.remove('submenu-open'); }});

				// Keep parent submenu (Admin) open
				const parentSubmenu = trigger.closest('.has-submenu[data-submenu="admin"]');
				if (parentSubmenu) {
					parentSubmenu.classList.add('active', 'submenu-open');
					const parentTrigger = parentSubmenu.querySelector('.submenu-trigger');
					if (parentTrigger) parentTrigger.setAttribute('aria-expanded', 'true');
				}

				submenu.classList.add('show');
				positionAdminLikeSubmenu(trigger, submenu);
				const isMobile = window.innerWidth <= 1200;
				if (!isMobile) {
					submenu.style.transition = 'none';
					requestAnimationFrame(() => {
						positionAdminLikeSubmenu(trigger, submenu);
						requestAnimationFrame(() => { submenu.style.transition = ''; });
					});
				}
				trigger.classList.add('is-selected');
				trigger.setAttribute('aria-expanded', 'true');
				const parentLi = trigger.closest('li');
				if (parentLi) parentLi.classList.add('submenu-open', 'active');
			}
		});
	});

	// Close when clicking outside
	document.addEventListener('click', (event) => {
		if (!event.target.closest('.admin-declaration-trigger') && !event.target.closest('.admin-declaration-submenu') && !event.target.closest('.submenu-trigger')) {
			closeAllAdminLikeSubmenus();
		}
	});

	// Reposition on window resize
	window.addEventListener('resize', () => {
		document.querySelectorAll('.admin-declaration-trigger.is-selected').forEach((trigger)=>{
			const submenu = getSubmenuForTrigger(trigger);
			positionAdminLikeSubmenu(trigger, submenu);
		});
	});

	// Reposition on menu collapse/expand
	const menuToggle = document.getElementById('menu-toggle');
	if (menuToggle) {
		menuToggle.addEventListener('click', () => {
			setTimeout(() => {
				document.querySelectorAll('.admin-declaration-trigger.is-selected').forEach((trigger)=>{
					const submenu = getSubmenuForTrigger(trigger);
					positionAdminLikeSubmenu(trigger, submenu);
				});
			}, 300);
		});
	}
})();

// Debug tool: Track mouse position and log on F9
(function initMouseDebug() {
	let lastMouseX = 0;
	let lastMouseY = 0;
	let isTracking = false;

	// Track mouse position continuously
	document.addEventListener('mousemove', function(e) {
		lastMouseX = e.clientX;
		lastMouseY = e.clientY;
	}, { passive: true });

	// Log mouse position and element info on F9
	document.addEventListener('keydown', function(e) {
		// F9 key code is 120
		if (e.key === 'F9' || e.keyCode === 120) {
			e.preventDefault();
			
			const info = {
				timestamp: new Date().toISOString(),
				position: {
					clientX: lastMouseX,
					clientY: lastMouseY,
					pageX: lastMouseX + window.scrollX,
					pageY: lastMouseY + window.scrollY,
					screenX: lastMouseX + window.screenX,
					screenY: lastMouseY + window.screenY
				},
				viewport: {
					width: window.innerWidth,
					height: window.innerHeight,
					scrollX: window.scrollX,
					scrollY: window.scrollY
				}
			};

			// Get element at mouse position
			const elementAtPoint = document.elementFromPoint(lastMouseX, lastMouseY);
			if (elementAtPoint) {
				const rect = elementAtPoint.getBoundingClientRect();
				const computed = window.getComputedStyle(elementAtPoint);
				
				info.element = {
					tagName: elementAtPoint.tagName,
					id: elementAtPoint.id || null,
					className: elementAtPoint.className || null,
					textContent: elementAtPoint.textContent ? elementAtPoint.textContent.trim().substring(0, 100) : null,
					boundingRect: {
						top: rect.top,
						right: rect.right,
						bottom: rect.bottom,
						left: rect.left,
						width: rect.width,
						height: rect.height
					},
					styles: {
						display: computed.display,
						position: computed.position,
						zIndex: computed.zIndex,
						backgroundColor: computed.backgroundColor,
						color: computed.color,
						fontSize: computed.fontSize,
						fontFamily: computed.fontFamily,
						opacity: computed.opacity,
						visibility: computed.visibility
					}
				};

				// Get all elements at this point (stack)
				const elementsStack = document.elementsFromPoint(lastMouseX, lastMouseY);
				info.elementsStack = elementsStack.map(el => ({
					tagName: el.tagName,
					id: el.id || null,
					className: el.className || null
				}));
			}

			// Log to console with formatting
			console.group('🖱️ Mouse Position Debug (F9)');
			console.log('📍 Position:', info.position);
			console.log('🖼️ Viewport:', info.viewport);
			if (info.element) {
				console.log('🎯 Element at cursor:', info.element.tagName + (info.element.id ? '#' + info.element.id : '') + (info.element.className ? '.' + info.element.className.split(' ').join('.') : ''));
				console.log('📦 Bounding Rect:', info.element.boundingRect);
				/*console.log('🎨 Styles:', info.element.styles);*/
					if (info.element.textContent) {
						console.log('📝 Text:', info.element.textContent);
					}
				/*console.log('📚 Elements Stack:', info.elementsStack);*/
			} else {
				console.warn('⚠️ No element found at cursor position');
			}
			/*console.log('📋 Full Info Object:', info);*/
			console.groupEnd();

			// Also log a copy-friendly version
			/*console.log('%c📋 Copy this JSON:', 'color: #7adcc9; font-weight: bold;', JSON.stringify(info, null, 2));*/
		}
	});
})();
