<div class="cart-container platform">
  <div class="cart-header">
    <h1>{{ 'cart.title' | translate }}</h1>
    @if (itemCount() > 0) {
      <button class="clear-cart-btn" (click)="clearCart()">
        <app-icon name="trash" [size]="16" />
        {{ 'cart.clear' | translate }}
      </button>
    }
  </div>

  @if (itemCount() === 0) {
    <div class="empty-cart">
      <app-empty-state [title]="'cart.empty' | translate" [description]="'cart.emptyDesc' | translate">
        <app-icon slot="icon" name="cart" [size]="64" />
        <div slot="actions">
          <app-button variant="primary" [routerLink]="'/' | langRoute">{{ 'cart.goShopping' | translate }}</app-button>
        </div>
      </app-empty-state>
    </div>
  }

  @if (itemCount() > 0) {
    <div class="cart-content">
      <div class="cart-items">
        @for (item of items(); track trackByItemId($index, item)) {
          <div class="cart-item-wrapper" 
               [class.swiped]="swipedItemId() === item.itemID"
               (touchstart)="onSwipeStart(item.itemID, $event)">
            <div class="cart-item">
              <a [routerLink]="['/product', item.itemID] | langRoute" class="item-image">
                <img [src]="getMainImage(item)" [alt]="itemName(item)" loading="lazy" (error)="onImageError($event)" />
              </a>
              
              <div class="item-info">
                <div class="item-header">
                  <a [routerLink]="['/product', item.itemID] | langRoute" class="item-name">{{ itemName(item) }}</a>
                  <button class="remove-btn" (click)="removeItem(item)" [attr.title]="'cart.removeItem' | translate" [attr.aria-label]="'cart.removeItem' | translate">
                    <app-icon name="x" [size]="18" />
                  </button>
                </div>
                
                @if (itemDesc(item)) {
                  <p class="item-description">{{ itemDesc(item) }}...</p>
                }

                @if (item.colour || (item.size && item.size.toLowerCase() !== 'default')) {
                  <div class="cart-item-variants">
                    @if (item.colour) {
                      <span class="cart-variant cart-variant-colour">
                        {{ 'itemDetail.colour' | translate }}:
                        <span class="cart-colour-swatch" [style.background-color]="item.colour" [title]="item.colour"></span>
                      </span>
                    }
                    @if (item.size && item.size.toLowerCase() !== 'default') {
                      <span class="cart-variant">{{ 'itemDetail.size' | translate }}: {{ item.size }}</span>
                    }
                  </div>
                }

                @if (item.badges && item.badges.length > 0) {
                  <div class="cart-item-badges">
                    @for (badge of item.badges; track badge) {
                      <span class="item-badge" [class]="getBadgeClass(badge)">{{ badge }}</span>
                    }
                  </div>
                }

                <div class="item-footer">
                  <div class="item-pricing">
                    @if (item.discount > 0) {
                      <div class="price-with-discount">
                        <span class="original-price">{{ item.price | currencyConvert:item.currency | number:'1.2-2' }} {{ currentCurrency }}</span>
                        <span class="current-price">{{ getDiscountedPrice(item) | currencyConvert:item.currency | number:'1.2-2' }} {{ currentCurrency }}</span>
                      </div>
                    } @else {
                      <span class="current-price">{{ item.price | currencyConvert:item.currency | number:'1.2-2' }} {{ currentCurrency }}</span>
                    }
                  </div>

                  <div class="quantity-controls">
                    <button class="qty-btn" (click)="decreaseQuantity(item)" [disabled]="item.quantity <= 1" [attr.aria-label]="'cart.decreaseQuantity' | translate">
                      <app-icon name="minus" [size]="14" />
                    </button>
                    <span class="qty-value" aria-live="polite" [attr.aria-label]="item.quantity + ' ' + ('cart.items' | translate)">{{ item.quantity }}</span>
                    <button class="qty-btn" (click)="increaseQuantity(item)" [attr.aria-label]="'cart.increaseQuantity' | translate">
                      <app-icon name="plus" [size]="14" />
                    </button>
                  </div>
                </div>

                @if (item.deliveryMode === 'digital' || item.deliveryOptions?.length) {
                  <app-delivery-selector
                    [item]="item"
                    (selectedDeliveryChange)="selectDelivery(item.itemID, $event)"
                  />
                }
              </div>
            </div>
            
            <button
              class="delete-btn-mobile"
              (click)="removeItem(item)"
              [attr.aria-label]="'cart.removeItem' | translate"
              [attr.tabindex]="swipedItemId() === item.itemID ? null : -1"
              [attr.aria-hidden]="swipedItemId() === item.itemID ? null : 'true'"
            >
              <app-icon name="trash" [size]="20" />
            </button>
          </div>
        }
      </div>

      <div class="cart-summary">
        <div class="summary-header">
          <h3>{{ 'cart.total' | translate }}</h3>
        </div>

        <div class="summary-row">
          <span>{{ 'cart.items' | translate }} ({{ itemCount() }})</span>
          <span class="value">{{ convertTotal(totalPrice()) | number:'1.2-2' }} {{ currentCurrency }}</span>
        </div>

        @if (hasDeliveryPrice()) {
          <div class="summary-row delivery">
            <span>{{ 'cart.deliveryLabel' | translate }}</span>
            <span class="value">{{ convertTotal(totalDeliveryPrice()) | number:'1.2-2' }} {{ currentCurrency }}</span>
          </div>
        }

        @if (!allRequiredDeliveriesSelected()) {
          <p class="delivery-warning" role="alert">
            <app-icon name="warning" [size]="16" />
            {{ 'cart.deliveryRequired' | translate }}
          </p>
        }

        <div class="summary-row total">
          <span>{{ 'cart.toPay' | translate }}</span>
          <span class="total-price">{{ convertTotal(totalWithDelivery()) | number:'1.2-2' }} {{ currentCurrency }}</span>
        </div>

        <div class="terms-agreement">
          <label class="checkbox-container">
            <input 
              type="checkbox" 
              [(ngModel)]="termsAccepted"
              id="terms-checkbox"
            />
            <span class="checkmark"></span>
            <span class="terms-text">
              {{ 'cart.agreeWith' | translate }}
              <!-- TODO(CMS): Replace these labels with backend-configured legal document links. -->
              <span>{{ 'cart.publicOffer' | translate }}</span>, 
              <span>{{ 'cart.returnPolicy' | translate }}</span>,
              <span>{{ 'cart.guaranteeTerms' | translate }}</span> {{ 'cart.and' | translate }}
              <span>{{ 'cart.privacyPolicy' | translate }}</span>
            </span>
          </label>
        </div>

        <div class="payment-method-actions">
          <button 
            class="checkout-btn qr-payment-btn" 
            (click)="checkout('qr')"
            [class.disabled]="isCheckoutDisabled"
            [disabled]="isCheckoutDisabled"
          >
            {{ 'cart.payViaQr' | translate }}
          </button>

          <button 
            class="checkout-btn card-payment-btn" 
            (click)="checkout('card')"
            [class.disabled]="isCheckoutDisabled"
            [disabled]="isCheckoutDisabled"
          >
            {{ 'cart.payViaCard' | translate }}
          </button>
        </div>

        @if (!isAuthenticated()) {
          <div class="cart-login-gate">
            <div class="login-gate-icon">
              <app-icon name="lock" [size]="32" />
            </div>
            <p class="login-gate-title">{{ 'cart.loginRequired' | translate }}</p>
            <p class="login-gate-desc">{{ 'cart.loginRequiredDesc' | translate }}</p>

            <button class="telegram-login-btn" (click)="requestLogin()">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/>
              </svg>
              {{ 'cart.loginWithTelegram' | translate }}
            </button>
          </div>
        }
      </div>
    </div>
  }
</div>

<!-- Payment Popup Modal -->
<app-dialog
  class="payment-dialog"
  [open]="showPaymentPopup()"
  size="md"
  [ariaLabel]="'cart.checkout' | translate"
  [closeOnBackdropClick]="false"
  [closeOnEscape]="!showBankPaymentPopup()"
  (closed)="closePaymentPopup()"
>
      <button class="close-modal-btn" (click)="closePaymentPopup()" [attr.aria-label]="'cart.close' | translate">
        <app-icon name="x" [size]="20" />
      </button>
      @if (paymentStatus() === 'creating') {
        <div class="payment-status-screen" role="status" aria-live="polite">
          <div class="spinner-large"></div>
          <h2>{{ 'cart.creatingPayment' | translate }}</h2>
          <p>{{ 'cart.waitFewSeconds' | translate }}</p>
        </div>
      }

      @if (paymentStatus() === 'waiting') {
        <div class="payment-active" role="status" aria-live="polite">
          <h2>{{ selectedPaymentMethod() === 'card' ? ('cart.waitingPayment' | translate) : ('cart.scanQr' | translate) }}</h2>
          
          @if (qrCodeUrl()) {
            <div class="qr-section">
              <div class="qr-wrapper">
                <img [src]="qrCodeUrl()" [attr.alt]="'cart.paymentQrAlt' | translate" class="qr-code" (error)="onImageError($event)" />
                <div class="scan-line"></div>
              </div>
            </div>
          }

          <div class="payment-info">
            <div class="payment-amount">
              <span class="label">{{ 'cart.amountToPay' | translate }}</span>
              <span class="amount">{{ convertTotal(totalWithDelivery()) | number:'1.2-2' }} {{ currentCurrency }}</span>
            </div>
            
            <div class="waiting-indicator">
              <div class="pulse-dot"></div>
              <span>{{ 'cart.waitingPayment' | translate }}</span>
            </div>
          </div>

          <div class="payment-actions">
            @if (paymentUrl()) {
              <button class="copy-btn" (click)="copyPaymentLink()">
                {{ linkCopied() ? ('cart.copied' | translate) : ('cart.copyLink' | translate) }}
              </button>
              <a [href]="paymentUrl()" target="_blank" rel="noopener noreferrer" class="open-btn">
                {{ 'cart.openNewTab' | translate }}
              </a>
            }
          </div>
        </div>
      }

      @if (paymentStatus() === 'error') {
        <div class="payment-status-screen error" role="alert" aria-live="assertive">
          <div class="error-icon" aria-hidden="true">!</div>
          <h2>{{ 'cart.paymentError' | translate }}</h2>
          <p>{{ 'cart.paymentErrorDesc' | translate }}</p>

          <div class="payment-error-actions">
            <button class="retry-payment-btn" (click)="retryPayment()">
              {{ 'cart.retryPayment' | translate }}
            </button>
          </div>
        </div>
      }

      @if (paymentStatus() === 'success') {
        <div class="payment-status-screen success" role="status" aria-live="polite">
          <div class="success-icon" aria-hidden="true">✓</div>
          <h2>{{ 'cart.paymentSuccess' | translate }}</h2>
          @if (!purchaseSubmitted()) {
            <p>{{ 'cart.paymentSuccessDesc' | translate }}</p>
            <form class="contact-capture-form" (ngSubmit)="submitEmail()">
              <label>
                <input
                  type="email"
                  name="email"
                  [value]="userEmail()"
                  [placeholder]="'cart.emailPlaceholder' | translate"
                  [attr.aria-invalid]="!!emailError()"
                  (input)="onEmailInput($event)"
                  (blur)="onEmailBlur()"
                  [disabled]="emailSubmitting()"
                />
                @if (emailError()) {
                  <span class="field-error">{{ emailError() }}</span>
                }
              </label>
              <label>
                <input
                  type="tel"
                  name="phone"
                  [value]="userPhone()"
                  [placeholder]="'cart.phonePlaceholder' | translate"
                  [attr.aria-invalid]="!!phoneError()"
                  (input)="onPhoneInput($event)"
                  (blur)="onPhoneBlur()"
                  [disabled]="emailSubmitting()"
                />
                @if (phoneError()) {
                  <span class="field-error">{{ phoneError() }}</span>
                }
              </label>
              <button type="submit" [disabled]="emailSubmitting()">
                {{ emailSubmitting() ? ('cart.sending' | translate) : ('cart.send' | translate) }}
              </button>
            </form>
          }
        </div>
      }

      @if (paymentStatus() === 'timeout') {
        <div class="payment-status-screen timeout" role="status" aria-live="polite">
          <div class="timeout-icon" aria-hidden="true">⏱</div>
          <h2>{{ 'cart.paymentTimeout' | translate }}</h2>
          <p>{{ 'cart.paymentTimeoutDesc' | translate }}</p>
          <p class="auto-close">{{ 'cart.autoClose' | translate }}</p>
        </div>
      }
</app-dialog>

@if (showBankPaymentPopup() && bankPaymentFrameUrl()) {
  <app-dialog
    class="bank-payment-dialog"
    [open]="showBankPaymentPopup()"
    size="lg"
    [ariaLabel]="'cart.payViaCard' | translate"
    [closeOnBackdropClick]="false"
    (closed)="closeBankPaymentPopup()"
  >
    <button class="close-modal-btn" (click)="closeBankPaymentPopup()" [attr.aria-label]="'cart.close' | translate">
      <app-icon name="x" [size]="20" />
    </button>
    <iframe [src]="bankPaymentFrameUrl()" class="bank-payment-frame" [attr.title]="'common.bankCardPayment' | translate"></iframe>
  </app-dialog>
}

<app-telegram-login />

<app-confirm-dialog
  [open]="clearCartConfirmOpen()"
  [titleText]="'cart.confirmClear' | translate"
  [message]="'cart.confirmClear' | translate"
  [destructive]="true"
  (confirmed)="confirmClearCart()"
  (cancelled)="clearCartConfirmOpen.set(false)"
/>


