<template>
  <div
    class="color-block"
    :style="style"
    :class="blockClass"
    @click="copyToClipboard"
  >
    <span>
      --{{name}}
    </span>
    <span>
      {{color}}
    </span>
  </div>
</template>

<script>
import getLuminosity from '../getLuminosity'
import copyToClipboard from '../copyToClipboard'

export default {
  props: {
    color: String,
    name: String,
  },

  data() {
    return {
      copied: false,
    }
  },

  computed: {
    isDark() {
      return getLuminosity(this.color) < 0.5
    },

    style() {
      return {
        'background-color': this.color,
      }
    },

    blockClass() {
      return {
        [this.isDark ? 'dark' : 'light']: true,
        copied: this.copied,
      }
    },
  },

  methods: {
    copyToClipboard() {
      if (window.getSelection().toString()) {
        return
      }

      const value = `var(--${this.name})`
      copyToClipboard(value)
      this.copied = true
      setTimeout(() => {
        this.copied = false
      }, 300)
    },
  },
}
</script>

<style
  lang="postcss"
  scoped
>
  .color-block {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    border: 1px black solid;
    border-radius: 5px;
    padding: 10px;
    cursor: pointer;

    &::before {
      opacity: 0;
      position: absolute;
      content: 'Copied!';
      width: 100%;
      height: 100%;
      background-color: inherit;
      display: inherit;
      flex-direction: inherit;
      justify-content: inherit;
      align-items: inherit;
      border-radius: inherit;
    }

    &.copied {
      color: transparent;
      user-select: none;

      &::before {
        opacity: 1;
      }
    }

    &.dark {
      color: white;
    }

    &.light {
      color: black;
    }

    & > * + * {
      margin-top: 0.25rem;
    }
  }
</style>
