'use strict';

window.NumberInput = {
  name: 'NumberInput',

  props: {
    min: {
      type: Number,
      default: Number.MIN_SAFE_INTEGER,
    },

    max: {
      type: Number,
      default: Number.MAX_SAFE_INTEGER,
    },

    value: {
      type: Number,
      default: 0,
    },

    disabled: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      currentValue: this.value,
    };
  },

  watch: {
    value: {
      handler(newValue) {
        if (newValue !== this.currentValue) {
          this.update(newValue);
        }
      },
      immediate: true,
    },
  },

  methods: {
    update(value) {
      const newValue = Math.min(this.max, Math.max(this.min, +value));

      if (newValue === this.currentValue) {
        this.$refs.input.value = newValue;
      } else {
        this.currentValue = newValue;
        this.$emit('input', newValue);
      }
    },
  },

  template: html`
    <input
      :min="min"
      :max="max"
      ref="input"
      type="number"
      :disabled="disabled"
      :value="currentValue"
      @change="update($event.target.value)"
    />
  `,
};
