<template>
  <div
      v-if="!hideDetails"
      class="nv-field-details"
      :class="[...sizeableClasses]"
  >
    <ul class="nv-field-details--messages">
      <li v-if="hint && (!messagesList.length || persistentHint)" v-text="hint"/>
      <li
          v-for="(message, idx) in messagesList"
          :key="idx"
          :class="`${message.class}`"
          v-text="message.text"
      />
    </ul>
    <div
        v-if="counter"
        class="nv-field-details--counter"
        :class="{ 'text-alert' : counterError }"
        v-text="counterText"
    />
  </div>
</template>

<script>
import {computed} from "vue";
import {useFieldDetailsProps} from "../../composables/fieldDetails";
import useSize, {useSizeProps} from "../../composables/sizeable";

export default {
  name: "NvFieldDetails",
  props: {
    ...useFieldDetailsProps,
    ...useSizeProps
  },
  setup(props) {
    // Size
    const {sizeableClasses} = useSize(props);

    // Messages
    const messagesList = computed(() => {
      let messagesError = props.messagesError;
      messagesError.length = Math.min(messagesError.length, props.errorCount);

      let messagesSuccess = props.messagesSuccess;
      messagesSuccess.length = Math.min(
          messagesError.length ? 0 : messagesSuccess.length,
          props.successCount
      );

      messagesError = messagesError.map((m) => ({
        text: m,
        class: "text-alert",
      }));
      messagesSuccess = messagesSuccess.map((m) => ({
        text: m,
        class: "text-success",
      }));
      return [...messagesError, ...messagesSuccess];
    });

    const counterError = computed(() => props.counter === true ? false : props.counterCompare ? props.counterCompare === '>' ? props.counterValue > props.counter : props.counterValue < props.counter : false)
    // const counterText = computed(() => props.counter === true ? props.counterValue : props.counterValue !== undefined ? `${props.counterValue}/${props.counter}` : '')
    const counterText = computed(() => {
          if (props.counter) {
            return props.counter === true ? props.counterValue !== undefined ? props.counterValue : '' : props.counterValue !== undefined ? `${props.counterValue}/${props.counter}` : props.counter
          } else {
            return props.counterValue !== undefined ? props.counterValue : ''
          }
        }
    )

    return {
      messagesList,
      sizeableClasses,
      counterError,
      counterText
    }
  }
}
</script>
