// `/feed` — `renderMode: 'isr'`. Same render path as SSR, but `voltro start`
// CACHES the HTML and serves the cached copy to every request within the
// `revalidate` window. After the window expires, the next request re-renders
// and replaces the cache.
//
// Use ISR for content that changes occasionally, is the same for every
// visitor (or only per-tenant), and is expensive to render (a CMS lookup, a
// third-party API). Cache hits return in <1ms.

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

// Cache window — a number (seconds) OR a string like '1 hour' / '30 seconds'.
export const revalidate = '10 seconds'

// Tenant-aware caching: the cache key includes the `x-tenant` request header,
// so tenant A's render is never served to tenant B. Leave it off for pages
// that don't vary by tenant (they then share ONE cache entry).
export const tenantAware = true

// 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.isr.title'],
  description: getCatalog(locale)['meta.isr.description'],
})

interface FeedData {
  readonly renderedAt: string
  readonly nonce: number
  readonly tenant: string
}

export const loader: LoaderFn<FeedData> = async ({ headers }) => ({
  renderedAt: new Date().toISOString(),
  nonce: Math.floor(Math.random() * 1_000_000),
  tenant: headers?.['x-tenant'] ?? 'anonymous',
})

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

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