<template>
  <div class="submission-form__text-answer submission-form">
    <textarea
      :placeholder="placeholder"
      :readonly="readonly"
      v-model="editText"
      :class="{ 'submission-form__textarea--readonly': readonly }"
      data-cy="submission-textarea"
      rows="1"
      class="borderless-textarea"
      v-auto-grow
      @input="input"
    />
    <div
      class="submission-form__save-status submission-form__save-status--saved"
      v-if="saved"
    >
      <tick-circle-icon class="submission-form__save-status-icon" />
    </div>
    <div
      class="submission-form__save-status submission-form__save-status--unsaved"
      v-if="!saved"
    >
      <loading-icon class="submission-form__save-status-icon submission-form__saving-icon" />
    </div>


  </div>
</template>

<script setup lang="ts">
  import {defineAsyncComponent, ref, watch} from 'vue';
  import EmojiBar from "@/components/ui/EmojiBar.vue";
const TickCircleIcon = defineAsyncComponent(() => import('@/components/icons/TickCircleIcon.vue'));
const LoadingIcon = defineAsyncComponent(() => import('@/components/icons/LoadingIcon.vue'));

interface Props {
  inputText: string;
  saved: boolean;
  readonly: boolean;
  placeholder: string;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: 'Ergebnis erfassen',
});

const editText = ref(props.inputText)

const emit = defineEmits(['input']);

const  containsEmoji = (text: String) =>{
  const emojis= ['🖐️', '👍', '👎', '👏', '👋', '🎉', '😍', '😮', '🤔']
  const graphemes = Array.from(text);
  const lastGrapheme = graphemes[graphemes.length - 1];
  return emojis.includes(lastGrapheme);
}

watch(() => props.inputText, (newValue) => {
  // TODO: Lorenz this is an ugly fix!
  if (containsEmoji(newValue)){
      editText.value = newValue;
  }
});


const input = (e: Event) => {
  const value = (e.target as HTMLInputElement).value;
  emit('input', value);
};
</script>

<style scoped lang="scss">
@import 'styles/helpers';

.submission-form {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  &__save-status {
    position: relative;
    align-items: center;
  }

  &__save-status-icon {
    width: 22px;
    height: 22px;
    fill: $color-silver-dark;
  }

  &__saving-icon {
    @include spin;
  }
}
</style>
