<template>
    <div class="input-group input-group-sm w-auto">
        <span class="input-group-text">/</span>
        <input
            v-model="rawPronunciation"
            class="form-control mw-input"
            :placeholder="$t('profile.pronunciation.ipa')"
            maxlength="255"
        >
        <span class="input-group-text">/</span>
        <PronunciationSpeaker
            v-for="voice in voices"
            :key="voice"
            class="btn btn-outline-secondary"
            :pronunciation="value"
            :voice="voice"
        />
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import type { PropType } from 'vue';

import { escapePronunciationString, unescapePronunciationString } from '../src/helpers.ts';
import useConfig from '../composables/useConfig.ts';

export default defineComponent({
    props: {
        value: { default: null, type: String as PropType<string | null> },
    },
    setup() {
        return {
            config: useConfig(),
        };
    },
    computed: {
        rawPronunciation: {
            get(): string {
                if (this.value) {
                    const phonemes = this.value.substring(1, this.value.length - 1);
                    return unescapePronunciationString(phonemes);
                } else {
                    return '';
                }
            },
            set(rawPronunciation: string) {
                let pronunciation;
                if (rawPronunciation) {
                    pronunciation = `/${escapePronunciationString(rawPronunciation)}/`;
                } else {
                    pronunciation = null;
                }

                this.$emit('input', pronunciation);
            },
        },
        voices(): string[] {
            if (this.config.pronunciation?.enabled) {
                return Object.keys(this.config.pronunciation.voices);
            } else {
                return [];
            }
        },
    },
});
</script>
