<template>
    <svg ref="counter" viewBox="0 0 16 9" class="o-counter" role="graphics-document document">
        <!-- The dx value is used to vertical align first text value on both rows, 0.75 multiply by longest text length  -->
        <text v-if="value1" x="50%" y="3.2">
            <tspan :class="{ 'js-counter-text': animation1 }" :dx="dxDiff()" font-size="3" text-anchor="middle"
                :data-duration="duration1" :data-count-to="value1">
                {{ begin1 }}
            </tspan>
            <tspan font-size="1" dx="0">{{ unit1 }}</tspan>
            <tspan v-if="year1" font-size="1" dx="0.5">{{ year1 }}</tspan>
        </text>
        <!-- second row -->
        <text v-if="value2" x="50%" y="7.2">
            <tspan :class="{ 'js-counter-text': animation2 }" :dx="dxDiff(value2)" font-size="3" text-anchor="middle"
                :data-duration="duration2" :data-count-to="value2">
                {{ begin2 }}
            </tspan>
            <tspan font-size="1" dx="0">{{ unit2 }}</tspan>
            <tspan v-if="year2" font-size="1" dx="0.5">{{ year2 }}</tspan>
        </text>
    </svg>
</template>

<script setup lang="ts">
import type Counter from './counter';
import { onMounted, onUnmounted, ref } from 'vue';

const props = withDefaults(defineProps<{
    value1?: number;
    value2?: number;
    begin1?: number;
    begin2?: number;
    unit1?: string;
    unit2?: string;
    year1?: number;
    year2?: number;
    duration1?: number;
    duration2?: number;
    animation1?: boolean;
    animation2?: boolean;
}>(),
    {
        begin1: 0,
        begin2: 0,
    }
);

// if animation is false, set begin to value
const begin1 = props.animation1 ? props.begin1 : props.value1;
const begin2 = props.animation2 ? props.begin2 : props.value2;
const counter = ref();

if (props.animation1 || props.animation2) {
    let instance: Counter | null;

    onMounted(async () => {
        // if animation is true, import counter script
        instance = await import('./counter').then(({ default: Counter }) => new Counter(counter.value));
    });

    onUnmounted(() => {
        instance?.destroy();
    })
}

// Verticaly align text values, the shortest text needs to be moved to the right. (longest text length * 0.75)
const dxDiff = (value = props.value1 as number) => {
    // if there is only one value, return 0
    if (isNaN(props.value1 as number) || isNaN(props.value2 as number) || isNaN(value as number)) {
        return 0;
    }
    const value1Length = value.toString().length;
    const value2Length = (value === props.value1 ? props.value2 as number : props.value1 as number).toString().length;
    // if both values are the same length or shorter, return 0
    if (value1Length >= value2Length) {
        return 0;
    }
    const diff = value2Length - value1Length;
    return diff * 0.75;
};



</script>