<script setup lang="ts">
import log from "loglevel";

interface Props {
  checked?: boolean;
  disabled?: boolean;
  label?: string;
}

const props = withDefaults(defineProps<Props>(), {
  checked: false,
  disabled: false,
  label: undefined,
});

const emit = defineEmits(["toggle"]);
const toggle = () => {
  emit("toggle");
};
const keydown = (e: KeyboardEvent) => {
  log.debug("keydown", e.type, e.key);
  if (e.key === " " && !props.disabled) {
    e.preventDefault();
    toggle();
  }
};
const input = (e: Event) => {
  const target = e.target as HTMLInputElement;
  log.debug("input", e.type, target.checked, target.value);
  emit("toggle");
};
</script>

<template>
  <div
    :class="{
      'opacity-50': disabled,
      'cursor-not-allowed': disabled,
    }"
    class="cursor-pointer inline-flex"
  >
    <label
      class="block bg-contain disabled:opacity-50 cy-checkbox cy-checkbox-checked bg-no-repeat pl-8 h-8 flex items-center"
      :class="
        checked
          ? 'bg-[url(/static/icons/icon-checkbox-checked.svg)] hover:bg-[url(/static/icons/icon-checkbox-checked-hover.svg)]'
          : 'bg-[url(/static/icons/icon-checkbox-unchecked.svg)] hover:bg-[url(/static/icons/icon-checkbox-unchecked-hover.svg)]'
      "
      tabindex="0"
      @keydown.stop="keydown"
    >
      <input
        ref="checkbox"
        :checked="checked"
        :value="checked"
        :disabled="disabled"
        class="sr-only"
        type="checkbox"
        @keydown="keydown"
        @input="input"
      />

      <span v-if="label" class="ml-4">
        {{ label }}
      </span>
    </label>
  </div>
</template>
