<template>
    <div class="bm-token-picker">
        <button
            type="button"
            class="bm-token-picker__btn"
            @click="open = !open"
        >Token ▾</button>
        <ul v-if="open" class="bm-token-picker__list">
            <li
                v-for="token in filteredTokens"
                :key="token.name"
                class="bm-token-picker__item"
                @click="pick(token)"
            >
                <span class="bm-token-picker__name">{{ token.name }}</span>
                <span
                    v-if="token.type === 'color'"
                    class="bm-token-picker__swatch"
                    :style="{ background: token.value }"
                ></span>
                <span class="bm-token-picker__value">{{ token.value }}</span>
            </li>
            <li v-if="filteredTokens.length === 0" class="bm-token-picker__empty">
                No tokens of type {{ tokenTypes.join('/') }}.
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    name: 'TokenPicker',
    props: {
        tokens:     { type: Array, required: true },
        tokenTypes: { type: Array, default: () => [] },
    },
    data() {
        return { open: false };
    },
    computed: {
        filteredTokens() {
            if (this.tokenTypes.length === 0) return this.tokens;
            return this.tokens.filter((t) => this.tokenTypes.includes(t.type));
        },
    },
    methods: {
        pick(token) {
            this.open = false;
            this.$emit('pick', token.name);
        },
    },
};
</script>
