@if (loading()) {
  <div class="pos-loading">
    <i class="pi pi-spin pi-spinner text-4xl"></i>
  </div>
} @else {
  @if (posLayout() === 'cashier') {
    <!-- ===== CASHIER LAYOUT ===== -->
    <div class="cashier-layout">
      <app-pos-header
        [cashierMode]="true"
        [session]="session()"
        [connectionStatus]="connectionStatus()"
        [pendingCount]="pendingCount()"
        [isSyncing]="offlineService.isSyncing()"
        [posLayout]="posLayout()"
        [keyboardEnabled]="onScreenKeyboardEnabled()"
        [keyboardVisible]="showOnScreenKeyboard()"
        (productSelected)="onProductSelected($event)"
        (exitRequested)="onExitRequested()"
        (layoutToggled)="toggleLayout()"
        (keyboardToggled)="toggleOnScreenKeyboard()"
        (keyboardSettingToggled)="toggleOnScreenKeyboardSetting()"
        (syncRequested)="onManualSync()"
      />

      <!-- On-screen Arabic keyboard overlay -->
      @if (showOnScreenKeyboard() && onScreenKeyboardEnabled()) {
        <div class="osk-overlay">
          <div class="osk-container" (click)="$event.stopPropagation()">
            <div class="osk-header">
              <i class="pi pi-calculator"></i>
              <span>{{ 'POS.ONSCREEN_KEYBOARD' | translate }}</span>
              <!-- Language toggle tabs -->
              <div class="osk-lang-tabs">
                <button class="osk-lang-tab" [class.active]="oskLang() === 'ar'" (click)="oskLang.set('ar')">عربي</button>
                <button class="osk-lang-tab" [class.active]="oskLang() === 'en'" (click)="oskLang.set('en')">EN</button>
                <button class="osk-lang-tab" [class.active]="oskLang() === 'symbols'" (click)="oskLang.set(oskLang() === 'symbols' ? 'ar' : 'symbols')">!#&</button>
              </div>
              <button class="osk-close" (click)="showOnScreenKeyboard.set(false)">
                <i class="pi pi-times"></i>
              </button>
            </div>
            <div class="osk-rows">
              @if (oskLang() === 'ar') {
                <!-- Arabic -->
                <div class="osk-row">
                  @for (char of ['ض','ص','ث','ق','ف','غ','ع','ه','خ','ح','ج']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['ش','س','ي','ب','ل','ا','ت','ن','م','ك','ط']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['ئ','ء','ؤ','ر','ﻻ','ى','ة','و','ز','ظ']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
              } @else if (oskLang() === 'en') {
                <!-- English -->
                <div class="osk-row">
                  @for (char of ['Q','W','E','R','T','Y','U','I','O','P']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['A','S','D','F','G','H','J','K','L']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['Z','X','C','V','B','N','M']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
              } @else {
                <!-- Symbols & Numbers -->
                <div class="osk-row">
                  @for (char of ['1','2','3','4','5','6','7','8','9','0']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['!','@','#','$','%','&','*','(',')','-']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
                <div class="osk-row">
                  @for (char of ['+','=','/','.','،',':',';','_','"','?']; track char) {
                    <button class="osk-key" (click)="onKeyboardChar(char)">{{ char }}</button>
                  }
                </div>
              }
              <!-- Row 4: special keys (always shown) -->
              <div class="osk-row osk-row-special">
                <button class="osk-key osk-wide" (click)="onKeyboardBackspace()">
                  <i class="pi pi-delete-left"></i>
                  {{ 'POS.BACKSPACE' | translate }}
                </button>
                <button class="osk-key osk-space" (click)="onKeyboardChar(' ')">
                  {{ 'POS.SPACE' | translate }}
                </button>
                <button class="osk-key osk-wide osk-clear" (click)="onKeyboardClear()">
                  <i class="pi pi-eraser"></i>
                  {{ 'POS.CLEAR' | translate }}
                </button>
                <button class="osk-key osk-wide osk-enter" (click)="onKeyboardEnter()">
                  <i class="pi pi-search"></i>
                  {{ 'POS.SEARCH' | translate }}
                </button>
              </div>
            </div>
          </div>
        </div>
      }

      <main class="cashier-main">
        <!-- Invoice area (left/right in RTL) -->
        <div class="cashier-invoice">
          <app-invoice-table
            [currencySymbol]="currencySymbol()"
            (paymentRequested)="onPaymentRequested()"
            (holdOrder)="onHoldOrder()"
            (showHeldOrders)="showHeldOrders.set(true)"
            (showCoupon)="showCoupon.set(true)"
            (closeSession)="onCloseSession()"
            (showReturn)="showReturn.set(true)"
            (keyboardRequested)="onScreenKeyboardEnabled() && showOnScreenKeyboard.set($event)"
          />
        </div>

        <!-- Controls area -->
        <div class="cashier-controls">
          <!-- Payment buttons -->
          <div class="cashier-pay-grid">
            <button class="cashier-pay-btn cash" (click)="onPayCash()" [disabled]="cartService.isEmpty() || paymentProcessing()">
              <i class="pi pi-money-bill"></i>
              <span>{{ 'POS.PAY_CASH' | translate }} (F10)</span>
            </button>
            <button class="cashier-pay-btn card" (click)="onPayCard()" [disabled]="cartService.isEmpty() || paymentProcessing()">
              <i class="pi pi-credit-card"></i>
              <span>{{ 'POS.PAY_CARD' | translate }} (F11)</span>
            </button>
          </div>

          <!-- Numpad (numbers only) -->
          <app-numpad [cashierMode]="true" />

          <!-- Quick Actions Footer -->
          <div class="cashier-quick-actions">
            <button class="cashier-action-btn" (click)="onPrintLastReceipt()">
              <i class="pi pi-print"></i>
              {{ 'POS.PRINT_LAST' | translate }}
            </button>
            <button class="cashier-action-btn" (click)="showHeldOrders.set(true)">
              <i class="pi pi-list"></i>
              {{ 'POS.ORDERS' | translate }}
            </button>
          </div>

          <!-- More Actions -->
          <div class="cashier-more-actions">
            <button class="cashier-small-btn" (click)="showReturn.set(true)">
              <i class="pi pi-replay"></i>
              {{ 'POS.RETURN' | translate }}
            </button>
            <button class="cashier-small-btn" (click)="showCoupon.set(true)">
              <i class="pi pi-percentage"></i>
              {{ 'POS.DISCOUNT' | translate }}
            </button>
            <button class="cashier-small-btn" (click)="onPaymentRequested()" [disabled]="cartService.isEmpty()">
              <i class="pi pi-wallet"></i>
              {{ 'POS.PAY' | translate }} (F1)
            </button>
            <button class="cashier-small-btn danger" (click)="onCloseSession()">
              <i class="pi pi-power-off"></i>
              {{ 'POS.CLOSE' | translate }}
            </button>
          </div>
        </div>
      </main>

      <app-pos-footer
        [connectionStatus]="connectionStatus()"
        [session]="session()"
      />
    </div>
  } @else {
    <!-- ===== EXISTING LAYOUTS (Modern / Classic / Retail) ===== -->
    <div class="pos-container">
      <!-- Header -->
      <app-pos-header
        [session]="session()"
        [connectionStatus]="connectionStatus()"
        [pendingCount]="pendingCount()"
        [posLayout]="posLayout()"
        (productSelected)="onProductSelected($event)"
        (exitRequested)="onExitRequested()"
        (layoutToggled)="toggleLayout()"
      />

      <!-- Main Area -->
      <div class="pos-main" [class.layout-classic]="posLayout() === 'classic'" [class.layout-retail]="posLayout() === 'retail'">
        @if (posLayout() === 'classic') {
          <!-- Classic: Cart+Numpad LEFT, Products RIGHT -->
          <div class="pos-left classic-left">
            <app-cart-panel
              [currencySymbol]="currencySymbol()"
              (paymentRequested)="onPaymentRequested()"
              (holdOrder)="onHoldOrder()"
              (showHeldOrders)="showHeldOrders.set(true)"
              (showCoupon)="showCoupon.set(true)"
              (closeSession)="onCloseSession()"
              (showReturn)="showReturn.set(true)"
            />

            <app-numpad [forceExpanded]="true" />
          </div>

          <div class="pos-right classic-right">
            <app-product-grid
              [products]="products()"
              [categories]="categories()"
              [selectedCategory]="selectedCategory()"
              [hasMore]="productsCurrentPage() < productsLastPage()"
              [loadingMore]="productsLoadingMore()"
              [totalProducts]="productsTotal()"
              (productSelected)="onProductSelected($event)"
              (categoryChanged)="onCategoryChanged($event)"
              (loadMore)="loadMoreProducts()"
            />
          </div>
        } @else {
          <!-- Modern/Retail: Products LEFT, Cart RIGHT -->
          <div class="pos-left">
            <app-product-grid
              [products]="products()"
              [categories]="categories()"
              [selectedCategory]="selectedCategory()"
              [retailMode]="posLayout() === 'retail'"
              [hasMore]="productsCurrentPage() < productsLastPage()"
              [loadingMore]="productsLoadingMore()"
              [totalProducts]="productsTotal()"
              (productSelected)="onProductSelected($event)"
              (categoryChanged)="onCategoryChanged($event)"
              (loadMore)="loadMoreProducts()"
            />
          </div>

          <div class="pos-right">
            <app-cart-panel
              [retailMode]="posLayout() === 'retail'"
              [currencySymbol]="currencySymbol()"
              (paymentRequested)="onPaymentRequested()"
              (holdOrder)="onHoldOrder()"
              (showHeldOrders)="showHeldOrders.set(true)"
              (showCoupon)="showCoupon.set(true)"
              (closeSession)="onCloseSession()"
              (showReturn)="showReturn.set(true)"
            />

            @if (posLayout() !== 'retail') {
              <app-numpad />
            }
          </div>
        }
      </div>
    </div>
  }

  <!-- Dialogs -->
  @if (showSessionOpen()) {
    <app-session-open-dialog
      (sessionOpened)="onSessionOpened($event)"
      (cancelled)="onExitRequested()"
    />
  }

  @if (showSessionClose()) {
    <app-session-close-dialog
      [session]="session()!"
      (sessionClosed)="onSessionClosed()"
      (cancelled)="showSessionClose.set(false)"
    />
  }

  @if (showPayment()) {
    <app-payment-dialog
      [session]="session()!"
      [currencySymbol]="currencySymbol()"
      (paymentComplete)="onPaymentComplete($event)"
      (cancelled)="showPayment.set(false)"
    />
  }

  @if (showReturn()) {
    <app-return-dialog
      [session]="session()!"
      (returnComplete)="showReturn.set(false)"
      (cancelled)="showReturn.set(false)"
    />
  }

  @if (showHeldOrders()) {
    <app-held-orders-dialog
      [sessionId]="session()?.id"
      (orderRestored)="onRestoreOrder($event)"
      (cancelled)="showHeldOrders.set(false)"
    />
  }

  @if (showVariantPicker() && variantProduct()) {
    <app-variant-picker
      [product]="variantProduct()!"
      (variantSelected)="onVariantSelected($event)"
      (cancelled)="showVariantPicker.set(false)"
    />
  }

  @if (showCoupon()) {
    <app-coupon-dialog
      (couponApplied)="cartService.applyCoupon($event); showCoupon.set(false)"
      (cancelled)="showCoupon.set(false)"
    />
  }

  @if (showReceiptPreview()) {
    <app-receipt-preview
      [receiptHtml]="lastReceiptHtml()"
      [visible]="showReceiptPreview()"
      (closed)="showReceiptPreview.set(false)"
      (printed)="showReceiptPreview.set(false)"
    />
  }
}

<!-- Quick Cash Payment Dialog -->
@if (showQuickCash()) {
  <p-dialog
    [visible]="true"
    [closable]="true"
    (onHide)="showQuickCash.set(false)"
    [header]="'POS.PAY_CASH' | translate"
    [style]="{width: '380px'}"
    [modal]="true"
  >
    <div class="quick-cash-dialog">
      <div class="quick-cash-total">
        <span class="qc-label">{{ 'POS.GRAND_TOTAL' | translate }}</span>
        <span class="qc-amount">{{ cartService.total() | number:'1.2-2' }} {{ currencySymbol() }}</span>
      </div>
      <div class="quick-cash-input">
        <label>{{ 'POS.AMOUNT_PAID' | translate }}</label>
        <input
          type="number"
          class="qc-input"
          [ngModel]="cashAmountPaid()"
          (ngModelChange)="onCashAmountChange($event)"
          (keydown.enter)="confirmCashPayment()"
          autofocus
        />
      </div>
      @if (cashChange() > 0) {
        <div class="quick-cash-change">
          <span class="qc-label">{{ 'POS.CHANGE' | translate }}</span>
          <span class="qc-change-amount">{{ cashChange() | number:'1.2-2' }} {{ currencySymbol() }}</span>
        </div>
      }
    </div>
    <ng-template pTemplate="footer">
      <button
        class="qc-confirm-btn"
        [disabled]="cashAmountPaid() < cartService.total() || paymentProcessing()"
        (click)="confirmCashPayment()"
      >
        @if (paymentProcessing()) {
          <i class="pi pi-spin pi-spinner"></i>
        } @else {
          <i class="pi pi-check"></i>
        }
        {{ 'POS.PAY_AND_PRINT' | translate }}
      </button>
    </ng-template>
  </p-dialog>
}

<!-- Payment Processing Overlay -->
@if (paymentProcessing()) {
  <div class="payment-processing-overlay">
    <div class="payment-processing-card">
      <i class="pi pi-spin pi-spinner"></i>
      <span>{{ 'POS.PROCESSING_PAYMENT' | translate }}</span>
    </div>
  </div>
}

<p-toast position="top-center" />
<p-confirmDialog />
