<div class="label-selector">
  <nsi-dropdown-button
    [disabled]="disabled"
    [fullWidth]="fullWidth"
    [popupRef]="labelSelection"
    [size]="size"
    [aspect]="aspect"
    [open]="open"
    [freeWidth]="fullWidth">
    <ng-content></ng-content>
  </nsi-dropdown-button>

  <pa-dropdown
    #labelSelection
    [dontAdjustPosition]="!fullWidth"
    [companionElement]="level2Element?.nativeElement"
    (onClose)="closeDropdowns()"
    (onOpen)="open = true">
    @for (labelSet of labelSets | keyvalue; track labelSet) {
      @if (labelSet.value.labels.length > 0) {
        <pa-option
          icon="chevron-right"
          iconOnRight
          popupOnRight
          [dontCloseOnSelect]="!labelSetSelection"
          [paPopup]="level2"
          [popupVerticalOffset]="-40"
          [selected]="selectedLabelSet === labelSet.key || labelSetExpandedId === labelSet.key"
          (selectOption)="onLevel1Selection(labelSet.key, labelSet.value)">
          <span
            class="label-color"
            [style.background-color]="labelSet.value.color"></span>
          {{ labelSet.value.title }}
        </pa-option>
      }
    }
  </pa-dropdown>

  <pa-dropdown
    #level2
    dontAdjustPosition
    keepOthersOpen>
    @if (labelValues.length > maxLabels) {
      <pa-option
        class="filter"
        dontCloseOnSelect>
        <pa-input
          icon="search"
          [(value)]="filter"
          (keyUp)="filterLabels(labelSetExpandedId)">
          {{ 'stash.search' | translate }}
        </pa-input>
      </pa-option>
    }

    @if (single || labelSetExpanded?.multiple || !displayRadioForNonMultiple) {
      @for (labelValue of filteredLabels || labelValues | slice: 0 : maxLabels; track labelValue) {
        <pa-option
          class="level2-option"
          [disabled]="labelSetSelection"
          [dontCloseOnSelect]="!single"
          (selectOption)="onOptionSelection(labelValue, $event)">
          @if (single) {
            {{ labelValue.label }}
          } @else {
            <pa-checkbox
              [value]="checkboxSelection.includes(labelValue.labelset + labelValue.label)"
              (change)="toggleLabel(labelValue)">
              {{ labelValue.label }}
            </pa-checkbox>
          }
        </pa-option>
      }
    } @else if (displayRadioForNonMultiple) {
      <pa-radio-group
        name="label-group"
        [(ngModel)]="radioValue">
        @for (labelValue of filteredLabels || labelValues | slice: 0 : maxLabels; track labelValue) {
          <pa-option
            class="level2-option"
            dontCloseOnSelect
            [disabled]="labelSetSelection"
            (selectOption)="onOptionSelection(labelValue, $event)">
            <pa-radio [value]="labelValue.labelset + labelValue.label">
              {{ labelValue.label }}
            </pa-radio>
          </pa-option>
        }
      </pa-radio-group>
    }
  </pa-dropdown>
</div>
