// @vitest-environment jsdom

import * as React from "react"
import { render, screen } from "@testing-library/react"
import { describe, expect, it } from "vitest"

import { I18nProvider } from "./i18n-provider"
import { useLocale, useLocales, useMessage, useTranslate } from "./hooks"
import { Translate } from "./translate"

const catalogs = {
  en: {
    greeting: "Hello",
  },
  "zh-Hans": {
    greeting: "你好",
  },
}

function HookProbe() {
  const locale = useLocale()
  const locales = useLocales()
  const message = useMessage("greeting")
  const translate = useTranslate()

  return (
    <output>
      {locale}|{locales.map((item) => item.locale).join(",")}|{message}|
      {translate("greeting")}
    </output>
  )
}

describe("i18n runtime", () => {
  it("provides locale information and reactive translation helpers", () => {
    render(
      <I18nProvider
        catalogs={catalogs}
        locale="zh-Hans"
        locales={[
          { label: "English", locale: "en" },
          { label: "简体中文", locale: "zh-Hans" },
        ]}
      >
        <HookProbe />
      </I18nProvider>
    )

    expect(screen.getByText("zh-Hans|en,zh-Hans|你好|你好")).toBeTruthy()
  })

  it("wraps Lingui Trans without adding a DOM element", () => {
    const { container } = render(
      <I18nProvider catalogs={catalogs} locale="en">
        <p>
          <Translate id="greeting" message="Fallback" />
        </p>
      </I18nProvider>
    )

    expect(container.innerHTML).toBe("<p>Hello</p>")
  })

  it("infers right-to-left locale direction", () => {
    function DirectionProbe() {
      return <span>{useLocales()[0]?.direction}</span>
    }

    render(
      <I18nProvider locale="ar" locales={["ar"]}>
        <DirectionProbe />
      </I18nProvider>
    )

    expect(screen.getByText("rtl")).toBeTruthy()
  })
})
