// Forgot password — URL `/forgot`. POST /auth/password-reset { email } always
// returns 202 (no account enumeration — the same "check your email" whether or
// not the address exists). The api emails a link to `/reset?token=…` (delivery
// needs `sendEmail` wired on the api; without it the route still 202s).
import type { ReactNode } from 'react'
import { useState, type FormEvent } from 'react'
import type { PageMeta } from '@voltro/web'
import { T, useT } from '@voltro/i18n'
import { AuthShell } from '../../components/AuthShell'
import { postAuth } from '../../lib/auth'
import { getCatalog } from '../../locales'

export const renderMode = 'static' as const

export const meta = ({ locale }: { readonly locale: string }): PageMeta => ({
  title: getCatalog(locale)['meta.forgot.title'],
})

export default function Forgot(): ReactNode {
  const [email, setEmail] = useState('')
  const [pending, setPending] = useState(false)
  const [sent, setSent] = useState(false)
  const emailLabel = useT('auth.email')

  const onSubmit = (e: FormEvent): void => {
    e.preventDefault()
    setPending(true)
    void postAuth('/auth/password-reset', { email })
      .then(() => { setSent(true); setPending(false) })
      .catch(() => { setSent(true); setPending(false) }) // still show the neutral message
  }

  return (
    <AuthShell titleId="forgot.title" footer={<a href="/login"><T id="forgot.toLogin" /></a>}>
      {sent ? (
        <p className="ok" role="status"><T id="forgot.sent" /></p>
      ) : (
        <form className="auth-form" onSubmit={onSubmit}>
          <p className="muted"><T id="forgot.body" /></p>
          <label>
            <span><T id="auth.email" /></span>
            <input type="email" required aria-label={emailLabel} value={email} onChange={(e) => setEmail(e.target.value)} />
          </label>
          <button type="submit" className="btn" disabled={pending}>
            <T id={pending ? 'auth.pending' : 'forgot.submit'} />
          </button>
        </form>
      )}
    </AuthShell>
  )
}
