<script setup>
import { ref, nextTick, computed } from "vue";
import { useFormBuilderStore } from "../store";
import { t } from '@/shared/i18n';

let store = useFormBuilderStore();

const props = defineProps({
  text: {
    type: String,
  },
  placeholder: {
    default: "No Label",
  },
  emptyLabel: {
    default: "No Label",
  },
});

let editing = ref(false);
let inputText = ref(null);
let hiddenText = ref(null);
let hiddenPlaceholder = ref(null);

let hiddenSpanWidth = computed(() => {
  if (hiddenText.value && props.text) {
    return hiddenText.value.offsetWidth + 15 + "px";
  } else if (!props.text) {
    return hiddenPlaceholder.value?.offsetWidth + 15 + "px" || "100px";
  }
  return "40px";
});

function focusOnLabel() {
  if (!store.readOnly) {
    editing.value = true;
    nextTick(() => inputText.value?.focus());
  }
}

defineExpose({ focusOnLabel });
</script>

<template>
  <div @dblclick="focusOnLabel" :title="t('Double click to edit label')">
    <input
      v-if="editing"
      class="input-text"
      ref="inputText"
      :disabled="store.readOnly"
      type="text"
      :placeholder="placeholder"
      :value="text"
      :style="{ width: hiddenSpanWidth }"
      @input="(event) => $emit('update:modelValue', event.target.value)"
      @keydown.enter="editing = false"
      @blur="editing = false"
      @click.stop
    />
    <span v-else-if="text" v-html="text"></span>
    <i v-else class="text-muted">
      {{ emptyLabel }}
    </i>
    <span class="hidden-span" ref="hiddenText" v-html="text"></span>
    <span class="hidden-span" ref="hiddenPlaceholder">{{ placeholder }}</span>
  </div>
</template>

<style lang="scss" scoped>
.input-text {
  border: none;
  min-width: 50px;
  padding: 0px !important;
  background-color: transparent;
  font-size: inherit;
  font-weight: inherit;
  color: inherit;

  &:focus {
    outline: none;
    background-color: inherit;
  }

  &::placeholder {
    font-style: italic;
    font-weight: normal;
  }
}

.hidden-span {
  visibility: hidden;
  position: absolute;
  width: max-content;
}

.text-muted {
  color: #9ca3af;
}
</style>
