// Public sign-in page — URL `/login`. The shell pre-renders (`static`) and
// hydrates for the button. This is a DEMO login: it just writes the cookie
// the dashboard gate looks for. A real app POSTs credentials to an api that
// returns a signed, HttpOnly session cookie — see AGENTS.md › Auth.
import type { ReactNode } from 'react'
import type { PageMeta } from '@voltro/web'
import { useNavigate } from '@voltro/web'
import { T } from '@voltro/i18n'
import { getCatalog } from '../../../locales/index'
import { SESSION_COOKIE } from '../../../lib/auth'

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 navigate = useNavigate()

  const onSignIn = (): void => {
    // Set the demo session cookie, then go where the gate sent us (the
    // RedirectError carries `?from=`), defaulting to the dashboard.
    document.cookie = `${SESSION_COOKIE}=ok; path=/; max-age=86400; samesite=lax`
    const from = new URLSearchParams(window.location.search).get('from') ?? '/dashboard'
    navigate(from)
  }

  return (
    <section className="hero">
      <h1><T id="login.heading" /></h1>
      <p className="muted"><T id="login.body" /></p>
      <p style={{ marginTop: '1.5rem' }}>
        <button type="button" className="btn" onClick={onSignIn}>
          <T id="login.cta" />
        </button>
      </p>
    </section>
  )
}
