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 || 'Thu gọn menu';
		const collapsedLabel = menuToggle.dataset.collapsedLabel || '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', () => {
			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');

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

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

	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
	};

	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 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');
			}
		};

		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
			if (link.classList.contains('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
	const declarationTriggers = document.querySelectorAll('.declaration-trigger');
	const declarationSubmenu = document.getElementById('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'));
        }
    };

	// Add click listeners to declaration triggers
	if (declarationTriggers.length > 0) {
        declarationTriggers.forEach((trigger, index) => {
			trigger.addEventListener('click', (event) => {
				event.preventDefault();
				event.stopPropagation();
				
				// Toggle declaration submenu
                if (declarationSubmenu) {
					const isVisible = declarationSubmenu.classList.contains('show');
					
                    if (isVisible) {
                        declarationSubmenu.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 {
						// Don't close the parent "Quản lý hồ sơ" submenu
						// Just show the declaration submenu
                        // Clear any previous selection on other submenu links
                        clearSubmenuSelection();
                        declarationSubmenu.classList.add('show');
                        // 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');
					}
				}
			});
		});
	}

	// Add click listeners to declaration submenu items
    const declarationSubmenuItems = document.querySelectorAll('.declaration-submenu-item');
	declarationSubmenuItems.forEach((item) => {
		item.addEventListener('click', (event) => {
			event.preventDefault();
			event.stopPropagation();
			// Don't close the submenu when clicking on items
		});
	});

	// 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();
		}
	});

	// 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' });
	});
});






