<script setup lang="ts">
import { ralClassicPallette, getColorHexFromRal } from '@/components/ral'

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

const goto_cam = use_goto_camera()

const onClick = (color: string) => {
    if (props.cb) {
        props.cb(color)
    }
    toggleOpen()
}
const isOpenPicker = ref<boolean>(false)
const toggleOpen = (value: boolean = !isOpenPicker) => {
    if (value == false) {
        goto_cam.value = undefined
    }
    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 class="color_picker" ref="picker">
        <template v-if="$slots.default">
            <div @click="open ? toggleOpen(!isOpenPicker) : onClick(props.color)">
                <slot></slot>
            </div>
        </template>
        <template v-else>
            <div class="color_picker-selected" @click="open ? toggleOpen(!isOpenPicker) : onClick(props.color)"
                :style="[props.color && { backgroundColor: getColorHexFromRal(props.color) ?? '' }]"
                :class="[{ 'color_picker-selected__active': active }]"></div>
        </template>

        <div class="color_picker-changer flex flex-wrap" v-if="isOpenPicker">
            <template v-for="col in ralClassicPallette">
                <div class="color size-5" :class="[{ 'outline outline-primary': props.color == col.hex }]"
                    :style="[{ backgroundColor: col.hex }]" @click="onClick(col.code)">
                </div>
            </template>
        </div>
    </div>
</template>
<style scoped>
.color_picker-selected:not([style*=color]) {
    background-image: conic-gradient(from 50deg, orange, yellow, green, cyan, blue, violet)
}
</style>