<script lang="ts">
  import * as DropdownMenu from '$lib/components/ui/dropdown-menu'
  import { Button } from '$lib/components/ui/button'
  import ChevronDownIcon from '@lucide/svelte/icons/chevron-down'

  let {
    label,
    options,
    selected = $bindable(),
    colorFor
  }: {
    label: string
    options: string[]
    selected: Set<string>
    colorFor?: (option: string) => string
  } = $props()

  function toggle(opt: string) {
    const next = new Set(selected)
    if (next.has(opt)) next.delete(opt)
    else next.add(opt)
    selected = next
  }

  const allSelected = $derived(options.length > 0 && options.every((o) => selected.has(o)))
</script>

<DropdownMenu.Root>
  <DropdownMenu.Trigger>
    {#snippet child({ props })}
      <Button {...props} variant="outline" size="sm" class="h-8 gap-1.5">
        {label}
        <span class="text-muted-foreground">{selected.size}/{options.length}</span>
        <ChevronDownIcon class="size-3.5 text-muted-foreground" />
      </Button>
    {/snippet}
  </DropdownMenu.Trigger>
  <DropdownMenu.Content class="max-h-80 w-56 overflow-y-auto" align="start">
    <DropdownMenu.Item
      closeOnSelect={false}
      onSelect={() => { selected = allSelected ? new Set() : new Set(options) }}
      class="text-xs text-muted-foreground"
    >
      {allSelected ? 'Deselect all' : 'Select all'}
    </DropdownMenu.Item>
    <DropdownMenu.Separator />
    {#each options as opt}
      <DropdownMenu.CheckboxItem
        closeOnSelect={false}
        checked={selected.has(opt)}
        onCheckedChange={() => toggle(opt)}
        class="text-xs"
      >
        {#if colorFor}
          <span class="size-2 shrink-0 rounded-full" style="background: {colorFor(opt)}"></span>
        {/if}
        {opt}
      </DropdownMenu.CheckboxItem>
    {/each}
    {#if options.length === 0}
      <p class="px-2 py-1.5 text-xs text-muted-foreground">No types loaded yet.</p>
    {/if}
  </DropdownMenu.Content>
</DropdownMenu.Root>
