<template>

<div ref="picker" id="picker" class="btn"><div class="label">Set username color</div></div>
</template>

<script setup>
import Color from 'color';
import Picker from 'vanilla-picker'
import { inject, onMounted, ref } from 'vue';
import { useUserStore } from '../../stores/userStore';

const requestUserData = inject('requestUserData')
const userStore = useUserStore()

const self = userStore.getSelf()

const picker = ref(null)
const usernameColor = ref(Color())

const bootstrapPrimaryColor = getComputedStyle(document.documentElement).getPropertyValue('--bs-primary')

onMounted(() => {
  const p = new Picker(picker.value)

  p.setOptions({
    alpha: false,
    color: self.color.hex() ?? bootstrapPrimaryColor
  })

  picker.value.style.backgroundColor = self.color.hex() ?? bootstrapPrimaryColor

  p.onChange = function(color)  {
    picker.value.style.backgroundColor = color.rgbaString
  }

  p.onOpen = function(color) {
    usernameColor.value = Color(color.hex)
  }

  p.onDone = function(color) {
    usernameColor.value = Color(color.hex)
    picker.value.style.backgroundColor = color.rgbaString

    userStore.setColor(-1, Color(color.hex))
    requestUserData()
  }

  p.onClose = function(color) {
    picker.value.style.backgroundColor = usernameColor.value.hex()
  }
})
</script>

<style>

#picker .label {
  background: inherit;
  background-clip: text;
  color: transparent;
  filter: invert(1) grayscale(1) contrast(9);
}
</style>
