<!-- Recommend the other 3 posts according to the tags and categories of the current post. -->

<!-- The total size of related posts -->
{% assign TOTAL_SIZE = 3 %}

<!-- An random integer that bigger than 0 -->
{% assign TAG_SCORE = 1 %}

<!-- Equals to TAG_SCORE / {max_categories_hierarchy} -->
{% assign CATEGORY_SCORE = 0.5 %}

{% assign SEPARATOR = ':' %}

{% assign match_posts = '' | split: '' %}

{% for category in page.categories %}
  {% assign match_posts = match_posts | push: site.categories[category] | uniq %}
{% endfor %}

{% for tag in page.tags %}
  {% assign match_posts = match_posts | push: site.tags[tag] | uniq %}
{% endfor %}

{% assign last_index = match_posts.size | minus: 1 %}
{% assign score_list = '' | split: '' %}

{% for i in (0..last_index) %}
  {% assign post = match_posts[i] %}

  {% if post.url == page.url %}
    {% continue %}
  {% endif %}

  {% assign score = 0 %}

  {% for tag in post.tags %}
    {% if page.tags contains tag %}
      {% assign score = score | plus: TAG_SCORE %}
    {% endif %}
  {% endfor %}

  {% for category in post.categories %}
    {% if page.categories contains category %}
      {% assign score = score | plus: CATEGORY_SCORE %}
    {% endif %}
  {% endfor %}

  {% if score > 0 %}
    {% capture score_item %}{{ score }}{{ SEPARATOR }}{{ i }}{% endcapture %}
    {% assign score_list = score_list | push: score_item %}
  {% endif %}
{% endfor %}

{% assign index_list = '' | split: '' %}

{% if score_list.size > 0 %}
  {% assign score_list = score_list | sort | reverse %}
  {% for entry in score_list limit: TOTAL_SIZE %}
    {% assign index = entry | split: SEPARATOR | last %}
    {% assign index_list = index_list | push: index %}
  {% endfor %}
{% endif %}

{% assign relate_posts = '' | split: '' %}

{% for index in index_list %}
  {% assign i = index | to_integer %}
  {% assign relate_posts = relate_posts | push: match_posts[i] %}
{% endfor %}

{% if relate_posts.size > 0 %}
  <aside id="related-posts" aria-labelledby="related-label">
    <h3 class="mb-4" id="related-label">
      {{- site.data.locales[include.lang].post.relate_posts -}}
    </h3>
    <nav class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-4 mb-4">
      {% for post in relate_posts %}
        <article class="col">
          <a href="{{ post.url | relative_url }}" class="post-preview card h-100">
            <div class="card-body">
              {% include datetime.html date=post.date lang=include.lang %}
              <h4 class="pt-0 my-2">{{ post.title }}</h4>
              <div class="text-muted">
                <p>
                  {% include no-linenos.html content=post.content %}
                  {{ content | markdownify | strip_html | truncate: 200 | escape }}
                </p>
              </div>
            </div>
          </a>
        </article>
      {% endfor %}
    </nav>
  </aside>
  <!-- #related-posts -->
{% endif %}
