<script setup lang="ts">
import { type CommandDefinition, useAllCommands } from '@/composables/command';
import { computed } from 'vue';

const props = defineProps<{
    search?: string;
}>();

const selected = defineModel<CommandDefinition | null>();

const search_value = computed(() => (props.search || '').toLowerCase());

const { data: command_data } = useAllCommands();

const sorted_cmd_data = computed(() => {
    const cmd_data = command_data.value;
    if (cmd_data != null) {
        return cmd_data
            .filter((entry) =>
                entry.name.toLowerCase().includes(search_value.value),
            )
            .sort((a, b) => a.name.localeCompare(b.name));
    }
    return [];
});

function onClick(cmd_entry: CommandDefinition) {
    selected.value = cmd_entry;
}
</script>

<template>
    <template v-if="sorted_cmd_data.length > 0">
        <div
            v-for="cmd_entry in sorted_cmd_data"
            :class="`row data ${selected?.name == cmd_entry.name ? 'selected' : ''}`"
            :key="cmd_entry.name"
            @click="() => onClick(cmd_entry)"
        >
            <span>
                {{ cmd_entry.name }}
            </span>
        </div>
    </template>
    <template v-else>
        <div class="row">
            <span> No Matches Found </span>
        </div>
    </template>
</template>

<style scoped lang="scss">
@use '@/assets/variables';
div {
    padding: 0.3em;
    border: 0;
    border-bottom: variables.$gray-3 solid 1px;
    border-top: 0;
}

.data.selected:has(~ .data:hover),
.data:hover ~ .data.selected {
    background-color: variables.$light-background-color;
}

.data.selected,
.data:hover {
    background-color: variables.$light2-background-color;
}
</style>
