// Sign in — URL `/login`. Email + password → POST /auth/sign-in (CSRF-guarded).
// On success we do a FULL navigation to the safelisted `?next=` (default
// AUTH_HOME) so the destination app's SSR gate re-runs with the fresh cookie.
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 { 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.login.title'],
})

export default function Login(): 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-in', { 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="login.title"
      footer={
        <>
          <a href="/forgot"><T id="login.forgot" /></a>
          <a href="/magic"><T id="login.magic" /></a>
          <a href="/signup"><T id="login.toSignup" /></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 aria-label={passwordLabel} value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>
        {failed ? <p className="error-text"><T id="auth.error" /></p> : null}
        <button type="submit" className="btn" disabled={pending}>
          <T id={pending ? 'auth.pending' : 'login.submit'} />
        </button>
      </form>
    </AuthShell>
  )
}
