import { usePage } from "@inertiajs/vue3";

type Replacements = Record<string, string | number>;

function resolve(obj: unknown, parts: string[]): string | undefined {
  let current: unknown = obj;
  for (const part of parts) {
    if (current === null || typeof current !== "object") return undefined;
    current = (current as Record<string, unknown>)[part];
  }
  return typeof current === "string" ? current : undefined;
}

export function useTranslations() {
  const page = usePage<{
    translations?: Record<string, unknown>;
  }>();

  /**
   * Translate a dot-notated key, e.g. `t('builder.nav.dashboard')`.
   * Returns the key itself when the translation is not found.
   * Replaces `:placeholder` tokens with values from the replacements map.
   */
  function t(key: string, replacements: Replacements = {}): string {
    const value = resolve(page.props.translations, key.split("."));
    let text = value ?? key;

    // Laravel-style pluralization: "singular form|plural form"
    if (text.includes("|") && replacements.count !== undefined) {
      const parts = text.split("|");
      text =
        Number(replacements.count) === 1 ? parts[0] : (parts[1] ?? parts[0]);
    }

    return text.replace(/:(\w+)/g, (_, k) =>
      String(replacements[k] ?? `:${k}`),
    );
  }

  return { t };
}
