Counting of monthly posts

I have a little problem with Hugo, I want to make an archive on the blog, which shows how many articles have been written in a given month.

The goal is to make it look like the right picture.
Here, what I’ve figured out, but as you can see in the left picture, is not quite as it should be, I need your advice/help.

<ul class="years">
    {{ range where .Site.Pages "Section" "year" }}
    {{ $years := .Date.Format "2006" }}
        <li>
        <a href="{{ .Permalink }}">{{ $years }}</a>

        <ul class="months">
            {{ $counter := 1 }}
            {{ $arr := (slice) }}

            {{ range .Site.RegularPages }}
                {{ $year := .Date.Format "2006" }}
                {{ $month := .Date.Format "01" }}
                {{ $date := string (.Date.Format "2006-01")}}
    
                {{ if in $arr $date }}
                    <!-- A -->
                    {{ $counter = add $counter 1 }}
                    {{ $arr = union $arr ( slice $date ) }}
                {{ else }}
                    <!-- B -->
                    {{ $counter = 1 }}
                    {{ $arr = (slice $date) }}
                {{ end }}

                {{ if eq $years $year }}
                    <li>
                    <a href="/archive/{{ $year }}/{{ $month }}/">
                        {{ .Date.Format "January" }} (Posts: {{ $counter }})
                    </a>
                    </li>
                {{ end }}

            {{ end }}
        </ul>

        </li>
    {{ end }}
</ul>

You can group by date by year, then by month: https://gohugo.io/templates/lists#by-date-1

Untested, but something like

{{ range .Pages.GroupByDate "2006" }}
<h3>{{ .Key }}</h3>
<ul>
    {{ range .Pages.GroupByDate "2006-01" }}
    <li>
      {{ .Key }} {{ len .Pages }}
    </li>
    {{ end }}
</ul>
{{ end }}