module SiteHelper

  def frontend_javascript_importmap_tags
    only_use = %w"application @hotwired/turbo-rails"
    importmap_json = JSON.parse(Rails.application.importmap.to_json(resolver: self))['imports'].select{ |k,v| only_use.include?(k)}
    safe_join [
          javascript_inline_importmap_tag(JSON.pretty_generate({ "imports" => importmap_json})),
          javascript_module_preload_tag(*importmap_json.map{|v| v[1]}),
          javascript_import_module_tag('application')
        ], "\n"
  end


  def node_title(node)
    parts = [node.page_title.blank? ? node.title : node.page_title ]
    parts << t(:client_name)
    parts.uniq.join(' - ')
  rescue
    t(:client_name)
  end


  def random_value(from, to)
    range = rand(2) == 0 ? (-to..-from) : (from..to)
    rand(range)
  end


  def parse_article_html(html)
    result = {}
    return result if html.blank?

    doc = Nokogiri::HTML.fragment(html, 'utf-8')

    first_link = doc.at_css('a')
    first_link.remove if first_link

    result[:title] = doc.at_css('h1')&.text
    result[:description] = doc.at_css('div')&.text
    result[:link] = first_link&.to_html

    doc.search('*').each do |node|
      while node.children.last and node.children.last.name == 'br'
        node.children.last.remove
      end
    end

    result[:html] = doc.to_html

    result
  end

end
