<template>
	<div
		class="min-h-screen relative flex items-center justify-center bg-scroll md:bg-fixed bg-cover bg-center bg-[url('https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg')] safe-area">
		<div class="absolute inset-0 bg-gradient-to-br from-[rgba(30,20,50,0.4)] to-[rgba(10,10,20,0.6)]"></div>

		<div
			class="relative z-10 w-full sm:w-[400px] max-w-[420px] sm:max-w-[92%] bg-white/10 backdrop-blur-2xl border border-white/20 rounded-2xl p-6 sm:p-8 shadow-2xl text-white">
			<div class="text-center mb-6">
				<h2 class="text-xl sm:text-2xl font-semibold tracking-wide mb-1">Welcome Back</h2>
				<p class="text-sm text-white/80">智慧英语 · 让学习更简单</p>
			</div>

			<div class="flex justify-center mb-6 border-b border-white/10">
				<button class="px-4 sm:px-5 py-2 text-white/70 hover:text-white transition"
					:class="mode === 'login' ? 'font-bold text-white border-b-2 border-white' : ''"
					@click="switchMode('login')">登录</button>
				<button class="px-4 sm:px-5 py-2 text-white/70 hover:text-white transition"
					:class="mode === 'register' ? 'font-bold text-white border-b-2 border-white' : ''"
					@click="switchMode('register')">注册</button>
			</div>

			<el-form :model="form" :rules="rules" ref="formRef" class="mt-2">
				<el-form-item prop="phone">
					<div class="input-glass relative mb-4 w-full">
						<el-input v-model="form.phone" maxlength="11" placeholder="请输入手机号 / 账号" />
						<i class="fas fa-user absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
					</div>
				</el-form-item>

				<transition name="tabfade" mode="out-in">
					<div :key="mode">
						<template v-if="mode === 'login'">
							<el-form-item prop="password">
								<div class="input-glass relative mb-4 w-full">
									<el-input v-model="form.password" type="password" maxlength="20" placeholder="请输入密码" />
									<i class="fas fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
								</div>
							</el-form-item>
						</template>
						<template v-else>
							<el-form-item prop="name">
								<div class="input-glass relative mb-4 w-full">
									<el-input v-model="form.name" maxlength="20" placeholder="姓名" />
									<i class="fas fa-id-card absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
								</div>
							</el-form-item>
							<el-form-item prop="password">
								<div class="input-glass relative mb-4 w-full">
									<el-input v-model="form.password" type="password" maxlength="20" placeholder="设置密码" />
									<i class="fas fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
								</div>
							</el-form-item>
							<el-form-item prop="password_repeat">
								<div class="input-glass relative mb-4 w-full">
									<el-input v-model="form.password_repeat" type="password" maxlength="20" placeholder="重复密码" />
									<i class="fas fa-lock absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
								</div>
							</el-form-item>
							<el-form-item prop="invitationCode">
								<div class="input-glass relative mb-4 w-full">
									<el-input v-model="form.invitationCode" maxlength="6" placeholder="邀请码" />
									<i class="fas fa-ticket absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
								</div>
							</el-form-item>
							<el-form-item prop="code">
								<div class="relative mb-2 flex items-center gap-2">
									<div class="input-glass relative flex-1">
										<el-input v-model="form.code" maxlength="6" placeholder="验证码" />
										<i class="fas fa-shield absolute left-4 top-1/2 -translate-y-1/2 text-white/80 text-lg pointer-events-none"></i>
									</div>
									<el-button class="rounded-lg bg-gradient-to-r from-blue-600 to-blue-400 text-white px-3 py-2"
										@click="sendCode" :disabled="codeDisabled || !form.phone">
										{{ codeBtnText }}
									</el-button>
								</div>
							</el-form-item>
						</template>
					</div>
				</transition>
			</el-form>

			<button
				class="w-full mt-3 px-4 py-3 rounded-xl bg-gradient-to-r from-blue-600 to-blue-400 text-white font-semibold shadow-lg hover:-translate-y-0.5 hover:shadow-xl transition disabled:opacity-70 disabled:cursor-not-allowed"
				:disabled="loading" @click="userLogin">
				<span v-if="!loading && mode === 'login'">立即登录</span>
				<span v-if="loading && mode === 'login'">登录中...</span>
				<span v-if="!loading && mode === 'register'">立即注册</span>
				<span v-if="loading && mode === 'register'">处理中...</span>
			</button>
		</div>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
	</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { login, getVerificationCode } from '@/api/user'
import { setToken } from '@/composables/auth'

const loading = ref(false)
const formRef = ref()
const mode = ref('login')
const codeDisabled = ref(false)
const codeBtnText = ref('发送验证码')
let timer = null
const form = reactive({
	phone: '',
	name: '',
	password: '',
	password_repeat: '',
	code: '',
	invitationCode: '',
})

const rules = {
	phone: [
		{ required: true, message: '请输入手机号', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入合法的手机号', trigger: ['blur', 'change'] },
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'blur' },
		{ min: 6, max: 20, message: '密码长度为6-20位', trigger: ['blur', 'change'] },
	],
	name: [
		{
			validator: (_r, v, cb) => {
				if (mode.value !== 'register') return cb()
				if (!v?.trim()) return cb(new Error('请输入姓名'))
				cb()
			}, trigger: ['blur', 'change']
		},
	],
	password_repeat: [
		{
			validator: (_r, v, cb) => {
				if (mode.value !== 'register') return cb()
				if (!v) return cb(new Error('请再次输入密码'))
				if (v !== form.password) return cb(new Error('两次密码不一致'))
				cb()
			}, trigger: ['blur', 'change']
		},
	],
	code: [
		{
			validator: (_r, v, cb) => {
				if (mode.value !== 'register') return cb()
				if (!v?.trim()) return cb(new Error('请输入验证码'))
				cb()
			}, trigger: ['blur', 'change']
		},
	],
}

async function userLogin() {
	if (loading.value) return
	formRef.value?.validate(async (valid) => {
		if (!valid) return
		loading.value = true
		try {
			const payload = mode.value === 'login'
				? {
					phone: form.phone.trim(),
					password: form.password.trim(),
				}
				: {
					phone: form.phone.trim(),
					name: form.name.trim(),
					password: form.password.trim(),
					code: form.code.trim(),
					invitationCode: form.invitationCode.trim()
				}
			const res = await login(payload)
			const data = res.data
			if (data?.success) {
				if (mode.value === 'login') {
					try { setToken(data.data) } catch { }
					ElMessage.success('登录成功')
					router.push('/')
				} else {
					ElMessage.success('注册成功')
					mode.value = 'login'
				}
			} else {
				ElMessage.error(data?.message || '登录失败')
			}
		} finally {
			loading.value = false
		}
	})
}

function switchMode(m) {
	mode.value = m
	formRef.value?.clearValidate()
}

async function sendCode() {
	if (!form.phone || codeDisabled.value) return
	codeDisabled.value = true
	try {
		await getVerificationCode({ phone: form.phone.trim() })
		ElMessage.success('验证码已发送')
		let count = 60
		codeBtnText.value = `${count}s`
		timer = setInterval(() => {
			count -= 1
			if (count <= 0) {
				clearInterval(timer)
				timer = null
				codeDisabled.value = false
				codeBtnText.value = '发送验证码'
			} else {
				codeBtnText.value = `${count}s`
			}
		}, 1000)
	} catch {
		codeDisabled.value = false
		codeBtnText.value = '发送验证码'
	}
}
</script>

<style scoped>
.input-glass :deep(.el-input__wrapper) {
  @apply w-full bg-white/10 border border-white/10 rounded-xl pl-10 transition;
}
.input-glass :deep(.el-input__wrapper:hover),
.input-glass :deep(.el-input__wrapper.is-focus) {
  @apply bg-white/15 border-white/50;
}
.input-glass :deep(.el-input__inner) {
  @apply text-white placeholder:text-white/70;
}
.tabfade-enter-active, .tabfade-leave-active {
  transition: all .25s ease;
}
.tabfade-enter-from {
  opacity: 0;
  transform: translateY(8px) scale(.98);
}
.tabfade-leave-to {
  opacity: 0;
  transform: translateY(-8px) scale(.98);
}
</style>
