class LanguagesController < ApplicationController

  before_action :set_locale_to_default, only: :index
  before_action :set_locale, only: :show
  before_action :set_node

  helper_method :accept_language

  def index

    not_found unless @node
  end


  def show
    @accept_language = params[:locale]

    not_found unless @node

    render :index
  end


  def update
    set_locale

    respond_to do |format|
      format.turbo_stream
    end
  end


private

  def set_node
    @node = Node.roots.viewable.first
  end

  def accept_language
    @accept_language ||= first_matching_language
  end


  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


  def set_locale_to_default
    I18n.locale = I18n.default_locale
  end

end
