<template>
  <div
    ref="container"
    v-drag="{
      drag: handleDrag,
      dragend: handleDrag,
    }">
    <slot></slot>
    <div
      ref="thumb"
      v-drag="{
        drag: handleDrag,
        dragend: handleDrag,
      }"
      :style="offset"
      class="mm-color-picker-slider--thumb">
    </div>
  </div>
</template>

<script>
import drag from "../../../directives/drag"

export default {
  directives: { drag },
  props: {
    axis: {
      type: String,
      default: "all",
      validator(value) {
        return ["x", "y", "all"].includes(value)
      },
    },
    x: {
      type: [String, Number],
    },
    y: {
      type: [String, Number],
    },
  },
  data() {
    return {
      localX: this.x,
      localY: this.y,
    }
  },
  computed: {
    offset() {
      const styles = {}
      if (["x", "all"].includes(this.axis)) {
        styles.left = this.localX
      }

      if (["y", "all"].includes(this.axis)) {
        styles.top = this.localY
      }

      return styles
    },
  },
  watch: {
    x() {
      this.localX = this.x
    },
    y() {
      this.localY = this.y
    },
  },

  methods: {
    handleDrag({ event }) {
      const { container } = this.$refs
      const rect = container.getBoundingClientRect()

      const height = rect.bottom - rect.top
      const width = rect.right - rect.left

      let top = event.clientY - rect.top
      let left = event.clientX - rect.left

      top = Math.max(Math.min(height, top), 0)
      left = Math.max(Math.min(width, left), 0)

      const ratioY = top / height * 100
      const ratioX = left / width * 100

      this.localX = `${ratioX}%`
      this.localY = `${ratioY}%`

      this.$emit("change", {
        height,
        width,
        top,
        left,
        ratioY,
        ratioX,
      })
    },
  },
}
</script>
