module PageflowScrolled
  # @api private
  module ReactServerSideRenderingHelper
    include Pageflow::RenderJsonHelper
    include PageflowScrolled::EntryJsonSeedHelper

    def render_scrolled_entry(entry)
      seed_json = render_json do |json|
        scrolled_entry_json_seed(json, entry)
      end

      ReactServerSideRenderingHelper.renderer.render('Root', "{seed: #{seed_json}}", {})
    end

    def self.renderer
      @renderer ||=
        ReactRenderer
        .new(files: ['pageflow-scrolled-server.js'],
             # Define required external globals.
             code: 'function videojs() {};')
    end

    # Normally react-rails either tries to auto detect which asset
    # container (i.e. Webpack, Sprockets) to use or relies on an app
    # wide configuration. Specify it explicitly to decouple Pageflow
    # Scrolled from host application configuration.
    class ReactRenderer < ::React::ServerRendering::BundleRenderer
      def asset_container_class
        ::React::ServerRendering::WebpackerManifestContainer
      end
    end
  end
end

module PageflowScrolled
  # @api private
  module ReactServerSideRenderingHelper
    include Pageflow::RenderJsonHelper
    include PageflowScrolled::EntryJsonSeedHelper

    def render_scrolled_entry(entry)
      seed_json = render_json do |json|
        scrolled_entry_json_seed(json, entry)
      end

      ReactServerSideRenderingHelper.renderer.render('Root', "{seed: #{seed_json}}", {})
    end

    def self.renderer
      if Rails.env.development?
        ReactServerSideRenderingHelper.new_renderer
      else
        @renderer ||= ReactServerSideRenderingHelper.new_renderer
      end
    end

    # Normally react-rails either tries to auto detect which asset
    # container (i.e. Webpack, Sprockets) to use or relies on an app
    # wide configuration. Specify it explicitly to decouple Pageflow
    # Scrolled from host application configuration.
    class ReactRenderer < ::React::ServerRendering::BundleRenderer
      def asset_container_class
        ::React::ServerRendering::WebpackerManifestContainer
      end
    end

    def self.new_renderer
      ReactRenderer
        .new(files: ['pageflow-scrolled-server.js'],
             # Define required external globals.
             code: 'function videojs() {};')
    end
  end
end

Remove renderer memoization in development
Remove renderer memoization in development

Having to restart the Rails server to synchronize server- and
client-side JS introduces an additional error source in many
development scenarios that otherwise don't have anything to do with
the SSR/CSR distinction.

To avoid this, we only memoize the renderer in environments that
aren't development.

REDMINE-18013
