<script setup lang="ts">
import { computed, ref, useTemplateRef, watch } from 'vue';
import NumericText from '@/components/NumericText.vue';

defineProps<{
    x: number;
    y: number;
    value: number;
}>();

const background_offset = computed(() => 5);
const y_offset = computed(() => 9);

const labelRef = useTemplateRef<SVGTextElement>('label-ref');

const value_text = ref('');
const label_width = ref(0);

watch(
    [value_text, labelRef],
    ([, label]) => {
        label_width.value = label?.getBBox().width || 0;
    },
    {
        flush: 'post',
    },
);

function update_value_text(text: string) {
    value_text.value = text;
}
</script>

<template>
    <rect
        :x="x - background_offset"
        :y="y - y_offset - background_offset"
        :width="label_width + background_offset * 2"
        :height="16 + background_offset * 2"
    ></rect>
    <text ref="label-ref" :x="x" :y="y">
        <NumericText
            :value="value"
            :max_width="6"
            @update="update_value_text"
        ></NumericText>
    </text>
</template>

<style scoped lang="scss">
@use '@/assets/variables';

rect {
    fill: variables.$background-color;
    stroke-width: 1px;
    stroke: var(--indexed-color);
}

text {
    font-family: variables.$text-font;
    text-anchor: start;
    stroke: var(--indexed-color);
    fill: var(--indexed-color);
    dominant-baseline: middle;
}
</style>
