<template>
  <div class="mc-radio" :class="[type === 'block' ? '' : 'is-inline',{'is-disabled': disabled,}]">
    <input 
      type="radio"
      :id="id"
      :name="name"
      :value="value"
      :checked="state"
      :disabled="disabled"
      @change="onChange"
    />
    <label :for="id">
      <span class="mc-radio_inner">
        <i class="mc-radio_circle"></i>
      </span><slot></slot>
    </label>
  </div>
</template>

<script>
  export default {
    model: {
      prop: 'modelValue',
      event: 'input'
    },
    props: {
      id: {
        type: String,
        default: function () {
          return 'radio-id-' + this._uid;
        },
      },
      name: {
        type: String,
        default: null,
      },
      value: {
        type: String|Number,
        default: '',
      },
      modelValue: {
        type: String|Number,
        default: undefined,
      },
      type: {
        type: String,
        default: 'inline'
      },
      checked: {
        type: Boolean,
        default: false,
      },
      disabled: Boolean,
    },
    computed: {
      state () {
        if (this.modelValue === undefined) {
          return this.checked;
        }
        return this.modelValue === this.value;
      }
    },
    methods: {
      toggle() {
        this.$emit('input', this.state ? '' : this.value);
      },
      onChange(){
        this.$nextTick(() => {
          this.$emit('change', this.model);
          this.$emit('input', this.state ? '' : this.value);
        });
      }
    },
    watch: {
      checked(newValue) {
        if (newValue !== this.state) {
          this.toggle();
        }
      }
    },
    mounted() {
      if (this.checked && !this.state) {
        this.toggle();
      }
    },
  }
</script>