// @vitest-environment jsdom
//
// `/feed` ISR page — its cache config exports (revalidate, tenantAware), the
// loader reading the `x-tenant` header, 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: Feed, meta, loader, renderMode, revalidate, tenantAware } = 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 — cache config', () => {
  test('is ISR with a revalidate window and is tenant-aware', () => {
    expect(renderMode).toBe('isr')
    expect(revalidate).toBe('10 seconds')
    expect(tenantAware).toBe(true)
    expect(meta({ locale: 'en' }).title).toContain('ISR')
  })
})

describe('feed — loader', () => {
  test('reads the tenant from the x-tenant header', async () => {
    const data = await loader({ headers: { 'x-tenant': 'acme' } } as never)
    expect(data.tenant).toBe('acme')
    expect(Number.isNaN(Date.parse(data.renderedAt))).toBe(false)
  })

  test('falls back to `anonymous` when x-tenant is absent', async () => {
    const data = await loader({ headers: {} } as never)
    expect(data.tenant).toBe('anonymous')
  })
})

describe('feed — render', () => {
  test('renders the tenant + nonce from loader data', () => {
    loaderData.mockReturnValue({ renderedAt: '2020-01-01T00:00:00.000Z', nonce: 7, tenant: 'acme' })
    render(createElement(Feed))
    expect(container.textContent).toContain('acme')
    expect(container.textContent).toContain('7')
  })
})
