<script setup lang="ts">
import converter from 'ral-hex-converter'

const props = defineProps(['color', 'cb', 'open', 'active'])
const open = props.open ?? true

const onClick = (color: string) => {
    if (props.cb) {
        props.cb(color)
    }
    toggleOpen()
}
const isOpenPicker = ref<boolean>(false)
const toggleOpen = (value: boolean = !isOpenPicker) => {
    isOpenPicker.value = value !== undefined ? value : !isOpenPicker.value
}
const picker = ref()
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>
        <div class="color_picker" ref="picker">
            <div class="color_picker-selected" :style="[{ backgroundColor: props.color }]"
                @click="open ? toggleOpen(!isOpenPicker) : onClick(props.color)"
                :class="[{ 'color_picker-selected__active': active }]"></div>
            <div class="color_picker-changer flex flex-wrap" v-if="isOpenPicker">
                <template v-for="col in converter.hex">
                    <div class="color size-5" :class="[{ 'outline outline-primary': props.color == col }]"
                        :style="[{ backgroundColor: col }]" @click="onClick(col)">
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>
<style scoped>
.color_picker-selected:not([style*=color]) {
    background-image: conic-gradient(from 50deg, orange, yellow, green, cyan, blue, violet)
}
</style>