import { useEffect, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { api } from '../../api/client.js'
import PlayerShell from './PlayerShell.jsx'
// Public, token-gated reset page (/account/reset/:token). Validates the link, lets
// the user choose a new password, then sends them to sign in fresh. Setting the
// password revokes every existing session (web + mobile) server-side and does NOT
// log them in here — so a 2FA account still passes TOTP on the next sign-in.
export default function ResetPassword() {
const { token } = useParams()
const navigate = useNavigate()
const [username, setUsername] = useState(null) // whose account this link is for
const [loadErr, setLoadErr] = useState('')
const [password, setPassword] = useState('')
const [confirm, setConfirm] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const [done, setDone] = useState(false)
useEffect(() => {
let active = true
api.getPasswordReset(token)
.then((r) => active && setUsername(r?.username || ''))
.catch((err) => active && setLoadErr(
err.status === 404 ? 'This reset link is invalid or has expired.' : 'Could not load this reset link.',
))
return () => { active = false }
}, [token])
async function onSubmit(e) {
e.preventDefault()
setError('')
if (password.length < 8) return setError('Password must be at least 8 characters.')
if (password !== confirm) return setError('The passwords do not match.')
setBusy(true)
try {
await api.resetPassword(token, password)
setDone(true)
} catch (err) {
if (err.status === 404) setError('This reset link is invalid or has already been used.')
else if (err.status === 429) setError('Too many attempts. Please try again in a little while.')
else if (err.status === 400) setError(err.message || 'Please check your password and try again.')
else setError('Could not reset your password right now. Please try again later.')
setBusy(false)
}
}
// ── Invalid link ───────────────────────────────────────────────────────────
if (loadErr) {
return (