// Magic link — URL `/magic`. Passwordless sign-in: POST /auth/magic-link
// { email } mints a single-use, short-lived token and (when `sendEmail` is wired
// on the api) emails a link to `/verify?token=…`. Always shows the neutral
// "check your email" so it can't be used to probe which addresses exist.
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.magic.title'],
})

export default function Magic(): 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/magic-link', { email })
      .then(() => { setSent(true); setPending(false) })
      .catch(() => { setSent(true); setPending(false) })
  }

  return (
    <AuthShell titleId="magic.title" footer={<a href="/login"><T id="magic.toLogin" /></a>}>
      {sent ? (
        <p className="ok" role="status"><T id="magic.sent" /></p>
      ) : (
        <form className="auth-form" onSubmit={onSubmit}>
          <p className="muted"><T id="magic.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' : 'magic.submit'} />
          </button>
        </form>
      )}
    </AuthShell>
  )
}
