class LanguagesController < ApplicationController
  def index
    redirect_to locale_root_path(locale: first_matching_language)
  end

private

  def first_matching_language
    accept_languages = request.env["HTTP_ACCEPT_LANGUAGE"].to_s.split(",").map { |l|
                          lang, q_factor = l.split(";q=")
                          [ lang, (q_factor || "1").to_f ]
                        }.sort_by { |_, q| -q }.map(&:first)

    available_languages = I18n.t("languages").keys.map(&:to_s)

    accept_languages.each do |lang|
      return lang if available_languages.include?(lang)

      lang_part = lang.split("-").first
      if available_languages.include?(lang_part)
        return lang_part
      else
        wildcard_match = available_languages.find { |l| l.start_with?("#{lang_part}-") }
        return wildcard_match if wildcard_match
      end
    end
    "en"
  end
end
