// `/` — `renderMode: 'ssr'`. The loader runs on the SERVER on EVERY request
// (`voltro start`), so the page is rendered fresh per visit — the timestamp
// and nonce change on each refresh, and the loader can read the incoming
// request (cookies, headers) to personalise the HTML before it's sent.
//
// Use SSR for anything that varies per request: a logged-in dashboard, a
// page that reads the visitor's cookie/locale, or any data that must NOT be
// cached across requests.

import type { ReactNode } from 'react'
import { useLoaderData, useServerRequest, type LoaderFn, type PageMeta } from '@voltro/web'
import { T } from '@voltro/i18n'
import { getCatalog } from '../locales'

export const renderMode = 'ssr' as const

// Locale-aware tab title + description: @voltro/web resolves meta({ locale })
// from the active locale (the `voltro:locale` cookie in this cookie-i18n app).
export const meta = ({ locale }: { readonly locale: string }): PageMeta => ({
  title:       getCatalog(locale)['meta.ssr.title'],
  description: getCatalog(locale)['meta.ssr.description'],
})

interface HomeData {
  readonly renderedAt: string
  readonly nonce: number
}

// The loader runs server-side per request. `headers` carries the incoming
// request headers (lowercased). To pull fresh data from YOUR reactive api
// instead of computing it here, declare an `apis` entry in app.config.ts and:
//
//   export const loader: LoaderFn<HomeData> = async ({ query, headers }) => ({
//     // `query` is present ONLY server-side (ssr/isr). It calls your api's
//     // rpc directly, forwarding the session cookie — same Subject as the WS.
//     latest: await query!('posts.latest', {}),
//   })
//
export const loader: LoaderFn<HomeData> = async () => ({
  renderedAt: new Date().toISOString(),
  nonce: Math.floor(Math.random() * 1_000_000),
})

export default function Home(): ReactNode {
  const data = useLoaderData<HomeData>()
  // `useServerRequest()` reads the request's cookies + headers — on the
  // server during SSR, and the same shape on the client. Drive cookie-backed
  // prefs (locale, theme) with it WITHOUT a hydration flash.
  const req = useServerRequest()
  const acceptLanguage = req?.headers['accept-language'] ?? 'unset'
  const themeCookie = req?.cookies['voltro:theme'] ?? 'unset'
  const code = (c: ReactNode) => <code>{c}</code>

  return (
    <section>
      <span className="badge"><T id="ssr.badge" /></span>
      <h1 style={{ marginTop: '0.75rem' }}><T id="ssr.heading" /></h1>
      <p className="lead"><T id="ssr.lead" /></p>

      <ul className="fields">
        <li><span className="k"><T id="field.renderedAt" /></span><span className="v">{data.renderedAt}</span></li>
        <li><span className="k"><T id="field.nonce" /></span><span className="v">{data.nonce}</span></li>
        <li><span className="k"><T id="ssr.field.acceptLanguage" /></span><span className="v">{acceptLanguage}</span></li>
        <li><span className="k"><T id="ssr.field.themeCookie" /></span><span className="v">{themeCookie}</span></li>
      </ul>

      <p className="note">
        <T id="ssr.note" values={{ code }} />
      </p>
    </section>
  )
}
