<script setup lang="ts">
import type { Example, ExampleValues } from '#shared/language/examples.ts';
import type { MorphemeValue } from '#shared/language/morphemes.ts';

const props = withDefaults(defineProps<{
    morpheme: string;
    exampleValues: ExampleValues;
    prefix?: MorphemeValue;
    suffix?: MorphemeValue;
    highlightsMorphemes?: Set<string>;
    examples?: Example[];
}>(), {
    highlightsMorphemes: (props) => {
        return new Set([props.morpheme]);
    },
});

const spelling = computed(() => {
    const spelling = props.exampleValues.morphemeValues.getSpelling(props.morpheme);
    if (spelling === undefined) {
        return undefined;
    }
    return (props.prefix?.spelling ?? '') + spelling + (props.suffix?.spelling ?? '');
});

const pronunciation = computed(() => {
    const pronunciation = props.exampleValues.morphemeValues.getPronunciation(props.morpheme);
    if (!pronunciation || pronunciation.startsWith('=')) {
        return undefined;
    }
    return `/${props.prefix?.pronunciation ?? ''}${pronunciation}${props.suffix?.pronunciation ?? ''}/`;
});

const visibleExamples = computed(() => {
    return props.examples?.filter((example) => {
        return example.areRequiredExampleValuesPresent(props.exampleValues) &&
            [...props.highlightsMorphemes.values()].some((morpheme) => example.hasMorpheme(morpheme));
    });
});
</script>

<template>
    <Popover v-if="spelling" resize>
        <Morpheme :morpheme :spelling :highlights-morphemes />
        <Pronunciation v-if="pronunciation" :pronunciation text />
        <template v-if="visibleExamples !== undefined && visibleExamples.length > 0" #content>
            <ul class="my-0 ps-3">
                <li v-for="(example, index) in visibleExamples" :key="index" class="my-1">
                    <ExampleItem :example :example-values />
                </li>
            </ul>
        </template>
    </Popover>
</template>
