{% from '@bonniernews/dn-design-system-web/components/icon-sprite/icon-sprite.njk' import IconUse %}
{% from '@bonniernews/dn-design-system-web/components/spinner/spinner.njk' import Spinner %}
{% from '@bonniernews/dn-design-system-web/njk-helpers/attributes.njk' import getAttributes %}

{% macro TextButton(params) %}
  {%- set componentClassName = "ds-text-btn" %}
  {%- set classNamePrefix = componentClassName + "--" %}

  {%- if params.iconName and params.iconPosition and params.iconPosition != "none" %}
    {% set iconSvg = IconUse({ icon: params.iconName, attributes: { "aria-hidden": "true" } }) %}
  {% endif %}

  {%- set classes = [
    componentClassName,
    "ds-force-px" if params.forcePx,
    "ds-loading" if params.loading,
    classNamePrefix + params.size if params.size and params.size !== "default",
    classNamePrefix + "full-width" if params.fullWidth,
    classNamePrefix + "mobile-full-width" if params.mobile and params.mobile.fullwWidth,
    classNamePrefix + "icon-" + params.iconPosition if iconSvg,
    classNamePrefix + "icon-only-mobile" if params.hideTextOnMobile,
    params.classNames if params.classNames
  ] | join(" ") %}
  {%- set text = params.text %}
  {%- set attributes = getAttributes(params.attributes) %}
  {%- set ariaLabel = 'aria-label="' + text + '"' if not params.attributes["aria-label"] else "" %}

  {%- set loadingHtml %}
    {% if (params.size == 'small') %}
      {{ Spinner({ size: "xsmall", variant: "primary", forcePx: params.forcePx, attributes: { "aria-hidden": "true" } }) }}
    {% else %}
      {{ Spinner({ size: "small", variant: "primary", forcePx: params.forcePx, attributes: { "aria-hidden": "true" } }) }}
    {% endif %}
  {% endset %}

  {%- if params.href %}
    <a href="{{ params.href | default('#', true) }}" {{ ariaLabel | safe }} class="{{ classes }}" {{- attributes | safe }}>
      <span class="ds-text-btn__text" aria-hidden="true">{{ text }}</span>
      {{- iconSvg | safe if iconSvg -}} {{ loadingHtml | safe }}
    </a>
  {%- else %}
    <button type="{{ params.type | default('button') }}" {{ ariaLabel | safe }} class="{{ classes }}" {{ "disabled" if params.disabled }} {{- attributes | safe }}>
      <span class="ds-text-btn__text" aria-hidden="true">{{ text }}</span>
      {{- iconSvg | safe if iconSvg -}} {{ loadingHtml | safe }}
    </button>
  {% endif %}
{% endmacro %}
