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

  <div class="toolbar">
    <div class="filters">
      <app-input type="search" [ngModel]="filters.search" (ngModelChange)="filtersChange.emit({ search: $event })" [placeholder]="'adminProducts.search' | translate" />
      <select [attr.aria-label]="'adminProducts.category' | translate" [ngModel]="filters.categoryId" (ngModelChange)="filtersChange.emit({ categoryId: $event || null })">
        <option [ngValue]="null">{{ 'adminProducts.allCategories' | translate }}</option>
        @for (category of categories; track category.id) {
          <option [ngValue]="category.id">{{ category.title }}</option>
        }
      </select>
      <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>
      <select [attr.aria-label]="'adminProducts.stockStatus' | translate" [ngModel]="filters.stock" (ngModelChange)="filtersChange.emit({ stock: $event })">
        <option value="all">{{ 'adminProducts.allStock' | translate }}</option>
        <option value="in_stock">{{ 'adminProducts.inStock' | translate }}</option>
        <option value="low_stock">{{ 'adminProducts.lowStock' | translate }}</option>
        <option value="out_of_stock">{{ 'adminProducts.outOfStock' | translate }}</option>
      </select>
      <select [attr.aria-label]="'adminProducts.sortTitle' | translate" [ngModel]="filters.sort" (ngModelChange)="filtersChange.emit({ sort: $event })">
        <option value="title">{{ 'adminProducts.sortTitle' | translate }}</option>
        <option value="price">{{ 'adminProducts.sortPrice' | translate }}</option>
        <option value="priority">{{ 'adminProducts.sortPriority' | translate }}</option>
        <option value="stock">{{ 'adminProducts.sortStock' | translate }}</option>
        <option value="updated">{{ 'adminProducts.sortUpdated' | translate }}</option>
      </select>
      <label class="check"><input type="checkbox" [checked]="filters.includeArchived" (change)="filtersChange.emit({ includeArchived: $any($event.target).checked })" /><span>{{ 'adminProducts.showArchived' | translate }}</span></label>
      <label class="check"><input type="checkbox" [checked]="infiniteScroll" (change)="infiniteScrollToggle.emit($any($event.target).checked)" /><span>{{ 'adminProducts.infiniteScroll' | 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 === 'table'" (click)="viewModeChange.emit('table')">{{ 'adminProducts.viewTable' | translate }}</app-button>
        <app-button variant="ghost" size="sm" [attr.aria-pressed]="viewMode === 'grid'" (click)="viewModeChange.emit('grid')">{{ 'adminProducts.viewGrid' | translate }}</app-button>
      </div>
      <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>
      <app-button variant="ghost" size="sm" (click)="columnsPanelOpen.set(!columnsPanelOpen())">{{ 'adminProducts.columns' | translate }}</app-button>
      <app-button variant="primary" (click)="create.emit()">{{ 'adminProducts.create' | translate }}</app-button>
    </div>
  </div>

  @if (columnsPanelOpen()) {
    <app-card padding="sm" class="columns-panel">
      @for (column of allColumns; track column) {
        <label class="check">
          <input type="checkbox" [checked]="isColumnVisible(column)" (change)="columnToggle.emit({ column, visible: $any($event.target).checked })" />
          <span>{{ ('adminProducts.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)="openAssignCategory()">{{ 'adminProducts.bulkAssignCategory' | translate }}</app-button>
      <app-button variant="secondary" size="sm" (click)="openAssignTags()">{{ 'adminProducts.bulkAssignTags' | 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,5]; 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 (products.length === 0) {
    <app-empty-state [title]="'adminProducts.emptyTitle' | translate" [description]="'adminProducts.emptyDescription' | translate">
      <span slot="actions">
        <app-button variant="primary" (click)="create.emit()">{{ 'adminProducts.create' | translate }}</app-button>
      </span>
    </app-empty-state>
    <p class="admin-products-card__guide">{{ 'adminProducts.emptyGuide' | translate }}</p>
  } @else if (viewMode === 'table') {
    <app-table [class.density-compact]="density === 'compact'">
      <thead>
        <tr>
          <th scope="col"><input type="checkbox" [attr.aria-label]="'adminProducts.selectAllRows' | translate" (change)="selectAll.emit($any($event.target).checked)" /></th>
          <th scope="col">{{ 'adminProducts.name' | translate }}</th>
          @if (isColumnVisible('sku')) { <th scope="col">{{ 'backoffice.sku' | translate }}</th> }
          @if (isColumnVisible('brand')) { <th scope="col">{{ 'adminProducts.brand' | translate }}</th> }
          @if (isColumnVisible('price')) { <th scope="col">{{ 'backoffice.price' | translate }}</th> }
          @if (isColumnVisible('stock')) { <th scope="col">{{ 'adminProducts.stockStatus' | translate }}</th> }
          @if (isColumnVisible('visibility')) { <th scope="col">{{ 'adminProducts.visibility' | translate }}</th> }
          @if (isColumnVisible('visits')) { <th scope="col">{{ 'adminProducts.views' | translate }}</th> }
          <th scope="col">{{ 'adminProducts.healthColumn' | translate }}</th>
          <th scope="col">{{ 'adminProducts.actions' | translate }}</th>
        </tr>
      </thead>
      <tbody>
        @for (product of products; track product.id) {
          <tr>
            <td><input type="checkbox" [checked]="isSelected(product.id)" [attr.aria-label]="('adminProducts.selectRow' | translate) + ': ' + product.name" (change)="selectionChange.emit({ id: product.id, checked: $any($event.target).checked })" /></td>
            <th scope="row">{{ product.name }}</th>
            @if (isColumnVisible('sku')) { <td>{{ product.sku }}</td> }
            @if (isColumnVisible('brand')) { <td>{{ product.brand }}</td> }
            @if (isColumnVisible('price')) { <td>{{ product.price }} {{ product.currency }}</td> }
            @if (isColumnVisible('stock')) {
              <td>
                <app-badge [variant]="product.stockStatus === 'out_of_stock' ? 'danger' : product.stockStatus === 'low_stock' ? 'warning' : 'success'">
                  {{ ('adminProducts.' + (product.stockStatus === 'out_of_stock' ? 'outOfStock' : product.stockStatus === 'low_stock' ? 'lowStock' : 'inStock')) | translate }}
                </app-badge>
              </td>
            }
            @if (isColumnVisible('visibility')) {
              <td>
                <app-badge [variant]="product.visible ? 'success' : 'neutral'">
                  {{ product.visible ? ('adminProducts.visible' | translate) : ('adminProducts.hidden' | translate) }}
                </app-badge>
              </td>
            }
            @if (isColumnVisible('visits')) { <td>{{ product.visits }}</td> }
            <td class="health-cell"><app-product-health-widget [items]="healthItems(product)" [completionPercent]="health(product).completionPercent" [compact]="true" /></td>
            <td class="actions">
              <app-button variant="secondary" size="sm" (click)="edit.emit(product.id)">{{ 'adminProducts.edit' | translate }}</app-button>
              <app-button variant="secondary" size="sm" (click)="duplicate.emit(product.id)">{{ 'adminProducts.duplicate' | translate }}</app-button>
              @if (product.archived) {
                <app-button variant="secondary" size="sm" (click)="restore.emit(product.id)">{{ 'adminCategories.restore' | translate }}</app-button>
              } @else {
                <app-button variant="secondary" size="sm" (click)="archive.emit(product.id)">{{ 'adminProducts.archive' | translate }}</app-button>
              }
              <app-button variant="danger" size="sm" (click)="delete.emit(product.id)">{{ 'adminProducts.delete' | translate }}</app-button>
            </td>
          </tr>
        }
      </tbody>
    </app-table>
  } @else {
    <div class="product-grid" [class.product-grid--compact]="density === 'compact'">
      @for (product of products; track product.id) {
        <app-card padding="sm" class="product-grid__item">
          <label class="product-grid__select">
            <input type="checkbox" [checked]="isSelected(product.id)" (change)="selectionChange.emit({ id: product.id, checked: $any($event.target).checked })" [attr.aria-label]="product.name" />
          </label>
          @if (product.media.images[0] || product.media.gallery[0]) {
            <img class="product-grid__image" [src]="product.media.images[0] || product.media.gallery[0]" [alt]="product.name" loading="lazy" />
          } @else {
            <div class="product-grid__image product-grid__image--placeholder">{{ 'adminProducts.noImage' | translate }}</div>
          }
          <h4 class="product-grid__name">{{ product.name }}</h4>
          <p class="product-grid__price">{{ product.price }} {{ product.currency }}</p>
          <app-badge [variant]="product.visible ? 'success' : 'neutral'">
            {{ product.visible ? ('adminProducts.visible' | translate) : ('adminProducts.hidden' | translate) }}
          </app-badge>
          <app-product-health-widget [items]="healthItems(product)" [completionPercent]="health(product).completionPercent" [compact]="true" />
          <div class="product-grid__actions">
            <app-button variant="secondary" size="sm" (click)="edit.emit(product.id)">{{ 'adminProducts.edit' | translate }}</app-button>
            <app-button variant="ghost" size="sm" (click)="duplicate.emit(product.id)">{{ 'adminProducts.duplicate' | translate }}</app-button>
            <app-button variant="ghost" size="sm" (click)="delete.emit(product.id)">{{ 'adminProducts.delete' | translate }}</app-button>
          </div>
        </app-card>
      }
    </div>
  }

  @if (products.length > 0) {
    <div class="pager">
      <span>{{ products.length }} / {{ total }} {{ 'adminProducts.items' | translate }}</span>
      @if (infiniteScroll) {
        @if (products.length < total) {
          <app-button variant="secondary" size="sm" (click)="loadMore.emit()">{{ 'adminProducts.loadMore' | translate }}</app-button>
        }
      } @else {
        <app-pagination [currentPage]="filters.page" [totalPages]="totalPages()" (pageChange)="filtersChange.emit({ page: $event })" />
      }
    </div>
  }

  <app-dialog [open]="assignCategoryOpen()" [titleText]="'adminProducts.bulkAssignCategory' | translate" size="sm" (closed)="assignCategoryOpen.set(false)">
    <div class="dialog-body">
      <select #categorySelect>
        @for (category of categories; track category.id) {
          <option [value]="category.id">{{ category.title }}</option>
        }
      </select>
      <div class="dialog-actions">
        <app-button variant="secondary" (click)="assignCategoryOpen.set(false)">{{ 'mediaLibrary.cancel' | translate }}</app-button>
        <app-button variant="primary" (click)="confirmAssignCategory(categorySelect.value)">{{ 'mediaLibrary.confirm' | translate }}</app-button>
      </div>
    </div>
  </app-dialog>

  <app-dialog [open]="assignTagsOpen()" [titleText]="'adminProducts.bulkAssignTags' | translate" size="sm" (closed)="assignTagsOpen.set(false)">
    <div class="dialog-body">
      <app-input [ngModel]="tagsInput()" (ngModelChange)="tagsInput.set($event)" [placeholder]="'adminProducts.tagsPlaceholder' | translate" />
      <div class="dialog-actions">
        <app-button variant="secondary" (click)="assignTagsOpen.set(false)">{{ 'mediaLibrary.cancel' | translate }}</app-button>
        <app-button variant="primary" (click)="confirmAssignTags()">{{ 'mediaLibrary.confirm' | translate }}</app-button>
      </div>
    </div>
  </app-dialog>
</section>
