module Pagy::I18n

def build(*locales)

Build the DATA hash out of the passed locales
def build(*locales)
  locales.each do |locale|
    locale[:filepath]  ||= Pagy.root.join('locales', "#{locale[:locale]}.yml")
    locale[:pluralize] ||= P11n::LOCALE[locale[:locale]]
    dictionary = YAML.safe_load(File.read(locale[:filepath], encoding: 'UTF-8'))
    raise I18nError, %(expected :locale "#{locale[:locale]}" not found in :filepath "#{locale[:filepath].inspect}") \
          unless dictionary.key?(locale[:locale])
    DATA[locale[:locale]] = [flatten(dictionary[locale[:locale]]), locale[:pluralize]]
  end
end

def flatten(initial, prefix = '')

Create a flat hash with dotted notation keys
def flatten(initial, prefix = '')
  initial.each.reduce({}) do |hash, (key, value)|
    hash.merge!(value.is_a?(Hash) ? flatten(value, "#{prefix}#{key}.") : { "#{prefix}#{key}" => value })
  end
end

def load(*locales)

Public method to configure the locales: overrides the default, build the DATA and freezes it
def load(*locales)
  DATA.clear
  build(*locales)
  DATA.freeze
end

def translate(locale, key, **opts)

Translate and pluralize the key with the locale DATA
def translate(locale, key, **opts)
  data, pluralize = DATA[locale]
  translation = data[key] || (opts[:count] && data[key += ".#{pluralize.call(opts[:count])}"]) \
                  or return %([translation missing: "#{key}"])
  translation.gsub(/%{[^}]+?}/) { |match| opts[:"#{match[2..-2]}"] || match }
end