# frozen_string_literal: true

module ApplicationHelper
  include Pagy::Frontend

  def title(text)
    content_for :title, text
  end

  def default_image_url
    keyword = %w[food drink nature girl film tech cat].sample
    "https://source.unsplash.com/random/507x265?#{keyword}=#{Random.hex(4)}"
  end

  def disable_with_spinner(text)
    spinner = <<~SPINNER
      <svg class="animate-spin mr-1 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
    SPINNER
    [spinner, text].join.html_safe
  end

  def auth_provider_url(provider = :github)
    if params["chrome-callback"].present?
      "/auth/#{provider}?chrome-callback=#{params['chrome-callback']}"
    else
      "/auth/#{provider}"
    end
  end

  def render_twitter_share_link(article)
    base = "https://twitter.com/intent/tweet?text="
    base += CGI.escape([
        article.title.to_s,
        article.tags.map { |x| "##{x.name}" }.join(" "),
        article_url(article)
      ].join(" ")
    )
    base
  end

  def link_to_active(text, url, options = {})
    route = Rails.application.routes.recognize_path(url)
    if options[:class]
      if controller_name == route[:controller] || (route[:controller] == "bookmarks" && controller_name == "home")
        options[:class] = options[:class] << " bg-gray-900"
      else
        options[:class] = options[:class] << " hover:bg-gray-700"
      end
    end
    link_to text, url, options
  end

  def sortby_link_to_active(text, url, current = :smart, options = {})
    if options[:class]
      if (params[:sortby].to_s == current.to_s) || (params[:sortby].blank? && current.to_s == "smart")
        options[:class] = options[:class] << " bg-gray-200"
      end
    end
    link_to text, url, options
  end

  def sortby
    valid_sortbys.include?(params[:sortby]) ? params[:sortby] : "smart"
  end

  def valid_sortbys
    %w[daily weekly monthly smart all]
  end

  def ga_tracking_id
    ENV["GA_TRACKING_ID"] || "G-MB9NLQDB07"
  end

  def transport_url
    if Rails.env.development?
      "http://localhost:8000/c7f4edce-58c3-4917-8f18-a2ea6c1b93dc"
    else
      File.join(ENV["SERVER_URL"], "c7f4edce-58c3-4917-8f18-a2ea6c1b93dc")
    end
  end

  def tag_url_for(tag)
    link_to articles_path(request.query_parameters.except(:page).merge(tag: tag.name)), class: "btn-tag" do
      concat "#{tag.name}"
    end
  end

  if Rails.env.development?
    def t(*args, **options, &block)
      super(*args, **options.merge(raise: true), &block)
    end
  end

  def render_rss_icon(tag)
    icon = <<~ICON
      <svg class="h-4 w-4 text-indigo-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 5c7.18 0 13 5.82 13 13M6 11a7 7 0 017 7m-6 0a1 1 0 11-2 0 1 1 0 012 0z" />
      </svg>
    ICON
    icon.html_safe if tag.is_rss?
  end

  def feedback_link
    if I18n.locale == :'zh-CN'
      "https://pingcap.com"
    else
      "https://en.pingcap.com"
    end
  end

  def hack_pagy
    <<~HTML
      <nav class="pagy-nav pagination" role="navigation" aria-label="pager"><span class="page prev disabled">‹&nbsp;上一页</span> <span class="page active">1</span> <span class="page"><a href="/articles?page=2" rel="next">2</a></span> <span class="page"><a href="/articles?page=3">3</a></span> <span class="page next"><a href="/articles?page=2" rel="next" aria-label="next">下一页&nbsp;›</a></span></nav>
    HTML
  end

  def pretty_time(num)
    return "N/A" if num.nil?
    duration = ActiveSupport::Duration.build(num.to_i).parts
    { years: "Y",
      months: "M",
      weeks: "W",
      days: "D",
      hours: "h",
      minutes: "m",
      seconds: "s"
    }.map do |part, unit|
      duration.has_key?(part) ? "#{duration[part]}#{unit}" : nil
    end.compact.join(" ")
  end

  def pretty_num(num)
    number_to_human(num, format: "%n%u", units: { thousand: "K", million: "M", billion: "B" })
  end

  def time_range_names
    map = {
      "week"       => "Week",
      "month"      => "Month",
      "7d"         => "Last 7 days",
      "30d"        => "Last 30 days",
      "6m"         => "Last 6 months",
      "12m"        => "Last 12 months"
    }
    map.default = "Last 7 days"
    map
  end
end
