{{ $is_list := .is_list }}
{{ $page := .page }}

{{/* Build normalized links (new API) */}}
{{ $built := partial "functions/build_links" (dict "page" $page "is_list" $is_list) }}

{{ $ctx := cond $is_list "list" "page" }}

{{/* English fallbacks if i18n key is missing in a locale */}}
{{ $fallbackByKey := dict
  "btn_pdf" "PDF"
  "btn_preprint" "Preprint"
  "btn_doi" "DOI"
  "btn_code" "Code"
  "btn_dataset" "Dataset"
  "btn_model" "Model"
  "btn_slides" "Slides"
  "btn_video" "Video"
  "btn_poster" "Poster"
  "btn_project" "Project"
  "btn_site" "Site"
  "btn_source" "Source Document"
  "btn_canonical" "Canonical"
  "btn_crosspost" "Crosspost"
  "btn_discussion" "Discussion"
  "btn_event" "Event"
  "btn_calendar" "Calendar"
  "btn_registration" "Registration"
  "btn_demo" "Demo"
  "btn_cite" "Cite"
}} 

{{ range $built }}
  {{ if in .contexts $ctx }}
    {{ $url := .url | default "" }}
    {{ $scheme := (urls.Parse $url).Scheme }}
    {{ $target := "" }}
    {{ $rel := slice }}
    {{ with .rel }}{{ $rel = . }}{{ end }}
    {{ if not $scheme }}
      {{ with ($page.Resources.GetMatch $url) }}
        {{ $url = .RelPermalink }}
      {{ else }}
        {{ $url = $url | relURL }}
      {{ end }}
    {{ else if in (slice "http" "https") $scheme }}
      {{ $target = "target=\"_blank\"" }}
      {{ $rel = $rel | append "noopener" }}
    {{ end }}

    {{ $classes := printf "hb-attachment-link %s" (cond $is_list "hb-attachment-link-small" "hb-attachment-link-large") }}
    {{ $label := .label }}
    {{ with .labelKey }}
      {{ if not $label }}
        {{ $label = (i18n .) | default (index $fallbackByKey .) | default "Link" }}
      {{ end }}
    {{ end }}
    {{ if not $label }}
      {{ $label = "Link" }}
    {{ end }}

    {{ if eq .type "bibtex" }}
      <button class="{{ $classes }} js-cite-clipboard cursor-pointer" type="button" data-filename="{{ $url }}">
        {{ partial "functions/get_icon" (dict "name" (.icon | default "hero/document-duplicate") "attributes" "style=\"height: 1em\" class='inline-block'") }}
        <span>{{ $label }}</span>
      </button>
    {{ else }}
      <a class="{{ $classes }}" href="{{ $url | safeURL }}" {{ $target | safeHTMLAttr }} {{ with $rel }}rel="{{ delimit . " " }}"{{ end }}>
        {{ partial "functions/get_icon" (dict "name" (.icon | default "hero/link") "attributes" "style=\"height: 1em\" class='inline-block'") }}
        {{ $label }}
      </a>
    {{ end }}
  {{ end }}
{{ end }}
