"use client"

import type { AppLocale } from "@cms/i18n"
import { createContext, type ReactNode, useContext, useMemo } from "react"

import type { AdminMessages } from "@/i18n/messages"
import { translateMessage } from "@/i18n/messages"

type AdminI18nContextValue = {
  locale: AppLocale
  messages: AdminMessages
}

const AdminI18nContext = createContext<AdminI18nContextValue | null>(null)

export function AdminI18nProvider({
  locale,
  messages,
  children,
}: {
  locale: AppLocale
  messages: AdminMessages
  children: ReactNode
}) {
  const value = useMemo(
    () => ({
      locale,
      messages,
    }),
    [locale, messages],
  )

  return <AdminI18nContext.Provider value={value}>{children}</AdminI18nContext.Provider>
}

export function useAdminI18n(): AdminI18nContextValue {
  const context = useContext(AdminI18nContext)

  if (!context) {
    throw new Error("useAdminI18n must be used inside AdminI18nProvider")
  }

  return context
}

export function useAdminT() {
  const { messages } = useAdminI18n()

  return useMemo(
    () => (key: string, fallback?: string) => translateMessage(messages, key, fallback),
    [messages],
  )
}
