// `/feed-swr` — ISR with `staleWhileRevalidate`. When the `revalidate` window
// expires, instead of blocking the next visitor on a fresh render, the cache
// serves the STALE HTML immediately AND kicks off a background re-render. The
// visitor never waits; the cache catches up out-of-band.

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

export const renderMode = 'isr' as const
export const revalidate = '5 seconds'
// Within this window AFTER `revalidate` expires, requests get the STALE HTML
// instantly + a background refresh runs. Beyond (revalidate + swr) the next
// request blocks on a fresh render, like plain ISR.
export const staleWhileRevalidate = '30 seconds'

// Locale-aware tab title + description (cookie-i18n — @voltro/web hands meta
// the active locale).
export const meta = ({ locale }: { readonly locale: string }): PageMeta => ({
  title:       getCatalog(locale)['meta.swr.title'],
  description: getCatalog(locale)['meta.swr.description'],
})

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

export const loader: LoaderFn<SwrData> = async () => ({
  renderedAt: new Date().toISOString(),
  nonce: Math.floor(Math.random() * 1_000_000),
})

export default function FeedSwr(): ReactNode {
  const data = useLoaderData<SwrData>()
  const code = (c: ReactNode) => <code>{c}</code>
  return (
    <section>
      <span className="badge"><T id="swr.badge" /></span>
      <h1 style={{ marginTop: '0.75rem' }}><T id="swr.heading" /></h1>
      <p className="lead"><T id="swr.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>
      </ul>

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