# frozen_string_literal: true

module Banzai
  module Filter
    # Using `[[_TOC_]]`, inserts a Table of Contents list.
    # This syntax is based on the Gollum syntax. This way we have
    # some consistency between with wiki and normal markdown.
    # If there ever emerges a markdown standard, we can implement
    # that here.
    #
    # The support for this has been removed from GollumTagsFilter
    #
    # Based on Banzai::Filter::GollumTagsFilter
    class TableOfContentsTagFilter < HTML::Pipeline::Filter
      TEXT_QUERY = %q(descendant-or-self::text()[ancestor::p and contains(., 'TOC')])

      def call
        return doc if context[:no_header_anchors]

        doc.xpath(TEXT_QUERY).each do |node|
          # A Gollum ToC tag is `[[_TOC_]]`, but due to MarkdownFilter running
          # before this one, it will be converted into `[[<em>TOC</em>]]`, so it
          # needs special-case handling
          process_toc_tag(node) if toc_tag?(node)
        end

        doc
      end

      private

      # Replace an entire `[[<em>TOC</em>]]` node with the result generated by
      # TableOfContentsFilter
      def process_toc_tag(node)
        node.parent.parent.replace(result[:toc].presence || '')
      end

      def toc_tag?(node)
        node.content == 'TOC' &&
          node.parent.name == 'em' &&
          node.parent.parent.text == '[[TOC]]'
      end
    end
  end
end
