<p-toast />
<p-confirmDialog />

<div class="products-page">
  <app-page-header title="PRODUCTS.TITLE" subtitle="PRODUCTS.SUBTITLE" (refresh)="retry()">
    <p-button
      [label]="'PRODUCTS.NEW_PRODUCT' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
    <p-button
      [label]="'PRODUCTS.ADD_MULTIPLE' | translate"
      icon="pi pi-plus-circle"
      [outlined]="true"
      (onClick)="openMulti()"
    />
    <p-button
      [label]="'PRODUCTS.IMPORT_CSV' | translate"
      icon="pi pi-upload"
      [outlined]="true"
      severity="secondary"
      (onClick)="openImport()"
    />
    <p-button
      icon="pi pi-barcode"
      [rounded]="true"
      [outlined]="true"
      severity="secondary"
      (onClick)="openBarcodeSettings()"
      pTooltip="{{ 'PRODUCTS.BARCODE_SETTINGS' | translate }}"
    />
    <p-button
      icon="pi pi-cog"
      [rounded]="true"
      [outlined]="true"
      severity="secondary"
      (onClick)="openSkuSettings()"
      pTooltip="{{ 'PRODUCTS.SKU_SETTINGS' | translate }}"
    />
    <p-button
      icon="pi pi-sitemap"
      [rounded]="true"
      [outlined]="showCategoryInName()"
      [severity]="showCategoryInName() ? 'info' : 'secondary'"
      (onClick)="toggleShowCategoryInName()"
      pTooltip="{{ 'PRODUCTS.SHOW_CATEGORY_PATH' | translate }}"
    />
    <p-button
      icon="pi pi-print"
      [rounded]="true"
      [outlined]="true"
      severity="secondary"
      (onClick)="openBatchPrint()"
      pTooltip="{{ 'PRODUCTS.BATCH_PRINT' | translate }}"
    />
    <p-button
      [icon]="viewMode() === 'table' ? 'pi pi-objects-column' : 'pi pi-list'"
      [rounded]="true"
      [outlined]="viewMode() === 'table'"
      [severity]="viewMode() === 'tree' ? 'info' : 'secondary'"
      (onClick)="toggleViewMode()"
      pTooltip="{{ 'PRODUCTS.TREE_VIEW' | translate }}"
    />
  </app-page-header>

  @if (viewMode() === 'table') {
    <ng-template #filtersTpl>
      <!-- Server-side Search Bar -->
      <div class="search-bar" style="display:flex; align-items:center; gap:0.75rem; padding:0.75rem 1rem; border-bottom:1px solid #e2e8f0; background:#f8fafc;">
        <i class="pi pi-search" style="color:#64748b;"></i>
        <input
          pInputText
          [value]="searchQuery()"
          (input)="onSearch($event)"
          [placeholder]="'PRODUCTS.SEARCH_PLACEHOLDER' | translate"
          style="flex:1; border:none; background:transparent; outline:none; font-size:0.95rem;"
        />
        @if (searchQuery()) {
          <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="secondary" size="small" (onClick)="clearSearch()" />
        }
        @if (searchLoading()) {
          <i class="pi pi-spinner pi-spin" style="color:#64748b;"></i>
        }
        @if (searchResults() !== null) {
          <span style="color:#64748b; font-size:0.85rem; white-space:nowrap;">{{ searchResults()!.length }} {{ 'COMMON.RESULTS' | translate }}</span>
        }
      </div>
    </ng-template>
    <ng-template #bodyTpl let-product>
      <tr>
        <td class="mono">{{ product.code }}</td>
        <td>{{ getProductDisplayName(product) }}</td>
        <td class="mono">{{ product.barcode || '—' }}</td>
        <td>
          <p-tag
            [value]="product.type?.label || product.type"
            [severity]="product.type?.value === 'service' ? 'info' : 'warn'"
          />
        </td>
        <td class="mono">{{ product.sale_price }}</td>
        <td class="mono">{{ product.purchase_price }}</td>
        <td>{{ product.category?.name || '—' }}</td>
        <td>
          <p-tag
            [value]="product.status?.label || product.status"
            [severity]="product.status?.value === 'active' ? 'success' : product.status?.value === 'inactive' ? 'danger' : 'warn'"
          />
        </td>
        <td>
          <div class="action-buttons">
            <p-button
              icon="pi pi-eye"
              [rounded]="true"
              [text]="true"
              severity="help"
              (onClick)="viewProduct(product)"
              pTooltip="{{ 'PRODUCTS.VIEW_PRODUCT' | translate }}"
            />
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editProduct(product)"
            />
            <p-button
              icon="pi pi-print"
              [rounded]="true"
              [text]="true"
              severity="secondary"
              (onClick)="openPrintDialog(product)"
              pTooltip="{{ 'PRODUCTS.PRINT_BARCODE' | translate }}"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteProduct(product)"
            />
          </div>
        </td>
      </tr>
    </ng-template>
    <app-data-table
      [data]="displayProducts()"
      [loading]="tableLoading()"
      [columns]="columns"
      [lazy]="true"
      [totalRecords]="totalRecords()"
      [first]="first"
      [rows]="pageSize"
      (onLazyLoad)="onPageChange($event)"
      (retry)="retry()"
      [bodyTpl]="bodyTpl"
      [filtersTpl]="filtersTpl"
    >
    </app-data-table>
  }

  @if (viewMode() === 'tree') {
    <div class="tree-view-card">
      <div class="tree-toolbar">
        <span class="tree-title">
          <i class="pi pi-objects-column"></i>
          {{ 'PRODUCTS.TREE_VIEW' | translate }}
        </span>
        <p-button
          icon="pi pi-refresh"
          [rounded]="true"
          [text]="true"
          severity="secondary"
          (onClick)="loadTreeView()"
          [loading]="treeLoading()"
        />
      </div>
      @if (treeLoading()) {
        <div class="tree-loading">
          <p-progressSpinner [style]="{ width: '40px', height: '40px' }" strokeWidth="4" />
        </div>
      } @else {
        <p-treetable
          [value]="treeNodes()"
          [columns]="[
            { field: 'code', header: ('PRODUCTS.CODE' | translate) },
            { field: 'name', header: ('PRODUCTS.NAME_AR' | translate) },
            { field: 'sale_price', header: ('PRODUCTS.SALE_PRICE' | translate) },
            { field: 'purchase_price', header: ('PRODUCTS.PURCHASE_PRICE' | translate) },
            { field: 'status', header: ('COMMON.STATUS' | translate) },
            { field: 'actions', header: ('COMMON.ACTIONS' | translate) }
          ]"
          [scrollable]="true"
          styleClass="tree-table-custom"
        >
          <ng-template #header let-columns>
            <tr>
              @for (col of columns; track col.field) {
                <th>{{ col.header }}</th>
              }
            </tr>
          </ng-template>
          <ng-template #body let-rowNode let-rowData="rowData">
            <tr>
              <td>
                <p-treeTableToggler [rowNode]="rowNode" />
                @if (rowData.isCategory) {
                  <span class="tree-cat-code mono">{{ rowData.code }}</span>
                } @else {
                  <span class="mono">{{ rowData.code }}</span>
                }
              </td>
              <td>
                @if (rowData.isCategory) {
                  <span class="tree-cat-name">
                    <i class="pi pi-folder-open"></i>
                    {{ rowData.name }}
                    <span class="tree-cat-count">({{ rowData.productCount }})</span>
                  </span>
                } @else {
                  <span class="tree-product-name">
                    <i class="pi pi-box"></i>
                    {{ rowData.name }}
                  </span>
                }
              </td>
              <td>
                @if (rowData.isProduct) {
                  <span class="mono">{{ rowData.sale_price }}</span>
                }
              </td>
              <td>
                @if (rowData.isProduct) {
                  <span class="mono">{{ rowData.purchase_price }}</span>
                }
              </td>
              <td>
                @if (rowData.isProduct) {
                  <p-tag
                    [value]="rowData.status?.label || rowData.status"
                    [severity]="rowData.status?.value === 'active' ? 'success' : rowData.status?.value === 'inactive' ? 'danger' : 'warn'"
                  />
                }
              </td>
              <td>
                @if (rowData.isProduct) {
                  <div class="action-buttons">
                    <p-button
                      icon="pi pi-eye"
                      [rounded]="true"
                      [text]="true"
                      severity="help"
                      (onClick)="viewProduct(rowData.product)"
                      pTooltip="{{ 'PRODUCTS.VIEW_PRODUCT' | translate }}"
                    />
                    <p-button
                      icon="pi pi-pencil"
                      [rounded]="true"
                      [text]="true"
                      severity="info"
                      (onClick)="editProduct(rowData.product)"
                    />
                    <p-button
                      icon="pi pi-print"
                      [rounded]="true"
                      [text]="true"
                      severity="secondary"
                      (onClick)="openPrintDialog(rowData.product)"
                      pTooltip="{{ 'PRODUCTS.PRINT_BARCODE' | translate }}"
                    />
                    <p-button
                      icon="pi pi-trash"
                      [rounded]="true"
                      [text]="true"
                      severity="danger"
                      (onClick)="deleteProduct(rowData.product)"
                    />
                  </div>
                }
              </td>
            </tr>
          </ng-template>
          <ng-template #empty>
            <tr>
              <td colspan="6" class="text-center">
                {{ 'COMMON.NO_DATA' | translate }}
              </td>
            </tr>
          </ng-template>
        </p-treetable>
      }
    </div>
  }
</div>

<!-- Single Product Dialog (new / edit) — Tabbed Layout -->
<app-form-dialog
  [(visible)]="editDialogVisible"
  [header]="editingProduct() ? ('PRODUCTS.EDIT_PRODUCT' | translate) : ('PRODUCTS.NEW_PRODUCT' | translate)"
  [saving]="savingProduct()"
  [width]="'850px'"
  (save)="onSaveEdit()"
>
  <form [formGroup]="productForm" class="dialog-form product-tabbed-form">
    <p-tabs value="0">
      <p-tablist>
        <p-tab value="0"><i class="pi pi-box"></i> {{ 'PRODUCTS.TAB_BASIC' | translate }}</p-tab>
        <p-tab value="1"><i class="pi pi-list"></i> {{ 'PRODUCTS.TAB_DETAILS' | translate }}</p-tab>
        <p-tab value="2"><i class="pi pi-th-large"></i> {{ 'PRODUCTS.TAB_VARIANTS' | translate }}</p-tab>
      </p-tablist>
      <p-tabpanels>
        <!-- ═══ TAB 1: Basic Info ═══ -->
        <p-tabpanel value="0">
          <div class="tab-content">
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.NAME_AR' | translate }} *</label>
                <input pInputText formControlName="name_ar" />
                @if (productForm.get('name_ar')?.touched && productForm.get('name_ar')?.hasError('required')) {
                  <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
                }
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.NAME_EN' | translate }}</label>
                <input pInputText formControlName="name_en" />
              </div>
            </div>
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.TYPE' | translate }} *</label>
                <p-select formControlName="type" [options]="typeOptions" optionLabel="label" optionValue="value" />
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.CATEGORY' | translate }}</label>
                <p-select
                  formControlName="product_category_id"
                  [options]="(categories$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [filter]="true"
                  filterBy="name,name_ar,name_en,code"
                  [showClear]="true"
                  [placeholder]="'PRODUCTS.SELECT_CATEGORY' | translate"
                  (onChange)="onCategoryChangeEdit()"
                />
              </div>
            </div>
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.UNIT' | translate }}</label>
                <p-select
                  formControlName="base_unit_id"
                  [options]="(units$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [filter]="true"
                  filterBy="name,name_ar,name_en"
                  [showClear]="true"
                  [placeholder]="'PRODUCTS.SELECT_UNIT' | translate"
                />
              </div>
              <div class="form-field">
                <label>{{ 'COMMON.STATUS' | translate }} *</label>
                <p-select formControlName="status" [options]="statusOptions" optionLabel="label" optionValue="value" />
              </div>
            </div>
            <h4 class="section-title">{{ 'PRODUCTS.PRICING' | translate }}</h4>
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.PURCHASE_PRICE' | translate }}</label>
                <p-inputNumber formControlName="purchase_price" [mode]="'decimal'" [minFractionDigits]="3" />
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.SALE_PRICE' | translate }}</label>
                <p-inputNumber formControlName="sale_price" [mode]="'decimal'" [minFractionDigits]="3" />
              </div>
            </div>
          </div>
        </p-tabpanel>

        <!-- ═══ TAB 2: Details ═══ -->
        <p-tabpanel value="1">
          <div class="tab-content">
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.CODE' | translate }}</label>
                <input pInputText formControlName="code" [placeholder]="'COMMON.AUTO_GENERATED' | translate" />
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.SKU' | translate }}</label>
                <div style="display:flex; gap:0.5rem; align-items:center;">
                  <input pInputText formControlName="sku" style="flex:1;" />
                  <p-button icon="pi pi-sync" [rounded]="true" [outlined]="true" severity="secondary" size="small" (onClick)="generateSku()" pTooltip="{{ 'PRODUCTS.GENERATE_SKU' | translate }}" />
                </div>
              </div>
            </div>
            <div class="form-field">
              <label>{{ 'PRODUCTS.BARCODE' | translate }}</label>
              <div style="display:flex; gap:0.5rem; align-items:center;">
                <input pInputText formControlName="barcode" style="flex:1;" />
                <p-button icon="pi pi-barcode" [rounded]="true" [outlined]="true" severity="secondary" size="small" (onClick)="generateBarcode()" pTooltip="{{ 'PRODUCTS.GENERATE_BARCODE' | translate }}" />
              </div>
            </div>
            <h4 class="section-title">{{ 'PRODUCTS.PRICING' | translate }}</h4>
            <div class="form-row">
              <div class="form-field">
                <label>{{ 'PRODUCTS.WHOLESALE_PRICE' | translate }}</label>
                <p-inputNumber formControlName="wholesale_price" [mode]="'decimal'" [minFractionDigits]="3" />
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.HALF_WHOLESALE_PRICE' | translate }}</label>
                <p-inputNumber formControlName="half_wholesale_price" [mode]="'decimal'" [minFractionDigits]="3" />
              </div>
            </div>
            <div class="form-field">
              <label>{{ 'PRODUCTS.DESCRIPTION' | translate }}</label>
              <input pInputText formControlName="description" />
            </div>

            <!-- Product Images (edit mode only) -->
            @if (editingProduct()) {
              <h4 class="section-title">{{ 'PRODUCTS.MAIN_IMAGE' | translate }}</h4>
              <div class="image-section">
                @if (productMainImageBlob() || productMainImage()) {
                  <div class="image-preview">
                    <img [src]="productMainImageBlob() || productMainImage()" alt="Product main image" />
                    <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="removeMainImage()" pTooltip="{{ 'PRODUCTS.DELETE_IMAGE' | translate }}" />
                  </div>
                }
                <div class="image-upload-btn">
                  <label class="upload-label">
                    <i class="pi pi-camera"></i>
                    {{ 'PRODUCTS.UPLOAD_IMAGE' | translate }}
                    <input type="file" accept="image/*" (change)="onMainImageSelect($event)" hidden />
                  </label>
                </div>
              </div>

              <h4 class="section-title">{{ 'PRODUCTS.GALLERY' | translate }}</h4>
              <div class="image-section">
                @if (productGallery().length > 0) {
                  <div class="gallery-grid">
                    @for (img of productGallery(); track img.id) {
                      <div class="gallery-item">
                        <img [src]="getGalleryBlobUrl(img) || getAttachmentUrl(img)" [alt]="img.file_name" />
                        <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" class="gallery-delete" (onClick)="deleteGalleryImage(img)" />
                      </div>
                    }
                  </div>
                }
                <div class="image-upload-btn">
                  <label class="upload-label">
                    <i class="pi pi-images"></i>
                    {{ 'PRODUCTS.UPLOAD_IMAGE' | translate }}
                    <input type="file" accept="image/*" multiple (change)="onGalleryImageSelect($event)" hidden />
                  </label>
                </div>
                @if (imageUploading()) {
                  <p-progressSpinner strokeWidth="4" [style]="{ width: '24px', height: '24px' }" />
                }
              </div>
            }

            <h4 class="section-title">{{ 'PRODUCTS.TRACK_INVENTORY' | translate }}</h4>
            <div class="form-row">
              <div class="form-field switch-field-wrap">
                <label>{{ 'PRODUCTS.TRACK_INVENTORY' | translate }}</label>
                <p-toggleSwitch formControlName="track_inventory" />
              </div>
              <div class="form-field">
                <label>{{ 'PRODUCTS.TRACKING_TYPE' | translate }}</label>
                <p-select formControlName="tracking_type" [options]="trackingTypeOptions" optionLabel="label" optionValue="value" />
              </div>
            </div>
            @if (productForm.get('track_inventory')?.value) {
              <div class="form-row">
                <div class="form-field">
                  <label>{{ 'PRODUCTS.REORDER_POINT' | translate }}</label>
                  <p-inputNumber formControlName="reorder_point" [min]="0" mode="decimal" [showButtons]="true" />
                </div>
                <div class="form-field">
                  <label>{{ 'PRODUCTS.MIN_STOCK' | translate }}</label>
                  <p-inputNumber formControlName="min_stock_level" [min]="0" mode="decimal" [showButtons]="true" />
                </div>
                <div class="form-field">
                  <label>{{ 'PRODUCTS.MAX_STOCK' | translate }}</label>
                  <p-inputNumber formControlName="max_stock_level" [min]="0" mode="decimal" [showButtons]="true" />
                </div>
              </div>
              @if (!editingProduct()) {
                <div class="form-row">
                  <div class="form-field">
                    <label>{{ 'PRODUCTS.INITIAL_QUANTITY' | translate }}</label>
                    <p-inputNumber formControlName="initial_quantity" [min]="0" mode="decimal" [showButtons]="true" />
                  </div>
                </div>
              }
            }
          </div>
        </p-tabpanel>

        <!-- ═══ TAB 3: Variants & More ═══ -->
        <p-tabpanel value="2">
          <div class="tab-content">
            <div class="form-field switch-field-wrap">
              <label>{{ 'PRODUCTS.HAS_VARIANTS' | translate }}</label>
              <p-toggleSwitch [(ngModel)]="hasVariants" [ngModelOptions]="{ standalone: true }" />
            </div>

            @if (hasVariants()) {
              <!-- Variant Type -->
              <div class="form-row">
                <div class="form-field">
                  <label>{{ 'PRODUCTS.VARIANT_TYPE' | translate }}</label>
                  <p-select [(ngModel)]="variantType" [ngModelOptions]="{ standalone: true }" [options]="variantTypeOptions" optionLabel="label" optionValue="value" />
                </div>
              </div>

              <!-- Variant Pricing Mode -->
              <div class="form-row">
                <div class="form-field">
                  <label>{{ 'PRODUCTS.VARIANT_PRICING' | translate }}</label>
                  <p-select [ngModel]="variantPricingMode()" (ngModelChange)="variantPricingMode.set($event)" [ngModelOptions]="{ standalone: true }" [options]="variantPricingOptions" optionLabel="label" optionValue="value" />
                </div>
              </div>

              <!-- Attribute Builder -->
              <div class="variant-builder">
                <label class="builder-label">{{ 'PRODUCTS.VARIANT_ATTRS' | translate }}</label>
                @for (attr of variantAttributes(); track $index; let i = $index) {
                  <div class="attr-row">
                    <input pInputText [(ngModel)]="attr.name" [ngModelOptions]="{ standalone: true }" [placeholder]="'PRODUCTS.ATTR_NAME_HINT' | translate" class="attr-name" />
                    <input pInputText [(ngModel)]="attr.values" [ngModelOptions]="{ standalone: true }" [placeholder]="'PRODUCTS.ATTR_VALUES_HINT' | translate" class="attr-values" />
                    @if (variantAttributes().length > 1) {
                      <p-button icon="pi pi-times" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="removeAttribute(i)" />
                    }
                  </div>
                }
                <div class="attr-actions">
                  <p-button [label]="'PRODUCTS.ADD_ATTRIBUTE' | translate" icon="pi pi-plus" severity="secondary" [outlined]="true" size="small" (onClick)="addAttribute()" />
                  <p-button [label]="'PRODUCTS.GENERATE_VARIANTS' | translate" icon="pi pi-th-large" severity="info" size="small" (onClick)="generateVariantCombinations()" />
                </div>
              </div>

              <!-- Generated Variants Grid -->
              @if (generatedVariants().length > 0) {
                <div class="variant-grid">
                  <div class="variant-grid-header">
                    <span>{{ generatedVariants().length }} {{ 'PRODUCTS.VARIANTS_GENERATED' | translate }}</span>
                  </div>
                  <div class="sub-table">
                    <table>
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>{{ 'PRODUCTS.VARIANT_COMBO' | translate }}</th>
                          <th>{{ 'PRODUCTS.SKU' | translate }}</th>
                          <th>{{ 'PRODUCTS.BARCODE' | translate }}</th>
                          @if (variantPricingMode() === 'single') {
                            <th>{{ 'PRODUCTS.SALE_PRICE' | translate }}</th>
                          } @else if (variantPricingMode() === 'multiple') {
                            <th>{{ 'PRODUCTS.SALE_PRICE' | translate }}</th>
                            <th>{{ 'PRODUCTS.WHOLESALE_PRICE' | translate }}</th>
                            <th>{{ 'PRODUCTS.HALF_WHOLESALE_PRICE' | translate }}</th>
                            <th>{{ 'PRODUCTS.VARIANT_ADDITIONAL_PRICE' | translate }}</th>
                          }
                        </tr>
                      </thead>
                      <tbody>
                        @for (row of generatedVariants(); track $index; let i = $index) {
                          <tr>
                            <td class="mono" style="width:40px; text-align:center;">{{ i + 1 }}</td>
                            <td>
                              @for (kv of (row.attributes | keyvalue); track kv.key) {
                                <p-tag [value]="kv.value" severity="info" styleClass="me-1" />
                              }
                            </td>
                            <td><input pInputText [(ngModel)]="row.sku" [ngModelOptions]="{ standalone: true }" style="width:120px;" /></td>
                            <td><input pInputText [(ngModel)]="row.barcode" [ngModelOptions]="{ standalone: true }" style="width:120px;" /></td>
                            @if (variantPricingMode() === 'single') {
                              <td><p-inputNumber [(ngModel)]="row.sale_price" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" [style]="{ width: '100px' }" /></td>
                            } @else if (variantPricingMode() === 'multiple') {
                              <td><p-inputNumber [(ngModel)]="row.sale_price" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" [style]="{ width: '90px' }" /></td>
                              <td><p-inputNumber [(ngModel)]="row.wholesale_price" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" [style]="{ width: '90px' }" /></td>
                              <td><p-inputNumber [(ngModel)]="row.half_wholesale_price" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" [style]="{ width: '90px' }" /></td>
                              <td><p-inputNumber [(ngModel)]="row.additional_price" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" [style]="{ width: '90px' }" /></td>
                            }
                          </tr>
                        }
                      </tbody>
                    </table>
                  </div>
                  @if (editingProduct()) {
                    <div style="margin-top:0.5rem;">
                      <p-button [label]="'PRODUCTS.ADD_VARIANTS_TO_PRODUCT' | translate" icon="pi pi-check" (onClick)="addNewVariantToProduct()" [loading]="variantsSaving()" />
                    </div>
                  }
                </div>
              }

              <!-- Existing Variants (edit mode) -->
              @if (editingProduct() && productVariants().length > 0) {
                <div class="variant-grid">
                  <div class="variant-grid-header">
                    <span>{{ 'PRODUCTS.EXISTING_VARIANTS' | translate }} ({{ productVariants().length }})</span>
                  </div>
                  <div class="sub-table">
                    <table>
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>{{ 'PRODUCTS.NAME_AR' | translate }}</th>
                          <th>{{ 'PRODUCTS.SKU' | translate }}</th>
                          <th>{{ 'PRODUCTS.BARCODE' | translate }}</th>
                          <th>{{ 'PRODUCTS.VARIANT_ADDITIONAL_PRICE' | translate }}</th>
                          <th>{{ 'PRODUCTS.PRICES' | translate }}</th>
                          <th>{{ 'PRODUCTS.VARIANT_ATTRIBUTES' | translate }}</th>
                          <th>{{ 'COMMON.STATUS' | translate }}</th>
                          <th></th>
                        </tr>
                      </thead>
                      <tbody>
                        @for (v of productVariants(); track v.id; let i = $index) {
                          <tr>
                            <td class="mono" style="width:40px; text-align:center;">{{ i + 1 }}</td>
                            <td>{{ v.name || '—' }}</td>
                            <td class="mono">{{ v.sku || '—' }}</td>
                            <td class="mono">{{ v.barcode || '—' }}</td>
                            <td class="mono">{{ v.additional_price || 0 }}</td>
                            <td class="mono" style="font-size:0.8rem;">{{ getVariantPriceText(v.id) }}</td>
                            <td>
                              @if (v.attributes) {
                                @for (key of (v.attributes | keyvalue); track key.key) {
                                  <p-tag [value]="key.key + ': ' + key.value" severity="info" styleClass="me-1" />
                                }
                              } @else {
                                <span>—</span>
                              }
                            </td>
                            <td>
                              <p-tag
                                [value]="v.is_active ? ('COMMON.ACTIVE' | translate) : ('COMMON.INACTIVE' | translate)"
                                [severity]="v.is_active ? 'success' : 'danger'"
                              />
                            </td>
                            <td>
                              <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="deleteExistingVariant(v)" />
                            </td>
                          </tr>
                        }
                      </tbody>
                    </table>
                  </div>
                </div>
              }
            }

            <!-- Product Units (edit only) -->
            @if (editingProduct()) {
              <h4 class="section-title">{{ 'PRODUCTS.ALTERNATIVE_UNITS' | translate }}</h4>
              @if (productUnits().length > 0) {
                <div class="sub-table">
                  <table>
                    <thead>
                      <tr>
                        <th>{{ 'PRODUCTS.UNIT' | translate }}</th>
                        <th>{{ 'PRODUCTS.CONVERSION_FACTOR' | translate }}</th>
                        <th>{{ 'PRODUCTS.PURCHASE_PRICE' | translate }}</th>
                        <th>{{ 'PRODUCTS.SALE_PRICE' | translate }}</th>
                      </tr>
                    </thead>
                    <tbody>
                      @for (pu of productUnits(); track pu.id) {
                        <tr>
                          <td>{{ pu.unit?.name || ('ID: ' + pu.unit_id) }}</td>
                          <td class="mono">{{ pu.conversion_factor }}</td>
                          <td class="mono">{{ pu.purchase_price }}</td>
                          <td class="mono">{{ pu.sale_price }}</td>
                        </tr>
                      }
                    </tbody>
                  </table>
                </div>
              }
              <div class="add-price-row">
                <p-select
                  [(ngModel)]="newUnitId"
                  [ngModelOptions]="{ standalone: true }"
                  [options]="(units$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [placeholder]="'PRODUCTS.SELECT_UNIT' | translate"
                  [filter]="true"
                />
                <p-inputNumber [(ngModel)]="newUnitFactor" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="2" />
                <p-button icon="pi pi-plus" [rounded]="true" (onClick)="addProductUnit()" [disabled]="!newUnitId()" />
              </div>
            }

            <!-- Prices section (edit only) -->
            @if (editingProduct()) {
              <h4 class="section-title">{{ 'PRODUCTS.PRICES' | translate }}</h4>
              @if (productPrices().length > 0) {
                <div class="sub-table">
                  <table>
                    <thead>
                      <tr>
                        <th>{{ 'PRODUCTS.PRICE_TYPE' | translate }}</th>
                        <th>{{ 'PRODUCTS.PRICE' | translate }}</th>
                        <th></th>
                      </tr>
                    </thead>
                    <tbody>
                      @for (price of productPrices(); track price.id) {
                        <tr>
                          <td>{{ $any(price.price_type).label || price.price_type }}</td>
                          <td class="mono">{{ price.price }}</td>
                          <td>
                            <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="deleteProductPrice(price)" />
                          </td>
                        </tr>
                      }
                    </tbody>
                  </table>
                </div>
              } @else {
                <p class="no-data-text">{{ 'PRODUCTS.NO_PRICES' | translate }}</p>
              }
              <div class="add-price-row">
                <p-select
                  [(ngModel)]="newPriceType"
                  [ngModelOptions]="{ standalone: true }"
                  [options]="priceTypeOptions"
                  optionLabel="label"
                  optionValue="value"
                  [placeholder]="'PRODUCTS.SELECT_PRICE_TYPE' | translate"
                />
                <p-inputNumber [(ngModel)]="newPriceAmount" [ngModelOptions]="{ standalone: true }" [mode]="'decimal'" [minFractionDigits]="3" />
                <p-button icon="pi pi-plus" [rounded]="true" (onClick)="addPrice()" [disabled]="!newPriceType() || !newPriceAmount()" />
              </div>
            }

            <!-- Serial Numbers (edit mode + serial/batch tracking) - Read-only list -->
            @if (editingProduct() && productForm.get('tracking_type')?.value !== 'none') {
              <h4 class="section-title">{{ 'PRODUCTS.SERIAL_NUMBERS' | translate }}</h4>
              <p class="serial-hint">{{ 'PRODUCTS.SERIALS_VIA_RECEIPTS' | translate }}</p>
              @if (serialsLoading()) {
                <div style="text-align:center; padding:1rem;">
                  <p-progressSpinner strokeWidth="4" [style]="{ width: '24px', height: '24px' }" />
                </div>
              } @else if (productSerials().length > 0) {
                <div class="sub-table">
                  <table>
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>{{ 'PRODUCTS.SERIAL_NUMBER' | translate }}</th>
                        @if (productForm.get('tracking_type')?.value === 'batch') {
                          <th>{{ 'PRODUCTS.BATCH_NUMBER' | translate }}</th>
                        }
                        <th>{{ 'PRODUCTS.EXPIRY_DATE' | translate }}</th>
                        <th>{{ 'COMMON.STATUS' | translate }}</th>
                        <th>{{ 'PRODUCTS.WAREHOUSE' | translate }}</th>
                      </tr>
                    </thead>
                    <tbody>
                      @for (s of productSerials(); track s.id; let i = $index) {
                        <tr>
                          <td class="mono" style="width:40px; text-align:center;">{{ i + 1 }}</td>
                          <td class="mono">{{ s.serial_number }}</td>
                          @if (productForm.get('tracking_type')?.value === 'batch') {
                            <td class="mono">{{ s.batch_number || '—' }}</td>
                          }
                          <td>{{ s.expiry_date || '—' }}</td>
                          <td>
                            <p-tag [value]="s.status.label" [severity]="getSerialStatusSeverity(s.status.value)" />
                          </td>
                          <td>{{ s.warehouse_id || '—' }}</td>
                        </tr>
                      }
                    </tbody>
                  </table>
                </div>
              } @else {
                <p class="no-data-text">{{ 'PRODUCTS.NO_SERIALS' | translate }}</p>
              }
            }
          </div>
        </p-tabpanel>
      </p-tabpanels>
    </p-tabs>
  </form>
</app-form-dialog>

<!-- Multi-Product Entry Dialog (full screen) -->
<p-dialog
  [header]="'PRODUCTS.ADD_MULTIPLE' | translate"
  [(visible)]="multiDialogVisible"
  [modal]="true"
  [style]="{ width: '100vw', height: '100vh' }"
  [closable]="!multiSaving()"
  (onHide)="hideMultiDialog()"
  [maximizable]="false"
  styleClass="multi-product-dialog"
>
  <form [formGroup]="multiForm">
    <!-- Defaults Bar -->
    <div class="multi-defaults-bar">
      <div class="default-field">
        <label>{{ 'PRODUCTS.CATEGORY' | translate }}</label>
        <p-select
          [ngModel]="multiDefaultCategoryId()"
          [ngModelOptions]="{standalone: true}"
          (ngModelChange)="onDefaultCategoryChange($event)"
          [options]="(categories$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,name_ar,name_en"
          [showClear]="true"
          [placeholder]="'PRODUCTS.SELECT_CATEGORY' | translate"
          appendTo="body"
        />
      </div>
      <div class="default-field">
        <label>{{ 'PRODUCTS.UNIT' | translate }}</label>
        <p-select
          [ngModel]="multiDefaultUnitId()"
          [ngModelOptions]="{standalone: true}"
          (ngModelChange)="multiDefaultUnitId.set($event)"
          [options]="(units$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,name_ar,name_en"
          [showClear]="true"
          [placeholder]="'PRODUCTS.SELECT_UNIT' | translate"
          appendTo="body"
        />
      </div>
      <div class="default-field default-info">
        <i class="pi pi-info-circle"></i>
        <span>{{ 'PRODUCTS.MULTI_DEFAULTS_HINT' | translate }}</span>
      </div>
    </div>

    <!-- Compact Table -->
    <div class="multi-product-table compact">
      <table>
        <thead>
          <tr>
            <th class="col-num">#</th>
            <th class="col-name-wide">{{ 'PRODUCTS.NAME_AR' | translate }} *</th>
            <th class="col-barcode">{{ 'PRODUCTS.BARCODE' | translate }}</th>
            <th class="col-price">{{ 'PRODUCTS.PURCHASE_PRICE' | translate }}</th>
            <th class="col-price">{{ 'PRODUCTS.SALE_PRICE' | translate }}</th>
            <th class="col-price">{{ 'PRODUCTS.HALF_WHOLESALE_PRICE' | translate }}</th>
            <th class="col-price">{{ 'PRODUCTS.WHOLESALE_PRICE' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="rows">
          @for (row of rows.controls; track row; let i = $index) {
            <tr [formGroupName]="$index" [class.invalid-row]="row.invalid && row.touched">
              <td class="col-num">{{ i + 1 }}</td>
              <td class="col-name-wide">
                <input pInputText formControlName="name_ar"
                  [placeholder]="'PRODUCTS.NAME_AR' | translate"
                  (input)="onMultiRowInput(i)" />
              </td>
              <td class="col-barcode">
                <input pInputText formControlName="barcode"
                  [placeholder]="'PRODUCTS.BARCODE' | translate"
                  (input)="onMultiRowInput(i)" />
              </td>
              <td class="col-price">
                <p-inputNumber formControlName="purchase_price" [mode]="'decimal'"
                  [minFractionDigits]="2" (onInput)="onMultiRowInput(i)" />
              </td>
              <td class="col-price">
                <p-inputNumber formControlName="sale_price" [mode]="'decimal'"
                  [minFractionDigits]="2"
                  (onBlur)="onMultiSalePriceChange(i)"
                  (onInput)="onMultiRowInput(i)" />
              </td>
              <td class="col-price">
                <p-inputNumber formControlName="half_wholesale_price" [mode]="'decimal'"
                  [minFractionDigits]="2" (onInput)="onMultiRowInput(i)" />
              </td>
              <td class="col-price">
                <p-inputNumber formControlName="wholesale_price" [mode]="'decimal'"
                  [minFractionDigits]="2" (onInput)="onMultiRowInput(i)" />
              </td>
              <td class="col-action">
                @if (rows.length > 1) {
                  <p-button
                    icon="pi pi-times"
                    [rounded]="true"
                    [text]="true"
                    severity="danger"
                    size="small"
                    (onClick)="removeRow(i)"
                    [disabled]="multiSaving()"
                  />
                }
              </td>
            </tr>
          }
        </tbody>
      </table>
    </div>
    <div class="multi-actions-row">
      <p-button
        [label]="'PRODUCTS.ADD_ROW' | translate"
        icon="pi pi-plus"
        severity="secondary"
        [outlined]="true"
        (onClick)="addRow()"
        [disabled]="multiSaving()"
        size="small"
      />
      <span class="row-count">{{ rows.length }} {{ 'PRODUCTS.ROWS' | translate }}</span>
      @if (multiSaving()) {
        <span class="save-progress">
          <p-progressSpinner strokeWidth="4" [style]="{ width: '20px', height: '20px' }" />
          {{ multiProgress() }} / {{ multiTotal() }}
        </span>
      }
    </div>
  </form>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="hideMultiDialog()"
      [disabled]="multiSaving()"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSaveMulti()"
      [loading]="multiSaving()"
    />
  </ng-template>
</p-dialog>

<!-- CSV Import Dialog -->
<p-dialog
  [header]="'PRODUCTS.IMPORT_CSV' | translate"
  [(visible)]="importDialogVisible"
  [modal]="true"
  [style]="{ width: '500px' }"
  [closable]="!importSaving()"
>
  <div class="import-dialog">
    <p>{{ 'PRODUCTS.IMPORT_INSTRUCTIONS' | translate }}</p>
    <p class="import-columns"><strong>{{ 'PRODUCTS.IMPORT_REQUIRED_COLUMNS' | translate }}</strong></p>
    <div class="import-file-input">
      <input type="file" accept=".csv" (change)="onFileSelect($event)" />
    </div>
    @if (importFile()) {
      <p class="import-file-name">{{ importFile()!.name }}</p>
    }
  </div>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="importDialogVisible.set(false)"
      [disabled]="importSaving()"
    />
    <p-button
      [label]="'COMMON.IMPORT' | translate"
      icon="pi pi-upload"
      (onClick)="onImportCsv()"
      [loading]="importSaving()"
      [disabled]="!importFile()"
    />
  </ng-template>
</p-dialog>

<!-- Barcode Settings Dialog -->
<p-dialog
  [header]="'PRODUCTS.BARCODE_SETTINGS' | translate"
  [(visible)]="barcodeSettingsVisible"
  [modal]="true"
  [style]="{ width: '420px' }"
>
  <div class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PRODUCTS.BARCODE_PREFIX' | translate }}</label>
        <input pInputText [ngModel]="barcodeSettings().prefix" (ngModelChange)="barcodeSettings.set({...barcodeSettings(), prefix: $event})" placeholder="e.g. 620" />
      </div>
      <div class="form-field">
        <label>{{ 'PRODUCTS.BARCODE_SUFFIX' | translate }}</label>
        <input pInputText [ngModel]="barcodeSettings().suffix" (ngModelChange)="barcodeSettings.set({...barcodeSettings(), suffix: $event})" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'PRODUCTS.BARCODE_LENGTH' | translate }}</label>
      <p-inputNumber [ngModel]="barcodeSettings().numberLength" (ngModelChange)="barcodeSettings.set({...barcodeSettings(), numberLength: $event})" [min]="4" [max]="20" [showButtons]="true" />
    </div>
    <div class="form-field switch-field-wrap">
      <label>{{ 'PRODUCTS.BARCODE_AUTO_GENERATE' | translate }}</label>
      <p-toggleSwitch [ngModel]="barcodeSettings().autoGenerate" (ngModelChange)="barcodeSettings.set({...barcodeSettings(), autoGenerate: $event})" />
    </div>
  </div>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="barcodeSettingsVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="saveBarcodeSettings()" />
  </ng-template>
</p-dialog>

<!-- SKU Settings Dialog -->
<p-dialog
  [header]="'PRODUCTS.SKU_SETTINGS' | translate"
  [(visible)]="skuSettingsVisible"
  [modal]="true"
  [style]="{ width: '420px' }"
>
  <div class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PRODUCTS.SKU_PREFIX' | translate }}</label>
        <input pInputText [ngModel]="skuSettings().prefix" (ngModelChange)="skuSettings.set({...skuSettings(), prefix: $event})" placeholder="e.g. SKU-" />
      </div>
      <div class="form-field">
        <label>{{ 'PRODUCTS.SKU_SUFFIX' | translate }}</label>
        <input pInputText [ngModel]="skuSettings().suffix" (ngModelChange)="skuSettings.set({...skuSettings(), suffix: $event})" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'PRODUCTS.SKU_LENGTH' | translate }}</label>
      <p-inputNumber [ngModel]="skuSettings().numberLength" (ngModelChange)="skuSettings.set({...skuSettings(), numberLength: $event})" [min]="4" [max]="20" [showButtons]="true" />
    </div>
    <div class="form-field switch-field-wrap">
      <label>{{ 'PRODUCTS.SKU_AUTO_GENERATE' | translate }}</label>
      <p-toggleSwitch [ngModel]="skuSettings().autoGenerate" (ngModelChange)="skuSettings.set({...skuSettings(), autoGenerate: $event})" />
    </div>
  </div>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="skuSettingsVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="saveSkuSettings()" />
  </ng-template>
</p-dialog>

<!-- Barcode Label Print Dialog -->
<p-dialog
  [header]="'PRODUCTS.PRINT_BARCODE' | translate"
  [(visible)]="printDialogVisible"
  [modal]="true"
  [style]="{ width: '600px' }"
>
  <div class="dialog-form">
    <!-- Label Size -->
    <div class="form-field">
      <label>{{ 'PRODUCTS.LABEL_SIZE' | translate }}</label>
      <p-select
        [ngModel]="labelConfig().size"
        (ngModelChange)="onLabelSizeChange($event)"
        [options]="labelSizeOptions"
        optionLabel="label"
        optionValue="value"
      />
    </div>
    @if (labelConfig().size === 'custom') {
      <div class="form-row">
        <div class="form-field">
          <label>{{ 'PRODUCTS.LABEL_WIDTH' | translate }} (mm)</label>
          <p-inputNumber [ngModel]="labelConfig().width" (ngModelChange)="updateLabelField('width', $event)" [min]="20" [max]="200" [showButtons]="true" />
        </div>
        <div class="form-field">
          <label>{{ 'PRODUCTS.LABEL_HEIGHT' | translate }} (mm)</label>
          <p-inputNumber [ngModel]="labelConfig().height" (ngModelChange)="updateLabelField('height', $event)" [min]="15" [max]="150" [showButtons]="true" />
        </div>
      </div>
    }
    <!-- Fields to show -->
    <div class="print-options">
      <div class="form-field switch-field-wrap">
        <p-checkbox [ngModel]="labelConfig().showName" (ngModelChange)="updateLabelField('showName', $event)" [binary]="true" inputId="showName" />
        <label for="showName">{{ 'PRODUCTS.SHOW_NAME' | translate }}</label>
      </div>
      <div class="form-field switch-field-wrap">
        <p-checkbox [ngModel]="labelConfig().showPrice" (ngModelChange)="updateLabelField('showPrice', $event)" [binary]="true" inputId="showPrice" />
        <label for="showPrice">{{ 'PRODUCTS.SHOW_PRICE' | translate }}</label>
      </div>
      <div class="form-field switch-field-wrap">
        <p-checkbox [ngModel]="labelConfig().showSku" (ngModelChange)="updateLabelField('showSku', $event)" [binary]="true" inputId="showSku" />
        <label for="showSku">{{ 'PRODUCTS.SHOW_SKU' | translate }}</label>
      </div>
      <div class="form-field switch-field-wrap">
        <p-checkbox [ngModel]="labelConfig().showBarcode" (ngModelChange)="updateLabelField('showBarcode', $event)" [binary]="true" inputId="showBarcode" />
        <label for="showBarcode">{{ 'PRODUCTS.BARCODE' | translate }}</label>
      </div>
    </div>
    <!-- Copies -->
    <div class="form-field">
      <label>{{ 'PRODUCTS.COPIES' | translate }}</label>
      <p-inputNumber [ngModel]="labelConfig().copies" (ngModelChange)="updateLabelField('copies', $event)" [min]="1" [max]="100" [showButtons]="true" />
    </div>
    <!-- Preview info -->
    <div class="print-info">
      <span>{{ printProducts().length }} {{ 'PRODUCTS.TITLE' | translate }} × {{ labelConfig().copies }} {{ 'PRODUCTS.COPIES' | translate }} = {{ printProducts().length * labelConfig().copies }} {{ 'PRODUCTS.LABELS_TOTAL' | translate }}</span>
    </div>
  </div>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="printDialogVisible.set(false)" />
    <p-button [label]="'PRODUCTS.PRINT' | translate" icon="pi pi-print" (onClick)="printLabels()" />
  </ng-template>
</p-dialog>
