<script lang="ts">
  interface Props {
    available: Record<number, string>;
    value: number;

    readonly?: boolean;
  }

  // inputs
  let { available, value = $bindable(), readonly }: Props = $props();

  // callbacks
  function onOptionSelect(e: Event) {
    const selected = Number((e.target as HTMLSelectElement).value);

    value |= selected;

    (e.target as HTMLSelectElement).value = '-';
  }

  function onBadgeRemove(flag: number) {
    value &= ~flag;
  }
</script>

<div class="flex flex-col gap-4">
  {#if !readonly}
    <select class="select select-xs w-min" onchange={onOptionSelect}>
      <option selected hidden>-</option>
      {#each Object.entries(available) as [flag, badge] (flag)}
        <option value={flag} hidden={(value & Number(flag)) !== 0}>{badge}</option>
      {/each}
    </select>
  {/if}
  <div class="flex flow flex-wrap gap-2">
    {#key value}
      {#each Object.entries(available) as [flag, badge] (flag)}
        {#if (value & Number(flag)) !== 0}
          <div class="badge badge-outline gap-1">
            {#if !readonly}
              <button class="cursor-pointer" type="button" onclick={() => onBadgeRemove(Number(flag))}>✕</button>
            {/if}
            <span>{badge}</span>
          </div>
        {/if}
      {/each}
    {/key}
  </div>
</div>
