<!--
    #VUE3 Todo

    Base class for classes that manage a checked state. In order to simplify the data
    synchronization with the input, we enable v-model binding by also providing a data property
    (checkedValue) that mirrors the checked prop. The intention is that this property will only be
    used internally as v-model.

-->

<script>
export default {
    emits: ['update:checked', 'checked', 'unchecked'],
    props: {
        /**
         * The value of the checked property.
         */
        checked: { type: Boolean, default: false },

        /**
         * Class that should be set on the component when checked.
         */
        checkedClass: { type: String, default: null },

        /**
         * Disables interaction.
         */
        disabled: { type: Boolean, default: false },
    },
    data() {
        return {
            checkedValue: this.checked,
        };
    },

    watch: {
        checked(nv) {
            // update checkedValue when checked changes
            this.checkedValue = nv;
        },

        checkedValue(nv) {
            // emit update when checkedValue changes
            this.$emit('update:checked', nv);

            if (nv) {
                this.$emit('checked');
            }
            if (!nv) {
                this.$emit('unchecked');
            }
        },
    },
    computed: {
        calcCheckedClass() {
            return this.checkedValue && this.checkedClass ? this.checkedClass : null;
        },
    },
    methods: {
        toggleChecked() {
            if (this.disabled) {
                return;
            }
            this.checkedValue = !this.checkedValue;
        },
    },
};
</script>
