# Adds lazy loading and async decoding to rendered <img> tags in HTML output.
# This keeps the UI unchanged while improving Lighthouse performance and best practices.

module Jekyll
  module LazyImageAttributes
    def self.add_lazy_loading(html)
      return html unless html.is_a?(String)

      # Add both attributes when both are missing.
      html = html.gsub(/<img(?![^>]*\bloading=)(?![^>]*\bdecoding=)([^>]*?)>/i) do |match|
        "<img loading=\"lazy\" decoding=\"async\"#{Regexp.last_match(1)}>"
      end

      # Add loading if only loading is missing.
      html = html.gsub(/<img(?![^>]*\bloading=)([^>]*?)>/i) do |match|
        "<img loading=\"lazy\"#{Regexp.last_match(1)}>"
      end

      # Add decoding if only decoding is missing.
      html = html.gsub(/<img(?![^>]*\bdecoding=)([^>]*?)>/i) do |match|
        "<img decoding=\"async\"#{Regexp.last_match(1)}>"
      end

      html
    end
  end

  Jekyll::Hooks.register [:pages, :documents], :post_render do |doc|
    next unless doc.output_ext == '.html'
    doc.output = LazyImageAttributes.add_lazy_loading(doc.output)
  end
end
