{{- $topics := .topics -}}
{{- $limit := default 3 .limit -}}
{{- $currentPath := .page.RelPermalink -}}

{{- $related := where (where site.RegularPages "Type" "interviews") "RelPermalink" "!=" $currentPath -}}
{{- $matchingInterviews := slice -}}

{{/* First try to find interviews with matching topics */}}
{{- range $related -}}
    {{- $matches := 0 -}}
    {{- range .Params.topics -}}
        {{- if in $topics . -}}
            {{- $matches = add $matches 1 -}}
        {{- end -}}
    {{- end -}}
    {{- if gt $matches 0 -}}
        {{- $matchingInterviews = $matchingInterviews | append (dict "page" . "matches" $matches) -}}
    {{- end -}}
{{- end -}}

{{/* If we found matching interviews, sort by number of matching topics */}}
{{- $finalInterviews := slice -}}
{{- if gt (len $matchingInterviews) 0 -}}
    {{- $finalInterviews = first $limit (sort $matchingInterviews "matches" "desc") -}}
{{- else -}}
    {{/* Fallback to showing other interviews sorted by date */}}
    {{- $finalInterviews = first $limit (sort $related "Date" "desc") -}}
{{- end -}}

{{- if gt (len $finalInterviews) 0 -}}
<div class="related-interviews flex flex-wrap gap-4">
    <h2 class="title text-3xl font-bold">Related Interviews</h2>
    <div class="wompum-container wompum-container--no-gap">
        <div class="wompum-grid" data-text="Related Interviews" data-columns="8" data-rows="1"></div>
    </div>
    <ul class="flex flex-col gap-4 w-full">
      {{ partial "interview-list" (dict "Pages" $finalInterviews) }}
    </ul>
</div>
{{- end -}}
