// Sign up — URL `/signup`. Email + password → POST /auth/sign-up (registers +
// auto signs in, setting the session cookie). A live password-strength meter is
// advisory; the api is the authority on policy.
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 { PasswordStrength } from '../../components/PasswordStrength'
import { AUTH_HOME } from '../../config'
import { postAuth } from '../../lib/auth'
import { nextFromLocation } from '../../lib/redirect'
import { getCatalog } from '../../locales'

export const renderMode = 'static' as const

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

export default function Signup(): ReactNode {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [pending, setPending] = useState(false)
  const [failed, setFailed] = useState(false)
  const emailLabel = useT('auth.email')
  const passwordLabel = useT('auth.password')

  const onSubmit = (e: FormEvent): void => {
    e.preventDefault()
    setPending(true)
    setFailed(false)
    void postAuth('/auth/sign-up', { email, password })
      .then((res) => {
        if (res.ok) window.location.assign(nextFromLocation(AUTH_HOME))
        else { setFailed(true); setPending(false) }
      })
      .catch(() => { setFailed(true); setPending(false) })
  }

  return (
    <AuthShell titleId="signup.title" footer={<a href="/login"><T id="signup.toLogin" /></a>}>
      <form className="auth-form" onSubmit={onSubmit}>
        <label>
          <span><T id="auth.email" /></span>
          <input type="email" required aria-label={emailLabel} value={email} onChange={(e) => setEmail(e.target.value)} />
        </label>
        <label>
          <span><T id="auth.password" /></span>
          <input type="password" required minLength={8} aria-label={passwordLabel} value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>
        <PasswordStrength value={password} />
        {failed ? <p className="error-text"><T id="auth.error" /></p> : null}
        <button type="submit" className="btn" disabled={pending}>
          <T id={pending ? 'auth.pending' : 'signup.submit'} />
        </button>
      </form>
    </AuthShell>
  )
}
