<!-- Display post keywords -->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import Message from '../base/Message.vue';
import { useWindowSize } from '@vueuse/core';

// Props
const props = defineProps<{
    keywords: string[];
}>();

// Post keywords
const keywords = ref(props.keywords);

// Keywords container
const keywordsContainer = ref<HTMLElement>(null);

// Computed trigger
const trigger = ref(0);

// Get visible keywords
const visibleKeywords = computed(() => {
	// Trigger reactivity
	trigger.value;

	// Return all keywords if container is not available
	if (!keywordsContainer.value) return keywords.value;

    // Get container width and keyword elements
    const containerWidth = keywordsContainer.value.offsetWidth;
    const keywordElements = Array.from(keywordsContainer.value.children);

    // Calculate visible keywords
    let totalWidth = 0;
    let visibleCount = 0;

    // Calculate amount of visible keywords
    for (const el of keywordElements) {
        totalWidth += (el as HTMLElement).offsetWidth + 6;

		// Check the width with additional space for hidden keyword count
        if (totalWidth + 40 > containerWidth) break;
        visibleCount++;
    }

    // Return only visible keywords
    return keywords.value.slice(0, visibleCount);
});

// Get hidden keyword count
const hiddenKeywordCount = computed(() => keywords.value.length - visibleKeywords.value.length);

// Update hidden keywords on window resize
const { width, height } = useWindowSize();

watch([width, height], () => {
	trigger.value++;
});
</script>

<template>
    <div class="flex gap-1.5 flex-wrap" ref="keywordsContainer" >
		<!-- Keywords -->
        <Message
            v-for="(keyword, i) in visibleKeywords"
            :key="i"
            :message="keyword"
            type="neutral"
            :show-icon="false"
        />

		<!--  Hidden keywords count -->
		<Message
            v-if="hiddenKeywordCount > 0"
            :message="`+${hiddenKeywordCount}`"
            type="neutral"
            :show-icon="false"
        />
    </div>
</template>

<style scoped></style>
