import { DateTime, TranslatableString } from "ChillMainAssets/types";
import { getLocale } from "translator";

/**
 * Localizes a translatable string object based on the current locale.
 * A fallback logic is implemented in case no translation is available for the current locale.
 *
 * @param translatableString Object containing translations for different locales
 * @param locale defaults to browser locale
 * @returns The localized string or null if no translation is available
 */

/**
 * Prepends the current HTML lang code to the given URL.
 * Example: If lang="fr" and url="/about", returns "/fr/about"
 *
 * @param url The URL to localize
 * @returns The localized URL
 */
export function localizedUrl(url: string): string {
  const locale = getLocale();
  // Ensure url starts with a slash and does not already start with /{lang}/
  const normalizedUrl = url.startsWith("/") ? url : `/${url}`;
  const langPrefix = `/${locale}`;
  if (normalizedUrl.startsWith(langPrefix + "/")) {
    return normalizedUrl;
  }
  return `${langPrefix}${normalizedUrl}`;
}

export function localizeString(
  translatableString: TranslatableString | null | undefined,
  locale?: string,
): string {
  if (!translatableString || Object.keys(translatableString).length === 0) {
    return "";
  }

  const currentLocale = locale || getLocale();

  if (translatableString[currentLocale]) {
    return translatableString[currentLocale];
  }

  // Define fallback locales
  const fallbackLocales: string[] = ["fr", "en"];

  for (const fallbackLocale of fallbackLocales) {
    if (translatableString[fallbackLocale]) {
      return translatableString[fallbackLocale];
    }
  }

  // No fallback translation found, use the first available
  const availableLocales = Object.keys(translatableString);
  if (availableLocales.length > 0) {
    return translatableString[availableLocales[0]];
  }

  return "";
}

const datetimeFormats: Record<
  string,
  Record<string, Intl.DateTimeFormatOptions>
> = {
  fr: {
    short: {
      year: "numeric",
      month: "numeric",
      day: "numeric",
    },
    text: {
      year: "numeric",
      month: "long",
      day: "numeric",
    },
    long: {
      year: "numeric",
      month: "numeric",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      hour12: false,
    },
    hoursOnly: {
      hour: "numeric",
      minute: "numeric",
      hour12: false,
    },
  },
};
export function localizeDateTimeFormat(
  dateTime: DateTime,
  format: keyof typeof datetimeFormats.fr = "short",
): string {
  const locale = getLocale();
  const options =
    datetimeFormats[locale]?.[format] || datetimeFormats.fr[format];
  return new Intl.DateTimeFormat(locale, options).format(
    new Date(dateTime.datetime),
  );
}

export default datetimeFormats;
