// @vitest-environment jsdom
//
// `/` — the bilingual landing template. A statically pre-rendered marketing
// page with zero framework JS on the wire (`renderMode='static'`,
// `interactive='none'`), localised per URL locale (Strategy B). Two things
// worth testing:
//   1. `meta({ locale })` is localized — it reads the REAL catalog via
//      getCatalog, so we assert en vs de titles/descriptions directly (no mock).
//   2. the rendered body shows localized copy. The page pulls strings from
//      @voltro/i18n (<T>); we mock it to resolve against the real catalog for a
//      controllable "current locale". The hero <h1> carries a `{{capProjectName}}`
//      scaffold placeholder, so we assert the heading EXISTS, not its text.

import { afterEach, describe, expect, test, vi } from 'vitest'
import { act, createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import en from '../locales/en'
import de from '../locales/de'

// Controllable "active locale" for the i18n mock.
const catalogs: Record<string, Record<string, string>> = { en, de }
let currentLocale = 'en'

// Minimal ICU-ish interpolation: replace {key} with values[key]. Rich-text
// tags (`<strong>`, `<code>`) are left inline as text — enough to assert the
// page rendered the right (localized) copy; react-intl injects real elements.
const fill = (msg: string, values?: Record<string, unknown>): string =>
  values ? msg.replace(/\{(\w+)\}/g, (_, k: string) => String(values[k] ?? `{${k}}`)) : msg

vi.mock('@voltro/i18n', () => ({
  // The locale catalogs call these at module top-level; identity mirrors the
  // real (compile-time-only) implementations so importing them doesn't throw.
  defineCatalog: <T,>(c: T): T => c,
  defineLocale:
    () =>
    <T,>(c: T): T =>
      c,
  T: ({ id, values }: { id: string; values?: Record<string, unknown> }) =>
    fill(catalogs[currentLocale]?.[id] ?? id, values),
}))

const { default: Index, meta, renderMode, interactive } = await import('./page')

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

let container: HTMLDivElement
let root: Root

const render = (node: ReactNode): void => {
  container = document.createElement('div')
  document.body.appendChild(container)
  act(() => {
    root = createRoot(container)
    root.render(node)
  })
}

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

describe('index — config + localized meta', () => {
  test('is a static page with no interactive JS on the wire', () => {
    expect(renderMode).toBe('static')
    expect(interactive).toBe('none')
  })

  test('meta() returns the English catalog title/description for locale en', () => {
    const m = meta({ locale: 'en' })
    expect(m.title).toBe('Home')
    expect(m.description).toContain('landing page')
  })

  test('meta() returns the German catalog title/description for locale de', () => {
    const m = meta({ locale: 'de' })
    expect(m.title).toBe('Start')
    expect(m.description).toContain('Landingpage')
  })

  test('meta() falls back to the default (en) catalog for an unknown locale', () => {
    expect(meta({ locale: 'zz' }).title).toBe('Home')
  })
})

describe('index — localized render', () => {
  test('renders a hero heading + the English Features section', () => {
    currentLocale = 'en'
    render(createElement(Index))
    expect(container.querySelector('main h1')).toBeTruthy()
    const featureSection = container.querySelector('#features')
    expect(featureSection).toBeTruthy()
    expect(featureSection!.querySelector('h2')!.textContent).toBe('Features')
    const bullets = Array.from(container.querySelectorAll('#features li'))
    expect(bullets).toHaveLength(3)
    expect(container.textContent).toContain('Reactive subscriptions')
    expect(container.querySelector('a[href="#features"]')).toBeTruthy()
    expect(container.textContent).toContain('Ready to start?')
  })

  test('renders the German copy when the active locale is de', () => {
    currentLocale = 'de'
    render(createElement(Index))
    expect(container.querySelector('#features h2')!.textContent).toBe('Funktionen')
    expect(container.textContent).toContain('Reaktive Subscriptions')
    expect(container.textContent).toContain('Bereit loszulegen?')
  })
})
