<template>
	<el-container style="height: 100vh; position: relative">
		<el-aside width="auto">
			<Sidebar
				@settings-menu-toggle="(position, name) => handleSettingsMenuToggle(position, name)"
			/>
		</el-aside>
		<el-container>
			<el-main style="padding: 0; overflow: auto" :style="mainStyle">
				<router-view />
			</el-main>
		</el-container>

		<!-- 帮助菜单面板 -->
		<div
			v-if="showSettingsMenu && menuType === 'help'"
			class="settings-menu-panel"
			:style="{ transform: `translate(${menuLeft}px, ${menuTop}px)` }"
		>
			<div class="settings-menu-list">
				<div class="settings-menu-item" @click="handleSettingsMenuClick('quick-start')">
					<div class="icon-wrapper">
						<SvgIcon name="video" />
					</div>
					<span>{{ t('settings.quickStart') }}</span>
				</div>
				<div class="settings-menu-item" @click="handleSettingsMenuClick('docs')">
					<div class="icon-wrapper">
						<SvgIcon name="book" />
					</div>
					<span>{{ t('settings.docs') }}</span>
				</div>
				<div class="settings-menu-item" @click="handleSettingsMenuClick('about')">
					<div class="icon-wrapper">
						<SvgIcon name="info" />
					</div>
					<span>{{ t('settings.about') }}</span>
				</div>
			</div>
		</div>

		<!-- 设置菜单面板 -->
		<div
			v-if="showSettingsMenu && menuType === 'settings'"
			class="settings-menu-panel"
			:style="{ transform: `translate(${menuLeft}px, ${menuTop}px)` }"
		>
			<div class="settings-menu-list">
				<div class="settings-menu-item" @click="handleSettingsMenuClick('user')">
					<div class="icon-wrapper">
						<SvgIcon name="user-round" />
					</div>
					<span>{{ t('settings.userCenter') }}</span>
				</div>
				<div class="settings-menu-item" @click="handleSettingsMenuClick('log-stream')">
					<div class="icon-wrapper">
						<SvgIcon name="log-in" />
					</div>
					<span>{{ t('settings.logStream') }}</span>
				</div>
				<div class="settings-menu-item" @click="handleSettingsMenuClick('model-log')">
					<div class="icon-wrapper">
						<SvgIcon name="log-in" />
					</div>
					<span>{{ t('settings.modelLog') }}</span>
				</div>
				<div class="settings-menu-item language-item" @click.stop>
					<div class="icon-wrapper">
						<SvgIcon name="service" />
					</div>
					<div class="language-content">
						<span class="language-title">{{ t('settings.language') }}</span>
						<div class="language-options">
							<button
								v-for="option in localeOptions"
								:key="option.value"
								type="button"
								class="language-option"
								:class="{ active: locale === option.value }"
								@click.stop="handleLocaleChange(option.value)"
							>
								{{ t(option.labelKey) }}
							</button>
						</div>
					</div>
				</div>
				<div class="settings-menu-item logout" @click="handleSettingsMenuClick('logout')">
					<div class="icon-wrapper">
						<SvgIcon name="door-open" />
					</div>
					<span>{{ t('settings.logout') }}</span>
				</div>
			</div>
		</div>
	</el-container>
</template>
<script setup lang="ts">
import { ref, provide, type CSSProperties, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

import Sidebar from '@/components/Sidebar/index.vue'
import { useI18n } from '@/composables/useI18n'
import type { LocaleType } from '@/i18n'

const router = useRouter()
const { locale, setLocale, t } = useI18n()
const mainStyle = ref<CSSProperties>()
const showSettingsMenu = ref(false)
const menuType = ref<'help' | 'settings'>('settings')
const menuTop = ref(0)
const menuLeft = ref(0)
const settingsButtonPos = ref({ top: 0, left: 0 })
const localeOptions: Array<{ value: LocaleType; labelKey: string }> = [
	{ value: 'zh-cn', labelKey: 'settings.languages.zh-cn' },
	{ value: 'en-us', labelKey: 'settings.languages.en-us' }
]

provide('layout', {
	setMainStyle(style: CSSProperties) {
		mainStyle.value = style
	}
})

const handleSettingsMenuToggle = (position: { top: number; left: number }, name: string) => {
	// 如果点击同一个菜单，则切换显示/隐藏
	// 如果点击不同菜单，则切换菜单类型
	if (showSettingsMenu.value && menuType.value === name) {
		showSettingsMenu.value = false
	} else {
		menuType.value = name as 'help' | 'settings'
		showSettingsMenu.value = true
		settingsButtonPos.value = { top: position.top, left: position.left }
		updateMenuPosition()
	}
}

const updateMenuPosition = () => {
	// 菜单出现在点击位置的右下方，偏移量较小
	let top = settingsButtonPos.value.top + 40 // 向下偏移40px
	let left = settingsButtonPos.value.left

	// 获取实际可用的视口大小（多层故障转移）
	const viewportHeight =
		document.documentElement.clientHeight || window.innerHeight || screen.height

	const viewportWidth = document.documentElement.clientWidth || window.innerWidth || screen.width

	// 防止菜单超出屏幕下方
	const menuHeight = menuType.value === 'settings' ? 270 : 165
	const maxTop = viewportHeight - menuHeight
	if (maxTop > 0) {
		top = Math.min(top, Math.max(0, maxTop - 10))
	}

	// 防止菜单超出屏幕右侧
	const menuWidth = 240
	const maxLeft = viewportWidth - menuWidth
	if (left > maxLeft && maxLeft > 0) {
		left = Math.max(0, maxLeft - 10)
	}

	menuTop.value = Math.max(0, top)
	menuLeft.value = Math.max(0, left)
}

const handleWindowResize = () => {
	if (showSettingsMenu.value) {
		updateMenuPosition()
	}
}

const handleSettingsMenuClick = (name: string) => {
	showSettingsMenu.value = false

	// 路由映射
	const routeMap: Record<string, string> = {
		'quick-start': '/quick-start',
		docs: '/docs',
		about: '/about',
		user: '/user-center',
		'log-stream': '/log-stream',
		'model-log': '/model-log',
		logout: ''
	}

	const route = routeMap[name]
	if (route) {
		router.push(route)
	} else if (name === 'logout') {
		// 处理退出登录
		console.log('Logout')
	}
}

const handleLocaleChange = (nextLocale: LocaleType) => {
	setLocale(nextLocale)
}

const handleClickOutside = (event: MouseEvent) => {
	const target = event.target as HTMLElement
	// 检查点击是否在菜单面板外部
	if (
		showSettingsMenu.value &&
		!target.closest('.settings-menu-panel') &&
		!target.closest('.bottom-item')
	) {
		showSettingsMenu.value = false
	}
}

onMounted(() => {
	window.addEventListener('resize', handleWindowResize)
	document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
	window.removeEventListener('resize', handleWindowResize)
	document.removeEventListener('click', handleClickOutside)
})
</script>

<style lang="less" scoped>
.settings-menu-panel {
	position: fixed;
	left: 0;
	top: 0;
	width: 240px;
	background: var(--bg-base);
	border: 1px solid var(--border-light);
	border-radius: 4px;
	box-shadow: var(--shadow-lg);
	z-index: 999;
	max-height: calc(100vh - 60px);
	overflow-y: auto;

	.settings-menu-list {
		.settings-menu-item {
			padding: 10px 8px;
			color: var(--text-secondary);
			cursor: pointer;
			transition: all 0.2s;
			font-size: 13px;
			white-space: nowrap;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.icon-wrapper {
				width: 25px;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			> span {
				flex: 1;
			}

			&.language-item {
				align-items: flex-start;
				cursor: default;
			}

			&:hover {
				background: var(--bg-base);
				color: var(--text-primary);
			}

			&.logout {
				color: #810042;
				border-top: 1px solid var(--border-light);
				margin-top: 4px;
				padding-top: 12px;

				&:hover {
					background: rgba(255, 107, 107, 0.1);
				}
			}
		}
	}
}

.language-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.language-title {
	color: var(--text-primary);
}

.language-options {
	display: flex;
	gap: 8px;
}

.language-option {
	border: 1px solid var(--border-light);
	background: var(--bg-container);
	color: var(--text-secondary);
	border-radius: 999px;
	padding: 4px 10px;
	font-size: 12px;
	cursor: pointer;
	transition: all 0.2s ease;
}

.language-option:hover {
	color: var(--text-primary);
	border-color: var(--el-color-primary-light-5);
}

.language-option.active {
	background: var(--el-color-primary-light-9);
	border-color: var(--el-color-primary);
	color: var(--el-color-primary);
}

@keyframes slideInRight {
	from {
		opacity: 0;
		transform: translateX(-8px);
	}
	to {
		opacity: 1;
		transform: translateX(0);
	}
}
</style>
