<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.sentTo }}</text>
					<text class="acct-sms-mobile">+{{ region }} {{ maskedHandset }}</text>
				</view>

				<view class="acct-pwd-card acct-sms-card">
					<text class="acct-pwd-label">{{ copy.codeLabel }}</text>
					<passcode-grid
						theme="light"
						:value="passcode"
						:alert="passcodeAlert"
						:disabled="submitting"
						@input="onPasscodeInput"
						@settled="onPasscodeSettled"
					/>
					<view class="acct-sms-resend">
						<text v-if="coolLeft > 0" class="acct-sms-resend__muted">
							{{ copy.resendIn }} {{ coolLeft }}s
						</text>
						<text
							v-else
							class="acct-sms-resend__link"
							@tap="resendPasscode"
						>{{ copy.resend }}</text>
						<text v-if="coolLeft > 0 && coolLeft < 50" class="acct-sms-resend__hint">
							{{ copy.notReceive }}
						</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.next }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import PasscodeGrid from '@/components/passport-kit/passcode-grid.vue'
import { requestPasscode } from '@/features/passport/credential-bridge'
import { passcodeShape, trimHandset } from '@/features/passport/form-rules'

export default {
	components: { PasscodeGrid },
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			scene: 'resetpwd',
			handset: '',
			region: '852',
			ticketId: '',
			passcode: '',
			passcodeAlert: false,
			coolLeft: 0,
			coolTimer: null,
			sending: false,
			submitting: false,
			redirect: ''
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				title: t('passport.title-sms-verify'),
				heroTitle: t('user.smsVerifyHeroTitle'),
				sentTo: t('passport.sms-sent-to'),
				codeLabel: t('user.smsVerifyCodeLabel'),
				resend: t('passport.sms-resend'),
				resendIn: t('passport.sms-resend-in'),
				notReceive: t('user.smsVerifyNotReceive'),
				next: t('passport.btn-next'),
				submitting: t('passport.btn-probing')
			}
		},
		maskedHandset() {
			const raw = this.handset
			if (raw.length <= 4) return raw
			return `${raw.slice(0, 3)}****${raw.slice(-4)}`
		},
		canSubmit() {
			return 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.scene) this.scene = query.scene
		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.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 || ''
			}
		}
		this.coolStart(60)
	},
	onShow() {
		this.resetSubmitState()
	},
	onUnload() {
		if (this.coolTimer) clearInterval(this.coolTimer)
	},
	methods: {
		goBack() {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.redirectTo({ url: '/pages/account/reset-password' })
			}
		},
		toast(msg) {
			if (this.$appKit && this.$appKit.msg) this.$appKit.msg(msg)
			else uni.showToast({ title: msg, icon: 'none' })
		},
		resetSubmitState() {
			this.submitting = false
			this.sending = false
			try {
				uni.hideLoading()
			} catch (_) {}
		},
		coolStart(sec) {
			this.coolLeft = sec
			if (this.coolTimer) clearInterval(this.coolTimer)
			this.coolTimer = setInterval(() => {
				this.coolLeft -= 1
				if (this.coolLeft <= 0) {
					clearInterval(this.coolTimer)
					this.coolTimer = null
				}
			}, 1000)
		},
		onPasscodeInput(val) {
			this.passcode = val
			this.passcodeAlert = false
		},
		onPasscodeSettled() {
			this.passcodeAlert = false
			if (this.scene === 'resetpwd') {
				this.onSubmit()
			}
		},
		buildResetSecretUrl() {
			const q = [
				`handset=${encodeURIComponent(this.handset)}`,
				`region=${encodeURIComponent(this.region)}`,
				`passcode=${encodeURIComponent(this.passcode)}`,
				`ticketId=${encodeURIComponent(this.ticketId || '')}`
			]
			if (this.redirect) q.push(`redirect=${encodeURIComponent(this.redirect)}`)
			return `/pages/account/reset-secret?${q.join('&')}`
		},
		async resendPasscode() {
			if (this.coolLeft > 0 || this.sending) return
			this.sending = true
			uni.showLoading({ mask: true })
			try {
				const { ticketId, needHumanCheck } = await requestPasscode({
					scene: this.scene,
					handset: this.handset,
					region: this.region
				})
				if (needHumanCheck) {
					this.toast(this.$t('passport.tip-need-captcha'))
					return
				}
				this.ticketId = ticketId
				this.passcode = ''
				this.coolStart(60)
				this.toast(this.$t('passport.tip-code-sent'))
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('passport.tip-code-failed'))
				}
			} finally {
				this.sending = false
				uni.hideLoading()
			}
		},
		onSubmit() {
			if (this.submitting) return
			if (!this.canSubmit) {
				this.passcodeAlert = true
				this.toast(this.$t('passport.err-passcode'))
				return
			}
			if (this.scene !== 'resetpwd') return
			this.submitting = true
			uni.navigateTo({
				url: this.buildResetSecretUrl(),
				complete: () => {
					this.resetSubmitState()
				}
			})
		}
	}
}
</script>

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

.acct-sms-mobile {
	font-size: 32rpx;
	font-weight: 600;
	color: #4a8cff;
	margin-top: 12rpx;
	letter-spacing: 1rpx;
}

.acct-sms-card {
	padding-bottom: 32rpx;
}

.acct-sms-resend {
	margin-top: 28rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.acct-sms-resend__muted {
	font-size: 26rpx;
	color: #8a8d9e;
}

.acct-sms-resend__link {
	font-size: 26rpx;
	color: #4a8cff;
	font-weight: 600;
}

.acct-sms-resend__hint {
	margin-top: 12rpx;
	font-size: 24rpx;
	color: #b8bcc8;
}
</style>
