// Verify — URL `/verify?token=…`. The landing the magic-link / email-verification
// mail points at. On mount it consumes the token via POST
// /auth/magic-link/callback: a valid token signs the user in (session cookie
// set) and we redirect home; an invalid/expired one shows a retry path. The same
// page doubles as the email-verification confirmation.
import type { ReactNode } from 'react'
import { useEffect, useState } from 'react'
import type { PageMeta } from '@voltro/web'
import { T } from '@voltro/i18n'
import { AuthShell } from '../../components/AuthShell'
import { AUTH_HOME } from '../../config'
import { postAuth } from '../../lib/auth'
import { nextFromLocation, tokenFromLocation } 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.verify.title'],
})

type State = 'pending' | 'success' | 'failed' | 'noToken'

export default function Verify(): ReactNode {
  const [state, setState] = useState<State>('pending')

  useEffect(() => {
    const token = tokenFromLocation()
    if (!token) { setState('noToken'); return }
    void postAuth('/auth/magic-link/callback', { token })
      .then((res) => {
        if (res.ok) {
          setState('success')
          window.location.assign(nextFromLocation(AUTH_HOME))
        } else {
          setState('failed')
        }
      })
      .catch(() => setState('failed'))
  }, [])

  return (
    <AuthShell titleId="verify.title" footer={state !== 'pending' ? <a href="/login"><T id="verify.toLogin" /></a> : null}>
      {state === 'pending' ? <p className="muted" role="status"><T id="verify.pending" /></p> : null}
      {state === 'success' ? <p className="ok" role="status"><T id="verify.success" /></p> : null}
      {state === 'failed' ? <p className="error-text" role="alert"><T id="verify.failed" /></p> : null}
      {state === 'noToken' ? <p className="error-text" role="alert"><T id="verify.noToken" /></p> : null}
    </AuthShell>
  )
}
