module NotesHelper
  def notes_preview(notes)
    NotePreview.new(self, notes).to_html
  end

  class NotePreview
    def initialize(view, notes)
      @view = view
      @notes = notes
    end

    def to_html
      return if notes.empty?

      safe_join [
        content,
        tag(:br),
        timestamp_with_author,
        link_to_additional_notes,
      ]
    end

    private

    attr_reader :view, :notes

    delegate :content_tag, :link_to, :mail_to, :pluralize, :safe_join, :tag, :time_ago_in_words, to: :view

    def first_note
      notes.first
    end

    def additional_notes
      notes.drop(1)
    end

    def content
      first_note.content
    end

    def link_to_additional_notes
      return if additional_notes.empty?

      badge = link_to([first_note.notable, :notes, locale: I18n.locale], remote: true, class: "badge badge-primary") do
        pluralize(additional_notes.size, "more note")
      end

      safe_join [
        tag(:br),
        badge,
      ]
    end

    def timestamp_with_author
      content_tag(:small) do
        safe_join [timestamp, author]
      end
    end

    def timestamp
      time_ago_in_words(first_note.created_at) + " ago "
    end

    def author_email
      first_note.email
    end

    def author
      safe_join ["(", mail_to(author_email), ")"]
    end
  end
end
