<?php /* pos/index.php — White Premium Design */
$sym       = setting('currency_symbol','Rs.');
$taxPct    = (float)setting('tax_percent','0');
$shopName  = setting('shop_name','MJPOS');
$cashier   = Auth::name();
$heldCount = count($_SESSION['held_bills'] ?? []);
$nowStr    = date('d M Y · H:i');

/* POS sidebar visibility by user role */
$posUserRole = '';
try {
    if (method_exists('Auth', 'role')) {
        $posUserRole = (string)Auth::role();
    } elseif (method_exists('Auth', 'user')) {
        $authUser = Auth::user();
        if (is_array($authUser)) {
            $posUserRole = (string)($authUser['role_name'] ?? $authUser['role'] ?? $authUser['user_type'] ?? '');
        } elseif (is_object($authUser)) {
            $posUserRole = (string)($authUser->role_name ?? $authUser->role ?? $authUser->user_type ?? '');
        }
    }
} catch (Throwable $e) {
    $posUserRole = '';
}

if ($posUserRole === '') {
    $posUserRole = (string)(
        $_SESSION['role_name'] ??
        $_SESSION['role'] ??
        $_SESSION['user_type'] ??
        $_SESSION['user']['role_name'] ??
        $_SESSION['user']['role'] ??
        $_SESSION['user']['user_type'] ??
        ''
    );
}

$posRoleKey = strtolower(trim(preg_replace('/[^a-z0-9]+/i', '_', $posUserRole), '_'));
$posIsCashier = in_array($posRoleKey, ['cashier', 'pos_cashier'], true);

try {
    $todayPrefix = date('Ymd');
    $lastSeq = Database::fetchColumn(
        "SELECT MAX(CAST(SUBSTRING_INDEX(invoice_no,'-',-1) AS UNSIGNED))
         FROM sales WHERE invoice_no LIKE ?",
        ["INV-{$todayPrefix}-%"]
    );
    $nextSeq = ((int)$lastSeq) + 1;
    $nextInvoiceNo = 'INV-' . $todayPrefix . '-' . str_pad($nextSeq, 4, '0', STR_PAD_LEFT);
} catch (Exception $e) {
    $nextInvoiceNo = 'INV-' . date('Ymd') . '-0001';
}

try {
    $stockViewProducts = Database::fetchAll(
        "SELECT id, product_code, product_name, barcode, current_stock, reorder_level, selling_price
         FROM products ORDER BY product_name ASC"
    );
} catch (Exception $e) {
    $stockViewProducts = [];
}
?>
<style>
/* MJPOS — Premium White POS UI */
:root{
  --accent:#2563eb;
  --accent-dark:#1d4ed8;
  --accent-soft:#eff6ff;
  --success:#16a34a;
  --danger:#dc2626;
  --warning:#d97706;
  --page:#f4f7fb;
  --surface:#ffffff;
  --surface-2:#f8fafc;
  --border:#e5e7eb;
  --border-strong:#d8dee8;
  --text:#0f172a;
  --muted:#64748b;
  --muted-2:#94a3b8;
  --shadow-sm:0 1px 2px rgba(15,23,42,.05),0 4px 12px rgba(15,23,42,.04);
  --shadow-md:0 12px 30px rgba(15,23,42,.08);
  --radius:14px;
}

*{box-sizing:border-box}
body{background:var(--page)}
#content{padding:0!important;background:var(--page)!important;overflow:hidden!important}

#pos-wrap{
  display:grid;
  grid-template-columns:minmax(0,1fr) 390px;
  height:calc(100vh - 52px);
  min-height:600px;
  background:var(--page);
}

#pos-left{
  display:flex;
  flex-direction:column;
  min-width:0;
  min-height:0;
  overflow:hidden;
  padding:16px;
  gap:12px;
}

#pos-right{
  display:flex;
  flex-direction:column;
  min-height:0;
  overflow-y:auto;
  background:var(--surface);
  border-left:1px solid var(--border);
  box-shadow:-10px 0 30px rgba(15,23,42,.04);
  scrollbar-width:thin;
}
#pos-right::-webkit-scrollbar,#cart-scroll::-webkit-scrollbar{width:5px}
#pos-right::-webkit-scrollbar-thumb,#cart-scroll::-webkit-scrollbar-thumb{background:#dbe2ea;border-radius:10px}

/* Search */
#search-wrap{position:relative;flex:1}
#product-search{
  width:100%;
  height:56px;
  padding:0 86px 0 52px;
  border:1px solid var(--border-strong);
  border-radius:16px;
  background:#fff;
  color:var(--text);
  font-size:.96rem;
  font-weight:650;
  box-shadow:var(--shadow-sm);
  outline:none;
  transition:.2s ease;
}
#product-search::placeholder{color:var(--muted-2);font-weight:500}
#product-search:focus{border-color:#93b4ff;box-shadow:0 0 0 4px rgba(37,99,235,.10),var(--shadow-sm)}
#search-icon{position:absolute;left:18px;top:50%;transform:translateY(-50%);font-size:1.2rem;color:var(--accent)!important;z-index:2}
#search-status-pill{position:absolute;right:12px;top:50%;transform:translateY(-50%);padding:5px 10px;border-radius:8px;background:var(--accent-soft);border:1px solid #dbeafe;color:var(--accent);font-size:.66rem;font-weight:800;letter-spacing:.04em}
#product-results{position:absolute;left:0;right:0;top:calc(100% + 8px);z-index:9999;display:none;max-height:390px;overflow:auto;background:#fff;border:1px solid #cbd5e1;border-radius:16px;box-shadow:var(--shadow-md)}
.pres-header{position:sticky;top:0;z-index:1;display:flex;justify-content:space-between;align-items:center;padding:9px 14px;background:#f8fbff;border-bottom:1px solid #e5edf8;color:var(--accent);font-size:.68rem;font-weight:800;border-radius:16px 16px 0 0}
.prod-item{display:flex;justify-content:space-between;align-items:center;gap:14px;padding:11px 14px;border-bottom:1px solid #f1f5f9;cursor:pointer;transition:.15s ease}
.prod-item:hover,.prod-item.active{background:#f7faff}
.prod-item.active{box-shadow:inset 3px 0 0 var(--accent)}
.prod-item.out{opacity:.5;cursor:not-allowed!important;background:#fff7f7!important}
.prod-item:last-child{border-bottom:0}

/* top action buttons */
#pos-left>div:first-child>.btn{min-width:58px;background:#fff!important;border:1px solid var(--border-strong)!important;color:var(--muted)!important;box-shadow:var(--shadow-sm);transition:.15s ease}
#pos-left>div:first-child>.btn:hover{transform:translateY(-1px);border-color:#b9c6d6!important;color:var(--text)!important;box-shadow:0 8px 18px rgba(15,23,42,.08)}
#pos-left>div:first-child>.btn-outline-warning{color:var(--warning)!important}
#pos-left>div:first-child>.btn-outline-danger{color:var(--danger)!important}

/* keyboard hints */
#kbd-bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:7px 12px;background:#fff;border:1px solid var(--border);border-radius:12px;box-shadow:var(--shadow-sm);font-size:.68rem}
#kbd-bar kbd{padding:2px 7px;background:#f8fafc;border:1px solid #dbe3ec;border-radius:5px;color:var(--accent);font-family:inherit;font-size:.65rem;font-weight:800;box-shadow:none}
#kbd-bar span{color:var(--text);font-weight:700}

/* cart */
#cart-wrap{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden}
#cart-scroll{flex:1;min-height:0;overflow:auto;background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow-sm)}
#cart-empty{display:none;min-height:100%;padding:64px 24px;flex-direction:column;align-items:center;justify-content:center;color:var(--muted)}
#cart-empty.show{display:flex}
#cart-empty i{color:#dbe3ec!important}
#cart-table{width:100%;margin:0;border-collapse:collapse;table-layout:fixed}
#cart-table thead th{position:sticky;top:0;z-index:2;padding:10px 8px;background:#f8fafc;color:#475569;border-bottom:1px solid var(--border);font-size:.66rem;font-weight:800;text-transform:uppercase;letter-spacing:.05em;white-space:nowrap}
#cart-table tbody td{padding:8px;border-bottom:1px solid #f0f3f7;color:var(--text);font-size:.8rem;vertical-align:middle}
#cart-table tbody tr:hover{background:#fafcff}
#cart-table tbody tr:last-child td{border-bottom:0}
.cart-qty-input,.cart-disc-input{background:#fff!important;border:1px solid var(--border-strong)!important;border-radius:8px!important;min-height:30px;color:var(--text)!important;box-shadow:none!important}
.cart-qty-input:focus,.cart-disc-input:focus{border-color:#9db7f5!important;box-shadow:0 0 0 3px rgba(37,99,235,.08)!important;outline:none}
#cart-footer{display:flex;align-items:center;gap:8px;padding:7px 3px 0;color:var(--muted);font-size:.74rem}
#cart-footer strong{color:var(--text)}
#cart-margin-display{margin-left:auto;padding:4px 9px;border-radius:8px;background:#ecfdf3;color:#15803d!important;font-size:.7rem;font-weight:800}

/* extras */
#cart-extras{padding:12px;background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:var(--shadow-sm)}
.extra-label{display:block;margin-bottom:5px;color:var(--muted);font-size:.63rem;font-weight:800;text-transform:uppercase;letter-spacing:.07em}
.extra-input,#customer-select,#walkin-phone,#bill-discount,#sale-note,.pmt-method-sel,.pmt-amount-inp,.pmt-det-input{width:100%;border:1px solid var(--border-strong)!important;border-radius:10px!important;background:#fff!important;color:var(--text)!important;transition:.15s ease;box-shadow:none!important}
.extra-input,#customer-select,#walkin-phone,#bill-discount,#sale-note{min-height:38px;padding:7px 10px;font-size:.8rem;font-weight:600}
.extra-input:focus,#customer-select:focus,#walkin-phone:focus,#bill-discount:focus,#sale-note:focus,.pmt-method-sel:focus,.pmt-amount-inp:focus,.pmt-det-input:focus{border-color:#93b4ff!important;box-shadow:0 0 0 3px rgba(37,99,235,.08)!important;outline:none}
.input-group-text{background:#f8fafc;border-color:var(--border-strong);color:var(--muted);font-weight:700}

/* totals */
#totals-card{background:#fff;border-bottom:1px solid var(--border)}
.total-row{display:flex;justify-content:space-between;align-items:center;padding:8px 18px;border-bottom:1px solid #f1f5f9;color:var(--muted);font-size:.8rem}
.total-row .tval{color:var(--text);font-weight:800}
#grand-total-row{display:flex;justify-content:space-between;align-items:center;padding:17px 18px;background:#0f172a}
#grand-total-row>span:first-child{color:#cbd5e1!important}
#display-total{color:#fff;font-size:2rem;font-weight:900;letter-spacing:-.03em;text-shadow:none}
#display-change-row,#display-balance-row{display:flex;justify-content:space-between;align-items:center;padding:9px 18px;border-bottom:1px solid #f1f5f9}
#display-change{font-size:1.1rem;font-weight:900}

/* payments */
#payment-card{background:#fff;border-bottom:1px solid var(--border)}
#payment-card>div:first-child{background:#fbfcfe!important;border-bottom:1px solid var(--border)!important;padding:10px 16px!important}
#payment-card>div:first-child button{background:#fff!important;border:1px solid var(--border-strong)!important;border-radius:8px!important;color:var(--accent)!important;box-shadow:var(--shadow-sm)}
#payment-card>div:nth-child(2){padding:12px 14px!important}
.pmt-row-wrap{margin-bottom:9px}
.pmt-row{display:flex;gap:7px;align-items:center}
.pmt-method-sel{width:auto;min-width:118px;padding:8px 9px;font-size:.75rem;font-weight:700}
.pmt-amount-inp{height:40px;padding:6px 12px;text-align:right;font-size:.95rem;font-weight:850;color:var(--accent)!important}
.remove-pmt-btn{width:34px;height:34px;border:1px solid #fecaca;background:#fff5f5;color:var(--danger);border-radius:9px;display:flex;align-items:center;justify-content:center}
.quick-btn{flex:1;min-width:0;padding:8px 4px;border:1px solid var(--border-strong);border-radius:9px;background:#fff;color:#475569;font-size:.7rem;font-weight:800;box-shadow:var(--shadow-sm)}
.quick-btn:hover{background:#f8fbff;border-color:#b9cdfc;color:var(--accent)}
.pmt-det-label{display:block;margin-bottom:4px;color:var(--muted-2);font-size:.63rem;font-weight:800;text-transform:uppercase;letter-spacing:.05em}
.pmt-det-input{padding:7px 9px;font-size:.78rem;font-weight:600}

/* process button */
#btn-process{width:calc(100% - 24px);height:58px;margin:12px;border:0;border-radius:13px;background:var(--accent);color:#fff;font-size:.98rem;font-weight:900;letter-spacing:.08em;text-transform:uppercase;box-shadow:0 10px 24px rgba(37,99,235,.22);transition:.18s ease}
#btn-process:hover:not(:disabled){background:var(--accent-dark);transform:translateY(-1px);box-shadow:0 14px 30px rgba(37,99,235,.28)}
#btn-process:disabled{background:#cbd5e1;box-shadow:none;cursor:not-allowed}

/* modals */
.modal-content{border:0!important;border-radius:16px!important;box-shadow:0 24px 60px rgba(15,23,42,.18)!important}
.modal-header{border-bottom:1px solid var(--border)!important}

/* stock view popup */
#stock-view-btn{color:#0369a1!important;border-color:#bae6fd!important;background:#f0f9ff!important}
#stock-view-btn:hover{color:#075985!important;border-color:#7dd3fc!important;background:#e0f2fe!important}
.stock-view-table-wrap{max-height:58vh;overflow:auto;border:1px solid var(--border);border-radius:10px}
#stock-view-table thead th{position:sticky;top:0;z-index:2;background:#0f172a;color:#fff;padding:11px 12px;font-size:.7rem;text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}
#stock-view-table tbody td{padding:10px 12px;border-color:#eef2f7;font-size:.8rem}
.stock-summary-pill{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border-radius:7px;font-size:.7rem;font-weight:850;border:1px solid}
.stock-summary-pill.total{color:#1d4ed8;background:#eff6ff;border-color:#bfdbfe}
.stock-summary-pill.available{color:#047857;background:#ecfdf5;border-color:#a7f3d0}
.stock-summary-pill.low{color:#b45309;background:#fffbeb;border-color:#fde68a}
.stock-summary-pill.out{color:#be123c;background:#fff1f2;border-color:#fecdd3}
.stock-qty,.stock-status{display:inline-flex;align-items:center;justify-content:center;min-width:72px;padding:5px 8px;border-radius:6px;font-size:.68rem;font-weight:900}
.stock-qty.ok,.stock-status.ok{color:#047857;background:#dcfce7}
.stock-qty.low,.stock-status.low{color:#b45309;background:#fef3c7}
.stock-qty.out,.stock-status.out{color:#be123c;background:#ffe4e6}
.stock-status{min-width:88px}

/* polished stock modal and aligned product table */
#stockViewModal .modal-dialog{max-width:min(1180px,calc(100vw - 32px));margin-left:auto;margin-right:auto}
#stockViewModal .modal-content{overflow:hidden!important;border:1px solid #dbe4ef!important;background:#fff!important}
#stockViewModal .modal-header{position:relative;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px 20px!important;background:linear-gradient(90deg,#f8fbff,#f4f7ff)!important}
#stockViewModal .modal-header>div{min-width:0;padding-right:10px}
#stockViewModal .btn-close{position:static!important;flex:0 0 auto;width:34px!important;height:34px!important;margin:0!important;padding:0!important;border:1px solid #d7e0eb!important;border-radius:7px!important;background-color:#fff!important;background-size:12px!important;box-shadow:0 4px 12px rgba(15,23,42,.08)!important;opacity:.8!important}
#stockViewModal .btn-close:hover{opacity:1!important;background-color:#fff1f2!important;border-color:#fecdd3!important;transform:none!important}
#stockViewModal .modal-body{padding:18px 20px 20px!important;overflow:hidden}
.stock-view-table-wrap{width:100%;max-height:58vh;overflow:auto;border:1px solid #dfe7f1;border-radius:7px!important;background:#fff}
#stock-view-table{width:100%!important;min-width:940px!important;table-layout:fixed!important;border-collapse:separate!important;border-spacing:0!important}
#stock-view-table thead th{vertical-align:middle!important;padding:12px 14px!important;border:0!important;border-right:1px solid rgba(255,255,255,.09)!important}
#stock-view-table thead th:last-child{border-right:0!important}
#stock-view-table tbody td{vertical-align:middle!important;padding:11px 14px!important;border-bottom:1px solid #edf2f7!important;overflow:hidden;text-overflow:ellipsis}
#stock-view-table tbody tr:last-child td{border-bottom:0!important}
#stock-view-table tbody tr:nth-child(even){background:#fbfdff}
#stock-view-table th:nth-child(1),#stock-view-table td:nth-child(1){width:54px;text-align:center}
#stock-view-table th:nth-child(2),#stock-view-table td:nth-child(2){width:27%;text-align:left}
#stock-view-table th:nth-child(3),#stock-view-table td:nth-child(3){width:22%;text-align:left}
#stock-view-table th:nth-child(4),#stock-view-table td:nth-child(4){width:14%;text-align:right}
#stock-view-table th:nth-child(5),#stock-view-table td:nth-child(5){width:12%;text-align:center}
#stock-view-table th:nth-child(6),#stock-view-table td:nth-child(6){width:13%;text-align:center}
#stock-view-table th:nth-child(7),#stock-view-table td:nth-child(7){width:12%;text-align:center}
#stock-view-table td:nth-child(2) .fw-bold{white-space:normal;line-height:1.3}
#stock-view-table td:nth-child(3) div{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
@media(max-width:767px){
  #stockViewModal .modal-dialog{max-width:calc(100vw - 16px);margin:8px auto}
  #stockViewModal .modal-header{padding:13px 14px!important}
  #stockViewModal .modal-body{padding:14px!important}
}

/* animations */
@keyframes rowSlide{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
@keyframes bumpScale{0%,100%{transform:scale(1)}40%{transform:scale(1.03)}}
.cart-row-new{animation:rowSlide .18s ease}.cart-bounce{animation:bumpScale .22s ease}

@media(max-width:1100px){#pos-wrap{grid-template-columns:minmax(0,1fr) 350px}}
@media(max-width:900px){#pos-wrap{grid-template-columns:1fr;height:auto;overflow:auto}#pos-right{border-left:0;border-top:1px solid var(--border)}#content{overflow:auto!important}}
@media print{#pos-wrap,#kbd-bar{display:none!important}}
</style>

<div id="pos-wrap">

<!-- ══════════════ LEFT ══════════════════════════════════════ -->
<div id="pos-left">

  <!-- Top bar -->
  <div style="display:flex;gap:8px;align-items:stretch">

    <!-- Search -->
    <div id="search-wrap" style="flex:1">
      <i class="bi bi-upc-scan text-primary" id="search-icon"></i>
      <input type="text" id="product-search"
             autocomplete="off" spellcheck="false"
             placeholder="Scan barcode or search product…">
      <div id="search-status-pill">F2</div>
      <div id="product-results"></div>
    </div>

    <!-- Action buttons -->
    <button class="btn btn-outline-info px-3" onclick="showStockView()" title="View Stock [F1]"
            id="stock-view-btn" style="border-radius:10px;border:2px solid #bae6fd">
      <i class="bi bi-box-seam d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">F1 Stock</span>
    </button>

    <button class="btn btn-outline-primary px-3" onclick="openPosPagePopup('sales')"
            id="sales-list-popup-btn" title="Sales List [F6]"
            style="border-radius:10px;border:2px solid #bfdbfe">
      <i class="bi bi-receipt-cutoff d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">F6 Sales</span>
    </button>

    <button class="btn btn-outline-success px-3" onclick="openPosPagePopup('credit')"
            id="credit-book-popup-btn" title="Credit Book [F7]"
            style="border-radius:10px;border:2px solid #bbf7d0">
      <i class="bi bi-journal-text d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">F7 Credit</span>
    </button>

    <button class="btn btn-outline-secondary px-3" onclick="holdBill()" title="Hold Bill [F4]"
            style="border-radius:10px;border:2px solid #e2e8f0">
      <i class="bi bi-pause-circle d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">F4</span>
    </button>

    <button class="btn btn-outline-warning px-3 position-relative" onclick="showHeldBills()"
            id="held-btn" style="border-radius:10px;border:2px solid #fde68a"
            title="Held Bills">
      <i class="bi bi-collection d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">Held</span>
      <?php if($heldCount > 0):?>
      <span class="held-badge" id="held-count-badge"><?= $heldCount ?></span>
      <?php else:?>
      <span class="held-badge" id="held-count-badge" style="display:none">0</span>
      <?php endif;?>
    </button>

    <button class="btn btn-outline-danger px-3" onclick="clearCart()"
            style="border-radius:10px;border:2px solid #fecaca" title="Clear [Del]">
      <i class="bi bi-trash3 d-block" style="font-size:1.1rem"></i>
      <span style="font-size:.6rem;font-weight:700">Del</span>
    </button>
  </div>

  <!-- Keyboard hints -->
  <div id="kbd-bar">
    <kbd>F1</kbd><span>Stock</span>
    <kbd>F2</kbd><span>Search</span>
    <kbd>F4</kbd><span>Hold</span>
    <kbd>F6</kbd><span>Sales</span>
    <kbd>F7</kbd><span>Credit</span>
    <kbd>Enter</kbd><span>Process</span>
    <kbd>Esc</kbd><span>Clear Search</span>
    <span style="margin-left:auto;color:#94a3b8;font-size:.65rem">
      <i class="bi bi-person me-1"></i><?= e($cashier) ?>
      &nbsp;·&nbsp; <?= $nowStr ?>
    </span>
  </div>

  <!-- Cart -->
  <div id="cart-wrap">
    <div id="cart-scroll">
      <div id="cart-empty" class="show">
        <i class="bi bi-cart3 d-block" style="font-size:3rem;opacity:.2;margin-bottom:10px"></i>
        <div class="fw-semibold">Cart is empty</div>
        <div style="font-size:.78rem">Scan a barcode or search for a product</div>
      </div>
      <table id="cart-table" style="display:none">
        <thead>
          <tr>
            <th style="width:28px">#</th>
            <th>Product</th>
            <th style="width: 150px;text-align:center">Qty</th>
            <th style="width: 85px;text-align: center;">Price</th>
            <th style="width: 75px;text-align: center;">Disc</th>
            <th style="width: 91px;text-align: center;">Total</th>
            <th style="width: 50px;"></th>
          </tr>
        </thead>
        <tbody id="cart-body"></tbody>
      </table>
    </div>

    <!-- Cart footer bar -->
    <div id="cart-footer">
      <div>
        <strong id="cart-count" class="text-dark">0</strong> item(s)
        &nbsp;·&nbsp;
        <strong id="cart-qty-total" class="text-dark">0</strong> qty
      </div>
      <div id="cart-margin-display" class="ms-auto text-success fw-semibold"></div>
    </div>
  </div>

  <!-- Customer + Discount + Note -->
  <div id="cart-extras">
    <div class="row g-2">
      <div class="col-md-4">
        <label class="extra-label">
          <i class="bi bi-person me-1 text-primary"></i>CUSTOMER
        </label>
        <select id="customer-select" onchange="onCustomerChange(this)">
          <option value="">Walk-in Customer</option>
          <?php foreach($customers as $c): ?>
          <option value="<?= $c['id'] ?>" data-limit="<?= $c['credit_limit']??0 ?>"
                  data-balance="<?= $c['current_balance']??0 ?>">
            <?= e($c['customer_name']) ?>
            <?php if($c['phone']??''): ?>(<?= e($c['phone']) ?>)<?php endif; ?>
          </option>
          <?php endforeach; ?>
        </select>

        <!-- Walk-in customer phone — shows only when no customer selected -->
        <div id="walkin-phone-wrap" style="margin-top:5px">
          <div class="input-group input-group-sm">
            <span class="input-group-text" style="font-size:.75rem">
              <i class="bi bi-telephone"></i>
            </span>
            <input type="tel" id="walkin-phone"
                   class="form-control extra-input"
                   placeholder="Walk-in phone (optional)"
                   maxlength="15"
                   style="font-size:.78rem">
          </div>
        </div>

        <div id="customer-info" style="font-size:.7rem;margin-top:3px;display:none">
          <span class="text-muted">Balance:</span>
          <span id="cust-balance" class="fw-semibold text-danger"></span>
          &nbsp;|&nbsp;
          <span class="text-muted">Limit:</span>
          <span id="cust-limit" class="fw-semibold"></span>
        </div>
      </div>
      <div class="col-md-4">
        <label class="extra-label">
          <i class="bi bi-tag me-1 text-warning"></i>BILL DISCOUNT
        </label>
        <div class="input-group input-group-sm">
          <span class="input-group-text" style="font-size:.8rem"><?= e($sym) ?></span>
          <input type="number" id="bill-discount" class="form-control extra-input"
                 min="0" step="0.01" value="0"
                 style="text-align:right;font-weight:700"
                 oninput="recalc()">
        </div>
      </div>
      <div class="col-md-4">
        <label class="extra-label">
          <i class="bi bi-chat-text me-1 text-info"></i>NOTE
        </label>
        <input type="text" id="sale-note" class="extra-input" placeholder="Optional note…">
      </div>
    </div>
  </div>

</div><!-- /pos-left -->

<!-- ══════════════ RIGHT ═════════════════════════════════════ -->
<div id="pos-right">

  <!-- Totals card -->
  <div id="totals-card" style="flex-shrink:0">
    <div class="total-row"><span class="text-muted">Subtotal</span>
      <span class="fw-semibold" id="display-subtotal"><?= $sym ?> 0.00</span></div>
    <div class="total-row"><span class="text-muted">Discount</span>
      <span class="text-danger" id="display-discount">− <?= $sym ?> 0.00</span></div>
    <div class="total-row"><span class="text-muted">Tax (<?= $taxPct ?>%)</span>
      <span id="display-tax"><?= $sym ?> 0.00</span></div>
    <div id="grand-total-row">
      <span style="color:#93c5fd;font-size:.85rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em">
        Grand Total
      </span>
      <span id="display-total"><?= $sym ?> 0.00</span>
    </div>
    <div id="display-change-row">
      <span style="color:#15803d;font-size:.82rem;font-weight:700">
        <i class="bi bi-cash me-1"></i>Change Due
      </span>
      <span id="display-change"><?= $sym ?> 0.00</span>
    </div>
    <div id="display-balance-row" class="total-row" style="background:#fef2f2">
      <span style="color:#dc2626;font-size:.78rem;font-weight:600">Balance Due</span>
      <span class="fw-bold text-danger" id="display-balance"><?= $sym ?> 0.00</span>
    </div>
    <div class="total-row border-top">
      <span class="text-muted" style="font-size:.75rem">Amount Paid</span>
      <span class="text-success fw-semibold" id="display-paid"><?= $sym ?> 0.00</span>
    </div>
  </div>

  <!-- Payment card -->
  <div id="payment-card">
    <div style="display:flex;justify-content:space-between;align-items:center;
                padding:8px 14px;border-bottom:1px solid #f1f5f9;background:#f8fafc">
      <span style="font-size:.8rem;font-weight:700">
        <i class="bi bi-credit-card me-1 text-primary"></i>PAYMENT
      </span>
      <button onclick="addPaymentRow()"
              style="border:1px solid #e2e8f0;border-radius:6px;background:#fff;
                     padding:3px 10px;font-size:.72rem;font-weight:700;cursor:pointer;color:#3b82f6">
        <i class="bi bi-plus me-1"></i>Split
      </button>
    </div>
    <div style="padding:10px 12px">
      <div id="payments-list"></div>
      <div id="quick-cash-btns" class="d-flex gap-1 flex-wrap mt-2"></div>
    </div>
  </div>

  <!-- Summary + Process -->
  <button id="btn-process" onclick="processSale()" disabled>
    <i class="bi bi-check-circle me-2"></i>PROCESS SALE
  </button>

</div><!-- /pos-right -->
</div><!-- /pos-wrap -->

<!-- ─── Held Bills Modal ─────────────────────────────────── -->
<div class="modal fade" id="heldModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title fw-bold"><i class="bi bi-collection me-2"></i>Held Bills</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-0" id="held-modal-body">
        <div class="text-center text-muted py-4">No held bills.</div>
      </div>
    </div>
  </div>
</div>

<!-- ─── Stock View Modal ─────────────────────────────────── -->
<div class="modal fade" id="stockViewModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-xl">
    <div class="modal-content">
      <div class="modal-header">
        <div>
          <h5 class="modal-title fw-bold mb-1"><i class="bi bi-box-seam me-2 text-info"></i>Stock View</h5>
          <div class="text-muted" style="font-size:.75rem">Search products and check available stock</div>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="position-relative mb-3">
          <i class="bi bi-search position-absolute" style="left:14px;top:50%;transform:translateY(-50%);color:#2563eb"></i>
          <input type="text" id="stock-view-search" class="form-control"
                 placeholder="Search by product name, code or barcode..."
                 autocomplete="off" oninput="filterStockView()"
                 style="height:46px;padding-left:42px;font-weight:650">
        </div>
        <div class="d-flex gap-2 flex-wrap mb-3" id="stock-summary"></div>
        <div class="table-responsive stock-view-table-wrap">
          <table class="table table-hover align-middle mb-0" id="stock-view-table">
            <thead><tr>
              <th style="width:55px">#</th><th>Product</th><th>Code / Barcode</th>
              <th class="text-end">Selling Price</th><th class="text-center">Reorder Level</th>
              <th class="text-center">Available Stock</th><th class="text-center">Status</th>
            </tr></thead>
            <tbody id="stock-view-body"></tbody>
          </table>
        </div>
        <div id="stock-view-empty" class="text-center text-muted py-5" style="display:none">
          <i class="bi bi-search d-block mb-2" style="font-size:2rem;opacity:.35"></i>No matching stock items found.
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ─── Sales List / Credit Book Popup ──────────────────── -->
<div class="modal fade" id="posPagePopupModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-fullscreen-xl-down" style="max-width:1280px;width:calc(100vw - 32px)">
    <div class="modal-content" style="height:calc(100vh - 38px)">
      <div class="modal-header py-2 px-3" id="pos-page-popup-header">
        <div class="d-flex align-items-center gap-2 min-width-0">
          <span id="pos-page-popup-icon" class="d-inline-flex align-items-center justify-content-center"></span>
          <div class="min-width-0">
            <h5 class="modal-title fw-bold mb-0" id="pos-page-popup-title">Details</h5>
            <div class="text-muted text-truncate" id="pos-page-popup-subtitle" style="font-size:.72rem"></div>
          </div>
        </div>
        <div class="d-flex align-items-center gap-2 ms-auto">
          <button type="button" class="btn btn-sm btn-light border" onclick="reloadPosPagePopup()" title="Refresh">
            <i class="bi bi-arrow-clockwise"></i>
          </button>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
      </div>
      <div class="modal-body p-0 position-relative" style="overflow:hidden">
        <div id="pos-page-popup-loader" class="position-absolute top-0 start-0 w-100 h-100 align-items-center justify-content-center bg-white" style="display:flex;z-index:3">
          <div class="text-center text-muted">
            <span class="spinner-border text-primary mb-2"></span>
            <div class="small fw-semibold">Loading...</div>
          </div>
        </div>
        <iframe id="pos-page-popup-frame" title="POS details" style="width:100%;height:100%;border:0;background:#f8fafc"></iframe>
      </div>
    </div>
  </div>
</div>

<!-- ─── Receipt Modal ────────────────────────────────────── -->
<div class="modal fade" id="receiptModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px">
    <div class="modal-content border-0 shadow-lg" id="receiptModalContent">
    </div>
  </div>
</div>

<?php
$jsData = [
  'APP_URL'     => APP_URL,
  'SYM'         => setting('currency_symbol','Rs.'),
  'TAX_PCT'     => (float)setting('tax_percent','0'),
  'CSRF'        => Auth::csrfToken(),
  'CASHIER'     => Auth::name(),
  'SHOP_NAME'   => setting('shop_name','MJPOS'),
];
?>
<script>
// ── Constants ─────────────────────────────────────────────
<?php foreach($jsData as $k=>$v): ?>
const <?= $k ?> = <?= json_encode($v) ?>;
<?php endforeach; ?>
const NEXT_INVOICE_NO = <?= json_encode($nextInvoiceNo) ?>;
const POS_USER_ROLE = <?= json_encode($posUserRole) ?>;
const POS_IS_CASHIER = <?= $posIsCashier ? 'true' : 'false' ?>;
const STOCK_VIEW_PRODUCTS = <?= json_encode($stockViewProducts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

// ── State ──────────────────────────────────────────────────
let cart     = [];
let pmtRowCount = 0;
let searchTimer = null;
let activeIndex = -1;
let barcodeBuffer = '', barcodeTimer = null, lastKeyTime = 0;

// ── Helpers ────────────────────────────────────────────────
function esc(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
function fmt(n){ return SYM + ' ' + parseFloat(n).toFixed(2); }
function toast(type, msg){
  const t = document.createElement('div');
  t.className = 'position-fixed top-0 end-0 m-3 alert alert-'+type+' shadow py-2 px-3';
  t.style.cssText = 'z-index:9999;font-size:.85rem;animation:slideIn .3s ease;min-width:200px';
  t.innerHTML = msg;
  document.body.appendChild(t);
  setTimeout(() => t.remove(), 3200);
}

// ── Keyboard ───────────────────────────────────────────────
document.addEventListener('keydown', e => {
  if (e.key === 'F1')  { e.preventDefault(); showStockView(); }
  if (e.key === 'F2')  { e.preventDefault(); focusSearch(); }
  if (e.key === 'F4')  { e.preventDefault(); holdBill(); }
  if (e.key === 'F6')  { e.preventDefault(); openPosPagePopup('sales'); }
  if (e.key === 'F7')  { e.preventDefault(); openPosPagePopup('credit'); }
  if (e.key === 'Delete' && document.activeElement.tagName !== 'INPUT') clearCart();
  if (e.key === 'Escape') hideResults();
  if (e.key === 'Enter' && document.activeElement !== document.getElementById('product-search')) {
    if (!document.getElementById('btn-process').disabled) processSale();
  }
});

function focusSearch(){ const s=document.getElementById('product-search'); s.focus(); s.select(); }

// ── Barcode scanner ────────────────────────────────────────
const searchInput = document.getElementById('product-search');
searchInput.addEventListener('keydown', function(e) {
  const now = Date.now();
  const gap = now - lastKeyTime;
  lastKeyTime = now;

  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    e.preventDefault(); navigateResults(e.key==='ArrowDown'?1:-1); return;
  }
  if (e.key === 'Enter') {
    e.preventDefault();
    const hi = document.querySelector('.prod-item.active');
    if (hi) { hi.click(); return; }
    const q = this.value.trim();
    if (q) { clearTimeout(searchTimer); searchProducts(q, true); }
    return;
  }
  if (e.key === 'Escape') { hideResults(); return; }

  if (e.key.length === 1) {
    barcodeBuffer = gap < 50 ? barcodeBuffer + e.key : e.key;
    clearTimeout(barcodeTimer);
    barcodeTimer = setTimeout(() => { barcodeBuffer = ''; }, 200);
    const isScanning = barcodeBuffer.length > 3 && gap < 50;
    setScanMode(isScanning);
  }
});

searchInput.addEventListener('input', function() {
  clearTimeout(searchTimer);
  const q = this.value.trim();
  if (!q) { hideResults(); setStatus('F2'); return; }
  setStatus('…');
  searchTimer = setTimeout(() => searchProducts(q, false), 200);
});

document.addEventListener('click', e => {
  if (!e.target.closest('#search-wrap')) hideResults();
});

function setScanMode(on) {
  const icon = document.getElementById('search-icon');
  icon.className = on ? 'bi bi-upc-scan text-success' : 'bi bi-search text-primary';
  if (on) setStatus('Scan');
}
function setStatus(t) {
  document.getElementById('search-status-pill').textContent = t||'F2';
}
function navigateResults(dir) {
  const items = document.querySelectorAll('.prod-item');
  if (!items.length) return;
  if (activeIndex >= 0 && items[activeIndex]) items[activeIndex].classList.remove('active');
  activeIndex = Math.max(0, Math.min(items.length-1, activeIndex+dir));
  items[activeIndex].classList.add('active');
  items[activeIndex].scrollIntoView({block:'nearest'});
}
function resetNav() { activeIndex = -1; }

// ── Stock View Popup ───────────────────────────────────────
function showStockView() {
  const input = document.getElementById('stock-view-search');
  if (input) input.value = '';
  renderStockView(STOCK_VIEW_PRODUCTS);
  const modalEl = document.getElementById('stockViewModal');
  bootstrap.Modal.getOrCreateInstance(modalEl).show();
  modalEl.addEventListener('shown.bs.modal', () => input?.focus(), {once:true});
}

function filterStockView() {
  const q = (document.getElementById('stock-view-search')?.value || '').trim().toLowerCase();
  const filtered = !q ? STOCK_VIEW_PRODUCTS : STOCK_VIEW_PRODUCTS.filter(p =>
    String(p.product_name || '').toLowerCase().includes(q) ||
    String(p.product_code || '').toLowerCase().includes(q) ||
    String(p.barcode || '').toLowerCase().includes(q)
  );
  renderStockView(filtered);
}

function renderStockView(items) {
  const body = document.getElementById('stock-view-body');
  const table = document.getElementById('stock-view-table');
  const empty = document.getElementById('stock-view-empty');
  const summary = document.getElementById('stock-summary');
  if (!body || !table || !empty || !summary) return;
  const all = STOCK_VIEW_PRODUCTS || [];
  const outCount = all.filter(p => parseFloat(p.current_stock || 0) <= 0).length;
  const lowCount = all.filter(p => {
    const stock = parseFloat(p.current_stock || 0), reorder = parseFloat(p.reorder_level || 0);
    return stock > 0 && stock <= reorder;
  }).length;
  summary.innerHTML = `
    <span class="stock-summary-pill total"><i class="bi bi-boxes"></i> Total ${all.length}</span>
    <span class="stock-summary-pill available"><i class="bi bi-check-circle"></i> Available ${all.length-outCount}</span>
    <span class="stock-summary-pill low"><i class="bi bi-exclamation-triangle"></i> Low ${lowCount}</span>
    <span class="stock-summary-pill out"><i class="bi bi-x-circle"></i> Out ${outCount}</span>
    <span class="ms-auto text-muted align-self-center" style="font-size:.72rem;font-weight:700">Showing ${items.length} item(s)</span>`;
  if (!items.length) {
    body.innerHTML=''; table.style.display='none'; empty.style.display='block'; return;
  }
  table.style.display='table'; empty.style.display='none';
  body.innerHTML = items.map((p,index) => {
    const stock=parseFloat(p.current_stock||0), reorder=parseFloat(p.reorder_level||0);
    const isOut=stock<=0, isLow=!isOut&&stock<=reorder;
    const cls=isOut?'out':(isLow?'low':'ok');
    const txt=isOut?'Out of Stock':(isLow?'Low Stock':'In Stock');
    return `<tr>
      <td class="text-muted">${index+1}</td>
      <td><div class="fw-bold">${esc(p.product_name)}</div></td>
      <td><div class="fw-semibold" style="font-size:.78rem">${esc(p.product_code||'—')}</div><div class="text-muted" style="font-size:.68rem">${esc(p.barcode||'No barcode')}</div></td>
      <td class="text-end fw-bold text-primary">${SYM} ${parseFloat(p.selling_price||0).toFixed(2)}</td>
      <td class="text-center">${reorder.toFixed(2)}</td>
      <td class="text-center"><span class="stock-qty ${cls}">${stock.toFixed(2)}</span></td>
      <td class="text-center"><span class="stock-status ${cls}">${txt}</span></td>
    </tr>`;
  }).join('');
}

// ── Search ─────────────────────────────────────────────────
async function searchProducts(q, exact=false) {
  setStatus('…');
  const box = document.getElementById('product-results');
  try {
    const res  = await fetch(APP_URL+'/products/search?q='+encodeURIComponent(q)+(exact?'&exact=1':''));
    const data = await res.json();
    if (!data.length) {
      box.innerHTML = `<div class="text-center text-muted py-3 small">
        <i class="bi bi-search me-1"></i>No results for "<strong>${esc(q)}</strong>"
      </div>`;
      box.style.display='block'; setStatus('0'); return;
    }
    if (exact && data.length===1) { addToCart(data[0]); setStatus(''); return; }
    resetNav();
    const headerHtml = `<div class="pres-header">
      <span>${data.length} result${data.length!=1?'s':''} for "<strong>${esc(q)}</strong>"</span>
      <span>↑↓ navigate · Enter select</span>
    </div>`;
    box.innerHTML = headerHtml + data.map(p => {
      const stock = parseFloat(p.current_stock);
      const isOut = stock<=0;
      const isLow = !isOut && stock<=(parseFloat(p.reorder_level)||5);
      const sb = isOut
        ? `<span class="badge bg-danger" style="font-size:.6rem">Out</span>`
        : isLow
        ? `<span class="badge bg-warning text-dark" style="font-size:.6rem">${stock} Low</span>`
        : `<span class="badge bg-success" style="font-size:.6rem">${stock}</span>`;
      const margin = p.cost_price>0 ? Math.round((p.selling_price-p.cost_price)/p.selling_price*100) : 0;
      return `<div class="prod-item${isOut?' out':''}" ${isOut?'':' onclick=\'addToCart('+JSON.stringify(p)+')\''}>
        <div style="min-width:0;flex:1">
          <div class="fw-semibold" style="font-size:.85rem">${esc(p.product_name)}</div>
          <div class="d-flex gap-2 align-items-center mt-1">
            <code style="font-size:.65rem;color:#94a3b8">${esc(p.product_code)}</code>
            ${sb}
            ${p.barcode?`<code style="font-size:.62rem;color:#cbd5e1">${esc(p.barcode)}</code>`:''}
          </div>
        </div>
        <div class="text-end flex-shrink-0">
          <div class="fw-bold text-primary" style="font-size:.95rem">${SYM} ${parseFloat(p.selling_price).toFixed(2)}</div>
          <div class="text-muted" style="font-size:.65rem">Cost ${SYM} ${parseFloat(p.cost_price).toFixed(2)} · ${margin}%</div>
        </div>
      </div>`;
    }).join('');
    box.style.display='block';
    setStatus(data.length.toString());
  } catch(e) { setStatus('!'); }
}

function hideResults() {
  document.getElementById('product-results').style.display='none';
  document.getElementById('product-results').innerHTML='';
  document.getElementById('product-search').value='';
  resetNav(); setScanMode(false); setStatus('F2');
}

// ── Cart ───────────────────────────────────────────────────
function addToCart(p) {
  if (parseFloat(p.current_stock) <= 0) {
    toast('warning', 'Out of stock: ' + p.product_name); return;
  }
  hideResults();
  const ex = cart.find(i => i.id == p.id);
  if (ex) {
    // Check stock before incrementing
    if (ex.qty >= parseFloat(p.current_stock)) {
      toast('warning', 'Max stock reached: ' + parseFloat(p.current_stock) + ' available');
      return;
    }
    ex.qty++;
    document.getElementById('crow-' + p.id)?.classList.add('cart-bounce');
    setTimeout(() => document.getElementById('crow-' + p.id)?.classList.remove('cart-bounce'), 350);
  } else {
    cart.push({
      id:           p.id,
      product_code: p.product_code,
      product_name: p.product_name,
      selling_price: parseFloat(p.selling_price) || 0,
      cost_price:    parseFloat(p.cost_price) || 0,
      tax_percent:   parseFloat(p.tax_percent || 0),
      line_discount: 0,
      qty:           1,
      max_stock:     parseFloat(p.current_stock)
    });
  }
  renderCart();
  // Flash green confirm on search icon
  const ic = document.getElementById('search-icon');
  ic.className = 'bi bi-check-circle text-success';
  setTimeout(() => ic.className = 'bi bi-search text-primary', 500);
  document.getElementById('product-search').focus();
}

function renderCart() {
  const tbody  = document.getElementById('cart-body');
  const table  = document.getElementById('cart-table');
  const empty  = document.getElementById('cart-empty');
  const btn    = document.getElementById('btn-process');

  if (!cart.length) {
    table.style.display='none'; empty.classList.add('show');
    document.getElementById('cart-count').textContent='0';
    document.getElementById('cart-qty-total').textContent='0';
    document.getElementById('cart-margin-display').textContent='';
    btn.disabled=true; recalc(); return;
  }
  table.style.display='table'; empty.classList.remove('show');

  tbody.innerHTML = cart.map((item,i) => {
    const lineTotal = (item.selling_price * item.qty) - item.line_discount;
    const margin    = item.selling_price>0
      ? Math.round((item.selling_price-item.cost_price)/item.selling_price*100) : 0;
    return `<tr id="crow-${item.id}" class="cart-row-new">
      <td class="text-muted">${i+1}</td>
      <td>
        <div class="fw-semibold" style="font-size:.82rem">${esc(item.product_name)}</div>
        <div style="font-size:.66rem;color:#94a3b8">
          ${esc(item.product_code)}
          <span class="ms-1 ${margin>=20?'text-success':margin>=10?'text-warning':'text-danger'}">${margin}%</span>
        </div>
      </td>
      <td>
        <div class="d-flex align-items-center gap-1 justify-content-center">
          <button onclick="changeQty(${item.id},-1)"
                  style="width:22px;height:22px;border:1px solid #e2e8f0;border-radius:5px;
                         background:#f8fafc;cursor:pointer;font-size:.7rem">−</button>
          <input type="number" class="cart-qty-input" value="${item.qty}" min="0.01" step="0.01"
                 onchange="setQty(${item.id},this.value)" style="width:50px">
          <button onclick="changeQty(${item.id},1)"
                  style="width:22px;height:22px;border:1px solid #e2e8f0;border-radius:5px;
                         background:#f8fafc;cursor:pointer;font-size:.7rem">+</button>
        </div>
      </td>
      <td class="text-end fw-semibold">${SYM} ${item.selling_price.toFixed(2)}</td>
      <td>
        <input type="number" class="cart-disc-input" value="${item.line_discount.toFixed(2)}"
               min="0" step="0.01"
               onchange="setLineDisc(${item.id},this.value)"
               style="width:62px;text-align:right">
      </td>
      <td class="text-end fw-bold text-primary">${SYM} ${lineTotal.toFixed(2)}</td>
      <td>
        <button onclick="removeItem(${item.id})"
                style="background:none;border:none;color:#ef4444;cursor:pointer;
                       padding:2px 4px;border-radius:4px;font-size:.85rem">
          <i class="bi bi-x-lg"></i>
        </button>
      </td>
    </tr>`;
  }).join('');

  const totalQty = cart.reduce((s,i)=>s+parseFloat(i.qty),0);
  const avgMargin = cart.length
    ? Math.round(cart.reduce((s,i)=>s+(i.selling_price>0?(i.selling_price-i.cost_price)/i.selling_price*100:0),0)/cart.length)
    : 0;
  document.getElementById('cart-count').textContent = cart.length;
  document.getElementById('cart-qty-total').textContent = totalQty.toFixed(2);
  document.getElementById('cart-margin-display').textContent = `Avg margin: ${avgMargin}%`;
  btn.disabled = false;
  recalc();
}

function changeQty(id, delta) {
  const item = cart.find(i => i.id == id);
  if (!item) return;
  const newQty = Math.round((item.qty + delta) * 100) / 100;
  if (newQty <= 0) {
    cart = cart.filter(i => i.id != id);
    renderCart(); return;
  }
  if (delta > 0 && item.max_stock && newQty > item.max_stock) {
    toast('warning', 'Only ' + item.max_stock + ' in stock'); return;
  }
  item.qty = newQty;
  renderCart();
}
function setQty(id, val) {
  const item = cart.find(i => i.id == id);
  if (!item) return;
  const newQty = Math.max(0.01, parseFloat(val) || 0.01);
  if (item.max_stock && newQty > item.max_stock) {
    toast('warning', 'Only ' + item.max_stock + ' in stock');
    item.qty = item.max_stock;
  } else {
    item.qty = newQty;
  }
  renderCart();
}
function setLineDisc(id, val) {
  const item = cart.find(i=>i.id==id);
  if (!item) return;
  item.line_discount = Math.max(0, parseFloat(val)||0);
  renderCart();
}
function removeItem(id) {
  cart = cart.filter(i=>i.id!=id); renderCart();
}
function clearCart() {
  if (cart.length && !confirm('Clear all items?')) return;
  cart=[]; window._holdId=0; renderCart();
  document.getElementById('bill-discount').value='0';
  document.getElementById('sale-note').value='';
  document.getElementById('customer-select').value='';
  onCustomerChange(document.getElementById('customer-select'));
  resetPaymentRows();
}

// ── Recalculate totals ─────────────────────────────────────
function recalc() {
  const subtotal  = cart.reduce((s,i)=>s+(i.selling_price*i.qty)-i.line_discount, 0);
  const billDisc  = parseFloat(document.getElementById('bill-discount').value)||0;
  const taxable   = Math.max(0, subtotal - billDisc);
  const tax       = Math.round(taxable * TAX_PCT) / 100;
  const total     = Math.round((taxable + tax) * 100) / 100;

  // Collect payments once
  const pmts      = collectPayments();
  const totalPaid = pmts.reduce((s,p)=>s+(['cash','card','bank_transfer','mobile','cheque'].includes(p.method)?p.amount:0),0);
  const totalCredit = pmts.reduce((s,p)=>s+(p.method==='credit'?p.amount:0),0);

  // Change = cash overpayment only (excluding credit)
  const change    = Math.max(0, Math.round((totalPaid - (total - totalCredit)) * 100) / 100);
  // Balance = amount still unpaid (credit portion)
  const balance   = Math.max(0, Math.round((total - totalPaid - totalCredit) * 100) / 100);

  document.getElementById('display-subtotal').textContent = fmt(subtotal);
  document.getElementById('display-discount').textContent = billDisc>0 ? '− '+fmt(billDisc) : fmt(0);
  document.getElementById('display-tax').textContent      = fmt(tax);
  document.getElementById('display-total').textContent    = SYM+' '+total.toFixed(2);
  document.getElementById('display-paid').textContent     = fmt(totalPaid+totalCredit);
  document.getElementById('display-balance').textContent  = fmt(balance);
  document.getElementById('display-change').textContent   = fmt(change);

  const changeRow = document.getElementById('display-change-row');
  changeRow.style.background = change>0 ? '#f0fdf4' : '#f8fafc';
  document.getElementById('display-change').style.color = change>0 ? '#16a34a' : '#94a3b8';

  // Balance due row — show red if there's an unpaid amount
  const balRow = document.getElementById('display-balance-row');
  if (balRow) {
    balRow.style.background = balance>0 ? '#fef2f2' : '#f8fafc';
    document.getElementById('display-balance').style.color = balance>0 ? '#dc2626' : '#94a3b8';
  }

  // Auto-fill first payment row if empty and there's a total
  const firstAmt = document.querySelector('#payments-list .pmt-amount-inp');
  if (firstAmt && !parseFloat(firstAmt.value) && total > 0 && pmts.length === 0) {
    firstAmt.placeholder = total.toFixed(2);
  }

  updateQuickCash(total);
}

// ── Payment rows ───────────────────────────────────────────
const PMT_OPTS = [
  {v:'cash',          l:' Cash'},
  {v:'card',          l:' Card'},
  {v:'bank_transfer', l:' Bank Transfer'},
  {v:'mobile',        l:' Mobile Pay'},
  {v:'cheque',        l:' Cheque'},
  {v:'credit',        l:' Credit'},
];

function makePaymentRow(removable=true) {
  const id  = 'prow'+pmtRowCount++;
  const rid = 'ref'+id;
  const did = 'det'+id;
  const opts = PMT_OPTS.map(o=>`<option value="${o.v}">${o.l}</option>`).join('');
  const div  = document.createElement('div');
  div.className='pmt-row-wrap'; div.id=id;
  div.innerHTML=`
    <!-- Method + Amount row -->
    <div class="pmt-row">
      <select class="pmt-method-sel" id="sel${id}" onchange="onPmtChange('${id}')" >
        ${opts}
      </select>
      <input type="number" class="pmt-amount-inp" id="amt${id}"
             step="0.01" min="0" placeholder="0.00" oninput="recalc()">
      ${removable
        ?`<button class="remove-pmt-btn"
                  onclick="document.getElementById('${id}').remove();recalc()"
                  title="Remove"><i class="bi bi-x"></i></button>`
        :'<span style="width:28px"></span>'
      }
    </div>
    <!-- Dynamic detail fields -->
    <div id="${did}" style="display:none;margin:0 0 8px 0;
         background:#f8fafc;border-radius:8px;padding:8px 10px;
         border:1px solid #e2e8f0;font-size:.78rem"></div>
  `;
  return div;
}

function onPmtChange(rowId) {
  const sel = document.getElementById('sel'+rowId);
  const det = document.getElementById('det'+rowId);
  const method = sel.value;
  recalc();
  renderPaymentDetail(det, method, rowId);
}

function renderPaymentDetail(det, method, rowId) {
  if (method === 'card') {
    det.style.display = 'block';
    det.innerHTML = `
      <div class="fw-semibold mb-2" style="color:#1d4ed8;font-size:.75rem">
        <i class="bi bi-credit-card me-1"></i>Card Payment Details
      </div>
      <div class="row g-2">
        <div class="col-6">
          <label class="pmt-det-label">Card Type</label>
          <select class="pmt-det-input" id="cardType${rowId}">
            <option value="visa"> Visa</option>
            <option value="mastercard"> Mastercard</option>
            <option value="amex"> Amex</option>
            <option value="other"> Other</option>
          </select>
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Last 4 Digits</label>
          <input type="text" class="pmt-det-input" id="cardLast4${rowId}"
                 maxlength="4" placeholder="•••• 1234"
                 oninput="this.value=this.value.replace(/\\D/g,'').slice(0,4)">
        </div>
        <div class="col-12">
          <label class="pmt-det-label">
            POS / Reference No.
            <span style="color:#16a34a;font-size:.65rem;margin-left:4px">
              <i class="bi bi-check-circle-fill"></i> Auto-filled with invoice no.
            </span>
          </label>
          <input type="text" class="pmt-det-input" id="cardRef${rowId}"
                 placeholder="e.g. POS-TXN-00123456"
                 value="${NEXT_INVOICE_NO}">
        </div>
      </div>`;
  }
  else if (method === 'cheque') {
    det.style.display = 'block';
    det.innerHTML = `
      <div class="fw-semibold mb-2" style="color:#92400e;font-size:.75rem">
        <i class="bi bi-file-earmark-text me-1"></i>Cheque Details
      </div>
      <div class="row g-2">
        <div class="col-6">
          <label class="pmt-det-label">Cheque Number <span style="color:#ef4444">*</span></label>
          <input type="text" class="pmt-det-input" id="chequeNo${rowId}"
                 placeholder="CHQ-001234" required>
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Bank Name</label>
          <input type="text" class="pmt-det-input" id="chequeBank${rowId}"
                 placeholder="e.g. Commercial Bank">
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Cheque Date</label>
          <input type="date" class="pmt-det-input" id="chequeDate${rowId}"
                 value="${new Date().toISOString().slice(0,10)}">
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Account Holder</label>
          <input type="text" class="pmt-det-input" id="chequeHolder${rowId}"
                 placeholder="Name on cheque">
        </div>
      </div>`;
  }
  else if (method === 'bank_transfer') {
    det.style.display = 'block';
    det.innerHTML = `
      <div class="fw-semibold mb-2" style="color:#0891b2;font-size:.75rem">
        <i class="bi bi-bank me-1"></i>Bank Transfer Details
      </div>
      <div class="row g-2">
        <div class="col-6">
          <label class="pmt-det-label">Transaction ID <span style="color:#ef4444">*</span></label>
          <input type="text" class="pmt-det-input" id="bankTxn${rowId}"
                 placeholder="TXN-123456789">
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Bank Name</label>
          <input type="text" class="pmt-det-input" id="bankName${rowId}"
                 placeholder="e.g. BOC, Sampath">
        </div>
      </div>`;
  }
  else if (method === 'credit') {
    const custId  = document.getElementById('customer-select').value;
    const custSel = document.getElementById('customer-select');
    const custOpt = custSel.selectedOptions[0];
    const balance = parseFloat(custOpt?.dataset?.balance||0);
    const limit   = parseFloat(custOpt?.dataset?.limit||0);
    const hasLimit= limit>0;
    const overLimit=hasLimit && (balance>=limit);
    det.style.display = 'block';
    det.innerHTML = custId
      ? `<div class="fw-semibold mb-2" style="color:#dc2626;font-size:.75rem">
           <i class="bi bi-journal-bookmark me-1"></i>Credit Details
         </div>
         <div class="row g-2">
           <div class="col-6">
             <div class="pmt-det-label">Customer</div>
             <div class="fw-semibold" style="font-size:.8rem">${esc(custOpt.text.split('(')[0].trim())}</div>
           </div>
           <div class="col-3">
             <div class="pmt-det-label">Balance</div>
             <div class="fw-bold text-danger" style="font-size:.8rem">${SYM} ${balance.toFixed(2)}</div>
           </div>
           <div class="col-3">
             <div class="pmt-det-label">Limit</div>
             <div class="fw-semibold ${overLimit?'text-danger':''}" style="font-size:.8rem">
               ${hasLimit ? SYM+' '+limit.toFixed(2) : '—'}
             </div>
           </div>
         </div>
         ${overLimit?`<div class="mt-2 p-2 rounded" style="background:#fef2f2;color:#dc2626;font-size:.72rem">
            Customer is at or over credit limit</div>`:''}
         <div class="mt-2">
           <label class="pmt-det-label">Credit Note / Reference</label>
           <input type="text" class="pmt-det-input" id="creditRef${rowId}"
                  placeholder="Optional reference">
         </div>`
      : `<div class="p-2 rounded d-flex align-items-center gap-2"
              style="background:#fef2f2;border:1px solid #fecaca">
           <i class="bi bi-exclamation-triangle text-danger"></i>
           <span style="color:#dc2626;font-size:.75rem;font-weight:600">
             Select a customer above before using Credit payment
           </span>
         </div>`;
  }
  else if (method === 'mobile') {
    det.style.display = 'block';
    det.innerHTML = `
      <div class="fw-semibold mb-2" style="color:#7c3aed;font-size:.75rem">
        <i class="bi bi-phone me-1"></i>Mobile Payment Details
      </div>
      <div class="row g-2">
        <div class="col-6">
          <label class="pmt-det-label">App / Provider</label>
          <select class="pmt-det-input" id="mobileApp${rowId}">
            <option value="frimi">FriMi</option>
            <option value="dialog_genie">Dialog Genie</option>
            <option value="lak_pay">LakPay</option>
            <option value="ezpay">EzPay</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div class="col-6">
          <label class="pmt-det-label">Reference No.</label>
          <input type="text" class="pmt-det-input" id="mobileRef${rowId}"
                 placeholder="Transaction ref">
        </div>
      </div>`;
  }
  else {
    det.style.display = 'none';
    det.innerHTML = '';
  }
}

function addPaymentRow() {
  document.getElementById('payments-list').appendChild(makePaymentRow(true));
}
function resetPaymentRows() {
  pmtRowCount=0;
  const pl=document.getElementById('payments-list');
  pl.innerHTML='';
  const row=makePaymentRow(false);
  pl.appendChild(row);
  recalc();
}
function collectPayments() {
  return [...document.querySelectorAll('.pmt-row-wrap')].map(wrap=>{
    const id     = wrap.id;
    const sel    = wrap.querySelector('.pmt-method-sel');
    const amt    = wrap.querySelector('.pmt-amount-inp');
    const method = sel?.value;
    const amount = parseFloat(amt?.value)||0;
    if (!amount) return null;

    // Collect reference/detail fields
    let reference = '';
    if (method==='card') {
      const t=wrap.querySelector('[id^="cardType"]')?.value||'';
      const l=wrap.querySelector('[id^="cardLast4"]')?.value||'';
      const r=wrap.querySelector('[id^="cardRef"]')?.value||'';
      reference=[t,l?'****'+l:'',r].filter(Boolean).join(' | ');
    } else if (method==='cheque') {
      const n=wrap.querySelector('[id^="chequeNo"]')?.value||'';
      const b=wrap.querySelector('[id^="chequeBank"]')?.value||'';
      const d=wrap.querySelector('[id^="chequeDate"]')?.value||'';
      reference=[n,b,d].filter(Boolean).join(' | ');
      if (!n) { return {method,amount,reference,error:'Cheque number required'}; }
    } else if (method==='bank_transfer') {
      const t=wrap.querySelector('[id^="bankTxn"]')?.value||'';
      const b=wrap.querySelector('[id^="bankName"]')?.value||'';
      reference=[t,b].filter(Boolean).join(' | ');
    } else if (method==='mobile') {
      const a=wrap.querySelector('[id^="mobileApp"]')?.value||'';
      const r=wrap.querySelector('[id^="mobileRef"]')?.value||'';
      reference=[a,r].filter(Boolean).join(' | ');
    } else if (method==='credit') {
      reference=wrap.querySelector('[id^="creditRef"]')?.value||'';
    }
    return {method, amount, reference};
  }).filter(p=>p&&p.amount>0);
}

function updateQuickCash(total) {
  const qb = document.getElementById('quick-cash-btns');
  if (!total || total<=0) { qb.innerHTML=''; return; }
  const suggestions = [total, Math.ceil(total/100)*100,
    Math.ceil(total/500)*500, Math.ceil(total/1000)*1000]
    .filter((v,i,a)=>v>0&&a.indexOf(v)===i).slice(0,4);
  qb.innerHTML = suggestions.map(v=>
    `<button class="quick-btn" onclick="setQuickCash(${v})">${SYM} ${v.toFixed(0)}</button>`
  ).join('');
}
function setQuickCash(val) {
  const inp=document.querySelector('#payments-list .pmt-amount-inp');
  if(inp){inp.value=val.toFixed(2);recalc();}
}

// ── Customer ───────────────────────────────────────────────
function onCustomerChange(sel) {
  const opt      = sel.selectedOptions[0];
  const info     = document.getElementById('customer-info');
  const phoneWrap= document.getElementById('walkin-phone-wrap');
  const phoneInp = document.getElementById('walkin-phone');

  if (sel.value) {
    // Named customer selected — hide walk-in phone field
    document.getElementById('cust-balance').textContent = fmt(opt.dataset.balance||0);
    document.getElementById('cust-limit').textContent   = fmt(opt.dataset.limit||0);
    info.style.display      = 'block';
    phoneWrap.style.display = 'none';
    phoneInp.value          = '';
  } else {
    // Walk-in customer — show phone field, hide credit info
    info.style.display      = 'none';
    phoneWrap.style.display = 'block';
  }

  // Refresh any credit payment detail rows
  document.querySelectorAll('.pmt-method-sel').forEach(s => {
    if (s.value === 'credit') {
      const rowId = s.id.replace('sel','');
      const det   = document.getElementById('det'+rowId);
      if (det) renderPaymentDetail(det, 'credit', rowId);
    }
  });
}

// ── Hold / recall ──────────────────────────────────────────
function holdBill() {
  if (!cart.length) { toast('warning','Cart is empty.'); return; }
  const held = JSON.parse(sessionStorage.getItem('mjpos_held')||'[]');
  held.push({
    id:Date.now(), cart:[...cart],
    customer:document.getElementById('customer-select').value,
    discount:document.getElementById('bill-discount').value,
    note:document.getElementById('sale-note').value,
    at:new Date().toLocaleTimeString(),
  });
  sessionStorage.setItem('mjpos_held',JSON.stringify(held));
  updateHeldBadge(held.length);
  clearCart();
  toast('success','Bill held. Cart cleared.');
}
function showHeldBills() {
  const held = JSON.parse(sessionStorage.getItem('mjpos_held')||'[]');
  const body = document.getElementById('held-modal-body');
  if (!held.length) {
    body.innerHTML='<div class="text-center text-muted py-4">No held bills.</div>';
  } else {
    body.innerHTML = held.map(h=>`
      <div class="d-flex align-items-center gap-2 p-3 border-bottom">
        <div class="flex-grow-1">
          <div class="fw-semibold small">${h.cart.length} item(s)</div>
          <small class="text-muted">${h.at}</small>
        </div>
        <button class="btn btn-sm btn-outline-primary" onclick="recallBill(${h.id})">Recall</button>
        <button class="btn btn-sm btn-outline-danger" onclick="deleteBill(${h.id})">Delete</button>
      </div>`).join('');
  }
  new bootstrap.Modal(document.getElementById('heldModal')).show();
}
function recallBill(id) {
  let held = JSON.parse(sessionStorage.getItem('mjpos_held')||'[]');
  const bill = held.find(h=>h.id===id);
  if (!bill) return;
  held = held.filter(h=>h.id!==id);
  sessionStorage.setItem('mjpos_held',JSON.stringify(held));
  cart=bill.cart;
  document.getElementById('customer-select').value=bill.customer||'';
  document.getElementById('bill-discount').value=bill.discount||0;
  document.getElementById('sale-note').value=bill.note||'';
  renderCart();
  updateHeldBadge(held.length);
  bootstrap.Modal.getInstance(document.getElementById('heldModal'))?.hide();
}
function deleteBill(id) {
  let held=JSON.parse(sessionStorage.getItem('mjpos_held')||'[]');
  held=held.filter(h=>h.id!==id);
  sessionStorage.setItem('mjpos_held',JSON.stringify(held));
  updateHeldBadge(held.length);
  showHeldBills();
}
function updateHeldBadge(n) {
  const b=document.getElementById('held-count-badge');
  b.textContent=n; b.style.display=n>0?'flex':'none';
}

// ── Process Sale ───────────────────────────────────────────
async function processSale() {
  if (!cart.length) return;
  const btn=document.getElementById('btn-process');
  btn.disabled=true;
  btn.innerHTML='<span class="spinner-border spinner-border-sm me-2"></span>Processing…';

  const payments=collectPayments();
  if (!payments.length) { toast('danger','Enter a payment amount.'); resetBtn(); return; }

  // Validate cheque number required
  const badCheque = payments.find(p=>p.method==='cheque' && p.error);
  if (badCheque) {
    toast('danger',' Cheque number is required.');
    resetBtn(); return;
  }

  const hasCredit=payments.some(p=>p.method==='credit');
  const custId=document.getElementById('customer-select').value;
  if (hasCredit&&!custId) {
    toast('danger',' Select a customer for Credit payment.');
    resetBtn();
    document.getElementById('customer-select').focus();
    return;
  }

  try {
    const body=new URLSearchParams({
      _mjpos_token:CSRF,
      cart_data:JSON.stringify(cart),
      customer_id:custId,
      walkin_phone:(!custId ? (document.getElementById('walkin-phone').value.trim()||'') : ''),
      discount:document.getElementById('bill-discount').value||'0',
      note:document.getElementById('sale-note').value||'',
      hold_id:window._holdId||0,
      payments:JSON.stringify(payments),
    });
    const res  = await fetch(APP_URL+'/pos/sale',{
      method:'POST',
      headers:{'X-Requested-With':'XMLHttpRequest'},
      body
    });
    const text = await res.text();
    let data;
    try {
      data = JSON.parse(text);
    } catch(parseErr) {
      // Server returned HTML (PHP error) — show first line
      const firstLine = text.replace(/<[^>]+>/g,'').trim().split('\n')[0].substring(0,120);
      console.error('POS server error:', text);
      toast('danger', 'Server error: ' + (firstLine || 'Check PHP error log'));
      resetBtn(); return;
    }

    if (data.success) {
      showReceiptModal(data);
      resetPOS();
      updateTargetBar(data.total);
      if (data.target_reached && data.target_data) {
        setTimeout(() => showCongrats(data.target_data), 1200);
      }
    } else {
      toast('danger',data.message||'Sale failed.'); resetBtn();
    }
  } catch(e) {
    console.error('POS fetch error:', e);
    toast('danger','Connection error — check internet. Details: '+e.message); resetBtn();
  }
}

function resetBtn() {
  const btn=document.getElementById('btn-process');
  btn.disabled=false;
  btn.innerHTML='<i class="bi bi-check-circle me-2"></i>PROCESS SALE';
}
function resetPOS() {
  cart=[]; window._holdId=0;
  document.getElementById('customer-select').value='';
  document.getElementById('walkin-phone').value='';
  onCustomerChange(document.getElementById('customer-select'));
  document.getElementById('bill-discount').value='0';
  document.getElementById('sale-note').value='';
  resetPaymentRows(); renderCart(); resetBtn();
  setTimeout(()=>document.getElementById('product-search').focus(), 300);
}
function showReceiptModal(data) {
  const changeDue=parseFloat(data.change_due||0);
  const balance  =parseFloat(data.balance||0);
  const total    =parseFloat(data.total||0);
  const paid     =parseFloat(data.paid||0);

  document.getElementById('receiptModalContent').innerHTML=`
    <div class="p-4 text-center">
      <div class="mb-3">
        <div style="width:70px;height:70px;border-radius:50%;background:#dcfce7;
                    display:inline-flex;align-items:center;justify-content:center;
                    animation:bounceIn .4s ease">
          <i class="bi bi-check-lg text-success" style="font-size:2rem"></i>
        </div>
      </div>
      <h5 class="fw-bold text-success mb-1">Sale Complete!</h5>
      <div class="text-muted mb-3 small">Invoice: <strong class="text-dark">${esc(data.invoice_no||'')}</strong></div>
      <div class="rounded-3 p-3 mb-3 text-start" style="background:#f8fafc;border:1px solid #e2e8f0">
        <div class="d-flex justify-content-between mb-1 small">
          <span class="text-muted">Total</span>
          <strong>${SYM} ${total.toFixed(2)}</strong>
        </div>
        <div class="d-flex justify-content-between mb-1 small">
          <span class="text-muted">Paid</span>
          <strong class="text-success">${SYM} ${paid.toFixed(2)}</strong>
        </div>
        ${changeDue>0?`
        <div class="d-flex justify-content-between pt-2 border-top mt-1">
          <span class="fw-bold text-primary">Change Due</span>
          <span class="fw-bold text-primary" style="font-size:1.1rem">${SYM} ${changeDue.toFixed(2)}</span>
        </div>`:''}
        ${balance>0?`
        <div class="d-flex justify-content-between pt-2 border-top mt-1">
          <span class="fw-bold text-danger">Credit Balance</span>
          <span class="fw-bold text-danger">${SYM} ${balance.toFixed(2)}</span>
        </div>`:''}
      </div>

      <!-- Print status -->
      <div id="printStatus" class="mb-2 small text-muted">
        <span class="spinner-border spinner-border-sm me-1"></span>Opening receipt…
      </div>

      <div class="d-flex gap-2 justify-content-center">
        <button class="btn btn-outline-secondary fw-semibold"
                onclick="openReceipt('${data.receipt_url||''}')">
          <i class="bi bi-printer me-1"></i>Print
        </button>
        <button class="btn btn-success fw-semibold px-4" onclick="closeReceiptModal()">
          <i class="bi bi-plus-circle me-1"></i>New Sale
        </button>
      </div>
      <div class="text-muted mt-2" style="font-size:.72rem">
        Auto-closing in <span id="rcCount">5</span>s
      </div>
    </div>`;

  const m = new bootstrap.Modal(
    document.getElementById('receiptModal'),
    {backdrop:'static', keyboard:false}
  );
  m.show();
  window._receiptModal = m;

  // ── Open receipt — printing is now self-managed by the receipt ──
  // ── page itself based on Background Printing System settings ──
  if (data.receipt_url) {
    const printWin = window.open(data.receipt_url, '_blank',
      'width=400,height=600,toolbar=0,menubar=0,scrollbars=1');

    const ps = document.getElementById('printStatus');
    if (printWin) {
      if (ps) {
        ps.innerHTML = '<i class="bi bi-printer-fill text-success me-1"></i>Receipt opened — printing per your settings';
      }
    } else {
      // Popup blocked — show message
      if (ps) {
        ps.innerHTML = `<i class="bi bi-exclamation-triangle text-warning me-1"></i>
          Popup blocked — <a href="${data.receipt_url}" target="_blank" class="fw-semibold">Open receipt manually</a>`;
      }
    }
  } else {
    const ps = document.getElementById('printStatus');
    if (ps) ps.style.display = 'none';
  }

  // ── Auto-close countdown ─────────────────────────────────
  let s = 5;
  window._receiptTimer = setInterval(() => {
    s--;
    const el = document.getElementById('rcCount');
    if (el) el.textContent = s;
    if (s <= 0) {
      clearInterval(window._receiptTimer);
      m.hide();
    }
  }, 1000);
}
function openReceipt(url){
  if(url)window.open(url,'_blank');
  closeReceiptModal();
}
function closeReceiptModal(){
  clearInterval(window._receiptTimer);
  window._receiptModal?.hide();
}

// ── Init ───────────────────────────────────────────────────
resetPaymentRows();
renderCart();
focusSearch();

// ── Automatic full-screen POS layout ──────────────────────
(function() {
  const sidebar = document.getElementById('sidebar');
  const content = document.getElementById('content');
  const topbar  = document.getElementById('topbar');
  const posWrap = document.getElementById('pos-wrap');

  // Cashier gets the distraction-free POS layout. Management roles keep the sidebar.
  if (POS_IS_CASHIER) {
    document.documentElement.classList.add('pos-fullscreen-page');
    document.body.classList.add('pos-fullscreen-page');

    if (sidebar) {
      sidebar.style.setProperty('display', 'none', 'important');
      sidebar.style.setProperty('width', '0', 'important');
      sidebar.style.setProperty('min-width', '0', 'important');
    }

    if (topbar) {
      topbar.style.removeProperty('display');
      topbar.style.setProperty('height', '55px', 'important');
      topbar.style.setProperty('min-height', '55px', 'important');
      topbar.style.setProperty('padding', '0 12px', 'important');
    }

    if (content) {
      content.style.setProperty('margin', '0', 'important');
      content.style.setProperty('padding', '0', 'important');
      content.style.setProperty('width', '100vw', 'important');
      content.style.setProperty('max-width', '100vw', 'important');
      content.style.setProperty('height', 'calc(100vh - 55px)', 'important');
      content.style.setProperty('overflow', 'hidden', 'important');
    }

    if (posWrap) {
      posWrap.style.setProperty('width', '100vw', 'important');
      posWrap.style.setProperty('height', 'calc(100vh - 55px)', 'important');
      posWrap.style.setProperty('min-height', 'calc(100vh - 55px)', 'important');
      posWrap.style.setProperty('max-height', 'calc(100vh - 55px)', 'important');
    }
  } else {
    document.documentElement.classList.remove('pos-fullscreen-page');
    document.body.classList.remove('pos-fullscreen-page');
    if (sidebar) {
      sidebar.style.removeProperty('display');
      sidebar.style.removeProperty('width');
      sidebar.style.removeProperty('min-width');
      sidebar.style.removeProperty('visibility');
      sidebar.style.removeProperty('opacity');
    }
  }

  // Restore the normal application layout before leaving the POS page.
  // This is especially important for cashier users when they click Home.
  function restoreApplicationLayout() {
    document.documentElement.classList.remove('pos-fullscreen-page');
    document.body.classList.remove('pos-fullscreen-page');

    if (sidebar) {
      sidebar.style.removeProperty('display');
      sidebar.style.removeProperty('width');
      sidebar.style.removeProperty('min-width');
      sidebar.style.removeProperty('visibility');
      sidebar.style.removeProperty('opacity');
    }

    const sidebarToggle = document.getElementById('sidebar-toggle');
    if (sidebarToggle) {
      sidebarToggle.style.removeProperty('display');
      sidebarToggle.style.removeProperty('visibility');
    }

    if (topbar) {
      topbar.style.removeProperty('height');
      topbar.style.removeProperty('min-height');
      topbar.style.removeProperty('padding');
    }

    if (content) {
      ['position','top','right','bottom','left','margin','padding','width',
       'max-width','height','max-height','overflow'].forEach(prop =>
        content.style.removeProperty(prop)
      );
    }

    if (posWrap) {
      ['width','height','min-height','max-height','margin'].forEach(prop =>
        posWrap.style.removeProperty(prop)
      );
    }
  }

  window.restoreApplicationLayout = restoreApplicationLayout;

  // Supports normal links and AJAX/SPA-style navigation used by Home buttons.
  document.addEventListener('click', event => {
    const link = event.target.closest('a[href]');
    if (!link) return;

    const href = (link.getAttribute('href') || '').trim();
    if (!href || href === '#' || href.startsWith('javascript:')) return;
    if (link.hasAttribute('download') || link.target === '_blank') return;

    restoreApplicationLayout();
  }, true);

  window.addEventListener('pagehide', restoreApplicationLayout);
  window.addEventListener('beforeunload', restoreApplicationLayout);

  // A user interaction is required by browsers for real fullscreen mode.
  // Double-click anywhere on the empty POS background to enter it.
  document.addEventListener('dblclick', async (event) => {
    if (event.target.closest('input,select,button,a,textarea,.modal')) return;
    try {
      if (!document.fullscreenElement) {
        await document.documentElement.requestFullscreen();
      }
    } catch (e) {
      console.debug('Browser fullscreen was not available:', e);
    }
  });
})();
</script>

<!-- ══════════════════════════════════════════════════
     DAILY TARGET — Progress bar (top of POS page)
     ══════════════════════════════════════════════════ -->
<?php
$targetEnabled = setting('daily_target_enabled','0') === '1';
$dailyTarget   = (float)(setting('daily_sales_target','0') ?: 0);
if ($targetEnabled && $dailyTarget > 0):
    $todaySales = (float)Database::fetchColumn(
        "SELECT COALESCE(SUM(total),0) FROM sales
         WHERE DATE(sale_date)=? AND status='completed' AND created_by=?",
        [date('Y-m-d'), Auth::id()]
    );
    $pct  = min(100, round($todaySales / $dailyTarget * 100, 1));
    $sym  = setting('currency_symbol','Rs.');
    $tClr = $pct >= 100 ? '#16a34a' : ($pct >= 70 ? '#d97706' : '#3b82f6');
    $tBg  = $pct >= 100 ? '#f0fdf4' : ($pct >= 70 ? '#fffbeb' : '#eff6ff');
    $tBdr = $pct >= 100 ? '#86efac' : ($pct >= 70 ? '#fde68a' : '#bfdbfe');
    $icon = $pct >= 100 ? 'bi-trophy-fill' : 'bi-bullseye';
    $lbl  = $pct >= 100 ? '🏆 Target Reached!' : 'Daily Target';
?>
<style>
/* ── Daily Target Bar ──────────────────────────────── */
#targetBar{
  position:fixed;
  top:90%;
  left:79%;
  right:15px;
  z-index:95;
  height:70px;
  background:<?=$tBg?>;
  border:2px solid <?=$tBdr?>;
  border-radius:14px;
  display:flex;
  align-items:center;
  gap:12px;
  padding:0 18px;
  box-shadow:0 4px 20px rgba(0,0,0,.12);
  transform:translateY(-50%);
}
#targetBar .tb-label{
  display:flex;align-items:center;gap:5px;
  font-size:.76rem;font-weight:700;
  color:<?=$tClr?>;white-space:nowrap;flex-shrink:0;
}
#targetBar .tb-track{
  flex:1;background:rgba(0,0,0,.1);
  border-radius:20px;height:10px;overflow:hidden;
  min-width:60px;
}
#targetBar .tb-fill{
  height:100%;border-radius:20px;
  background:<?=$tClr?>;
  width:<?=$pct?>%;
  transition:width .6s ease;
  box-shadow:0 0 6px <?=$tClr?>66;
}
#targetBar .tb-val{
  font-size:.74rem;font-weight:800;
  color:<?=$tClr?>;white-space:nowrap;flex-shrink:0;
  background:rgba(255,255,255,.8);
  padding:3px 10px;border-radius:20px;
  border:1px solid <?=$tBdr?>;
}
/* No content push needed — floating widget */
</style>

<div id="targetBar">
  <div class="tb-label">
    <i class="bi <?=$icon?>" style="font-size:.85rem"></i>
    <?=$lbl?>
  </div>
  <div class="tb-track">
    <div class="tb-fill" id="targetFill"></div>
  </div>
  <div class="tb-val" id="targetPct">
    <?=$sym?><?=number_format($todaySales,0)?>
    &nbsp;/&nbsp;
    <?=$sym?><?=number_format($dailyTarget,0)?>
    &nbsp;&nbsp;<?=$pct?>%
  </div>
</div>
<?php endif; ?>

<!-- ══════════════════════════════════════════════════
     CONGRATULATIONS POPUP MODAL
     ══════════════════════════════════════════════════ -->
<div id="congratsModal" style="display:none;position:fixed;inset:0;z-index:9999;
  background:rgba(0,0,0,.6);backdrop-filter:blur(4px);
  align-items:center;justify-content:center">

  <!-- Confetti canvas -->
  <canvas id="confettiCanvas" style="position:absolute;inset:0;pointer-events:none;width:100%;height:100%"></canvas>

  <!-- Card -->
  <div id="congratsCard" style="position:relative;z-index:2;background:#fff;
    border-radius:24px;padding:40px 32px;text-align:center;max-width:420px;width:90%;
    box-shadow:0 24px 60px rgba(0,0,0,.3);animation:popIn .4s cubic-bezier(.34,1.56,.64,1)">

    <!-- Trophy -->
    <div style="font-size:4rem;margin-bottom:8px;animation:bounce 1s infinite">🏆</div>

    <div style="font-size:1.7rem;font-weight:900;color:#0f172a;margin-bottom:6px">
      Congratulations!
    </div>
    <div style="font-size:.95rem;color:#64748b;margin-bottom:20px" id="congratsName">
      You've reached your daily target!
    </div>

    <!-- Stats -->
    <div style="background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 100%);
      border-radius:16px;padding:20px;margin-bottom:20px;color:#fff">
      <div style="font-size:.75rem;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em">
        Today's Sales
      </div>
      <div style="font-size:2rem;font-weight:900;margin:4px 0" id="congratsAmt">—</div>
      <div style="display:flex;align-items:center;justify-content:center;gap:8px;margin-top:8px">
        <div style="flex:1;background:rgba(255,255,255,.2);border-radius:20px;height:6px">
          <div style="background:#22c55e;height:100%;border-radius:20px;width:100%"></div>
        </div>
        <span style="font-size:.8rem;color:#22c55e;font-weight:700">Target ✓</span>
      </div>
      <div style="font-size:.75rem;color:#94a3b8;margin-top:6px" id="congratsTarget"></div>
    </div>

    <!-- Stars -->
    <div style="font-size:1.5rem;margin-bottom:16px">⭐⭐⭐⭐⭐</div>

    <button onclick="closeCongrats()"
      style="background:linear-gradient(135deg,#3b82f6,#1d4ed8);color:#fff;border:none;
        border-radius:12px;padding:12px 32px;font-size:1rem;font-weight:700;cursor:pointer;
        width:100%;box-shadow:0 4px 15px rgba(59,130,246,.4)">
      Continue Selling! 💪
    </button>
  </div>
</div>

<style>
@keyframes popIn{from{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}
@keyframes bounce{0%,100%{transform:translateY(0)}50%{transform:translateY(-10px)}}
@keyframes confettiFall{to{transform:translateY(110vh) rotate(720deg);opacity:0}}
</style>

<script>
// ── Daily target update after each sale ─────────────────
<?php if($targetEnabled && $dailyTarget > 0): ?>
const DAILY_TARGET     = <?=$dailyTarget?>;
const TARGET_SYM       = '<?=e($sym)?>';
let   todaySalesTotal  = <?=$todaySales?>;

function updateTargetBar(saleTotal) {
  todaySalesTotal += parseFloat(saleTotal) || 0;
  const pct   = Math.min(100, (todaySalesTotal / DAILY_TARGET * 100)).toFixed(1);
  const fill  = document.getElementById('targetFill');
  const val   = document.getElementById('targetPct');
  const bar   = document.getElementById('targetBar');
  if (!fill) return;

  const clr = pct >= 100 ? '#16a34a' : pct >= 70 ? '#d97706' : '#3b82f6';
  const bg  = pct >= 100 ? '#f0fdf4' : pct >= 70 ? '#fffbeb' : '#eff6ff';
  const bdr = pct >= 100 ? '#86efac' : pct >= 70 ? '#fde68a' : '#bfdbfe';

  fill.style.width      = pct + '%';
  fill.style.background = clr;
  fill.style.boxShadow  = `0 0 6px ${clr}66`;
  if (bar) { bar.style.background = bg; bar.style.borderBottomColor = bdr; }
  if (val) {
    val.style.color       = clr;
    val.style.borderColor = bdr;
    val.innerHTML = TARGET_SYM + Math.round(todaySalesTotal).toLocaleString('en')
      + ' &nbsp;/&nbsp; '
      + TARGET_SYM + Math.round(DAILY_TARGET).toLocaleString('en')
      + ' &nbsp;&nbsp;' + pct + '%';
  }
  const lbl = document.querySelector('#targetBar .tb-label');
  if (lbl && pct >= 100)
    lbl.innerHTML = '<i class="bi bi-trophy-fill" style="font-size:.85rem"></i> 🏆 Target Reached!';
}
<?php else: ?>
function updateTargetBar(t){}
<?php endif; ?>

// ── Congratulations popup ────────────────────────────────
function showCongrats(data) {
  const sym = '<?=e(setting("currency_symbol","Rs."))?>';
  document.getElementById('congratsName').textContent  =
    '🎉 ' + (data.cashier || 'Cashier') + ' — Daily target reached!';
  document.getElementById('congratsAmt').textContent   =
    sym + parseFloat(data.today_total).toLocaleString('en',{minimumFractionDigits:2});
  document.getElementById('congratsTarget').textContent =
    'Target: ' + sym + parseFloat(data.target).toLocaleString('en',{minimumFractionDigits:2});

  const modal = document.getElementById('congratsModal');
  modal.style.display = 'flex';

  // Confetti!
  launchConfetti();

  // Auto-close after 8 seconds
  setTimeout(closeCongrats, 8000);
}

function closeCongrats() {
  document.getElementById('congratsModal').style.display = 'none';
  stopConfetti();
}

// ── Confetti engine ──────────────────────────────────────
let confettiInterval = null;
const confettiColors = ['#3b82f6','#22c55e','#f59e0b','#ef4444','#8b5cf6','#ec4899','#06b6d4'];

function launchConfetti() {
  const canvas = document.getElementById('confettiCanvas');
  const ctx    = canvas.getContext('2d');
  canvas.width  = window.innerWidth;
  canvas.height = window.innerHeight;

  const pieces = Array.from({length:120}, () => ({
    x: Math.random() * canvas.width,
    y: -20 - Math.random() * 200,
    w: 8 + Math.random() * 10,
    h: 4 + Math.random() * 6,
    r: Math.random() * Math.PI * 2,
    vx: (Math.random() - 0.5) * 4,
    vy: 2 + Math.random() * 4,
    vr: (Math.random() - 0.5) * 0.2,
    color: confettiColors[Math.floor(Math.random() * confettiColors.length)],
    opacity: 1
  }));

  let frame = 0;
  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    pieces.forEach(p => {
      p.x  += p.vx;
      p.y  += p.vy;
      p.r  += p.vr;
      p.vy *= 1.01;
      if (p.y > canvas.height) {
        p.y = -20; p.x = Math.random() * canvas.width; p.vy = 2 + Math.random() * 4;
      }
      ctx.save();
      ctx.globalAlpha = p.opacity;
      ctx.fillStyle   = p.color;
      ctx.translate(p.x, p.y);
      ctx.rotate(p.r);
      ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h);
      ctx.restore();
    });
    if (frame++ < 300) confettiInterval = requestAnimationFrame(draw);
    else ctx.clearRect(0, 0, canvas.width, canvas.height);
  }
  draw();
}

function stopConfetti() {
  if (confettiInterval) cancelAnimationFrame(confettiInterval);
  const c = document.getElementById('confettiCanvas');
  c.getContext('2d').clearRect(0, 0, c.width, c.height);
}

// ── Hook into processSale response ──────────────────────
const _origShowReceipt = showReceiptModal;
// Override sale success to update target bar
const origProcessSale = window.processSale;
</script>
<style>
/* ==========================================================
   MJPOS — FINAL PREMIUM COLORFUL WHITE UI OVERRIDES
   UI-only layer. Existing PHP and JavaScript stay unchanged.
   ========================================================== */
:root{
  --brand:#2563eb;
  --brand-2:#4f46e5;
  --cyan:#0891b2;
  --emerald:#059669;
  --amber:#d97706;
  --rose:#e11d48;
  --violet:#7c3aed;
  --ink:#0f172a;
  --slate:#64748b;
  --line:#e2e8f0;
  --soft:#f8fafc;
}

body{
  background:
    radial-gradient(circle at 10% 0%,rgba(37,99,235,.055),transparent 28%),
    radial-gradient(circle at 85% 5%,rgba(124,58,237,.045),transparent 26%),
    #f5f7fb!important;
}

#pos-wrap{background:transparent}
#pos-left{padding:14px 16px 12px;gap:11px}
#pos-right{
  margin:10px 10px 10px 0;
  border:1px solid rgba(226,232,240,.95);
  border-radius:20px;
  box-shadow:0 18px 48px rgba(15,23,42,.10);
  overflow-y:auto;
}

/* Top search and actions */
#product-search{
  border:1px solid #dbe4f0;
  background:rgba(255,255,255,.96);
  box-shadow:0 7px 20px rgba(15,23,42,.065);
}
#product-search:hover{border-color:#c5d2e3}
#product-search:focus{
  border-color:#7da2ff;
  box-shadow:0 0 0 4px rgba(37,99,235,.10),0 12px 28px rgba(37,99,235,.10);
}
#search-status-pill{
  color:#1d4ed8;
  background:linear-gradient(135deg,#eff6ff,#eef2ff);
  border-color:#c7d7fe;
  box-shadow:inset 0 1px 0 rgba(255,255,255,.8);
}
#product-results{border-color:#cbd9ec;box-shadow:0 22px 52px rgba(15,23,42,.16)}
.pres-header{background:linear-gradient(90deg,#eff6ff,#f5f3ff);color:#3730a3}
.prod-item:hover,.prod-item.active{background:linear-gradient(90deg,#eff6ff 0%,#faf5ff 100%)}

#pos-left>div:first-child>.btn{
  width:62px;
  min-width:62px;
  height:56px;
  padding:5px 8px!important;
  border-radius:15px!important;
  position:relative;
  overflow:hidden;
}
#pos-left>div:first-child>.btn::before{
  content:"";
  position:absolute;
  inset:0;
  opacity:.08;
  background:currentColor;
  transition:.18s ease;
}
#pos-left>div:first-child>.btn:hover::before{opacity:.14}
#pos-left>div:first-child>.btn i,#pos-left>div:first-child>.btn span{position:relative;z-index:1}
#pos-left>div:first-child>.btn-outline-secondary{
  color:#b45309!important;
  border-color:#fde4a8!important;
  background:linear-gradient(145deg,#fff,#fffbeb)!important;
}
#pos-left>div:first-child>.btn-outline-warning{
  color:#6d28d9!important;
  border-color:#ddd0ff!important;
  background:linear-gradient(145deg,#fff,#f5f3ff)!important;
}
#pos-left>div:first-child>.btn-outline-danger{
  color:#dc2626!important;
  border-color:#fecaca!important;
  background:linear-gradient(145deg,#fff,#fff1f2)!important;
}
#pos-left>div:first-child>.btn:hover{transform:translateY(-2px) scale(1.015)}
.held-badge{box-shadow:0 4px 12px rgba(124,58,237,.35)}

/* Keyboard strip */
#kbd-bar{
  border-color:#e1e8f2;
  background:rgba(255,255,255,.88);
  backdrop-filter:blur(10px);
}
#kbd-bar kbd{
  color:#4338ca;
  border-color:#d8ddff;
  background:linear-gradient(180deg,#fff,#eef2ff);
  box-shadow:0 2px 0 #d8ddff;
}

/* Cart */
#cart-scroll{
  border-color:#e0e7f0;
  box-shadow:0 10px 30px rgba(15,23,42,.065);
}
#cart-table thead th{
  background:linear-gradient(180deg,#172554,#1e3a8a);
  color:#eaf2ff;
  border-bottom:0;
  padding-top:11px;
  padding-bottom:11px;
}
#cart-table tbody tr:nth-child(even){background:#fbfdff}
#cart-table tbody tr:hover{background:linear-gradient(90deg,#eff6ff,#faf5ff)}
#cart-table tbody td:nth-child(6){color:#1d4ed8!important}
#cart-table tbody button[onclick^="changeQty"]{
  color:#334155;
  border-color:#d7e0eb!important;
  background:linear-gradient(180deg,#fff,#f1f5f9)!important;
  box-shadow:0 2px 5px rgba(15,23,42,.06);
  transition:.15s ease;
}
#cart-table tbody button[onclick^="changeQty"]:hover{
  color:#1d4ed8;
  border-color:#93b4ff!important;
  background:#eff6ff!important;
  transform:translateY(-1px);
}
#cart-table tbody button[onclick^="removeItem"]{
  width:27px;height:27px;
  display:inline-flex;align-items:center;justify-content:center;
  background:#fff1f2!important;
  border:1px solid #fecdd3!important;
  border-radius:8px!important;
}
#cart-table tbody button[onclick^="removeItem"]:hover{background:#ffe4e6!important;transform:scale(1.05)}
.cart-qty-input{font-weight:850!important;color:#1e40af!important}
.cart-disc-input{color:#b45309!important;background:#fffbeb!important}
#cart-empty i{
  width:78px;height:78px;
  display:flex!important;align-items:center;justify-content:center;
  border-radius:24px;
  background:linear-gradient(145deg,#eff6ff,#f5f3ff);
  color:#7894d6!important;
  opacity:1!important;
  box-shadow:inset 0 0 0 1px #dbeafe;
}
#cart-margin-display{background:linear-gradient(135deg,#ecfdf5,#f0fdf4);border:1px solid #bbf7d0}

/* Customer / discount / note */
#cart-extras{
  border-color:#e0e7f0;
  box-shadow:0 9px 25px rgba(15,23,42,.06);
}
.extra-label i{width:20px;height:20px;border-radius:7px;display:inline-flex;align-items:center;justify-content:center;background:#f1f5f9}
#customer-select:focus{border-color:#7c3aed!important;box-shadow:0 0 0 3px rgba(124,58,237,.09)!important}
#bill-discount{color:#b45309!important;background:#fffbeb!important}
#sale-note:focus{border-color:#0891b2!important;box-shadow:0 0 0 3px rgba(8,145,178,.09)!important}

/* Totals panel */
#totals-card{border-bottom-color:#e8edf4}
.total-row{padding:9px 18px}
#display-subtotal{color:#1e40af!important}
#display-discount{color:#e11d48!important}
#display-tax{color:#7c3aed!important;font-weight:800}
#grand-total-row{
  background:linear-gradient(125deg,#0f172a 0%,#1e3a8a 55%,#3730a3 100%);
  box-shadow:inset 0 1px 0 rgba(255,255,255,.08);
  position:relative;
  overflow:hidden;
}
#grand-total-row::after{
  content:"";
  position:absolute;
  width:150px;height:150px;border-radius:50%;
  right:-50px;top:-75px;
  background:rgba(255,255,255,.07);
}
#display-total{position:relative;z-index:1;color:#fff!important;text-shadow:0 4px 14px rgba(0,0,0,.18)}
#display-change-row{background:#f0fdf4!important}
#display-change{color:#059669!important}
#display-balance-row{background:#fff1f2!important}
#display-paid{color:#047857!important;font-weight:850!important}

/* Payment */
#payment-card>div:first-child{
  background:linear-gradient(90deg,#f8fafc,#f5f3ff)!important;
}
#payment-card>div:first-child span:first-child{color:#312e81;font-weight:850!important}
#payment-card>div:first-child button{
  color:#4f46e5!important;
  border-color:#c7d2fe!important;
  background:#eef2ff!important;
}
#payment-card>div:first-child button:hover{background:#e0e7ff!important;transform:translateY(-1px)}
.pmt-row-wrap{
  padding:8px;
  border:1px solid #edf1f6;
  border-radius:12px;
  background:#fcfdff;
}
.pmt-method-sel{color:#3730a3!important;font-weight:800;background:#f5f3ff!important}
.pmt-amount-inp{color:#1d4ed8!important;background:#eff6ff!important}
.remove-pmt-btn{cursor:pointer;transition:.15s ease}
.remove-pmt-btn:hover{background:#ffe4e6;transform:scale(1.05)}
.quick-btn:nth-child(1){color:#047857;border-color:#a7f3d0;background:#ecfdf5}
.quick-btn:nth-child(2){color:#1d4ed8;border-color:#bfdbfe;background:#eff6ff}
.quick-btn:nth-child(3){color:#7c3aed;border-color:#ddd6fe;background:#f5f3ff}
.quick-btn:nth-child(4){color:#b45309;border-color:#fde68a;background:#fffbeb}
.quick-btn:hover{filter:brightness(.98);transform:translateY(-1px);box-shadow:0 7px 16px rgba(15,23,42,.08)}

/* Process Sale */
#btn-process{
  background:linear-gradient(120deg,#059669 0%,#0d9488 48%,#2563eb 100%);
  box-shadow:0 13px 30px rgba(5,150,105,.24);
}
#btn-process::before{
  content:"";
  position:absolute;
  inset:0;
  background:linear-gradient(100deg,transparent 20%,rgba(255,255,255,.18) 48%,transparent 75%);
  transform:translateX(-120%);
  transition:transform .55s ease;
}
#btn-process:hover:not(:disabled)::before{transform:translateX(120%)}
#btn-process:hover:not(:disabled){background:linear-gradient(120deg,#047857,#0891b2,#1d4ed8);box-shadow:0 16px 35px rgba(37,99,235,.28)}
#btn-process:disabled{background:linear-gradient(120deg,#cbd5e1,#dbe2ea);color:#f8fafc}

/* Alerts / modals */
.alert{border:0!important;border-radius:12px!important;box-shadow:0 16px 35px rgba(15,23,42,.16)!important}
.modal-backdrop.show{opacity:.38}
.modal-content{overflow:hidden}
.modal-header{background:linear-gradient(90deg,#f8fafc,#eef2ff)}
#held-modal-body .btn-outline-primary{border-color:#bfdbfe;color:#1d4ed8;background:#eff6ff}
#held-modal-body .btn-outline-danger{border-color:#fecdd3;color:#be123c;background:#fff1f2}

/* Daily target floating widget */
#targetBar{
  left:auto!important;
  right:24px!important;
  top:auto!important;
  bottom:90px!important;
  width:350px!important;
  height:64px!important;
  transform:none!important;
  border-width:1px!important;
  border-radius:18px!important;
  box-shadow:0 18px 38px rgba(15,23,42,.16)!important;
  backdrop-filter:blur(12px);
}
#targetBar .tb-track{height:8px!important;background:rgba(15,23,42,.10)!important}
#targetBar .tb-val{box-shadow:0 4px 12px rgba(15,23,42,.07)}

/* Congratulations popup */
#congratsCard{border:1px solid rgba(255,255,255,.7);box-shadow:0 30px 85px rgba(15,23,42,.34)!important}
#congratsCard button{background:linear-gradient(120deg,#059669,#2563eb)!important;transition:.18s ease}
#congratsCard button:hover{transform:translateY(-2px);box-shadow:0 10px 25px rgba(37,99,235,.32)!important}

/* Better focus and motion */
button,select,input{transition:border-color .15s ease,box-shadow .15s ease,transform .15s ease,background .15s ease}
button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid rgba(37,99,235,.18)!important;outline-offset:2px}

@media(max-width:1100px){
  #pos-right{margin-right:7px}
  #targetBar{right:16px!important;width:320px!important}
}
@media(max-width:900px){
  #pos-left{padding:10px}
  #pos-right{margin:0 10px 12px;border-radius:18px}
  #pos-wrap{gap:0}
  #targetBar{position:relative!important;right:auto!important;bottom:auto!important;width:auto!important;margin:10px 12px!important}
}
@media(max-width:600px){
  #pos-left>div:first-child{flex-wrap:wrap}
  #search-wrap{flex-basis:100%}
  #pos-left>div:first-child>.btn{flex:1;width:auto;min-width:0}
  #kbd-bar{display:none}
  #cart-extras .col-md-4{margin-bottom:6px}
  #pos-right{margin:0 6px 10px;border-radius:15px}
  #display-total{font-size:1.65rem}
  .pmt-row{flex-wrap:wrap}
  .pmt-method-sel{width:100%;min-width:100%}
  .pmt-amount-inp{flex:1}
}
</style>

<style>
/* =========================================================
   FINAL LAYOUT FIXES - matched to supplied screenshot
   Focus: Walk-in phone, Bill Discount and Daily Target card
   ========================================================= */

/* Keep the lower customer area aligned and contained */
#cart-extras{
  padding:14px 14px 12px!important;
  overflow:visible!important;
}
#cart-extras .row{
  align-items:flex-start!important;
}
#cart-extras .col-md-4{
  position:relative;
  min-width:0;
}

/* Customer select + walk-in phone become one clean vertical control group */
#cart-extras .col-md-4:first-child{
  display:flex;
  flex-direction:column;
}
#customer-select{
  height:40px!important;
  min-height:40px!important;
}
#walkin-phone-wrap{
  margin-top:7px!important;
  width:100%!important;
}
#walkin-phone-wrap .input-group{
  width:100%!important;
  flex-wrap:nowrap!important;
}
#walkin-phone-wrap .input-group-text{
  width:40px!important;
  min-width:40px!important;
  height:40px!important;
  padding:0!important;
  display:flex!important;
  align-items:center!important;
  justify-content:center!important;
  background:linear-gradient(145deg,#f8fafc,#eff6ff)!important;
  border:1px solid #d9e2ef!important;
  border-right:0!important;
  border-radius:11px 0 0 11px!important;
  color:#64748b!important;
}
#walkin-phone{
  height:40px!important;
  min-height:40px!important;
  border:1px solid #d9e2ef!important;
  border-left:0!important;
  border-radius:0 11px 11px 0!important;
  background:#fff!important;
  padding:0 12px!important;
  box-shadow:none!important;
}
#walkin-phone:focus{
  border-color:#93c5fd!important;
  box-shadow:0 0 0 3px rgba(59,130,246,.10)!important;
}
#walkin-phone-wrap:focus-within .input-group-text{
  border-color:#93c5fd!important;
  color:#2563eb!important;
  background:#eff6ff!important;
}

/* Discount field: fix currency prefix and input alignment */
#cart-extras .col-md-4:nth-child(2) .input-group{
  width:100%!important;
  flex-wrap:nowrap!important;
}
#cart-extras .col-md-4:nth-child(2) .input-group-text{
  width:42px!important;
  min-width:42px!important;
  height:40px!important;
  padding:0!important;
  display:flex!important;
  align-items:center!important;
  justify-content:center!important;
  background:linear-gradient(145deg,#fffdf5,#fff7dc)!important;
  border:1px solid #f1d996!important;
  border-right:0!important;
  border-radius:11px 0 0 11px!important;
  color:#b45309!important;
  font-weight:850!important;
}
#bill-discount{
  height:40px!important;
  min-height:40px!important;
  border:1px solid #f1d996!important;
  border-left:0!important;
  border-radius:0 11px 11px 0!important;
  background:linear-gradient(180deg,#fffdf7,#fffaf0)!important;
  color:#b45309!important;
  padding:0 13px!important;
  text-align:right!important;
  font-weight:850!important;
  box-shadow:none!important;
}
#bill-discount:focus{
  border-color:#f59e0b!important;
  box-shadow:0 0 0 3px rgba(245,158,11,.11)!important;
}
#cart-extras .col-md-4:nth-child(2) .input-group:focus-within .input-group-text{
  border-color:#f59e0b!important;
  background:#fff7ed!important;
}

/* Note input same exact height as the other controls */
#sale-note{
  height:40px!important;
  min-height:40px!important;
}

/* Daily target: place as a proper card inside the right panel bottom area */
#targetBar{
  position:fixed!important;
  left:auto!important;
  right:15px!important;
  bottom:13px!important;
  top:auto!important;
  width:370px!important;
  min-width:0!important;
  height:auto!important;
  min-height:58px!important;
  padding:10px 12px!important;
  display:grid!important;
  grid-template-columns:auto minmax(46px,1fr) auto!important;
  align-items:center!important;
  gap:9px!important;
  transform:none!important;
  border:1px solid #bfdbfe!important;
  border-radius:16px!important;
  background:linear-gradient(135deg,rgba(239,246,255,.98),rgba(255,255,255,.98))!important;
  box-shadow:0 14px 32px rgba(37,99,235,.14),0 4px 10px rgba(15,23,42,.07)!important;
  backdrop-filter:blur(14px)!important;
  overflow:hidden!important;
  z-index:120!important;
}
#targetBar::before{
  content:"";
  position:absolute;
  inset:0 auto 0 0;
  width:4px;
  background:linear-gradient(180deg,#2563eb,#7c3aed);
}
#targetBar .tb-label{
  display:flex!important;
  align-items:center!important;
  gap:6px!important;
  min-width:max-content!important;
  font-size:.72rem!important;
  font-weight:850!important;
  color:#2563eb!important;
  line-height:1.1!important;
  white-space:nowrap!important;
}
#targetBar .tb-label i{
  width:22px!important;
  height:22px!important;
  border-radius:8px!important;
  display:inline-flex!important;
  align-items:center!important;
  justify-content:center!important;
  background:#dbeafe!important;
  color:#2563eb!important;
}
#targetBar .tb-track{
  width:100%!important;
  min-width:44px!important;
  height:7px!important;
  border-radius:999px!important;
  background:#dbe3ee!important;
  overflow:hidden!important;
  box-shadow:inset 0 1px 2px rgba(15,23,42,.08)!important;
}
#targetBar .tb-fill{
  min-width:5px!important;
  height:100%!important;
  border-radius:999px!important;
  background:linear-gradient(90deg,#3b82f6,#6366f1)!important;
  box-shadow:none!important;
}
#targetBar .tb-val{
  min-width:max-content!important;
  padding:5px 9px!important;
  border:1px solid #c7d2fe!important;
  border-radius:999px!important;
  background:#fff!important;
  color:#2563eb!important;
  font-size:.66rem!important;
  font-weight:900!important;
  line-height:1!important;
  white-space:nowrap!important;
  box-shadow:0 4px 12px rgba(37,99,235,.08)!important;
}

/* Ensure the fixed widget stays visually inside the right column on large screens */
@media (min-width:901px){
  #pos-right{
    padding-bottom:100px!important;
  }
}

/* Responsive fixes */
@media (max-width:1200px){
  #targetBar{
    right:16px!important;
    width:304px!important;
    grid-template-columns:auto minmax(38px,1fr) auto!important;
  }
}
@media (max-width:900px){
  #targetBar{
    position:relative!important;
    right:auto!important;
    bottom:auto!important;
    width:calc(100% - 24px)!important;
    margin:10px 12px 14px!important;
  }
  #pos-right{padding-bottom:0!important;}
}
@media (max-width:767px){
  #cart-extras .col-md-4{
    width:100%!important;
    margin-bottom:10px!important;
  }
  #cart-extras .col-md-4:last-child{margin-bottom:0!important;}
}
@media (max-width:520px){
  #targetBar{
    grid-template-columns:1fr auto!important;
    row-gap:8px!important;
  }
  #targetBar .tb-track{
    grid-column:1 / -1!important;
    grid-row:2!important;
  }
}
</style>

<!-- Compact 5px corner radius override -->
<style>
:root{--radius:5px!important}

/* Main panels and cards */
#product-search,
#product-results,
.pres-header,
#kbd-bar,
#cart-scroll,
#cart-extras,
#pos-right,
#totals-card,
#payment-card,
.pmt-row-wrap,
.modal-content,
.alert,
#targetBar,
#congratsCard{
  border-radius:5px!important;
}

/* Form controls and buttons */
#search-status-pill,
.extra-input,
#customer-select,
#walkin-phone,
#bill-discount,
#sale-note,
.pmt-method-sel,
.pmt-amount-inp,
.pmt-det-input,
.cart-qty-input,
.cart-disc-input,
.input-group-text,
.quick-btn,
.remove-pmt-btn,
#add-split-btn,
#payment-card button,
#btn-process,
.pos-action-btn,
#pos-left > div:first-child > button,
#held-modal-body button,
.btn,
.form-control,
.form-select{
  border-radius:5px!important;
}

/* Small badges and helper UI */
#kbd-bar kbd,
#cart-margin-display,
.pi-stock,
.badge,
#targetBar .tb-track,
#targetBar .tb-fill,
#targetBar .tb-val{
  border-radius:5px!important;
}

/* Keep true circular elements circular */
.held-badge,
.cart-row-num,
#receiptModalContent [style*="border-radius:50%"],
#grand-total-row::after{
  border-radius:50%!important;
}

/* Remove rounded table header corners */
#cart-table thead th:first-child,
#cart-table thead th:last-child{
  border-radius:0!important;
}
</style>

<style>
html.pos-fullscreen-page,
body.pos-fullscreen-page{
  width:100%!important;
  height:100%!important;
  margin:0!important;
  padding:0!important;
  overflow:hidden!important;
}
body.pos-fullscreen-page #sidebar{
  display:none!important;
}
body.pos-fullscreen-page #topbar{
  display:flex!important;
  height:55px!important;
  min-height:55px!important;
  padding:0 12px!important;
}
body.pos-fullscreen-page #content{
  position:fixed!important;
  top:55px!important;
  right:0!important;
  bottom:0!important;
  left:0!important;
  width:100vw!important;
  height:calc(100vh - 55px)!important;
  max-width:none!important;
  margin:0!important;
  padding:0!important;
  overflow:hidden!important;
}
body.pos-fullscreen-page #pos-wrap{
  width:100vw!important;
  height:calc(100vh - 55px)!important;
  min-height:calc(100vh - 55px)!important;
  max-height:calc(100vh - 55px)!important;
  margin:0!important;
}
body.pos-fullscreen-page #pos-left{
  padding-top:10px!important;
}
body.pos-fullscreen-page #targetBar{
  right:15px!important;
  bottom:13px!important;
}
</style>

<style>
/* Hide sidebar toggle button only while the POS page is active */
body.pos-fullscreen-page #sidebar-toggle{
  display:none!important;
}
</style>

<style>
/* Stock View modal visibility / stacking fix */
#stockViewModal{
  position:fixed!important;
  inset:0!important;
  z-index:20050!important;
  width:100vw!important;
  height:100vh!important;
  overflow-x:hidden!important;
  overflow-y:auto!important;
}
#stockViewModal.show{display:block!important;opacity:1!important}
#stockViewModal .modal-dialog{
  position:relative!important;
  z-index:20052!important;
  width:min(1180px,calc(100vw - 32px))!important;
  max-width:1180px!important;
  margin:24px auto!important;
  transform:none!important;
  opacity:1!important;
}
#stockViewModal .modal-content{
  position:relative!important;
  z-index:20053!important;
  background:#fff!important;
  color:#0f172a!important;
  opacity:1!important;
  visibility:visible!important;
  min-height:420px!important;
  max-height:calc(100vh - 48px)!important;
  overflow:hidden!important;
  box-shadow:0 28px 80px rgba(15,23,42,.32)!important;
}
#stockViewModal .modal-header,
#stockViewModal .modal-body{
  background:#fff!important;
  opacity:1!important;
  visibility:visible!important;
}
#stockViewModal .modal-body{overflow:auto!important}
#stockViewModal + .modal-backdrop,
body > .modal-backdrop{z-index:20040!important}
body > .modal-backdrop.show{opacity:.48!important}
body.modal-open #content,
body.modal-open #pos-wrap{filter:none!important;opacity:1!important}
@media(max-width:900px){
  #stockViewModal .modal-dialog{
    width:calc(100vw - 16px)!important;
    margin:8px auto!important;
  }
  #stockViewModal .modal-content{max-height:calc(100vh - 16px)!important}
  .stock-view-table-wrap{max-height:60vh!important}
}
</style>

<script>
/* Ensure Stock View is mounted directly under BODY so fixed POS layout cannot cover it. */
(function(){
  const originalShowStockView = window.showStockView;
  window.showStockView = function(){
    const modalEl = document.getElementById('stockViewModal');
    if (!modalEl) return;

    if (modalEl.parentElement !== document.body) {
      document.body.appendChild(modalEl);
    }

    document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
    document.body.classList.remove('modal-open');
    document.body.style.removeProperty('padding-right');

    const input = document.getElementById('stock-view-search');
    if (input) input.value = '';
    if (typeof renderStockView === 'function') renderStockView(STOCK_VIEW_PRODUCTS || []);

    const oldInstance = bootstrap.Modal.getInstance(modalEl);
    if (oldInstance) oldInstance.dispose();

    const instance = new bootstrap.Modal(modalEl, {
      backdrop: true,
      keyboard: true,
      focus: true
    });
    instance.show();

    modalEl.addEventListener('shown.bs.modal', function(){
      modalEl.style.opacity = '1';
      modalEl.style.visibility = 'visible';
      input?.focus();
    }, {once:true});
  };
})();
</script>


<style>
/* Sales List + Credit Book popup */
#posPagePopupModal{z-index:20120!important}
#posPagePopupModal .modal-dialog{margin:19px auto!important}
#posPagePopupModal .modal-content{
  border:1px solid #dbe4f0!important;
  border-radius:8px!important;
  overflow:hidden!important;
  background:#fff!important;
  box-shadow:0 28px 90px rgba(15,23,42,.32)!important;
}
#posPagePopupModal .modal-header{
  min-height:62px;
  background:linear-gradient(90deg,#f8fafc,#eff6ff)!important;
  border-bottom:1px solid #dbe4f0!important;
}
#posPagePopupModal .btn-close{margin:0!important;flex:0 0 auto}
#pos-page-popup-icon{
  width:38px;height:38px;border-radius:7px;
  background:#dbeafe;color:#1d4ed8;font-size:1.05rem;flex:0 0 auto;
}
body > .modal-backdrop{z-index:20110!important}
@media(max-width:1199.98px){
  #posPagePopupModal .modal-dialog{width:100%!important;margin:0!important}
  #posPagePopupModal .modal-content{height:100vh!important;border-radius:0!important}
}
/* Distinct top action button treatments */
#sales-list-popup-btn{color:#1d4ed8!important;background:linear-gradient(145deg,#fff,#eff6ff)!important}
#credit-book-popup-btn{color:#047857!important;background:linear-gradient(145deg,#fff,#ecfdf5)!important}
</style>

<script>
/* Popup pages and cashier sidebar cleanup */
(function(){
  const popupConfig = {
    sales: {
      title: 'Sales List',
      subtitle: 'View and search completed sales',
      icon: 'bi-receipt-cutoff',
      fallback: APP_URL + '/sales'
    },
    credit: {
      title: 'Credit Book',
      subtitle: 'View customer credit balances and transactions',
      icon: 'bi-journal-text',
      fallback: APP_URL + '/credit-book'
    }
  };

  let currentPopupType = 'sales';

  function normalizedText(el){
    return (el?.textContent || '').replace(/\s+/g,' ').trim().toLowerCase();
  }

  function findSidebarLink(type){
    const patterns = type === 'sales'
      ? ['sales list','sales history','all sales','sales']
      : ['credit book','customer credit','credits','credit'];
    const links = [...document.querySelectorAll('#sidebar a, .sidebar a, aside a')];
    return links.find(a => {
      const text = normalizedText(a);
      return patterns.some(p => text === p || text.includes(p));
    }) || null;
  }

  function resolvePopupUrl(type){
    const link = findSidebarLink(type);
    const href = link?.getAttribute('href');
    if (href && href !== '#' && !href.toLowerCase().startsWith('javascript:')) {
      try { return new URL(href, window.location.href).href; } catch(e) {}
    }
    return popupConfig[type].fallback;
  }

  function hideSidebarItems(){
    ['sales','credit'].forEach(type => {
      const link = findSidebarLink(type);
      if (!link) return;
      const item = link.closest('li,.nav-item,.sidebar-item') || link;
      item.style.setProperty('display','none','important');
      item.dataset.posPopupHidden = type;
    });
  }

  window.openPosPagePopup = function(type){
    if (!popupConfig[type]) return;
    currentPopupType = type;
    const cfg = popupConfig[type];
    const modalEl = document.getElementById('posPagePopupModal');
    const frame = document.getElementById('pos-page-popup-frame');
    const loader = document.getElementById('pos-page-popup-loader');
    if (!modalEl || !frame) return;

    if (modalEl.parentElement !== document.body) document.body.appendChild(modalEl);
    document.getElementById('pos-page-popup-title').textContent = cfg.title;
    document.getElementById('pos-page-popup-subtitle').textContent = cfg.subtitle + ' · ' + (type === 'sales' ? 'F6' : 'F7');
    document.getElementById('pos-page-popup-icon').innerHTML = '<i class="bi '+cfg.icon+'"></i>';
    loader.style.display = 'flex';
    frame.src = resolvePopupUrl(type);

    const old = bootstrap.Modal.getInstance(modalEl);
    if (old) old.dispose();
    new bootstrap.Modal(modalEl,{backdrop:true,keyboard:true,focus:true}).show();
  };

  window.reloadPosPagePopup = function(){
    const frame = document.getElementById('pos-page-popup-frame');
    const loader = document.getElementById('pos-page-popup-loader');
    if (!frame) return;
    loader.style.display = 'flex';
    try { frame.contentWindow.location.reload(); }
    catch(e) { frame.src = resolvePopupUrl(currentPopupType); }
  };

  document.getElementById('pos-page-popup-frame')?.addEventListener('load', function(){
    const loader = document.getElementById('pos-page-popup-loader');
    if (loader) loader.style.display = 'none';
    try {
      const doc = this.contentDocument;
      if (!doc) return;
      const sidebar = doc.querySelector('#sidebar,.sidebar,aside');
      const topbar = doc.querySelector('#topbar,.topbar');
      const content = doc.querySelector('#content,main,.main-content');
      if (sidebar) sidebar.style.setProperty('display','none','important');
      if (topbar) topbar.style.setProperty('display','none','important');
      if (content) {
        content.style.setProperty('margin','0','important');
        content.style.setProperty('padding','16px','important');
        content.style.setProperty('width','100%','important');
        content.style.setProperty('max-width','100%','important');
      }
      doc.documentElement.style.background = '#f8fafc';
      doc.body.style.background = '#f8fafc';
    } catch(e) {
      console.debug('Popup page layout could not be adjusted:', e);
    }
  });

  // Sales List and Credit Book sidebar entries are hidden only for cashier users.
  if (POS_IS_CASHIER) {
    hideSidebarItems();
    const observer = new MutationObserver(hideSidebarItems);
    observer.observe(document.body,{childList:true,subtree:true});
  }
})();
</script>

<!-- POS breadcrumb: hide Home link only on the POS page -->
<style>
body.pos-fullscreen-page .breadcrumb > .breadcrumb-item:first-child,
body.pos-fullscreen-page .page-breadcrumb > .breadcrumb-item:first-child,
body.pos-fullscreen-page #topbar .breadcrumb > li:first-child,
body.pos-fullscreen-page #topbar .page-breadcrumb > li:first-child {
  display:none!important;
}

/* Remove the slash/separator that Bootstrap adds before POS */
body.pos-fullscreen-page .breadcrumb > .breadcrumb-item:nth-child(2)::before,
body.pos-fullscreen-page .page-breadcrumb > .breadcrumb-item:nth-child(2)::before,
body.pos-fullscreen-page #topbar .breadcrumb > li:nth-child(2)::before,
body.pos-fullscreen-page #topbar .page-breadcrumb > li:nth-child(2)::before {
  display:none!important;
  content:none!important;
  padding:0!important;
}
</style>

<script>
(function hidePosHomeBreadcrumb(){
  function applyFix(){
    const scopes = document.querySelectorAll('#topbar, .topbar, header, .page-header');
    scopes.forEach(scope => {
      scope.querySelectorAll('.breadcrumb a, .page-breadcrumb a').forEach(link => {
        if (link.textContent.trim().toLowerCase() !== 'home') return;

        const item = link.closest('.breadcrumb-item, li');
        if (item) item.style.setProperty('display', 'none', 'important');
        else link.style.setProperty('display', 'none', 'important');

        const breadcrumb = link.closest('.breadcrumb, .page-breadcrumb');
        if (breadcrumb) {
          const visibleItems = [...breadcrumb.children].filter(el => getComputedStyle(el).display !== 'none');
          if (visibleItems[0]) visibleItems[0].classList.add('pos-first-visible-breadcrumb');
        }
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', applyFix, {once:true});
  } else {
    applyFix();
  }

  const observer = new MutationObserver(applyFix);
  observer.observe(document.documentElement, {childList:true, subtree:true});
})();
</script>

<style>
body.pos-fullscreen-page .pos-first-visible-breadcrumb::before{
  display:none!important;
  content:none!important;
  padding:0!important;
}
</style>
