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

const props = defineProps(['color', 'cb', 'name', 'type', 'goto_cam', 'goto_target'])

const goto_cam = use_goto_camera()
const goto_target = use_goto_target()
const open_calc = use_open_calc()

const picker = ref()
const is_open = ref<boolean>(open_calc.value.includes(props.name))

const toggleOpen = (value: boolean = !is_open) => {
    is_open.value = value
    if (value == true) open_calc.value = [props.name]
    else if (value == false && open_calc.value.includes(props.name)) open_calc.value = []

    if (value == true && props.goto_cam) goto_cam.value = props.goto_cam
    if (value == true && props.goto_target) goto_target.value = props.goto_target
}

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

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

onMounted(() => {
    document.addEventListener('click', clickOutside)
})
onUnmounted(() => {
    document.removeEventListener('click', clickOutside)
})

watch(open_calc, () => {
    if (open_calc.value.includes(props.name) && is_open.value !== true) {
        is_open.value = true
    } else if (!open_calc.value.includes(props.name) && is_open.value !== false) {
        is_open.value = false
    }
})
</script>
<template>
    <div class="picker" ref="picker">
        <template v-if="$slots.default">
            <div @click="toggleOpen(!is_open)">
                <slot></slot>
            </div>
        </template>
        <template v-else>
            <div class="picker-selected" @click="toggleOpen(!is_open)"
                :style="[props.color && { backgroundColor: getColorHexFromRal(props.color) ?? '' }]"></div>
        </template>

        <div class="picker-changer flex flex-wrap" v-if="is_open">
            <template v-if="props.type == 'color'">
                <DropdownColorPicker :color="props.color" :cb="onClick" />
            </template>
            <template v-else-if="props.type == 'pattern'">
                <DropdownList :color="props.color" :cb="onClick" />
            </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>