<template>
	<view class="acct-pwd-page">
		<view class="acct-pwd-nav" :style="{ paddingTop: statusBar + 'px' }">
			<view class="acct-pwd-nav-row">
				<view class="acct-pwd-back" @tap="goBack">
					<text class="acct-pwd-back-icon">←</text>
				</view>
				<text class="acct-pwd-nav-title">{{ copy.title }}</text>
				<view class="acct-pwd-nav-placeholder" />
			</view>
		</view>

		<scroll-view
			scroll-y
			class="acct-pwd-scroll"
			:style="{ height: scrollHeight + 'px' }"
		>
			<view class="acct-pwd-body" :style="{ paddingBottom: safeBottom + 'px' }">
				<view class="acct-pwd-hero">
					<view class="acct-pwd-hero-icon-wrap">
						<text class="acct-pwd-hero-icon">🔐</text>
					</view>
					<text class="acct-pwd-hero-title">{{ copy.heroTitle }}</text>
					<text class="acct-pwd-hero-desc">{{ copy.heroDesc }}</text>
				</view>

				<view class="acct-pwd-card">
					<text class="acct-pwd-label">{{ copy.handsetLabel }}</text>
					<view class="acct-pwd-phone-row">
						<region-picker
							v-model="region"
							class="acct-pwd-region"
							:disabled="phoneLocked"
							:title="copy.regionTitle"
							:search-placeholder="copy.regionSearch"
							:empty-text="copy.regionEmpty"
						/>
						<input
							v-model="handset"
							class="acct-pwd-input"
							:disabled="phoneLocked"
							:placeholder="copy.handsetPlaceholder"
							placeholder-class="acct-pwd-input__placeholder"
							type="number"
							maxlength="15"
							@input="onHandsetInput"
						/>
					</view>
					<text class="acct-pwd-hint">{{ copy.fieldHint }}</text>
					<text v-if="phoneLocked" class="acct-pwd-locked-tip">{{ copy.lockedTip }}</text>
				</view>

				<button
					class="acct-pwd-submit"
					:disabled="!canSubmit || probing"
					:loading="probing"
					:class="{ 'acct-pwd-submit--off': !canSubmit, 'acct-pwd-submit--busy': probing }"
					@tap="onNext"
				>
					<text class="acct-pwd-submit__text">{{ probing ? copy.probing : copy.next }}</text>
				</button>

				<view class="acct-pwd-help">
					<text class="acct-pwd-help__title">{{ copy.helpTitle }}</text>
					<text class="acct-pwd-help__line">· {{ copy.help1 }}</text>
					<text class="acct-pwd-help__line">· {{ copy.help2 }}</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { mapState } from 'vuex'
import RegionPicker from '@/components/passport-kit/region-picker.vue'
import { requestPasscode, verifyHandsetUsed } from '@/features/passport/credential-bridge'
import { looksLikeHandset, trimHandset } from '@/features/passport/form-rules'
import { DEFAULT_REGION } from '@/features/passport/region-dialcodes'

export default {
	components: { RegionPicker },
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			handset: '',
			region: DEFAULT_REGION,
			phoneLocked: false,
			probing: false,
			redirect: ''
		}
	},
	computed: {
		...mapState('user', {
			profile: (state) => state
		}),
		copy() {
			const t = this.$t.bind(this)
			return {
				title: t('user.resetPwdTitle'),
				heroTitle: t('user.resetPwdHeroTitle'),
				heroDesc: t('user.resetPwdHeroDesc'),
				handsetLabel: t('passport.label-handset-reg'),
				handsetPlaceholder: t('passport.ph-handset-recover'),
				fieldHint: t('passport.field-hint-region'),
				lockedTip: t('user.resetPwdLockedTip'),
				regionTitle: t('passport.region-title'),
				regionSearch: t('passport.region-search'),
				regionEmpty: t('passport.region-empty'),
				next: t('passport.btn-next'),
				probing: t('passport.btn-probing'),
				helpTitle: t('passport.help-title'),
				help1: t('passport.help-1'),
				help2: t('passport.help-2')
			}
		},
		canSubmit() {
			return looksLikeHandset(this.handset)
		}
	},
	onLoad(query) {
		const sys = uni.getSystemInfoSync()
		this.statusBar = sys.statusBarHeight || 0
		this.safeBottom = sys.safeAreaInsets ? sys.safeAreaInsets.bottom : 0
		const navH = this.statusBar + uni.upx2px(88)
		this.scrollHeight = (sys.windowHeight || 667) - navH

		let handset = ''
		let region = ''
		if (query && query.handset) {
			try {
				handset = trimHandset(decodeURIComponent(query.handset))
			} catch (_) {
				handset = trimHandset(query.handset)
			}
		}
		if (query && query.region) {
			try {
				region = String(decodeURIComponent(query.region)).replace(/^\+/, '')
			} catch (_) {
				region = String(query.region).replace(/^\+/, '')
			}
		}
		if (query && query.redirect) {
			try {
				this.redirect = decodeURIComponent(query.redirect)
			} catch (_) {
				this.redirect = query.redirect || ''
			}
		}
		if (query && query.lock === '1') {
			this.phoneLocked = true
		}

		if (!handset && this.profile && this.profile.mobile) {
			handset = trimHandset(this.profile.mobile)
		}
		if (!region && this.profile && this.profile.area_code) {
			region = String(this.profile.area_code).replace(/^\+/, '')
		}
		if (handset) this.handset = handset
		if (region) this.region = region
		if (!this.phoneLocked && this.profile && this.profile.isLogin && looksLikeHandset(this.handset)) {
			this.phoneLocked = true
		}
	},
	onShow() {
		this.resetSubmitState()
	},
	methods: {
		goBack() {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.navigateTo({
					url: '/pages/account/security',
					fail: () => uni.switchTab({ url: '/pages/mine/index' })
				})
			}
		},
		onHandsetInput(e) {
			this.handset = trimHandset(e.detail.value)
		},
		toast(msg) {
			if (this.$appKit && this.$appKit.msg) this.$appKit.msg(msg)
			else uni.showToast({ title: msg, icon: 'none' })
		},
		resetSubmitState() {
			this.probing = false
			try {
				uni.hideLoading()
			} catch (_) {}
		},
		buildSmsVerifyUrl(ticketId) {
			const params = [
				`scene=resetpwd`,
				`handset=${encodeURIComponent(this.handset)}`,
				`region=${encodeURIComponent(this.region)}`,
				`ticketId=${encodeURIComponent(ticketId || '')}`
			]
			if (this.redirect) {
				params.push(`redirect=${encodeURIComponent(this.redirect)}`)
			}
			return `/pages/account/sms-verify?${params.join('&')}`
		},
		goSmsVerify(ticketId) {
			return new Promise((resolve) => {
				uni.navigateTo({
					url: this.buildSmsVerifyUrl(ticketId),
					success: () => resolve(true),
					fail: () => resolve(false)
				})
			})
		},
		async onNext() {
			if (this.probing) return
			if (!this.canSubmit) {
				this.toast(this.$t('passport.err-handset'))
				return
			}
			this.probing = true
			uni.showLoading({ title: this.copy.probing, mask: true })
			try {
				const { taken } = await verifyHandsetUsed({
					handset: this.handset,
					region: this.region
				})
				if (!taken) {
					this.toast(this.$t('passport.err-not-exist'))
					return
				}
				const { ticketId, needHumanCheck } = await requestPasscode({
					scene: 'resetpwd',
					handset: this.handset,
					region: this.region
				})
				if (needHumanCheck) {
					this.toast(this.$t('passport.tip-need-captcha'))
					return
				}
				const navigated = await this.goSmsVerify(ticketId)
				if (!navigated) {
					this.toast(this.$t('passport.err-network'))
				}
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('passport.err-network'))
				}
			} finally {
				this.resetSubmitState()
			}
		}
	}
}
</script>

<style scoped>
.acct-pwd-page {
	min-height: 100vh;
	background-color: #f4f6fb;
}

.acct-pwd-nav {
	background-color: #ffffff;
	border-bottom: 1rpx solid #eef1f6;
}

.acct-pwd-nav-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	height: 88rpx;
	padding: 0 24rpx;
	box-sizing: border-box;
}

.acct-pwd-back {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.acct-pwd-back-icon {
	font-size: 40rpx;
	color: #1a1d26;
	line-height: 1;
}

.acct-pwd-nav-title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1d26;
}

.acct-pwd-nav-placeholder {
	width: 64rpx;
}

.acct-pwd-body {
	padding: 28rpx 28rpx 40rpx;
	box-sizing: border-box;
}

.acct-pwd-hero {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 32rpx;
	padding: 32rpx 24rpx 8rpx;
}

.acct-pwd-hero-icon-wrap {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	background: linear-gradient(145deg, #eef4ff 0%, #e8f0fe 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 28rpx rgba(74, 140, 255, 0.12);
	margin-bottom: 20rpx;
}

.acct-pwd-hero-icon {
	font-size: 56rpx;
	line-height: 1;
}

.acct-pwd-hero-title {
	font-size: 34rpx;
	font-weight: 700;
	color: #1a1d26;
	margin-bottom: 10rpx;
}

.acct-pwd-hero-desc {
	font-size: 26rpx;
	color: #8a8d9e;
	text-align: center;
	line-height: 1.5;
	padding: 0 16rpx;
}

.acct-pwd-card {
	background-color: #ffffff;
	border-radius: 24rpx;
	padding: 28rpx;
	box-shadow: 0 6rpx 24rpx rgba(74, 140, 255, 0.06);
	margin-bottom: 28rpx;
}

.acct-pwd-label {
	display: block;
	font-size: 26rpx;
	font-weight: 600;
	color: #4b5563;
	margin-bottom: 16rpx;
}

.acct-pwd-phone-row {
	display: flex;
	flex-direction: row;
	align-items: stretch;
}

.acct-pwd-region {
	flex-shrink: 0;
}

.acct-pwd-input {
	flex: 1;
	height: 96rpx;
	padding: 0 24rpx;
	font-size: 30rpx;
	color: #1a1d26;
	background-color: #f7f9fc;
	border: 1rpx solid #e5e9f2;
	border-left: none;
	border-radius: 0 20rpx 20rpx 0;
	box-sizing: border-box;
}

.acct-pwd-input__placeholder {
	color: #b8bcc8;
}

.acct-pwd-hint {
	display: block;
	margin-top: 14rpx;
	font-size: 24rpx;
	color: #8a8d9e;
	line-height: 1.45;
}

.acct-pwd-locked-tip {
	display: block;
	margin-top: 10rpx;
	font-size: 24rpx;
	color: #4a8cff;
}

.acct-pwd-submit {
	width: 100%;
	height: 96rpx;
	line-height: 96rpx;
	border-radius: 48rpx;
	border: none;
	background: linear-gradient(135deg, #4a8cff 0%, #6b5cff 100%);
	box-shadow: 0 12rpx 32rpx rgba(74, 140, 255, 0.28);
}

.acct-pwd-submit::after {
	border: none;
}

.acct-pwd-submit--off {
	opacity: 0.45;
	box-shadow: none;
}

.acct-pwd-submit--busy {
	opacity: 0.88;
}

.acct-pwd-submit__text {
	font-size: 32rpx;
	font-weight: 600;
	color: #ffffff;
}

.acct-pwd-help {
	margin-top: 28rpx;
	padding: 24rpx 28rpx;
	border-radius: 20rpx;
	background-color: #ffffff;
	box-shadow: 0 4rpx 16rpx rgba(74, 140, 255, 0.04);
}

.acct-pwd-help__title {
	display: block;
	font-size: 26rpx;
	font-weight: 600;
	color: #4a8cff;
	margin-bottom: 12rpx;
}

.acct-pwd-help__line {
	display: block;
	font-size: 24rpx;
	color: #8a8d9e;
	line-height: 1.55;
}
</style>

<style>
/* 区号选择器浅色主题（账号设置流） */
.acct-pwd-phone-row .region-trigger {
	background-color: #f7f9fc !important;
	border: 1rpx solid #e5e9f2 !important;
	border-right: none !important;
	border-radius: 20rpx 0 0 20rpx !important;
}

.acct-pwd-phone-row .region-trigger__code {
	color: #1a1d26 !important;
}

.acct-pwd-phone-row .region-trigger__caret {
	color: #8a8d9e !important;
}
</style>
