<template>
    <div class="bm-token-value">
        <!-- Token-bound mode -->
        <div v-if="boundToken" class="bm-token-value__token-display">
            <code>{{ boundToken }}</code>
            <button type="button" class="bm-token-value__clear" @click="clear">×</button>
        </div>

        <!-- Raw value mode -->
        <template v-else>
            <select
                v-if="isSelect"
                class="bm-token-value__select"
                :value="rawValue"
                @change="setRaw($event.target.value)"
            >
                <option value="">—</option>
                <option v-for="opt in options" :key="opt" :value="opt">{{ opt }}</option>
            </select>
            <input
                v-else
                type="text"
                class="bm-token-value__input"
                :placeholder="placeholder"
                :value="rawValue"
                @input="setRaw($event.target.value)"
            />
        </template>

        <TokenPicker
            v-if="tokenTypes.length"
            :tokens="tokens"
            :token-types="tokenTypes"
            @pick="setToken"
        />
    </div>
</template>

<script>
import TokenPicker from './TokenPicker.vue';

export default {
    name: 'TokenValueInput',
    components: { TokenPicker },
    props: {
        value:      { type: Object, default: () => ({}) },
        tokens:     { type: Array, required: true },
        tokenTypes: { type: Array, default: () => [] },
        input:      { type: String, default: 'text' },
        options:    { type: Array, default: () => [] },
    },
    computed: {
        boundToken() { return this.value && this.value.token ? this.value.token : null; },
        rawValue()   { return this.value && this.value.raw !== undefined ? this.value.raw : ''; },
        isSelect()   { return this.input === 'select' && this.options.length > 0; },
        placeholder() {
            if (this.input.startsWith('length')) return 'e.g. 16px';
            if (this.input.startsWith('color'))  return 'e.g. #0f55c4';
            return '';
        },
    },
    methods: {
        setRaw(v) {
            if (v === '' || v === null) this.$emit('input', null);
            else this.$emit('input', { raw: v });
        },
        setToken(name) { this.$emit('input', { token: name }); },
        clear()        { this.$emit('input', null); },
    },
};
</script>
