<script lang="ts">
  import { Check } from 'lucide-svelte';

  interface Props {
    checked: boolean;
    label?: string;
    disabled?: boolean;
    onChange: (checked: boolean) => void;
  }

  let { checked, label = '', disabled = false, onChange }: Props = $props();

  function toggle() {
    if (disabled) return;
    onChange(!checked);
  }

  function handleKeydown(e: KeyboardEvent) {
    if (e.key === ' ' || e.key === 'Enter') {
      e.preventDefault();
      toggle();
    }
  }
</script>

<label class="cb-root" class:disabled class:checked>
  <button
    class="cb-box"
    class:checked
    class:disabled
    role="checkbox"
    aria-checked={checked}
    aria-label={label}
    {disabled}
    onclick={toggle}
    onkeydown={handleKeydown}
  >
    <span class="cb-check" class:visible={checked}>
      <Check size={12} strokeWidth={3} />
    </span>
  </button>
  {#if label}
    <span class="cb-label">{label}</span>
  {/if}
</label>

<style>
  .cb-root {
    display: flex; align-items: center; gap: 0.5rem;
    cursor: pointer; user-select: none;
  }
  .cb-root.disabled { opacity: 0.4; cursor: not-allowed; }

  .cb-box {
    width: 1rem; height: 1rem; flex-shrink: 0;
    border: 1px solid var(--ctp-surface2); border-radius: 0.1875rem;
    background: var(--ctp-surface0); padding: 0;
    cursor: pointer; position: relative;
    display: flex; align-items: center; justify-content: center;
    transition: background 0.12s, border-color 0.12s;
  }
  .cb-box:hover:not(.disabled) { border-color: var(--ctp-blue); }
  .cb-box:focus-visible { outline: 2px solid var(--ctp-blue); outline-offset: 1px; }
  .cb-box.checked {
    background: var(--ctp-blue); border-color: var(--ctp-blue);
  }
  .cb-box.disabled { cursor: not-allowed; }

  .cb-check {
    display: flex; align-items: center; justify-content: center;
    color: var(--ctp-base);
    opacity: 0; transform: scale(0.6);
    transition: opacity 0.12s, transform 0.12s;
  }
  .cb-check.visible { opacity: 1; transform: scale(1); }

  .cb-label {
    font-size: 0.8125rem; color: var(--ctp-text);
  }
</style>
