<app-dialog
  [open]="open()"
  [titleText]="'mediaLibrary.title' | translate"
  size="lg"
  (closed)="requestClose()"
>
  <div class="media-picker">
    <div class="media-picker__toolbar">
      <app-input
        [ngModel]="facade.search()"
        (ngModelChange)="facade.setSearch($event)"
        [placeholder]="'mediaLibrary.searchPlaceholder' | translate"
      />
      <app-select [options]="kindOptions()" [ngModel]="facade.kind() || 'all'" (ngModelChange)="setKind($event)" [ariaLabel]="'mediaLibrary.allTypes' | translate" [fullWidth]="false" />
      <app-button variant="ghost" size="sm" (click)="showRecentOnly()">{{ 'mediaLibrary.sortRecent' | translate }}</app-button>
      <input
        #fileInput
        type="file"
        accept="image/jpeg,image/png,image/webp,image/gif,image/svg+xml,application/pdf"
        hidden
        (change)="onFileSelected($event)"
      />
      <app-button variant="secondary" [loading]="facade.uploading()" (click)="triggerFileInput()">
        {{ (facade.uploading() ? 'mediaLibrary.uploading' : 'mediaLibrary.upload') | translate }}
      </app-button>
    </div>

    @if (facade.error()) {
      <p class="media-picker__error" role="alert">{{ facade.error() }}</p>
    }

    @if (facade.loading()) {
      <div class="media-picker__grid">
        @for (i of [1, 2, 3, 4]; track i) {
          <app-skeleton shape="rect" height="110px" />
        }
      </div>
    } @else if (facade.items().length === 0) {
      <app-empty-state
        [title]="'mediaLibrary.emptyTitle' | translate"
        [description]="'mediaLibrary.emptyDescription' | translate"
      />
    } @else {
      <div class="media-picker__grid" role="listbox" [attr.aria-label]="'mediaLibrary.title' | translate" tabindex="0" (keydown)="onGridKeydown($event)">
        @for (asset of facade.items(); track asset.id; let i = $index) {
          <app-card
            padding="sm"
            [interactive]="true"
            role="option"
            [attr.aria-selected]="i === focusedIndex()"
            [class.media-picker__card--focused]="i === focusedIndex()"
            (click)="pick(asset)"
          >
            @if (asset.mimeType.startsWith('image/')) {
              <img class="media-picker__preview" [src]="asset.url" [alt]="asset.filename" loading="lazy" />
            } @else {
              <div class="media-picker__preview media-picker__preview--file">{{ asset.mimeType }}</div>
            }
            <span class="media-picker__filename">{{ asset.filename }}</span>
          </app-card>
        }
      </div>

      @if (totalPages() > 1) {
        <app-pagination [currentPage]="facade.page()" [totalPages]="totalPages()" (pageChange)="facade.setPage($event)" />
      }
    }
  </div>
</app-dialog>
