"use client";

import {
  Children,
  cloneElement,
  isValidElement,
  type ReactElement,
  type ReactNode,
} from "react";
import { useI18n } from "@/components/i18n-provider";
import { translateStaticUiText } from "@/lib/i18n-dictionaries";

const LOCALIZED_STRING_PROPS = [
  "aria-label",
  "aria-description",
  "alt",
  "buttonLabel",
  "description",
  "emptyLabel",
  "helpText",
  "label",
  "pendingLabel",
  "placeholder",
  "title",
] as const;

function localizeNode(node: ReactNode, locale: ReturnType<typeof useI18n>["locale"]): ReactNode {
  if (typeof node === "string") {
    return translateStaticUiText(locale, node);
  }

  if (Array.isArray(node)) {
    return node.map((child) => localizeNode(child, locale));
  }

  if (!isValidElement(node)) {
    return node;
  }

  const element = node as ReactElement<Record<string, unknown>>;

  if (element.props["data-i18n-skip"] === true) {
    return element;
  }

  const nextProps: Record<string, unknown> = {};

  for (const propName of LOCALIZED_STRING_PROPS) {
    const value = element.props[propName];

    if (typeof value === "string") {
      nextProps[propName] = translateStaticUiText(locale, value);
    }
  }

  if ("children" in element.props) {
    nextProps.children = Children.map(element.props.children as ReactNode, (child) =>
      localizeNode(child, locale),
    );
  }

  return cloneElement(element, nextProps);
}

export function StaticUiLocalizer({ children }: { children: ReactNode }) {
  const { locale } = useI18n();
  return <>{localizeNode(children, locale)}</>;
}
