<script setup lang="ts">
import { getFilename, patterns } from '../pattern';

const props = defineProps(['color', 'cb', 'open', 'active'])
const open = props.open ?? true
const is_open = ref<boolean>(false)
const picker = ref()

const onClick = (color: string) => {
    if (props.cb) {
        props.cb(color)
    }
    toggleOpen()
}

const toggleOpen = (value: boolean = !is_open) => {
    is_open.value = value !== undefined ? value : !is_open.value
}

const clickOutside = (e: Event) => {
    if (!picker.value.contains(e.target)) {
        toggleOpen(false)
    }
}

onMounted(() => {
    document.addEventListener('click', clickOutside)
})
onUnmounted(() => {
    document.removeEventListener('click', clickOutside)
})
</script>
<template>
    <div class="list_picker" ref="picker">
        <div class="list_picker-selected" @click="open ? toggleOpen(!is_open) : onClick(props.color)"
            :class="[{ 'list_picker-selected__active': active }]">
            <NuxtImg :src="getFilename(patterns[1].name)" />
        </div>
        <div class="list_picker-changer" v-if="is_open">
            <div class="list_picker-list">
                <template v-for="item in patterns">
                    <NuxtImg :src="getFilename(item.name)" class="list_picker-item" @click="onClick(item.name)"
                        v-if="item.filename" />
                    <span class=" list_picker-item list_picker-item--empty" @click="onClick(item.name)" v-else />
                </template>
            </div>
        </div>
    </div>
</template>