{% from "nhsuk/macros/attributes.njk" import nhsukAttributes %}

{#- Set classes for this component #}
{%- set classNames = "nhsuk-link" -%}

{#- Support heading as string #}
{%- set heading = parent.params.heading if parent.params.heading is mapping and parent.params.heading is not escaped else {
  text: parent.params.heading if parent.params.heading is string else undefined,
  html: parent.params.heading if parent.params.heading is escaped else undefined
} -%}

{%- if params.classes %}
  {% set classNames = classNames ~ " " ~ params.classes %}
{% endif %}

{#- Determine type of element to use, if not explicitly set #}
{%- if params.href and not params.type %}
  {% set element = "a" %}
{% else %}
  {% set element = "button" %}
{% endif %}

{%- set attributesHtml %}
  {{- nhsukAttributes({
    class: classNames,
    id: {
      value: params.id,
      optional: true
    }
  }) -}}

  {% if element == "button" %}
    {{- nhsukAttributes({
      name: {
        value: params.name,
        optional: true
      },
      type: params.type | default("submit"),
      value: {
        value: params.value,
        optional: true
      }
    }) -}}
  {% elif element == "a" %}
    {{- nhsukAttributes({
      href: params.href | default("#")
    }) -}}
  {% endif %}

  {{- nhsukAttributes(params.attributes) -}}
{% endset -%}

<{{ element }} {{- attributesHtml | safe }}>
  {%- if params.html -%}
    {{- params.html | safe | trim | indent(2) -}}
  {%- elif params.text -%}
    {{- params.text | trim | indent(2) -}}
  {%- endif -%}
  {%- if params.visuallyHiddenText or heading.text or heading.html -%}
  <span class="nhsuk-u-visually-hidden">
    {%- if params.visuallyHiddenText %} {{ params.visuallyHiddenText }}{% endif -%}
    {%- if heading.text or heading.html %} ({{ heading.html | safe if heading.html else heading.text }}){% endif -%}
  </span>
  {%- endif -%}
</{{ element }}>
