module ExpansionHelper
  def expand_section(name)
    Section.new(self, name).expand
  end

  def section_expanded?(name)
    Section.new(self, name).expanded?
  end

  def within_section(name)
    Section.new(self, name).within_me do
      yield
    end
  end

  class Section
    attr_reader :context, :name

    def initialize(context, name)
      @context = context
      @name = name
    end

    def expand
      return if expanded?

      if element[:class].include? "collapse"
        trigger.click
      end
    end

    def expanded?
      element[:class].include? "show"
    end

    def within_me
      within "##{name}" do
        yield
      end
    end

    private

    delegate :find, :within, to: :context

    def element
      find("##{name}", visible: :all)
    end

    def trigger
      find("[data-target=\"##{name}\"]", visible: :all)
    end
  end
end

RSpec.configure do |config|
  config.include ExpansionHelper
end
