<section class="admin-categories-card">
  @if (dashboardStats) {
    <app-categories-dashboard [stats]="dashboardStats" (openCategory)="edit.emit($event)" />
  }

  <div class="toolbar">
    <div class="filters">
      <app-input type="search" [ngModel]="filters.search" (ngModelChange)="filtersChange.emit({ search: $event })" [placeholder]="'adminCategories.search' | translate" />
      <select [attr.aria-label]="'adminProducts.visibility' | translate" [ngModel]="filters.visibility" (ngModelChange)="filtersChange.emit({ visibility: $event })">
        <option value="all">{{ 'adminProducts.allVisibility' | translate }}</option>
        <option value="visible">{{ 'adminProducts.visible' | translate }}</option>
        <option value="hidden">{{ 'adminProducts.hidden' | translate }}</option>
      </select>
      <label class="check"><input type="checkbox" [checked]="filters.includeDeleted" (change)="filtersChange.emit({ includeDeleted: $any($event.target).checked })" /><span>{{ 'adminCategories.showDeleted' | translate }}</span></label>
    </div>
    <div class="toolbar__view-controls">
      <div class="view-toggle" role="group" [attr.aria-label]="'adminProducts.viewMode' | translate">
        <app-button variant="ghost" size="sm" [attr.aria-pressed]="viewMode === 'tree'" (click)="viewModeChange.emit('tree')">{{ 'adminCategories.viewTree' | translate }}</app-button>
        <app-button variant="ghost" size="sm" [attr.aria-pressed]="viewMode === 'table'" (click)="viewModeChange.emit('table')">{{ 'adminProducts.viewTable' | translate }}</app-button>
        <app-button variant="ghost" size="sm" [attr.aria-pressed]="viewMode === 'cards'" (click)="viewModeChange.emit('cards')">{{ 'adminCategories.viewCards' | translate }}</app-button>
      </div>
      @if (viewMode === 'tree') {
        <app-button variant="ghost" size="sm" (click)="expandAll.emit()">{{ 'adminCategories.expandAll' | translate }}</app-button>
        <app-button variant="ghost" size="sm" (click)="collapseAll.emit()">{{ 'adminCategories.collapseAll' | translate }}</app-button>
      } @else {
        <div class="view-toggle" role="group" [attr.aria-label]="'adminProducts.density' | translate">
          <app-button variant="ghost" size="sm" [attr.aria-pressed]="density === 'comfortable'" (click)="densityChange.emit('comfortable')">{{ 'adminProducts.densityComfortable' | translate }}</app-button>
          <app-button variant="ghost" size="sm" [attr.aria-pressed]="density === 'compact'" (click)="densityChange.emit('compact')">{{ 'adminProducts.densityCompact' | translate }}</app-button>
        </div>
        @if (viewMode === 'table') {
          <app-button variant="ghost" size="sm" (click)="columnsPanelOpen.set(!columnsPanelOpen())">{{ 'adminProducts.columns' | translate }}</app-button>
        }
      }
      <app-button variant="primary" (click)="create.emit()">{{ 'adminCategories.create' | translate }}</app-button>
    </div>
  </div>

  @if (columnsPanelOpen() && viewMode === 'table') {
    <app-card padding="sm" class="columns-panel">
      @for (column of allColumns; track column) {
        <label class="check">
          <input type="checkbox" [checked]="visibleColumns.includes(column)" (change)="columnToggle.emit({ column, visible: $any($event.target).checked })" />
          <span>{{ ('adminCategories.column_' + column) | translate }}</span>
        </label>
      }
    </app-card>
  }

  @if (selectedIds.length > 0) {
    <div class="bulk-actions">
      <span>{{ selectedIds.length }} {{ 'adminProducts.selectedCount' | translate }}</span>
      <app-button variant="secondary" size="sm" (click)="bulkVisibility.emit(true)">{{ 'adminProducts.bulkShow' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="bulkVisibility.emit(false)">{{ 'adminProducts.bulkHide' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="openAssignParent()">{{ 'adminCategories.bulkAssignParent' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="openBulkImagePicker()">{{ 'adminCategories.bulkAssignImage' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="bulkDuplicate.emit()">{{ 'adminProducts.bulkDuplicateAction' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="bulkExport.emit()">{{ 'adminProducts.bulkExportAction' | translate }}</app-button>
      <app-button variant="danger" size="sm" (click)="bulkDelete.emit()">{{ 'adminProducts.bulkDelete' | translate }}</app-button>
    </div>
  }

  @if (loading) {
    <div class="skeleton-rows" role="status" aria-live="polite" aria-busy="true">
      @for (i of [1,2,3,4]; track i) { <app-skeleton shape="rect" height="40px" /> }
      <span class="sr-only">{{ 'common.loading' | translate }}</span>
    </div>
  } @else if (error) {
    <app-empty-state [title]="'common.errorTitle' | translate" [description]="'common.errorDescription' | translate" />
  } @else if (treeRows.length === 0) {
    <app-empty-state [title]="'adminCategories.emptyTitle' | translate" [description]="'adminCategories.emptyDescription' | translate">
      <span slot="actions">
        <app-button variant="primary" (click)="create.emit()">{{ 'adminCategories.create' | translate }}</app-button>
      </span>
    </app-empty-state>
    <p class="admin-categories-card__guide">{{ 'adminCategories.emptyGuide' | translate }}</p>
  } @else if (viewMode === 'tree') {
    <ul class="category-tree" role="tree" [attr.aria-label]="'adminCategories.title' | translate">
      @for (row of treeRows; track row.category.id; let i = $index) {
        <li
          role="treeitem"
          [id]="'category-tree-row-' + row.category.id"
          [attr.aria-level]="row.depth + 1"
          [attr.aria-expanded]="row.hasChildren ? isExpanded(row.category.id) : null"
          [attr.aria-selected]="isSelected(row.category.id)"
          tabindex="0"
          class="category-tree__row"
          [class.category-tree__row--deleted]="row.category.deletedAt"
          [style.paddingLeft.px]="row.depth * 20"
          draggable="true"
          (dragstart)="onDragStart(row.category.id)"
          (dragover)="$event.preventDefault()"
          (drop)="onDrop(row)"
          (keydown)="onTreeKeydown($event, row, i)"
        >
          <div class="category-tree__row-main">
            @if (row.hasChildren) {
              <button type="button" class="category-tree__toggle" (click)="toggleExpand.emit(row.category.id)" [attr.aria-label]="(isExpanded(row.category.id) ? 'adminCategories.collapseNode' : 'adminCategories.expandNode') | translate">
                {{ isExpanded(row.category.id) ? '▾' : '▸' }}
              </button>
            } @else {
              <span class="category-tree__toggle-spacer"></span>
            }
            <input type="checkbox" [checked]="isSelected(row.category.id)" (change)="selectionChange.emit({ id: row.category.id, checked: $any($event.target).checked })" [attr.aria-label]="row.category.title" />
            <span class="category-tree__icon">{{ row.category.icon || '📁' }}</span>
            <span class="category-tree__title">{{ row.category.title }}</span>
            @if (row.category.deletedAt) {
              <app-badge variant="neutral">{{ 'adminCategories.deletedBadge' | translate }}</app-badge>
            } @else {
              <app-badge [variant]="row.category.status === 'published' ? 'success' : 'neutral'">{{ ('adminCategories.status.' + row.category.status) | translate }}</app-badge>
              @if (!row.category.visible) {
                <app-badge variant="neutral">{{ 'adminProducts.hidden' | translate }}</app-badge>
              }
            }
            <span class="category-tree__items">{{ row.category.itemsCount }} {{ 'adminCategories.items' | translate }}</span>
            <app-category-health-widget [items]="healthItems(row.category)" [completionPercent]="health(row.category).completionPercent" [compact]="true" />
          </div>
          <div class="category-tree__actions">
            <button type="button" class="category-tree__reorder-btn" [disabled]="!canMoveUp(row)" (click)="moveRowUp(row)" [attr.aria-label]="'adminCategories.moveUp' | translate">
              <app-icon name="arrowUp" [size]="16" />
            </button>
            <button type="button" class="category-tree__reorder-btn" [disabled]="!canMoveDown(row)" (click)="moveRowDown(row)" [attr.aria-label]="'adminCategories.moveDown' | translate">
              <app-icon name="arrowDown" [size]="16" />
            </button>
            @if (row.category.parentId) {
              <app-button variant="ghost" size="sm" (click)="jumpToParent.emit(row.category.id)">{{ 'adminCategories.jumpToParent' | translate }}</app-button>
            }
            @if (row.category.deletedAt) {
              <app-button variant="secondary" size="sm" (click)="restore.emit(row.category.id)">{{ 'adminCategories.restore' | translate }}</app-button>
            } @else {
              <app-button variant="secondary" size="sm" (click)="edit.emit(row.category.id)">{{ 'adminCategories.edit' | translate }}</app-button>
              <app-button variant="danger" size="sm" (click)="delete.emit(row.category.id)">{{ 'adminProducts.delete' | translate }}</app-button>
            }
          </div>
        </li>
      }
    </ul>
  } @else if (viewMode === 'table') {
    <app-table [class.density-compact]="density === 'compact'">
      <thead>
        <tr>
          <th scope="col"><input type="checkbox" [attr.aria-label]="'adminCategories.selectAllRows' | translate" (change)="selectAll.emit($any($event.target).checked)" /></th>
          <th scope="col">{{ 'adminCategories.title' | translate }}</th>
          @if (visibleColumns.includes('slug')) { <th scope="col">{{ 'adminCategories.slug' | translate }}</th> }
          @if (visibleColumns.includes('items')) { <th scope="col">{{ 'adminCategories.items' | translate }}</th> }
          @if (visibleColumns.includes('status')) { <th scope="col">{{ 'backoffice.status' | translate }}</th> }
          @if (visibleColumns.includes('visibility')) { <th scope="col">{{ 'adminProducts.visibility' | translate }}</th> }
          <th scope="col">{{ 'adminProducts.healthColumn' | translate }}</th>
          <th scope="col">{{ 'adminProducts.actions' | translate }}</th>
        </tr>
      </thead>
      <tbody>
        @for (category of flatCategories; track category.id) {
          <tr [class.deleted]="category.deletedAt">
            <td><input type="checkbox" [checked]="isSelected(category.id)" [attr.aria-label]="('adminCategories.selectRow' | translate) + ': ' + category.title" (change)="selectionChange.emit({ id: category.id, checked: $any($event.target).checked })" /></td>
            <th scope="row">{{ category.icon }} {{ category.title }}</th>
            @if (visibleColumns.includes('slug')) { <td>{{ category.slug }}</td> }
            @if (visibleColumns.includes('items')) { <td>{{ category.itemsCount }}</td> }
            @if (visibleColumns.includes('status')) {
              <td><app-badge [variant]="category.status === 'published' ? 'success' : 'neutral'">{{ ('adminCategories.status.' + category.status) | translate }}</app-badge></td>
            }
            @if (visibleColumns.includes('visibility')) {
              <td><label class="check"><input type="checkbox" [checked]="category.visible" [attr.aria-label]="('adminCategories.toggleVisibility' | translate) + ': ' + category.title" (change)="toggleVisible.emit({ id: category.id, visible: $any($event.target).checked })" /></label></td>
            }
            <td class="health-cell"><app-category-health-widget [items]="healthItems(category)" [completionPercent]="health(category).completionPercent" [compact]="true" /></td>
            <td class="actions">
              @if (category.deletedAt) {
                <app-button variant="secondary" size="sm" (click)="restore.emit(category.id)">{{ 'adminCategories.restore' | translate }}</app-button>
              } @else {
                <app-button variant="secondary" size="sm" (click)="edit.emit(category.id)">{{ 'adminCategories.edit' | translate }}</app-button>
                <app-button variant="danger" size="sm" (click)="delete.emit(category.id)">{{ 'adminProducts.delete' | translate }}</app-button>
              }
            </td>
          </tr>
        }
      </tbody>
    </app-table>
  } @else {
    <div class="category-grid" [class.category-grid--compact]="density === 'compact'">
      @for (category of flatCategories; track category.id) {
        <app-card padding="sm" class="category-grid__item">
          <label class="category-grid__select">
            <input type="checkbox" [checked]="isSelected(category.id)" (change)="selectionChange.emit({ id: category.id, checked: $any($event.target).checked })" [attr.aria-label]="category.title" />
          </label>
          @if (category.imageUrl) {
            <img class="category-grid__image" [src]="category.imageUrl" [alt]="category.imageAlt || category.title" loading="lazy" />
          } @else {
            <div class="category-grid__image category-grid__image--placeholder">{{ category.icon || '📁' }}</div>
          }
          <h4 class="category-grid__name">{{ category.title }}</h4>
          <p class="category-grid__items">{{ category.itemsCount }} {{ 'adminCategories.items' | translate }}</p>
          <app-category-health-widget [items]="healthItems(category)" [completionPercent]="health(category).completionPercent" [compact]="true" />
          <div class="category-grid__actions">
            <app-button variant="secondary" size="sm" (click)="edit.emit(category.id)">{{ 'adminProducts.edit' | translate }}</app-button>
            <app-button variant="ghost" size="sm" (click)="delete.emit(category.id)">{{ 'adminProducts.delete' | translate }}</app-button>
          </div>
        </app-card>
      }
    </div>
  }

  <app-dialog [open]="assignParentOpen()" [titleText]="'adminCategories.bulkAssignParent' | translate" size="sm" (closed)="assignParentOpen.set(false)">
    <div class="dialog-body">
      <select #parentSelect>
        <option value="">{{ 'adminCategories.noParent' | translate }}</option>
        @for (category of allCategories; track category.id) {
          <option [value]="category.id">{{ category.title }}</option>
        }
      </select>
      <div class="dialog-actions">
        <app-button variant="secondary" (click)="assignParentOpen.set(false)">{{ 'mediaLibrary.cancel' | translate }}</app-button>
        <app-button variant="primary" (click)="confirmAssignParent(parentSelect.value)">{{ 'mediaLibrary.confirm' | translate }}</app-button>
      </div>
    </div>
  </app-dialog>

  <app-media-picker [open]="imagePickerOpen()" (selected)="onBulkImagePicked($event)" (closed)="imagePickerOpen.set(false)" />
</section>
