<template>
  <component
      :is="componentTag"
      :href="href"
      :to="to"
      :disabled="computedDisabled"
      class="nv-btn"
      :class="[
      ...sizeableClasses,
      colorClass,
      {
        'nv-btn--outlined': outlined,
        'nv-btn--loading': loading,
        'nv-btn--icon': icon && emptyDefaultSlot && !iconRight,
        'nv-btn--icon-left': icon && !emptyDefaultSlot,
        'nv-btn--icon-right': iconRight,
        'nv-btn--default': !color,
      },
    ]"
  >
    <NvIcon v-if="icon" :icon="icon"/>
    <span v-if="!emptyDefaultSlot"><slot/></span>
    <NvIcon v-if="iconRight" :icon="iconRight"/>
  </component>
</template>

<script>
import useSize, {useSizeProps} from "../../composables/sizeable";
import {isEmptySlot} from "../../composables/slot";
import {computed, inject} from "vue";

const BTN_COLORS = ["primary", "dark"];

export default {
  props: {
    ...useSizeProps,
    loading: Boolean,
    outlined: Boolean,
    icon: String,
    iconRight: String,
    color: {
      type: String,
      validator: (value) => ["primary", "dark"].includes(value),
    },
    disabled: Boolean,
    to: String,
    href: String,
    tag: {
      type: String,
      default: "button",
    },
    nuxt: Boolean,
  },
  setup(props, {slots}) {
    //---- Tag
    const componentTag = computed(() => {
      return props.href
          ? "a"
          : props.to
              ? props.nuxt
                  ? "nuxt-link"
                  : "router-link"
              : props.tag;
    });

    //---- Size
    const {sizeableClasses} = useSize(props);

    const parentDisabled = inject("parentDisabled", undefined);
    const computedDisabled = computed(() => parentDisabled || props.disabled);
    //---- Color
    const colorClass = BTN_COLORS.includes(props.color)
        ? `nv-btn--${props.color}`
        : "nv-btn--default";

    const emptyDefaultSlot = slots.default ? isEmptySlot(slots.default) : true;

    return {
      colorClass,
      componentTag,
      computedDisabled,
      sizeableClasses,
      emptyDefaultSlot
    };
  },
};
</script>
