module TabsHelper
  ##
  # Build a tab container in which to place tabs. Intended for use with a block using {#tab}.
  # @yield Yields to a block that may modify +@building_tabs+ to add tabs.
  # @return [ActiveSupport::SafeBuffer]
  def tabs
    @building_tabs = []
    yield
    tabs = @building_tabs.join("\n")
    @building_tabs = []
    tag.div raw(tabs), class: 'tabs'
  end

  ##
  # Build a tab and add it to the container generated by {#tabs}.
  # @param text [String] Link text.
  # @param link_url [String] Link URL.
  # @option opts :is_active [Boolean] Is the tab active?
  # @option opts :class [String] Additional classes to add to the tab.
  # @yieldreturn [ActiveSupport::SafeBuffer] Pass an optional block instead of +text+ and +link_url+ to customize the
  #   content of the tab link.
  # @return [Array<ActiveSupport::SafeBuffer>] The in-progress +@building_tabs+ array.
  def tab(text = nil, link_url = nil, **opts, &block)
    active = opts[:is_active] || false
    opts.delete :is_active
    opts[:class] = if opts[:class]
                     "#{opts[:class]} tabs--tab#{' tab__active' if active}"
                   else
                     "tabs--tab#{' tab__active' if active}"
                   end

    @building_tabs << if block_given?
                        link_to link_url, **opts, &block
                      else
                        link_to text, link_url, **opts
                      end
  end
end
