// @vitest-environment jsdom
//
// `/feed-swr` ISR + stale-while-revalidate page — its cache config exports,
// the loader, and the render.

import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { act, createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { I18nProvider } from '@voltro/i18n'
import enCatalog from '../../locales/en'

const loaderData = vi.fn<() => unknown>()
vi.mock('@voltro/web', () => ({ useLoaderData: () => loaderData() }))

const { default: FeedSwr, meta, loader, renderMode, revalidate, staleWhileRevalidate } =
  await import('./page')

;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true

let container: HTMLDivElement
let root: Root

// The page uses <T>, so it needs an <I18nProvider> (real English catalog).
const render = (node: ReactNode): void => {
  container = document.createElement('div')
  document.body.appendChild(container)
  act(() => {
    root = createRoot(container)
    root.render(
      createElement(I18nProvider, { locale: 'en', messages: enCatalog, defaultLocale: 'en', children: node }),
    )
  })
}

beforeEach(() => {
  loaderData.mockReset()
})

afterEach(() => {
  if (root) act(() => root.unmount())
  container?.remove()
  document.body.innerHTML = ''
})

describe('feed-swr — cache config', () => {
  test('is ISR with both a revalidate and a stale-while-revalidate window', () => {
    expect(renderMode).toBe('isr')
    expect(revalidate).toBe('5 seconds')
    expect(staleWhileRevalidate).toBe('30 seconds')
    expect(meta({ locale: 'en' }).title).toContain('stale-while-revalidate')
  })
})

describe('feed-swr — loader', () => {
  test('resolves a fresh ISO timestamp + a numeric nonce', async () => {
    const data = await loader({} as never)
    expect(Number.isNaN(Date.parse(data.renderedAt))).toBe(false)
    expect(typeof data.nonce).toBe('number')
  })
})

describe('feed-swr — render', () => {
  test('renders the loader data', () => {
    loaderData.mockReturnValue({ renderedAt: '2020-01-01T00:00:00.000Z', nonce: 99 })
    render(createElement(FeedSwr))
    expect(container.textContent).toContain('2020-01-01T00:00:00.000Z')
    expect(container.textContent).toContain('99')
  })
})
