import { isValidElement, cloneElement } from 'preact';
import { useCallback } from 'preact/hooks';
import { useApi } from './api.mjs';

/**
 * Returns the `I18nTranslate` interface used to translate strings.
 */
function useTranslate() {
  const {
    i18n
  } = useApi();
  const translate = useCallback((...args) => {
    const translation = i18n.translate(...args);
    if (!Array.isArray(translation)) {
      return translation;
    }
    return translation.map((part, index) => {
      if (isValidElement(part)) {
        return cloneElement(part, {
          key: index
        });
      }
      return part;
    });
  }, [i18n]);
  return translate;
}

export { useTranslate };
