/**
 * WooCommerce My Account 页面自定义脚本
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		// 只在 my-account 页面执行
		if (!$('body').hasClass('woocommerce-account')) {
			return;
		}

		// Management 子菜单展开/折叠功能
		$('.tooto-menu-toggle').on('click', function(e) {
			e.preventDefault();
			var $parent = $(this).closest('.tooto-has-submenu');
			var $submenu = $parent.find('.tooto-submenu');
			
			if ($parent.hasClass('tooto-submenu-expanded')) {
				$parent.removeClass('tooto-submenu-expanded');
				$submenu.slideUp(200);
			} else {
				$parent.addClass('tooto-submenu-expanded');
				$submenu.slideDown(200);
			}
		});

		// 如果当前页面在子菜单中，确保父菜单展开
		if ($('.tooto-submenu-item-2-active').length > 0) {
			$('.tooto-has-submenu').addClass('tooto-submenu-expanded');
			$('.tooto-submenu').show();
		}

		// Profile Picture 预览
		// 点击头像容器触发文件选择
		$('.tooto-profile-picture-container').on('click', function() {
			$('#profile_picture').trigger('click');
		});
		$('#profile_picture').on('change', function(e) {
			var file = e.target.files[0];
			if (file) {
				var reader = new FileReader();
				reader.onload = function(e) {
					$('.tooto-profile-picture-preview').attr('src', e.target.result);
				};
				reader.readAsDataURL(file);
			}
		});

		// 自定义下拉选择器功能
		$('.tooto-custom-select').each(function() {
			var $select = $(this);
			var $trigger = $select.find('.tooto-custom-select-trigger');
			var $options = $select.find('.tooto-custom-select-options');
			var $hiddenSelect = $('#' + $select.data('target'));
			var $valueDisplay = $select.find('.tooto-custom-select-value');

			// 点击触发器打开/关闭下拉
			$trigger.on('click', function(e) {
				e.stopPropagation();
				var isOpen = $select.hasClass('open');
				
				// 关闭所有其他下拉
				$('.tooto-custom-select').removeClass('open');
				
				// 切换当前下拉
				if (!isOpen) {
					$select.addClass('open');
				}
			});

			// 点击选项
			$select.find('.tooto-custom-select-option').on('click', function(e) {
				e.stopPropagation();
				var $option = $(this);
				var value = $option.data('value');
				var text = $option.text();

				// 更新显示值
				$valueDisplay.text(text);

				// 更新选中状态
				$select.find('.tooto-custom-select-option').removeClass('selected');
				$option.addClass('selected');

				// 更新隐藏的 select
				$hiddenSelect.val(value).trigger('change');

				// 关闭下拉
				$select.removeClass('open');

				// 添加视觉反馈
				$trigger.addClass('changed');
				setTimeout(function() {
					$trigger.removeClass('changed');
				}, 300);
			});

			// 点击外部关闭下拉
			$(document).on('click', function(e) {
				if (!$(e.target).closest('.tooto-custom-select').length) {
					$select.removeClass('open');
				}
			});
		});

		// Mobile Navigation Toggle
		var $mobileToggle = $('.tooto-account-mobile-toggle');
		var $mobileOverlay = $('.tooto-account-mobile-overlay');
		var $nav = $('.woocommerce-MyAccount-navigation.tooto-custom-navigation');

		function toggleMobileMenu() {
			$nav.toggleClass('active');
			$mobileOverlay.toggleClass('active');
			$('body').toggleClass('tooto-account-menu-open');
		}

		$mobileToggle.on('click', function(e) {
			e.preventDefault();
			toggleMobileMenu();
		});

		$mobileOverlay.on('click', function(e) {
			e.preventDefault();
			toggleMobileMenu();
		});

		// Close menu when clicking a link (optional, but good UX)
		$nav.find('a').on('click', function() {
			// Don't close if it's the toggle for submenu
			if ($(this).hasClass('tooto-menu-toggle')) {
				return;
			}
			if ($nav.hasClass('active')) {
				toggleMobileMenu();
			}
		});

		// Mobile Filter Modal
		var $modal = $('#tooto-mobile-filter-modal');
		var $trigger = $('.tooto-mobile-filter-trigger');
		var $close = $('.tooto-mobile-filter-close');
		var $overlay = $('.tooto-mobile-filter-overlay');

		$trigger.on('click', function() {
			$modal.css('display', 'flex');
		});

		function closeModal() {
			$modal.hide();
		}

		$close.on('click', closeModal);
		$overlay.on('click', closeModal);

		// Logout Confirm Modal
		function ensureLogoutModal() {
			if ($('#tooto-logout-confirm-modal').length) return $('#tooto-logout-confirm-modal');
			var modalHtml = '\
			<div id="tooto-logout-confirm-modal" class="tooto-modal" style="display:none;">\
				<div class="tooto-modal-overlay"></div>\
				<div class="tooto-modal-content">\
					<h3 class="tooto-modal-title">Confirm Logout</h3>\
					<p class="tooto-modal-message">Are you sure you want to log out?</p>\
					<div class="tooto-modal-actions">\
						<button type="button" class="button tooto-modal-cancel">Cancel</button>\
						<button type="button" class="button tooto-modal-confirm">Log Out</button>\
					</div>\
				</div>\
			</div>';
			$('body').append(modalHtml);
			return $('#tooto-logout-confirm-modal');
		}

		$('.woocommerce-MyAccount-navigation-link--customer-logout a').on('click', function(e) {
			e.preventDefault();
			var logoutUrl = $(this).attr('href');
			var accentColor = $(this).css('color');
			var $logoutModal = ensureLogoutModal();

			// Apply accent color
			$logoutModal.get(0).style.setProperty('--tooto-accent-color', accentColor);

			$logoutModal.data('logout-url', logoutUrl).fadeIn(150);
		});

		$(document).on('click', '#tooto-logout-confirm-modal .tooto-modal-cancel', function() {
			$('#tooto-logout-confirm-modal').fadeOut(150);
		});
		$(document).on('click', '#tooto-logout-confirm-modal .tooto-modal-overlay', function() {
			$('#tooto-logout-confirm-modal').fadeOut(150);
		});
		$(document).on('click', '#tooto-logout-confirm-modal .tooto-modal-confirm', function() {
			var url = $('#tooto-logout-confirm-modal').data('logout-url');
			if (url) {
				window.location.href = url;
			}
		});
		var $editWrapper = $('.tooto-edit-address-wrapper');
		if ($editWrapper.length) {
			function disableSelectEnhancements() {
				var $targets = $editWrapper.find('select.country_select, select.state_select, select.select, select.woocommerce-select');
				$targets.each(function() {
					var $el = $(this);
					try { if ($.fn.selectWoo) { $el.selectWoo('destroy'); } } catch (e) {}
					try { if ($.fn.select2) { $el.select2('destroy'); } } catch (e) {}
					$el.removeClass('select2-hidden-accessible wc-enhanced-select');
					$el.removeAttr('aria-hidden');
					$el.show();
					$el.next('.select2, .select2-container').remove();
				});
			}
			disableSelectEnhancements();
			$(document.body).on('country_to_state_changed wc-enhanced-select-init updated_wc_div', disableSelectEnhancements);
			if (typeof MutationObserver !== 'undefined') {
				var obs = new MutationObserver(function(mutations) {
					for (var i = 0; i < mutations.length; i++) {
						var nodes = mutations[i].addedNodes;
						for (var j = 0; j < nodes.length; j++) {
							var $n = $(nodes[j]);
							if ($n.closest($editWrapper).length && ($n.hasClass('select2-container') || $n.find('.select2-container').length)) {
								disableSelectEnhancements();
							}
						}
					}
				});
				obs.observe(document.body, { childList: true, subtree: true });
			}
		}

	});

})(jQuery);
