<template>
  <div class="checkbox" ref="wrapper">
    <div class="wrapper d-flex align-items-center" @click="toggleCheck">
      <div class="icon lg-large">
        <SpIcon v-if="checked" name="sp-checkbox-checked" />
        <SpIcon v-else name="sp-checkbox-unchecked" />
      </div>
      <div class="text h600">
        <slot />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, watch } from "vue";

export default defineComponent({
  props: {
    value: {
      default: false,
      type: Boolean,
    },
  },
  setup(props, { emit }) {
    const checked = ref<boolean>(false);
    const wrapper = ref<HTMLElement | null>(null);
    onMounted((): void => {
      checked.value = props.value;

      const anchor = wrapper.value.querySelector("a");

      if (anchor) {
        anchor.addEventListener("click", (e: Event) => {
          e.stopPropagation();
        });
      }
    });

    const toggleCheck = (): void => {
      checked.value = !checked.value;
      emit("input", checked.value);
    };

    watch(
      (): boolean => props.value,
      (newVal: boolean): void => {
        checked.value = newVal;
      }
    );

    return {
      toggleCheck,
      wrapper,
      checked,
    };
  },
});
</script>
