<template>
	<view class="login-page">
		<!-- 背景装饰 -->
		<view class="bg-decor">
			<view class="bg-circle circle-1" />
			<view class="bg-circle circle-2" />
			<view class="bg-circle circle-3" />
		</view>

		<view class="login-container">
			<!-- 品牌区 -->
			<view class="brand-section">
				<view class="brand-logo-card">
					<image class="brand-logo-img" src="/static/logo.jpg" mode="aspectFit" />
					<view class="brand-badge">
						<TnIcon name="safe-fill" :size="24" color="#4ECDC4" />
					</view>
				</view>
				<text class="brand-name">毛球手账</text>
				<text class="brand-slogan">让宠物健康管理像记账一样简单</text>

				<!-- 特性标签 -->
				<view class="feature-row">
					<view v-for="feature in features" :key="feature.text" class="feature-tag">
						<TnIcon :name="feature.icon" :size="26" :color="feature.color" />
						<text class="feature-text">{{ feature.text }}</text>
					</view>
				</view>
			</view>

			<!-- 登录区 -->
			<view class="login-section">
				<view class="divider">
					<view class="divider-line" />
					<text class="divider-text">微信登录</text>
					<view class="divider-line" />
				</view>

				<button class="wx-login-btn" :disabled="!agreed || loggingIn"
					:hover-class="(!agreed || loggingIn) ? '' : 'wx-btn-hover'" :loading="loggingIn"
					@click="handleLogin">
					<text class="wx-btn-text">{{ loggingIn ? '登录中...' : '微信一键登录' }}</text>
				</button>

				<!-- 用户协议 -->
				<view class="agreement">
					<view class="agreement-checkbox" :class="{ active: agreed }" @click="agreed = !agreed">
						<TnIcon v-if="agreed" name="check" :size="24" color="#FFFFFF" />
					</view>
					<text class="agreement-text">
						我已阅读并同意
						<text class="agreement-link" @click.stop="showAgreement('user')">《用户协议》</text>
						<text class="agreement-link" @click.stop="showAgreement('privacy')">《隐私政策》</text>
					</text>
				</view>
			</view>

			<view class="copyright">
				<text class="copyright-text">登录即表示你同意为你的宠物健康负责</text>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive } from 'vue'

	interface Feature {
		icon : string
		text : string
		color : string
	}

	const agreed = ref(false)
	const loggingIn = ref(false)

	const features : Feature[] = [
		{ icon: 'notice-fill', text: '智能提醒', color: '#F97316' },
		{ icon: 'write-fill', text: '健康档案', color: '#14B8A6' },
		{ icon: 'cloud-fill', text: '云端同步', color: '#3B82F6' },
	]

	function handleLogin() {
		if (loggingIn.value || !agreed.value) return
		doLogin()
	}

	async function doLogin() {
		loggingIn.value = true
		uni.showLoading({ title: '登录中...', mask: true })
		try {
			// 1. 获取微信登录 code（仅 code 发给云函数，云函数自行换 openid）
			const loginRes = await new Promise<any>((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: reject,
				})
			})

			if (!loginRes.code) {
				throw new Error('获取登录凭证失败')
			}

			// 2. 调用云函数登录（云函数用 code 向微信换 openid，查库返回用户数据）
			const res = await uniCloud.callFunction({
				name: 'login',
				data: {
					code: loginRes.code,
				},
			})

			if (res.result.code !== 0) {
				throw new Error(res.result.message || '登录失败')
			}

			// 3. 保存登录态
			const { token, userInfo } = res.result.data
			uni.setStorageSync('token', token)
			uni.setStorageSync('uid', userInfo._id)
			uni.setStorageSync('userInfo', userInfo)

			uni.hideLoading()
			uni.showToast({ title: '登录成功', icon: 'success' })

			// 4. 跳转首页（非 tabBar 页面，使用 reLaunch）
			setTimeout(() => {
				uni.reLaunch({ url: '/pages/index/index' })
			}, 600)
		} catch (err : any) {
			console.error('登录失败:', err)
			uni.hideLoading()
			uni.showToast({ title: err.message || '登录失败，请重试', icon: 'none' })
		} finally {
			loggingIn.value = false
		}
	}

	function showAgreement(type : 'user' | 'privacy') {
		uni.showModal({
			title: type === 'user' ? '用户协议' : '隐私政策',
			content:
				type === 'user'
					? '欢迎使用毛球手账！我们致力于保护你的宠物健康数据安全。使用本应用即表示你同意我们为你提供宠物健康管理服务。'
					: '我们仅收集用于提供宠物健康管理服务所必需的信息，包括你的微信昵称、头像以及宠物档案数据。我们承诺不向第三方出售你的数据。',
			showCancel: false,
		})
	}
</script>

<style lang="scss">
	$primary: #F97316;
	$primary-light: #FB923C;
	$primary-bg: #FFF7ED;
	$text-dark: #431407;
	$text-muted: #9CA3AF;

	.login-page {
		min-height: 100vh;
		background: linear-gradient(160deg, #FFF7ED 0%, #FFEDD5 60%, #FFE4C4 100%);
		position: relative;
		overflow: hidden;
		box-sizing: border-box;
	}

	// === 背景装饰圆 ===
	.bg-decor {
		position: absolute;
		inset: 0;
		pointer-events: none;
	}

	.bg-circle {
		position: absolute;
		border-radius: 50%;
		background: rgba(249, 115, 22, 0.06);
	}

	.circle-1 {
		width: 400rpx;
		height: 400rpx;
		top: -120rpx;
		right: -140rpx;
	}

	.circle-2 {
		width: 300rpx;
		height: 300rpx;
		top: 40%;
		left: -160rpx;
		background: rgba(78, 205, 196, 0.07);
	}

	.circle-3 {
		width: 220rpx;
		height: 220rpx;
		bottom: 15%;
		right: -100rpx;
		background: rgba(249, 115, 22, 0.05);
	}

	.login-container {
		position: relative;
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		padding: 0 48rpx;
		box-sizing: border-box;
	}

	// === 品牌区 ===
	.brand-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 140rpx;
	}

	.brand-logo-card {
		position: relative;
		width: 220rpx;
		height: 220rpx;
		border-radius: 56rpx;
		background: #FFFFFF;
		border: 4rpx solid #FED7AA;
		box-shadow:
			0 16rpx 40rpx rgba(249, 115, 22, 0.15),
			inset 2rpx 2rpx 0 rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
		box-sizing: border-box;
		margin-bottom: 32rpx;
	}

	.brand-logo-img {
		width: 100%;
		height: 100%;
		border-radius: 40rpx;
	}

	.brand-badge {
		position: absolute;
		bottom: -12rpx;
		right: -12rpx;
		width: 52rpx;
		height: 52rpx;
		border-radius: 50%;
		background: #FFFFFF;
		border: 4rpx solid #4ECDC4;
		box-shadow: 0 6rpx 16rpx rgba(78, 205, 196, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.brand-name {
		font-size: 56rpx;
		font-weight: 800;
		color: $text-dark;
		letter-spacing: 4rpx;
		margin-bottom: 16rpx;
	}

	.brand-slogan {
		font-size: 26rpx;
		color: #7C2D12;
		opacity: 0.75;
		margin-bottom: 48rpx;
	}

	// === 特性标签 ===
	.feature-row {
		display: flex;
		gap: 20rpx;
	}

	.feature-tag {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 14rpx 24rpx;
		background: rgba(255, 255, 255, 0.85);
		border-radius: 40rpx;
		border: 2rpx solid #FED7AA;
		box-shadow: 0 6rpx 16rpx rgba(249, 115, 22, 0.08);
	}

	.feature-text {
		font-size: 22rpx;
		font-weight: 600;
		color: $text-dark;
	}

	// === 登录区 ===
	.login-section {
		margin-top: 120rpx;
	}

	.divider {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-bottom: 40rpx;
	}

	.divider-line {
		flex: 1;
		height: 2rpx;
		background: rgba(124, 45, 18, 0.15);
	}

	.divider-text {
		font-size: 24rpx;
		color: $text-muted;
	}

	.wx-login-btn {
		width: 100%;
		height: 104rpx;
		line-height: 104rpx;
		background: linear-gradient(135deg, #07C160 0%, #06AD56 100%) !important;
		border-radius: 52rpx;
		font-size: 34rpx;
		box-shadow: 0 12rpx 28rpx rgba(7, 193, 96, 0.3);
		transition: all 0.2s ease;

		&::after {
			border: none;
		}
	}

	/* 重置微信小程序按钮默认灰色背景，确保绿色生效 */
	page .wx-login-btn,
	page .wx-login-btn[disabled],
	page .wx-login-btn.is-disabled {
		background-color: #07C160 !important;
		opacity: 0.6;
	}

	.wx-btn-hover {
		transform: translateY(2rpx) scale(0.98);
		opacity: 0.9;
	}

	.wx-btn-text {
		font-size: 34rpx;
		font-weight: 600;
		letter-spacing: 2rpx;
		color: #FFFFFF;
	}

	// === 用户协议 ===
	.agreement {
		display: flex;
		align-items: flex-start;
		justify-content: center;
		gap: 12rpx;
		margin-top: 36rpx;
	}

	.agreement-checkbox {
		width: 36rpx;
		height: 36rpx;
		border-radius: 10rpx;
		border: 2rpx solid #D1D5DB;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		margin-top: 2rpx;
		transition: all 0.2s ease;

		&.active {
			background: $primary;
			border-color: $primary;
		}
	}

	.agreement-text {
		font-size: 22rpx;
		color: $text-muted;
		line-height: 1.6;
	}

	.agreement-link {
		color: $primary;
		font-weight: 500;
	}

	// === 版权 ===
	.copyright {
		display: flex;
		justify-content: center;
		margin-top: auto;
		padding: 40rpx 0 60rpx;
	}

	.copyright-text {
		font-size: 20rpx;
		color: #B0A49A;
	}
</style>
