# frozen_string_literal: true

module PagesHelper
  include ApplicationHelper

  def print_contributors(contributors)
    contributors.map do |c|
      if c.is_a?(Hash) && c['name'].is_a?(String) && c['link'].is_a?(String)
        link_to c['name'], c['link'], target: 'blank'
      end
    end.to_sentence.html_safe
  end

  def print_partners(data)
    html = ''
    data.each do |d|
      break unless valid_hash?('partners', d)

      image = image_tag(d['image_link'], alt: d['name'])
      link = link_to(image, d['link'], target: 'blank')
      html += content_tag(:div, link, class: 'partner')
    end
    html.html_safe
  end

  def home_data_json
    {
      data: moments_or_strategy_props(@stories),
      lastPage: @stories.last_page?
    }
  end

  def setup_stories
    @stories = Kaminari.paginate_array(get_stories(current_user, true))
                       .page(params[:page])
    @stories&.select! do |story|
      current_user.id == story.user_id ||
        (
          (story.viewers.include?(current_user.id) &&
          current_user.mutual_allies?(User.find_by(id: story.user_id)))
        )
    end
  end

  private

  def valid_hash?(data_type, data)
    basic_check = data.is_a?(Hash) && data['name'].is_a?(String) &&
                  data['link'].is_a?(String)
    return false unless basic_check

    valid_data_type?(data_type, data)
  end

  def valid_data_type?(data_type, data)
    data['image_link'].is_a?(String) if data_type == 'partners'
  end
end
