<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>
					<text class="acct-reset-handset">+{{ region }} {{ maskedHandset }}</text>
				</view>

				<view class="acct-pwd-card">
					<text class="acct-pwd-label">{{ copy.secretLabel }}</text>
					<view class="acct-reset-input-wrap">
						<input
							v-model="secret"
							class="acct-reset-input"
							:password="!showSecret"
							:placeholder="copy.secretPlaceholder"
							placeholder-class="acct-reset-input__placeholder"
							maxlength="20"
						/>
						<text class="acct-reset-eye" @tap="showSecret = !showSecret">
							{{ showSecret ? copy.hide : copy.show }}
						</text>
					</view>

					<view v-if="secret.length" class="acct-reset-meter">
						<view
							v-for="bar in 4"
							:key="bar"
							class="acct-reset-meter__bar"
							:class="meterClass(bar)"
						/>
						<text class="acct-reset-meter__txt">{{ meterLabel }}</text>
					</view>
				</view>

				<button
					class="acct-pwd-submit"
					:disabled="!canSubmit || submitting"
					:loading="submitting"
					:class="{ 'acct-pwd-submit--off': !canSubmit, 'acct-pwd-submit--busy': submitting }"
					@tap="onSubmit"
				>
					<text class="acct-pwd-submit__text">{{ submitting ? copy.submitting : copy.submit }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { resetSecretBySms } from '@/features/account/account-security-gateway'
import { passcodeShape, secretInRange, trimHandset } from '@/features/passport/form-rules'

export default {
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			handset: '',
			region: '852',
			passcode: '',
			ticketId: '',
			secret: '',
			showSecret: false,
			submitting: false,
			redirect: ''
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				title: t('passport.title-reset-secret'),
				heroTitle: t('user.resetSecretHeroTitle'),
				heroDesc: t('passport.subtitle-reset-secret'),
				secretLabel: t('passport.label-new-secret'),
				secretPlaceholder: t('passport.ph-new-secret'),
				show: t('passport.btn-show'),
				hide: t('passport.btn-hide'),
				submit: t('passport.btn-reset-secret'),
				submitting: t('passport.btn-probing'),
				ok: t('passport.tip-reset-secret-ok')
			}
		},
		maskedHandset() {
			const raw = this.handset
			if (raw.length <= 4) return raw
			return `${raw.slice(0, 3)}****${raw.slice(-4)}`
		},
		secretStrength() {
			const v = this.secret
			if (!secretInRange(v)) return 0
			let score = 1
			if (/[A-Z]/.test(v) && /[a-z]/.test(v)) score += 1
			if (/\d/.test(v)) score += 1
			if (/[^A-Za-z0-9]/.test(v)) score += 1
			return score
		},
		meterLabel() {
			const t = this.$t.bind(this)
			return [
				'',
				t('passport.meter-weak'),
				t('passport.meter-mid'),
				t('passport.meter-good'),
				t('passport.meter-great')
			][this.secretStrength]
		},
		canSubmit() {
			return secretInRange(this.secret) && passcodeShape(this.passcode)
		}
	},
	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

		if (query && query.handset) {
			try {
				this.handset = trimHandset(decodeURIComponent(query.handset))
			} catch (_) {
				this.handset = trimHandset(query.handset)
			}
		}
		if (query && query.region) {
			try {
				this.region = String(decodeURIComponent(query.region)).replace(/^\+/, '')
			} catch (_) {
				this.region = String(query.region).replace(/^\+/, '')
			}
		}
		if (query && query.passcode) {
			try {
				this.passcode = decodeURIComponent(query.passcode)
			} catch (_) {
				this.passcode = query.passcode
			}
		}
		if (query && query.ticketId) {
			try {
				this.ticketId = decodeURIComponent(query.ticketId)
			} catch (_) {
				this.ticketId = query.ticketId || ''
			}
		}
		if (query && query.redirect) {
			try {
				this.redirect = decodeURIComponent(query.redirect)
			} catch (_) {
				this.redirect = query.redirect || ''
			}
		}
	},
	onShow() {
		this.resetSubmitState()
	},
	methods: {
		goBack() {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.redirectTo({ url: '/pages/account/sms-verify' })
			}
		},
		toast(msg) {
			if (this.$appKit && this.$appKit.msg) this.$appKit.msg(msg)
			else uni.showToast({ title: msg, icon: 'none' })
		},
		resetSubmitState() {
			this.submitting = false
			try {
				uni.hideLoading()
			} catch (_) {}
		},
		meterClass(bar) {
			if (bar <= this.secretStrength) {
				if (this.secretStrength === 1) return 'acct-reset-meter__bar--weak'
				if (this.secretStrength === 2) return 'acct-reset-meter__bar--ok'
				return 'acct-reset-meter__bar--great'
			}
			return ''
		},
		async onSubmit() {
			if (this.submitting) return
			if (!this.canSubmit) {
				this.toast(this.$t('passport.err-secret'))
				return
			}
			this.submitting = true
			uni.showLoading({ title: this.copy.submitting, mask: true })
			try {
				await resetSecretBySms({
					handset: this.handset,
					region: this.region,
					passcode: this.passcode,
					secret: this.secret,
					ticketId: this.ticketId
				})
				this.toast(this.copy.ok)
				const target = this.redirect || '/pages/passport/signin?mode=secret'
				setTimeout(() => {
					uni.reLaunch({
						url: target,
						fail: () => uni.redirectTo({ url: target })
					})
				}, 400)
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('passport.tip-reset-secret-failed'))
				}
			} finally {
				this.resetSubmitState()
			}
		}
	}
}
</script>

<style scoped>
@import './account-flow.css';

.acct-reset-handset {
	font-size: 28rpx;
	color: #8a8d9e;
	margin-top: 8rpx;
}

.acct-reset-input-wrap {
	display: flex;
	flex-direction: row;
	align-items: center;
	height: 96rpx;
	padding: 0 24rpx;
	background-color: #f7f9fc;
	border: 1rpx solid #e5e9f2;
	border-radius: 20rpx;
	box-sizing: border-box;
}

.acct-reset-input {
	flex: 1;
	height: 96rpx;
	font-size: 30rpx;
	color: #1a1d26;
}

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

.acct-reset-eye {
	font-size: 26rpx;
	color: #4a8cff;
	padding-left: 16rpx;
	flex-shrink: 0;
}

.acct-reset-meter {
	display: flex;
	flex-direction: row;
	align-items: center;
	margin-top: 20rpx;
}

.acct-reset-meter__bar {
	width: 48rpx;
	height: 8rpx;
	margin-right: 12rpx;
	border-radius: 4rpx;
	background-color: #e5e9f2;
}

.acct-reset-meter__bar--weak {
	background-color: #f59e0b;
}

.acct-reset-meter__bar--ok {
	background-color: #4a8cff;
}

.acct-reset-meter__bar--great {
	background-color: #34d399;
}

.acct-reset-meter__txt {
	font-size: 24rpx;
	color: #8a8d9e;
}
</style>
