Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript
405 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Merchant & Supervisor Hub - {{APP_NAME}}</title>
  <script>
    /* Apply saved theme pref (system | light | dark) before first paint to avoid a flash. */
    (function () {
      var p = 'system';
      try { var v = localStorage.getItem('youpi-theme'); if (v === 'light' || v === 'dark') p = v; } catch (e) {}
      var dark = p === 'dark' || (p === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
      document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    })();
  </script>
  <style>
    /* YOUPI Merchant & Supervisor Hub
       Direction: a payments ledger. Cool stone neutrals, one emerald accent,
       Sora for display (brand, headings, figures), DM Sans for UI text, both self-hosted
       from /fonts because the CSP is style-src 'self'. Icons: Heroicons outline sprite.
       One radius scale (6 controls / 10 surfaces / 4 tags). */
    @font-face {
      font-family: "DM Sans";
      src: url("/fonts/dm-sans.woff2") format("woff2");
      font-weight: 100 1000;
      font-display: swap;
    }

    @font-face {
      font-family: "Sora";
      src: url("/fonts/sora.woff2") format("woff2");
      font-weight: 100 800;
      font-display: swap;
    }

    :root,
    [data-theme="light"] {
      --theme: light;
      --font-ui: "DM Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
      --font-display: "Sora", "DM Sans", system-ui, sans-serif;
      --font-mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
      --r-ctl: 6px;
      --r-surf: 10px;
      --r-tag: 4px;

      --bg: #eef0ee;
      --bg-header: #12201c;
      --bg-nav: #f7f8f6;
      --bg-subnav: #eef0ee;
      --bg-card: #fbfcfb;
      --bg-surface: #f2f4f1;
      --bg-box: #fbfcfb;
      --bg-elevated: #e8ebe7;
      --bg-slot: #fbfcfb;
      --bg-table-th: #f2f4f1;
      --bg-input: #ffffff;

      --border: #d9ddd7;
      --border-focus: #0f766e;
      --border-subtle: #e4e7e2;
      --border-hover: #b8beb5;

      --text: #1b2421;
      --text-muted: #55625d;
      --text-dim: #66726c;
      --text-heading: #101a17;

      --primary: #0f766e;
      --primary-hover: #0b5f58;
      --primary-glow: rgba(15, 118, 110, 0.18);
      --primary-light: rgba(15, 118, 110, 0.07);

      --success: #15803d;
      --success-glow: rgba(21, 128, 61, 0.18);
      --danger: #b91c1c;
      --danger-glow: rgba(185, 28, 28, 0.18);
      --warning: #b45309;
      --warning-bg: rgba(180, 83, 9, 0.07);
      --warning-glow: rgba(180, 83, 9, 0.18);
      --info: #0369a1;
      --info-glow: rgba(3, 105, 161, 0.18);

      --card-shadow: 0 1px 0 rgba(16, 26, 23, 0.04);
      --card-shadow-hover: 0 6px 18px -8px rgba(16, 26, 23, 0.18);

      --badge-success-bg: #e6f4ea;
      --badge-success-text: #166534;
      --badge-success-border: #b7dfc3;
      --badge-danger-bg: #fbe9e7;
      --badge-danger-text: #991b1b;
      --badge-danger-border: #f0bdb7;
      --badge-warning-bg: #fbf0dc;
      --badge-warning-text: #8a4208;
      --badge-warning-border: #ecd19b;
      --badge-info-bg: #e3f0f7;
      --badge-info-text: #075985;
      --badge-info-border: #b5d5e6;
      --badge-neutral-bg: #e8ebe7;
      --badge-neutral-text: #46524d;
      --badge-neutral-border: #d2d7d0;

      --btn-sec-bg: #fbfcfb;
      --btn-sec-text: #28332f;
      --btn-sec-border: #c9cec7;
      --btn-sec-hover-bg: #eef0ee;
      --btn-sec-hover-text: #101a17;

      --tr-hover: #f2f4f1;
      --focus-ring: rgba(15, 118, 110, 0.22);

      --kpi-vol-color: #0f766e;
      --kpi-success-color: #1b2421;
      --kpi-queue-color: #b45309;
      --kpi-pending-color: #b91c1c;

      --header-bg: #12201c;
      --header-border: #12201c;
      --header-title: #f1f5f2;
      --nav-bg: #f7f8f6;
      --nav-border: #d9ddd7;
      --subnav-bg: #eef0ee;
      --subnav-border: #d9ddd7;
      --pill-bg: transparent;
      --pill-text: #55625d;
      --pill-border: transparent;
    }

    [data-theme="dark"] {
      --theme: dark;

      --bg: #0b0f0e;
      --bg-header: #070a09;
      --bg-nav: #0f1514;
      --bg-subnav: #0b0f0e;
      --bg-card: #121917;
      --bg-surface: #172120;
      --bg-box: #0f1514;
      --bg-elevated: #1d2927;
      --bg-slot: #0f1514;
      --bg-table-th: #0f1514;
      --bg-input: #0b0f0e;

      --border: #243230;
      --border-focus: #2dd4bf;
      --border-subtle: rgba(255, 255, 255, 0.07);
      --border-hover: #364643;

      --text: #e6ece9;
      --text-muted: #94a39e;
      --text-dim: #8a9a94;
      --text-heading: #f4f8f6;

      --primary: #14b8a6;
      --primary-hover: #2dd4bf;
      --primary-glow: rgba(45, 212, 191, 0.2);
      --primary-light: rgba(45, 212, 191, 0.08);

      --success: #4ade80;
      --success-glow: rgba(74, 222, 128, 0.18);
      --danger: #f87171;
      --danger-glow: rgba(248, 113, 113, 0.18);
      --warning: #fbbf24;
      --warning-bg: rgba(251, 191, 36, 0.08);
      --warning-glow: rgba(251, 191, 36, 0.18);
      --info: #7dd3fc;
      --info-glow: rgba(125, 211, 252, 0.18);

      --card-shadow: none;
      --card-shadow-hover: 0 8px 24px -10px rgba(0, 0, 0, 0.7);

      --badge-success-bg: rgba(74, 222, 128, 0.12);
      --badge-success-text: #86efac;
      --badge-success-border: rgba(74, 222, 128, 0.3);
      --badge-danger-bg: rgba(248, 113, 113, 0.12);
      --badge-danger-text: #fca5a5;
      --badge-danger-border: rgba(248, 113, 113, 0.3);
      --badge-warning-bg: rgba(251, 191, 36, 0.12);
      --badge-warning-text: #fcd34d;
      --badge-warning-border: rgba(251, 191, 36, 0.3);
      --badge-info-bg: rgba(125, 211, 252, 0.12);
      --badge-info-text: #bae6fd;
      --badge-info-border: rgba(125, 211, 252, 0.3);
      --badge-neutral-bg: #1d2927;
      --badge-neutral-text: #a5b3ae;
      --badge-neutral-border: #2e3d3a;

      --btn-sec-bg: #172120;
      --btn-sec-text: #d6dfdb;
      --btn-sec-border: #2e3d3a;
      --btn-sec-hover-bg: #1f2d2b;
      --btn-sec-hover-text: #ffffff;

      --tr-hover: rgba(255, 255, 255, 0.025);
      --focus-ring: rgba(45, 212, 191, 0.25);

      --kpi-vol-color: #2dd4bf;
      --kpi-success-color: #e6ece9;
      --kpi-queue-color: #fbbf24;
      --kpi-pending-color: #f87171;

      --header-bg: #070a09;
      --header-border: #1a2523;
      --header-title: #f4f8f6;
      --nav-bg: #0f1514;
      --nav-border: #1a2523;
      --subnav-bg: #0b0f0e;
      --subnav-border: #1a2523;
      --pill-bg: transparent;
      --pill-text: #94a39e;
      --pill-border: transparent;
    }

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: var(--font-ui);
    }

    code,
    pre,
    kbd,
    samp {
      font-family: var(--font-mono);
    }

    body,
    header,
    nav,
    .card,
    .kpi-box,
    table,
    th,
    td,
    input,
    select,
    textarea,
    .sub-nav-pill,
    .store-switch-badge,
    .settings-group-box,
    .slot-card {
      transition: background-color 0.2s ease, color 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
    }

    body {
      background: var(--bg);
      color: var(--text);
      min-height: 100dvh;
      display: flex;
      flex-direction: column;
      overflow-x: hidden;
      font-size: 15px;
      line-height: 1.5;
      -webkit-font-smoothing: antialiased;
    }

    /* Header: always an ink bar, in both themes, so the brand reads the same everywhere */
    header {
      background: var(--header-bg);
      border-bottom: 1px solid var(--header-border);
      padding: 0 1.75rem;
      min-height: 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 1rem;
      flex-wrap: wrap;
      position: sticky;
      top: 0;
      z-index: 1000;
    }

    header .badge-info,
    header .store-switch-badge:not(.is-online):not(.is-offline) {
      background: rgba(255, 255, 255, 0.06);
      border-color: rgba(255, 255, 255, 0.14);
      color: #d9e4df;
    }

    header>.header-quick-stats>div[onclick] {
      background: rgba(255, 255, 255, 0.06) !important;
      border-color: rgba(255, 255, 255, 0.14) !important;
    }

    header>.header-quick-stats>div[onclick]>span:first-child {
      color: #9fb2ab !important;
    }

    .brand-group {
      display: flex;
      align-items: center;
      gap: 0.9rem;
    }

    .brand-title {
      font-size: 1.1rem;
      font-weight: 800;
      color: var(--header-title);
      display: flex;
      align-items: center;
      gap: 0.5rem;
      letter-spacing: 0.02em;
    }

    .brand-badge {
      font-size: 0.7rem;
      font-weight: 600;
      padding: 0.2rem 0.55rem;
      border-radius: var(--r-tag);
      background: transparent;
      color: #9fb2ab;
      border: 1px solid rgba(255, 255, 255, 0.16);
      letter-spacing: 0.06em;
      text-transform: uppercase;
    }

    .header-quick-stats {
      display: flex;
      align-items: center;
      gap: 0.6rem;
      flex-wrap: wrap;
      padding: 0.5rem 0;
    }



    .store-switch-badge {
      display: inline-flex;
      align-items: center;
      gap: 0.45rem;
      padding: 0.3rem 0.65rem;
      border-radius: var(--r-ctl);
      font-size: 0.75rem;
      font-weight: 600;
      cursor: pointer;
      border: 1px solid var(--border);
      background: var(--bg-card);
      color: var(--text);
      user-select: none;
    }

    .store-switch-badge:hover {
      filter: brightness(1.08);
    }

    .store-switch-badge.is-online {
      background: rgba(74, 222, 128, 0.14);
      border-color: rgba(74, 222, 128, 0.4);
      color: #86efac;
    }

    .store-switch-badge.is-offline {
      background: rgba(248, 113, 113, 0.14);
      border-color: rgba(248, 113, 113, 0.4);
      color: #fca5a5;
    }

    .live-pulse-badge {
      display: inline-flex;
      align-items: center;
      gap: 0.45rem;
      background: transparent;
      border: 1px solid rgba(74, 222, 128, 0.35);
      color: #86efac;
      padding: 0.3rem 0.65rem;
      border-radius: var(--r-ctl);
      font-size: 0.73rem;
      font-weight: 600;
    }

    .pulse-dot {
      width: 7px;
      height: 7px;
      border-radius: 50%;
      background: #4ade80;
      animation: pulseAnim 2s infinite ease-in-out;
    }

    @keyframes pulseAnim {

      0%,
      100% {
        opacity: 1;
      }

      50% {
        opacity: 0.35;
      }
    }

    /* Primary navigation: flat tab strip, active tab marked by an accent bar */
    .main-nav-bar {
      background: var(--nav-bg);
      border-bottom: 1px solid var(--nav-border);
      display: flex;
      gap: 0.25rem;
      padding: 0 1.75rem;
      overflow-x: auto;
      position: sticky;
      top: 60px;
      z-index: 999;
    }

    .main-nav-btn {
      padding: 0.85rem 1.1rem;
      cursor: pointer;
      border: none;
      background: transparent;
      font-weight: 600;
      color: var(--text-muted);
      border-bottom: 2px solid transparent;
      margin-bottom: -1px;
      white-space: nowrap;
      transition: color 0.15s ease, border-color 0.15s ease;
      font-size: 0.9rem;
      display: flex;
      align-items: center;
      gap: 0.55rem;
    }

    .main-nav-btn:hover {
      color: var(--text);
    }

    .main-nav-btn.active {
      color: var(--text-heading);
      border-bottom-color: var(--primary);
      background: transparent;
    }

    .main-nav-btn:focus-visible,
    .sub-nav-pill:focus-visible,
    .btn:focus-visible {
      outline: 2px solid var(--border-focus);
      outline-offset: 2px;
    }

    /* Secondary navigation: quiet segmented row */
    .sub-nav-bar {
      background: var(--subnav-bg);
      border-bottom: 1px solid var(--subnav-border);
      display: flex;
      gap: 0.25rem;
      padding: 0.5rem 1.75rem;
      overflow-x: auto;
    }

    .sub-nav-pill {
      padding: 0.38rem 0.8rem;
      cursor: pointer;
      border: 1px solid var(--pill-border);
      background: var(--pill-bg);
      border-radius: var(--r-ctl);
      font-weight: 600;
      color: var(--pill-text);
      white-space: nowrap;
      font-size: 0.8rem;
      display: flex;
      align-items: center;
      gap: 0.4rem;
    }

    .sub-nav-pill:hover {
      color: var(--text);
      background: var(--bg-elevated);
    }

    .sub-nav-pill.active {
      color: #ffffff;
      background: var(--primary);
      border-color: var(--primary);
    }

    [data-theme="dark"] .sub-nav-pill.active {
      color: #04201c;
    }



    /* Theme switch (System / Light / Dark). Lives in the always-dark header. */
    .theme-switch {
      display: inline-flex;
      gap: 2px;
      padding: 2px;
      border: 1px solid rgba(255, 255, 255, 0.16);
      border-radius: var(--r-ctl);
      background: rgba(255, 255, 255, 0.04);
    }

    .theme-switch button {
      display: inline-flex;
      align-items: center;
      gap: 0.35rem;
      padding: 0.25rem 0.55rem;
      border: none;
      border-radius: 4px;
      background: transparent;
      color: #9fb2ab;
      font-size: 0.73rem;
      font-weight: 600;
      cursor: pointer;
    }

    .theme-switch button:hover {
      color: #ffffff;
    }

    .theme-switch button.active {
      background: rgba(255, 255, 255, 0.16);
      color: #ffffff;
    }

    .theme-switch button:focus-visible {
      outline: 2px solid #2dd4bf;
      outline-offset: 1px;
    }

    /* Display face */
    .brand-title,
    .card-heading,
    .kpi-value,
    h1,
    h2,
    h3,
    h4 {
      font-family: var(--font-display);
    }

    .kpi-value {
      font-family: var(--font-display);
      letter-spacing: -0.02em;
    }

    /* Heroicons + status dots */
    .i {
      width: 1.15em;
      height: 1.15em;
      flex: none;
      vertical-align: -0.2em;
      fill: none;
      stroke: currentColor;
      stroke-width: 1.6;
      stroke-linecap: round;
      stroke-linejoin: round;
    }

    .dot {
      display: inline-block;
      width: 0.6em;
      height: 0.6em;
      border-radius: 50%;
      flex: none;
      vertical-align: 0.02em;
      background: currentColor;
    }

    .dot-red { background: #ef4444; }
    .dot-green { background: #22c55e; }
    .dot-yellow { background: #f59e0b; }
    .dot-blue { background: #3b82f6; }
    .dot-purple { background: #8b5cf6; }
    .dot-black { background: #0f172a; box-shadow: 0 0 0 1px #64748b; }
    .dot-off { background: transparent; box-shadow: inset 0 0 0 1.5px #94a3b8; }

    main {
      padding: 1.75rem;
      max-width: 1480px;
      width: 100%;
      margin: 0 auto;
      flex: 1;
    }

    /* KPI row: one ruled strip, not four floating cards. Figures are mono + tabular. */
    .kpi-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
      gap: 0;
      margin-bottom: 1.5rem;
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--r-surf);
      overflow: hidden;
    }

    .kpi-box {
      background: transparent;
      border: none;
      border-right: 1px solid var(--border);
      border-radius: 0;
      padding: 1.1rem 1.35rem;
      position: relative;
      box-shadow: none;
    }

    .kpi-box:last-child {
      border-right: none;
    }

    .kpi-box::before {
      content: "";
      position: absolute;
      left: 0;
      top: 1.1rem;
      bottom: 1.1rem;
      width: 3px;
      background: var(--primary);
      opacity: 0.85;
      border-radius: 0 2px 2px 0;
    }

    .kpi-title {
      font-size: 0.72rem;
      color: var(--text-muted);
      font-weight: 600;
      letter-spacing: 0.04em;
      text-transform: uppercase;
    }

    .kpi-value {
      font-family: var(--font-display);
      font-variant-numeric: tabular-nums;
      font-size: 1.85rem;
      font-weight: 600;
      margin-top: 0.3rem;
      letter-spacing: -0.03em;
      line-height: 1.15;
    }

    /* Surfaces */
    .card {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--r-surf);
      padding: 1.4rem;
      margin-bottom: 1.5rem;
      box-shadow: var(--card-shadow);
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 1.15rem;
      padding-bottom: 1rem;
      border-bottom: 1px solid var(--border-subtle);
      flex-wrap: wrap;
      gap: 0.75rem;
    }

    .card-heading {
      font-size: 1.02rem;
      font-weight: 700;
      color: var(--text-heading);
      display: flex;
      align-items: center;
      gap: 0.55rem;
      letter-spacing: -0.005em;
    }

    .card-subtext {
      font-size: 0.82rem;
      color: var(--text-muted);
      margin-top: 0.25rem;
      line-height: 1.5;
      max-width: 70ch;
    }

    .settings-group-box {
      background: var(--bg-surface);
      border: 1px solid var(--border);
      border-radius: var(--r-surf);
      padding: 1.15rem;
      margin-bottom: 1.15rem;
    }

    .group-box-title {
      font-size: 0.74rem;
      font-weight: 700;
      text-transform: uppercase;
      color: var(--text-muted);
      letter-spacing: 0.06em;
      margin-bottom: 0.9rem;
    }

    .selling-mode-card {
      background: var(--bg-surface);
      border: 1px solid var(--border);
      border-radius: var(--r-surf);
      padding: 1.15rem;
      cursor: pointer;
      transition: border-color 0.15s ease, background-color 0.15s ease;
    }

    .selling-mode-card:hover {
      border-color: var(--border-hover);
    }

    .selling-mode-card.mode-selected-online {
      border: 1.5px solid var(--primary);
      background: var(--primary-light);
    }

    .selling-mode-card.mode-selected-offline {
      border: 1.5px solid var(--warning);
      background: var(--warning-bg);
    }

    /* Tables: header row quiet, rows separated by a single hairline */
    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.87rem;
    }

    th {
      text-align: left;
      padding: 0.65rem 0.9rem;
      background: var(--bg-table-th);
      color: var(--text-muted);
      font-weight: 600;
      border-bottom: 1px solid var(--border);
      text-transform: uppercase;
      font-size: 0.7rem;
      letter-spacing: 0.06em;
    }

    td {
      padding: 0.8rem 0.9rem;
      border-bottom: 1px solid var(--border-subtle);
      color: var(--text);
      vertical-align: middle;
    }

    tr:last-child td {
      border-bottom: none;
    }

    tr:hover td {
      background: var(--tr-hover);
    }

    /* Tags (status) */
    .badge {
      display: inline-flex;
      align-items: center;
      gap: 0.35rem;
      padding: 0.2rem 0.5rem;
      border-radius: var(--r-tag);
      font-size: 0.73rem;
      font-weight: 600;
      line-height: 1.3;
    }

    .badge-success {
      background: var(--badge-success-bg);
      color: var(--badge-success-text);
      border: 1px solid var(--badge-success-border);
    }

    .badge-danger {
      background: var(--badge-danger-bg);
      color: var(--badge-danger-text);
      border: 1px solid var(--badge-danger-border);
    }

    .badge-warning {
      background: var(--badge-warning-bg);
      color: var(--badge-warning-text);
      border: 1px solid var(--badge-warning-border);
    }

    .badge-info {
      background: var(--badge-info-bg);
      color: var(--badge-info-text);
      border: 1px solid var(--badge-info-border);
    }

    .badge-neutral {
      background: var(--badge-neutral-bg);
      color: var(--badge-neutral-text);
      border: 1px solid var(--badge-neutral-border);
    }

    /* Buttons */
    .btn {
      padding: 0.5rem 0.95rem;
      border-radius: var(--r-ctl);
      border: 1px solid transparent;
      font-weight: 600;
      cursor: pointer;
      font-size: 0.84rem;
      display: inline-flex;
      align-items: center;
      gap: 0.45rem;
      text-decoration: none;
      transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
      user-select: none;
    }

    .btn:active:not(:disabled) {
      transform: translateY(1px);
    }

    .btn-primary {
      background: var(--primary);
      color: #ffffff;
      border-color: var(--primary);
    }

    .btn-primary:hover {
      background: var(--primary-hover);
      border-color: var(--primary-hover);
    }

    [data-theme="dark"] .btn-primary {
      color: #04201c;
    }

    .btn-success {
      background: #15803d;
      color: #ffffff;
      border-color: #15803d;
    }

    .btn-success:hover {
      background: #166534;
    }

    .btn-danger {
      background: #b91c1c;
      color: #ffffff;
      border-color: #b91c1c;
    }

    .btn-danger:hover {
      background: #991b1b;
    }

    .btn-secondary {
      background: var(--btn-sec-bg);
      color: var(--btn-sec-text);
      border: 1px solid var(--btn-sec-border);
    }

    .btn-secondary:hover {
      background: var(--btn-sec-hover-bg);
      color: var(--btn-sec-hover-text);
    }

    .btn:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    /* Forms */
    input[type="text"],
    input[type="url"],
    input[type="password"],
    textarea,
    select {
      background: var(--bg-input);
      border: 1px solid var(--border-hover);
      border-radius: var(--r-ctl);
      color: var(--text);
      font-size: 0.88rem;
      padding: 0.6rem 0.8rem;
    }

    input::placeholder,
    textarea::placeholder {
      color: var(--text-dim);
    }

    input[type="text"]:focus,
    input[type="url"]:focus,
    input[type="password"]:focus,
    textarea:focus,
    select:focus {
      outline: none;
      border-color: var(--border-focus);
      box-shadow: 0 0 0 3px var(--focus-ring);
    }

    /* Terminal */
    .terminal-container {
      background: #060908;
      border: 1px solid #1a2523;
      border-radius: var(--r-surf);
      height: 380px;
      overflow-y: auto;
      padding: 1rem;
      font-family: var(--font-mono);
      font-size: 0.79rem;
      line-height: 1.65;
      color: #b6c9c2;
    }

    .log-line {
      margin-bottom: 0.15rem;
      word-break: break-all;
      font-family: var(--font-mono);
    }

    .log-ts {
      color: #62736d;
      margin-right: 0.5rem;
    }

    .log-svc {
      color: #2dd4bf;
      font-weight: 600;
      margin-right: 0.5rem;
    }

    .log-stderr {
      color: #fca5a5;
    }

    .log-system {
      color: #bef264;
    }

    /* Slots */
    .queue-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
      gap: 1rem;
      margin-bottom: 1.5rem;
    }

    .slot-card {
      border: 1px dashed var(--border-hover);
      border-radius: var(--r-surf);
      padding: 1.15rem;
      background: var(--bg-slot);
      text-align: center;
    }

    .slot-card.busy-active {
      border-style: solid;
      border-color: var(--primary);
      background: var(--primary-light);
    }

    .slot-card.busy-proc {
      border-style: solid;
      border-color: var(--warning);
      background: var(--warning-bg);
    }

    /* Modals */
    .modal-overlay {
      position: fixed;
      inset: 0;
      background: rgba(7, 10, 9, 0.7);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 1rem;
      z-index: 10000;
      backdrop-filter: blur(3px);
    }

    .modal-box {
      background: var(--bg-card);
      max-width: 520px;
      width: 100%;
      border-radius: var(--r-surf);
      padding: 1.6rem;
      border: 1px solid var(--border);
      box-shadow: 0 24px 60px -20px rgba(0, 0, 0, 0.5);
    }

    [hidden] {
      display: none !important;
    }

    /* Cashier dock: incoming counter payments */
    .cashier-floating-dock {
      position: fixed;
      bottom: 24px;
      right: 24px;
      z-index: 100000;
      display: flex;
      flex-direction: row-reverse;
      flex-wrap: wrap-reverse;
      gap: 12px;
      max-width: calc(100vw - 48px);
      pointer-events: none;
    }

    .cashier-modal-card {
      pointer-events: auto;
      width: 350px;
      max-width: 100%;
      background: var(--bg-card);
      border: 1px solid var(--border-hover);
      border-top: 3px solid var(--success);
      border-radius: var(--r-surf);
      box-shadow: 0 18px 44px -14px rgba(0, 0, 0, 0.45);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      animation: cashierSlideUp 0.28s cubic-bezier(0.16, 1, 0.3, 1);
    }

    @keyframes cashierSlideUp {
      from {
        opacity: 0;
        transform: translateY(16px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .cashier-modal-card.is-card-terminal {
      border-top-color: var(--info);
    }

    .cashier-modal-header {
      padding: 10px 14px;
      background: var(--bg-surface);
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 8px;
    }

    .cashier-modal-badge {
      font-size: 11px;
      font-weight: 700;
      letter-spacing: 0.05em;
      text-transform: uppercase;
      padding: 3px 8px;
      border-radius: var(--r-tag);
    }

    .cashier-badge-cash {
      background: var(--badge-success-bg);
      color: var(--badge-success-text);
      border: 1px solid var(--badge-success-border);
    }

    .cashier-badge-card {
      background: var(--badge-info-bg);
      color: var(--badge-info-text);
      border: 1px solid var(--badge-info-border);
    }

    .cashier-btn-minimize {
      background: var(--btn-sec-bg);
      border: 1px solid var(--border);
      color: var(--text-muted);
      width: 26px;
      height: 26px;
      border-radius: var(--r-ctl);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

    .cashier-modal-body {
      padding: 14px;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .cashier-modal-amount-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: var(--bg-surface);
      border: 1px solid var(--border);
      border-radius: var(--r-ctl);
      padding: 10px 12px;
      font-variant-numeric: tabular-nums;
    }

    .cashier-modal-actions {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      margin-top: 4px;
    }

    .cashier-btn-accept {
      background: #15803d;
      color: #ffffff;
      border: 1px solid #15803d;
      border-radius: var(--r-ctl);
      padding: 8px 10px;
      font-size: 12.5px;
      font-weight: 600;
      cursor: pointer;
    }

    .cashier-btn-accept:hover {
      background: #166534;
    }

    .cashier-btn-decline {
      background: var(--badge-danger-bg);
      color: var(--badge-danger-text);
      border: 1px solid var(--badge-danger-border);
      border-radius: var(--r-ctl);
      padding: 8px 10px;
      font-size: 12.5px;
      font-weight: 600;
      cursor: pointer;
    }

    .cashier-modal-card.is-minimized {
      width: auto;
      min-width: 240px;
      max-width: 340px;
    }

    .cashier-modal-card.is-minimized .cashier-modal-body {
      display: none;
    }

    .cashier-modal-card.is-minimized .cashier-modal-header {
      border-bottom: none;
      padding: 8px 12px;
    }

    @media (max-width: 767px) {

      header,
      .main-nav-bar,
      .sub-nav-bar {
        padding-left: 1rem;
        padding-right: 1rem;
      }

      header {
        position: static;
        padding-top: 0.6rem;
        padding-bottom: 0.6rem;
      }

      .main-nav-bar {
        top: 0;
      }

      main {
        padding: 1rem;
      }

      .kpi-box {
        border-right: none;
        border-bottom: 1px solid var(--border);
      }

      .kpi-box:last-child {
        border-bottom: none;
      }

      .cashier-floating-dock {
        left: 12px;
        right: 12px;
        bottom: 12px;
        max-width: none;
      }

      .cashier-modal-card {
        width: 100%;
      }
    }

    @media (prefers-reduced-motion: reduce) {

      *,
      *::before,
      *::after {
        animation: none !important;
        transition: none !important;
      }
    }
  </style>
</head>

<body>

  <svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true"><symbol id="i-archive-box" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m20.25 7.5-.625 10.632a2.25 2.25 0 0 1-2.247 2.118H6.622a2.25 2.25 0 0 1-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125Z"/></symbol><symbol id="i-arrow-down" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5 12 21m0 0-7.5-7.5M12 21V3"/></symbol><symbol id="i-arrow-down-on-square" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 8.25H7.5a2.25 2.25 0 0 0-2.25 2.25v9a2.25 2.25 0 0 0 2.25 2.25h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25H15M9 12l3 3m0 0 3-3m-3 3V2.25"/></symbol><symbol id="i-arrow-down-tray" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3"/></symbol><symbol id="i-arrow-path" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"/></symbol><symbol id="i-arrow-right" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3"/></symbol><symbol id="i-arrow-top-right-on-square" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></symbol><symbol id="i-banknotes" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0 1 15.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 0 1 3 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 0 0-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 0 1-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 0 0 3 15h-.75M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm3 0h.008v.008H18V10.5Zm-12 0h.008v.008H6V10.5Z"/></symbol><symbol id="i-beaker" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 0 1-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 0 1 4.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0 1 12 15a9.065 9.065 0 0 0-6.23-.693L5 14.5m14.8.8 1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0 1 12 21c-2.773 0-5.491-.235-8.135-.687-1.718-.293-2.3-2.379-1.067-3.61L5 14.5"/></symbol><symbol id="i-bell" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0"/></symbol><symbol id="i-bell-alert" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0M3.124 7.5A8.969 8.969 0 0 1 5.292 3m13.416 0a8.969 8.969 0 0 1 2.168 4.5"/></symbol><symbol id="i-bolt" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m3.75 13.5 10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75Z"/></symbol><symbol id="i-bolt-slash" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M11.412 15.655 9.75 21.75l3.745-4.012M9.257 13.5H3.75l2.659-2.849m2.048-2.194L14.25 2.25 12 10.5h8.25l-4.707 5.043M8.457 8.457 3 3m5.457 5.457 7.086 7.086m0 0L21 21"/></symbol><symbol id="i-book-open" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.967 8.967 0 0 0 6 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 0 1 6 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 0 1 6-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0 0 18 18a8.967 8.967 0 0 0-6 2.292m0-14.25v14.25"/></symbol><symbol id="i-building-office-2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 21h19.5m-18-18v18m10.5-18v18m6-13.5V21M6.75 6.75h.75m-.75 3h.75m-.75 3h.75m3-6h.75m-.75 3h.75m-.75 3h.75M6.75 21v-3.375c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21M3 3h12m-.75 4.5H21m-3.75 3.75h.008v.008h-.008v-.008Zm0 3h.008v.008h-.008v-.008Zm0 3h.008v.008h-.008v-.008Z"/></symbol><symbol id="i-building-storefront" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 21v-7.5a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 .75.75V21m-4.5 0H2.36m11.14 0H18m0 0h3.64m-1.39 0V9.349M3.75 21V9.349m0 0a3.001 3.001 0 0 0 3.75-.615A2.993 2.993 0 0 0 9.75 9.75c.896 0 1.7-.393 2.25-1.016a2.993 2.993 0 0 0 2.25 1.016c.896 0 1.7-.393 2.25-1.015a3.001 3.001 0 0 0 3.75.614m-16.5 0a3.004 3.004 0 0 1-.621-4.72l1.189-1.19A1.5 1.5 0 0 1 5.378 3h13.243a1.5 1.5 0 0 1 1.06.44l1.19 1.189a3 3 0 0 1-.621 4.72M6.75 18h3.75a.75.75 0 0 0 .75-.75V13.5a.75.75 0 0 0-.75-.75H6.75a.75.75 0 0 0-.75.75v3.75c0 .414.336.75.75.75Z"/></symbol><symbol id="i-chart-bar" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z"/></symbol><symbol id="i-chat-bubble-left-right" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 0 1-.825-.242m9.345-8.334a2.126 2.126 0 0 0-.476-.095 48.64 48.64 0 0 0-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0 0 11.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155"/></symbol><symbol id="i-check" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5"/></symbol><symbol id="i-check-circle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></symbol><symbol id="i-chevron-up" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5"/></symbol><symbol id="i-clipboard-document" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 7.5V6.108c0-1.135.845-2.098 1.976-2.192.373-.03.748-.057 1.123-.08M15.75 18H18a2.25 2.25 0 0 0 2.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 0 0-1.123-.08M15.75 18.75v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5A3.375 3.375 0 0 0 6.375 7.5H5.25m11.9-3.664A2.251 2.251 0 0 0 15 2.25h-1.5a2.251 2.251 0 0 0-2.15 1.586m5.8 0c.065.21.1.433.1.664v.75h-6V4.5c0-.231.035-.454.1-.664M6.75 7.5H4.875c-.621 0-1.125.504-1.125 1.125v12c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V16.5a9 9 0 0 0-9-9Z"/></symbol><symbol id="i-clock" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></symbol><symbol id="i-cloud" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15a4.5 4.5 0 0 0 4.5 4.5H18a3.75 3.75 0 0 0 1.332-7.257 3 3 0 0 0-3.758-3.848 5.25 5.25 0 0 0-10.233 2.33A4.502 4.502 0 0 0 2.25 15Z"/></symbol><symbol id="i-cog-6-tooth" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"/>
  <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></symbol><symbol id="i-computer-desktop" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 17.25v1.007a3 3 0 0 1-.879 2.122L7.5 21h9l-.621-.621A3 3 0 0 1 15 18.257V17.25m6-12V15a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 15V5.25m18 0A2.25 2.25 0 0 0 18.75 3H5.25A2.25 2.25 0 0 0 3 5.25m18 0V12a2.25 2.25 0 0 1-2.25 2.25H5.25A2.25 2.25 0 0 1 3 12V5.25"/></symbol><symbol id="i-credit-card" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 8.25h19.5M2.25 9h19.5m-16.5 5.25h6m-6 2.25h3m-3.75 3h15a2.25 2.25 0 0 0 2.25-2.25V6.75A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25v10.5A2.25 2.25 0 0 0 4.5 19.5Z"/></symbol><symbol id="i-device-phone-mobile" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 1.5H8.25A2.25 2.25 0 0 0 6 3.75v16.5a2.25 2.25 0 0 0 2.25 2.25h7.5A2.25 2.25 0 0 0 18 20.25V3.75a2.25 2.25 0 0 0-2.25-2.25H13.5m-3 0V3h3V1.5m-3 0h3m-3 18.75h3"/></symbol><symbol id="i-document-text" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></symbol><symbol id="i-envelope" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75"/></symbol><symbol id="i-exclamation-triangle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"/></symbol><symbol id="i-eye" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z"/>
  <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></symbol><symbol id="i-globe-alt" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 21a9.004 9.004 0 0 0 8.716-6.747M12 21a9.004 9.004 0 0 1-8.716-6.747M12 21c2.485 0 4.5-4.03 4.5-9S14.485 3 12 3m0 18c-2.485 0-4.5-4.03-4.5-9S9.515 3 12 3m0 0a8.997 8.997 0 0 1 7.843 4.582M12 3a8.997 8.997 0 0 0-7.843 4.582m15.686 0A11.953 11.953 0 0 1 12 10.5c-2.998 0-5.74-1.1-7.843-2.918m15.686 0A8.959 8.959 0 0 1 21 12c0 .778-.099 1.533-.284 2.253m0 0A17.919 17.919 0 0 1 12 16.5c-3.162 0-6.133-.815-8.716-2.247m0 0A9.015 9.015 0 0 1 3 12c0-1.605.42-3.113 1.157-4.418"/></symbol><symbol id="i-globe-europe-africa" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m20.893 13.393-1.135-1.135a2.252 2.252 0 0 1-.421-.585l-1.08-2.16a.414.414 0 0 0-.663-.107.827.827 0 0 1-.812.21l-1.273-.363a.89.89 0 0 0-.738 1.595l.587.39c.59.395.674 1.23.172 1.732l-.2.2c-.212.212-.33.498-.33.796v.41c0 .409-.11.809-.32 1.158l-1.315 2.191a2.11 2.11 0 0 1-1.81 1.025 1.055 1.055 0 0 1-1.055-1.055v-1.172c0-.92-.56-1.747-1.414-2.089l-.655-.261a2.25 2.25 0 0 1-1.383-2.46l.007-.042a2.25 2.25 0 0 1 .29-.787l.09-.15a2.25 2.25 0 0 1 2.37-1.048l1.178.236a1.125 1.125 0 0 0 1.302-.795l.208-.73a1.125 1.125 0 0 0-.578-1.315l-.665-.332-.091.091a2.25 2.25 0 0 1-1.591.659h-.18c-.249 0-.487.1-.662.274a.931.931 0 0 1-1.458-1.137l1.411-2.353a2.25 2.25 0 0 0 .286-.76m11.928 9.869A9 9 0 0 0 8.965 3.525m11.928 9.868A9 9 0 1 1 8.965 3.525"/></symbol><symbol id="i-key" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1 1 21.75 8.25Z"/></symbol><symbol id="i-link" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 0 1 1.242 7.244l-4.5 4.5a4.5 4.5 0 0 1-6.364-6.364l1.757-1.757m13.35-.622 1.757-1.757a4.5 4.5 0 0 0-6.364-6.364l-4.5 4.5a4.5 4.5 0 0 0 1.242 7.244"/></symbol><symbol id="i-lock-closed" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z"/></symbol><symbol id="i-lock-open" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 10.5V6.75a4.5 4.5 0 1 1 9 0v3.75M3.75 21.75h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H3.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z"/></symbol><symbol id="i-magnifying-glass" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/></symbol><symbol id="i-map" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 6.75V15m6-6v8.25m.503 3.498 4.875-2.437c.381-.19.622-.58.622-1.006V4.82c0-.836-.88-1.38-1.628-1.006l-3.869 1.934c-.317.159-.69.159-1.006 0L9.503 3.252a1.125 1.125 0 0 0-1.006 0L3.622 5.689C3.24 5.88 3 6.27 3 6.695V19.18c0 .836.88 1.38 1.628 1.006l3.869-1.934c.317-.159.69-.159 1.006 0l4.994 2.497c.317.158.69.158 1.006 0Z"/></symbol><symbol id="i-moon" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z"/></symbol><symbol id="i-no-symbol" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M18.364 18.364A9 9 0 0 0 5.636 5.636m12.728 12.728A9 9 0 0 1 5.636 5.636m12.728 12.728L5.636 5.636"/></symbol><symbol id="i-phone" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 6.75c0 8.284 6.716 15 15 15h2.25a2.25 2.25 0 0 0 2.25-2.25v-1.372c0-.516-.351-.966-.852-1.091l-4.423-1.106c-.44-.11-.902.055-1.173.417l-.97 1.293c-.282.376-.769.542-1.21.38a12.035 12.035 0 0 1-7.143-7.143c-.162-.441.004-.928.38-1.21l1.293-.97c.363-.271.527-.734.417-1.173L6.963 3.102a1.125 1.125 0 0 0-1.091-.852H4.5A2.25 2.25 0 0 0 2.25 4.5v2.25Z"/></symbol><symbol id="i-play" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"/></symbol><symbol id="i-play-circle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/>
  <path stroke-linecap="round" stroke-linejoin="round" d="M15.91 11.672a.375.375 0 0 1 0 .656l-5.603 3.113a.375.375 0 0 1-.557-.328V8.887c0-.286.307-.466.557-.327l5.603 3.112Z"/></symbol><symbol id="i-plus" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></symbol><symbol id="i-question-mark-circle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"/></symbol><symbol id="i-rocket-launch" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.59 14.37a6 6 0 0 1-5.84 7.38v-4.8m5.84-2.58a14.98 14.98 0 0 0 6.16-12.12A14.98 14.98 0 0 0 9.631 8.41m5.96 5.96a14.926 14.926 0 0 1-5.841 2.58m-.119-8.54a6 6 0 0 0-7.381 5.84h4.8m2.581-5.84a14.927 14.927 0 0 0-2.58 5.84m2.699 2.7c-.103.021-.207.041-.311.06a15.09 15.09 0 0 1-2.448-2.448 14.9 14.9 0 0 1 .06-.312m-2.24 2.39a4.493 4.493 0 0 0-1.757 4.306 4.493 4.493 0 0 0 4.306-1.758M16.5 9a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0Z"/></symbol><symbol id="i-scale" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v17.25m0 0c-1.472 0-2.882.265-4.185.75M12 20.25c1.472 0 2.882.265 4.185.75M18.75 4.97A48.416 48.416 0 0 0 12 4.5c-2.291 0-4.545.16-6.75.47m13.5 0c1.01.143 2.01.317 3 .52m-3-.52 2.62 10.726c.122.499-.106 1.028-.589 1.202a5.988 5.988 0 0 1-2.031.352 5.988 5.988 0 0 1-2.031-.352c-.483-.174-.711-.703-.59-1.202L18.75 4.971Zm-16.5.52c.99-.203 1.99-.377 3-.52m0 0 2.62 10.726c.122.499-.106 1.028-.589 1.202a5.989 5.989 0 0 1-2.031.352 5.989 5.989 0 0 1-2.031-.352c-.483-.174-.711-.703-.59-1.202L5.25 4.971Z"/></symbol><symbol id="i-server-stack" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5.25 14.25h13.5m-13.5 0a3 3 0 0 1-3-3m3 3a3 3 0 1 0 0 6h13.5a3 3 0 1 0 0-6m-16.5-3a3 3 0 0 1 3-3h13.5a3 3 0 0 1 3 3m-19.5 0a4.5 4.5 0 0 1 .9-2.7L5.737 5.1a3.375 3.375 0 0 1 2.7-1.35h7.126c1.062 0 2.062.5 2.7 1.35l2.587 3.45a4.5 4.5 0 0 1 .9 2.7m0 0a3 3 0 0 1-3 3m0 3h.008v.008h-.008v-.008Zm0-6h.008v.008h-.008v-.008Zm-3 6h.008v.008h-.008v-.008Zm0-6h.008v.008h-.008v-.008Z"/></symbol><symbol id="i-shield-check" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75m-3-7.036A11.959 11.959 0 0 1 3.598 6 11.99 11.99 0 0 0 3 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285Z"/></symbol><symbol id="i-shopping-bag" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 10.5V6a3.75 3.75 0 1 0-7.5 0v4.5m11.356-1.993 1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 0 1-1.12-1.243l1.264-12A1.125 1.125 0 0 1 5.513 7.5h12.974c.576 0 1.059.435 1.119 1.007ZM8.625 10.5a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm7.5 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"/></symbol><symbol id="i-shopping-cart" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z"/></symbol><symbol id="i-signal" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.348 14.652a3.75 3.75 0 0 1 0-5.304m5.304 0a3.75 3.75 0 0 1 0 5.304m-7.425 2.121a6.75 6.75 0 0 1 0-9.546m9.546 0a6.75 6.75 0 0 1 0 9.546M5.106 18.894c-3.808-3.807-3.808-9.98 0-13.788m13.788 0c3.808 3.807 3.808 9.98 0 13.788M12 12h.008v.008H12V12Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"/></symbol><symbol id="i-sparkles" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904 9 18.75l-.813-2.846a4.5 4.5 0 0 0-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 0 0 3.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 0 0 3.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 0 0-3.09 3.09ZM18.259 8.715 18 9.75l-.259-1.035a3.375 3.375 0 0 0-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 0 0 2.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 0 0 2.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 0 0-2.456 2.456ZM16.894 20.567 16.5 21.75l-.394-1.183a2.25 2.25 0 0 0-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 0 0 1.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 0 0 1.423 1.423l1.183.394-1.183.394a2.25 2.25 0 0 0-1.423 1.423Z"/></symbol><symbol id="i-stop" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5.25 7.5A2.25 2.25 0 0 1 7.5 5.25h9a2.25 2.25 0 0 1 2.25 2.25v9a2.25 2.25 0 0 1-2.25 2.25h-9a2.25 2.25 0 0 1-2.25-2.25v-9Z"/></symbol><symbol id="i-sun" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z"/></symbol><symbol id="i-swatch" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4.098 19.902a3.75 3.75 0 0 0 5.304 0l6.401-6.402M6.75 21A3.75 3.75 0 0 1 3 17.25V4.125C3 3.504 3.504 3 4.125 3h5.25c.621 0 1.125.504 1.125 1.125v4.072M6.75 21a3.75 3.75 0 0 0 3.75-3.75V8.197M6.75 21h13.125c.621 0 1.125-.504 1.125-1.125v-5.25c0-.621-.504-1.125-1.125-1.125h-4.072M10.5 8.197l2.88-2.88c.438-.439 1.15-.439 1.59 0l3.712 3.713c.44.44.44 1.152 0 1.59l-2.879 2.88M6.75 17.25h.008v.008H6.75v-.008Z"/></symbol><symbol id="i-tag" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z"/>
  <path stroke-linecap="round" stroke-linejoin="round" d="M6 6h.008v.008H6V6Z"/></symbol><symbol id="i-user" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z"/></symbol><symbol id="i-viewfinder-circle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 3.75H6A2.25 2.25 0 0 0 3.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0 1 20.25 6v1.5m0 9V18A2.25 2.25 0 0 1 18 20.25h-1.5m-9 0H6A2.25 2.25 0 0 1 3.75 18v-1.5M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></symbol><symbol id="i-wrench-screwdriver" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M11.42 15.17 17.25 21A2.652 2.652 0 0 0 21 17.25l-5.877-5.877M11.42 15.17l2.496-3.03c.317-.384.74-.626 1.208-.766M11.42 15.17l-4.655 5.653a2.548 2.548 0 1 1-3.586-3.586l6.837-5.63m5.108-.233c.55-.164 1.163-.188 1.743-.14a4.5 4.5 0 0 0 4.486-6.336l-3.276 3.277a3.004 3.004 0 0 1-2.25-2.25l3.276-3.276a4.5 4.5 0 0 0-6.336 4.486c.091 1.076-.071 2.264-.904 2.95l-.102.085m-1.745 1.437L5.909 7.5H4.5L2.25 3.75l1.5-1.5L7.5 4.5v1.409l4.26 4.26m-1.745 1.437 1.745-1.437m6.615 8.206L15.75 15.75M4.867 19.125h.008v.008h-.008v-.008Z"/></symbol><symbol id="i-x-circle" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></symbol><symbol id="i-x-mark" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12"/></symbol></svg>


  <!-- TOP HEADER -->
  <header>
    <div class="brand-group">
      <div class="brand-title">
        <span>🛡️ {{APP_NAME}}</span>
      </div>
      <span class="brand-badge">Merchant &amp; Supervisor Hub</span>
    </div>

    <div class="header-quick-stats">
      <!-- Theme: System (default) / Light / Dark -->
      <div class="theme-switch" role="radiogroup" aria-label="Colour theme"><button type="button" role="radio" data-theme-pref="system" onclick="setThemePref('system')" title="Follow system setting"><svg class="i" aria-hidden="true"><use href="#i-computer-desktop"/></svg>System</button><button type="button" role="radio" data-theme-pref="light" onclick="setThemePref('light')" title="Light theme"><svg class="i" aria-hidden="true"><use href="#i-sun"/></svg>Light</button><button type="button" role="radio" data-theme-pref="dark" onclick="setThemePref('dark')" title="Dark theme"><svg class="i" aria-hidden="true"><use href="#i-moon"/></svg>Dark</button></div>

      <!-- YOUPI Store Port 5000 Switch Badge -->
      <div class="store-switch-badge is-offline" id="headerStoreBadge" onclick="toggleYoupiStore()"
        title="Click to 1-Click Enable/Disable YOUPI Showcase Store on Port 5000">
        <span id="headerStoreDot">●</span>
        <span id="headerStoreText">Store (5000): Checking...</span>
      </div>

      <!-- Merchant Account Switcher -->
      <div style="display:flex; align-items:center; gap:0.35rem; background:var(--bg-card); padding:0.25rem 0.6rem; border-radius:9999px; border:1px solid var(--border);">
        <span style="font-size:0.75rem;">🏪</span>
        <select id="headerMerchantSelector" onchange="onMerchantSwitch(this.value)" style="font-size:0.75rem; font-weight:700; background:transparent; border:none; color:var(--text-main); cursor:pointer; outline:none; max-width:140px;">
          <option value="00000000-0000-0000-0000-000000000001">Default Store</option>
        </select>
        <button type="button" class="btn btn-secondary" onclick="openNewMerchantModal()" style="padding:0.15rem 0.45rem; font-size:0.7rem; border-radius:9999px;" title="Create/Onboard New Merchant">+ New</button>
      </div>

      <!-- Active VPA Display -->
      <span class="badge badge-info" id="accountVpaDisplay" style="cursor:pointer;"
        onclick="switchSection('storeSettings', 'subTabVpa')">
        VPA: Loading...
      </span>

      <!-- Environment Mode -->
      <div
        style="display:flex; align-items:center; gap:0.4rem; background:var(--bg-card); padding:0.3rem 0.75rem; border-radius:9999px; border:1px solid var(--border); cursor:pointer;"
        onclick="switchSection('developerHub', 'subViewDevCloudflare')">
        <span style="font-size:0.72rem; color:var(--text-muted); font-weight:700;">ENV:</span>
        <span class="badge badge-info" id="headerEnvBadge" style="font-size:0.72rem; padding:0.15rem 0.5rem;">💻
          LOCALHOST</span>
      </div>

      <!-- Live Polling Indicator -->
      <div class="live-pulse-badge">
        <div class="pulse-dot"></div>
        <span>Live Syncing</span>
      </div>
    </div>
  </header>

  <!-- MAIN NAVIGATION BAR: 3 HIGH-LEVEL SECTIONS -->
  <nav class="main-nav-bar">
    <button class="main-nav-btn active" id="mainNavOperations" onclick="switchSection('operations')">
      <span>🏪</span>
      <span>Daily Merchant Operations</span>
    </button>
    <button class="main-nav-btn" id="mainNavStoreSettings" onclick="switchSection('storeSettings')">
      <span>⚙️</span>
      <span>Store Settings</span>
    </button>
    <button class="main-nav-btn" id="mainNavDeveloperHub" onclick="switchSection('developerHub')">
      <span>🛠️</span>
      <span>Developer &amp; Infrastructure Hub</span>
    </button>
    <button class="main-nav-btn" id="mainNavSecurity" onclick="switchSection('security')">
      <span>🛡️</span>
      <span>Security</span>
    </button>
  </nav>

  <!-- SECONDARY SUB-NAVIGATION BAR (Dynamically adapts per section) -->
  <nav class="sub-nav-bar" id="subNavBar">
    <!-- Filled dynamically or toggled based on current section -->
  </nav>

  <main>

    <!-- ========================================================================= -->
    <!-- SECTION 1: DAILY MERCHANT OPERATIONS                                      -->
    <!-- ========================================================================= -->
    <div id="sectionOperations">

      <!-- KPI Summary Cards -->
      <div class="kpi-row">
        <div class="kpi-box">
          <div class="kpi-title">Today's Volume</div>
          <div class="kpi-value" id="kpiVol" style="color:var(--kpi-vol-color);">₹0.00</div>
        </div>
        <div class="kpi-box">
          <div class="kpi-title">Successful Payments</div>
          <div class="kpi-value" id="kpiSuccessCount" style="color:var(--kpi-success-color);">0</div>
        </div>
        <div class="kpi-box">
          <div class="kpi-title">In Waiting Queue</div>
          <div class="kpi-value" id="kpiQueueCount" style="color:var(--kpi-queue-color);">0</div>
        </div>
        <div class="kpi-box">
          <div class="kpi-title">Pending Counter Payments</div>
          <div class="kpi-value" id="kpiPendingCounterCount" style="color:var(--kpi-pending-color);">0</div>
        </div>
      </div>

      <!-- Verification Standards Metric Row (2-Layer Engine: SMS + Gmail) -->
      <div class="kpi-row" style="margin-top:-0.5rem; margin-bottom:1.5rem;">
        <div class="kpi-box">
          <div class="kpi-title">Single Verified (1 Source)</div>
          <div class="kpi-value" id="kpiSingleVerify" style="color:var(--info); font-size:1.5rem;">0</div>
        </div>
        <div class="kpi-box">
          <div class="kpi-title">Dual Verified (2 Sources: SMS + Gmail)</div>
          <div class="kpi-value" id="kpiDualVerify" style="color:var(--success); font-size:1.5rem;">0</div>
        </div>
      </div>

      <!-- SUB-VIEW 1.1: LIVE QUEUE & SLOTS -->
      <div id="subViewOpsLive">
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🔴 Real-Time Receiving Account Slot Ownership (UPI Invariant)</div>
              <div class="card-subtext">Guarantees zero payment collision by rotating dynamic slots per receiving UPI
                VPA.</div>
            </div>
            <div style="display:flex; gap:0.5rem;">
              <button class="btn btn-secondary" onclick="fetchLiveData()">Force Refresh</button>
              <button class="btn btn-danger" onclick="promptClearAllQueue()">Clear Waiting Queue</button>
            </div>
          </div>

          <div class="queue-grid">
            <!-- Active 5:00 Slot -->
            <div class="slot-card" id="slotActiveBox">
              <div style="font-size:0.8rem; font-weight:700; color:var(--text-muted); text-transform:uppercase;">
                Active Slot (5-Minute Window)</div>
              <div id="slotActiveContent" style="padding:1rem 0; color:var(--text-muted);">
                No customer actively checking out right now.
              </div>
            </div>

            <!-- Processing 30s Slot -->
            <div class="slot-card" id="slotProcBox">
              <div style="font-size:0.8rem; font-weight:700; color:var(--text-muted); text-transform:uppercase;">
                Processing Slot (30s Verification Window)</div>
              <div id="slotProcContent" style="padding:1rem 0; color:var(--text-muted);">
                No payment in verification window.
              </div>
            </div>
          </div>

          <!-- Waiting Queue Table -->
          <div style="margin-top:1.5rem;">
            <div style="font-size:0.92rem; font-weight:700; margin-bottom:0.75rem; color:var(--text-heading);">
              ⏳ Waiting Customer Queue
            </div>
            <div style="overflow-x:auto;">
              <table>
                <thead>
                  <tr>
                    <th>Queue #</th>
                    <th>Order</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Enqueued At</th>
                  </tr>
                </thead>
                <tbody id="queueTableBody">
                  <tr>
                    <td colspan="5" style="text-align:center; color:var(--text-muted); padding:1rem;">Waiting queue is
                      empty.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 1.2: COUNTER DESK (CASHIER POS) -->
      <div id="subViewOpsCounter" hidden>
        <!-- Mode Card: Cash/Card Counter Desk (Offline) -->
        <div class="card" id="counterDeskOfflineCard">
          <div class="card-header">
            <div>
              <div class="card-heading">🏪 Cash &amp; Card Billing Counter Desk (Live Counter Payment Requests)</div>
              <div class="card-subtext">Real-time incoming payment requests from checkout screens. Verify banknotes or
                POS slips and approve immediately.</div>
            </div>
            <div style="display:flex; align-items:center; gap:0.6rem;">
              <span class="badge badge-info" id="operatorDisplay">Cashier Desk #1</span>
              <button class="btn btn-secondary" onclick="fetchCounterPayments()">Refresh</button>
            </div>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>Payment ID</th>
                  <th>Amount</th>
                  <th>Counter Method</th>
                  <th>Requested At</th>
                  <th>Cashier Actions</th>
                </tr>
              </thead>
              <tbody id="counterTableBody">
                <tr>
                  <td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No pending counter
                    payments right now.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Mode Card: COD Orders (Online) -->
        <div class="card" id="counterDeskCodCard" style="display:none;">
          <div class="card-header">
            <div>
              <div class="card-heading">📦 Cash on Delivery (COD) Verified Orders</div>
              <div class="card-subtext">Orders placed with Cash on Delivery payment confirmation. Ready for fulfillment
                and dispatch.</div>
            </div>
            <button class="btn btn-secondary" onclick="fetchCodOrders()">Refresh Orders</button>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>Payment Ref</th>
                  <th>Amount</th>
                  <th>Customer Name</th>
                  <th>Phone</th>
                  <th>Placed At</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody id="codOrdersTableBody">
                <tr>
                  <td colspan="7" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No COD orders
                    placed yet.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 1.3: TRANSACTIONS LEDGER -->
      <div id="subViewOpsTransactions" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">💳 Payment Transactions Ledger</div>
              <div class="card-subtext">Comprehensive transaction audit history with automated bank observer attribution
                &amp; verification tiers.</div>
            </div>
            <button class="btn btn-secondary" onclick="fetchPaymentsLedger()">Refresh</button>
          </div>
          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Order ID</th>
                  <th>Payment ID</th>
                  <th>Amount</th>
                  <th>Method</th>
                  <th>Status</th>
                  <th>Verification Tier</th>
                  <th>Channel Sources</th>
                  <th>Created At</th>
                  <th>Completed At</th>
                </tr>
              </thead>
              <tbody id="paymentsLedgerTbody">
                <tr>
                  <td colspan="9" style="text-align:center; padding:1.5rem;">Loading transactions...</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 1.4: PAYMENT OBSERVERS LIVE STATUS -->
      <div id="subViewOpsObservers" hidden>
        <div
          style="font-size:1.15rem; font-weight:800; color:var(--text-heading); margin-bottom:1rem; display:flex; align-items:center; gap:0.5rem;">
          <span>📡</span> Payment Observers (SMS & Gmail)
        </div>
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:1.5rem;">
          <!-- Android Companion Card -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-header">
              <div class="card-heading">📱 Android SMS Gateway</div>
              <span class="badge badge-info" id="smsGatewayBadge">STANDBY</span>
            </div>
            <p class="card-subtext" style="margin-bottom:1rem;">
              Native Android observer app captures credit SMS notifications in real-time from bank-linked handsets.
            </p>
            <div
              style="background:var(--bg-surface); border:1px solid var(--border); border-radius:0.5rem; padding:1rem; margin-bottom:1rem;">
              <div style="font-size:0.8rem; font-weight:700; color:var(--text-muted); margin-bottom:0.4rem;">Enrollment
                Secret:</div>
              <code id="smsTokenVal" style="color:var(--info); font-weight:700; font-size:0.85rem;">Loading...</code>
              <button class="btn btn-secondary" style="font-size:0.7rem; padding:0.2rem 0.5rem; margin-left:0.5rem;"
                onclick="copySmsToken()">📋 Copy</button>
            </div>
            <div style="display:flex; gap:0.5rem;">
              <a class="btn btn-success" href="/youpi-sms-gateway.apk" download="youpi-sms-gateway.apk">📲 Download
                Companion APK</a>
              <button class="btn btn-secondary" onclick="switchSection('developerHub', 'subTabAndroid')">Configure
                Pairing ↗</button>
            </div>
          </div>

          <!-- Gmail Direct API Card -->
          <div class="card" style="margin-bottom:0;">
            <div class="card-header">
              <div class="card-heading">📧 Gmail Direct API</div>
              <span class="badge badge-info" id="gmailConfigBadge">NOT CONFIGURED</span>
            </div>
            <p class="card-subtext" style="margin-bottom:1rem;">
              Direct Google Cloud OAuth poller reading transaction credit alerts directly from your merchant inbox.
            </p>
            <div
              style="background:var(--bg-surface); border:1px solid var(--border); border-radius:0.5rem; padding:1rem; margin-bottom:1rem;">
              <div style="font-size:0.8rem; color:var(--text-muted); line-height:1.5;">
                Dual-verification engine matches transactions across both SMS and Gmail channels for 100% fraud
                immunity.
              </div>
            </div>
            <button class="btn btn-primary" onclick="switchSection('developerHub', 'subTabGmail')">Configure Gmail API
              ↗</button>
          </div>
        </div>
      </div>

    </div>


    <!-- ========================================================================= -->
    <!-- SECTION 2: STORE SETTINGS                                                 -->
    <!-- ========================================================================= -->
    <div id="sectionStoreSettings" hidden>

      <!-- SUB-VIEW 2.1: BRAND IDENTITY & WHITE-LABEL VISUAL CUSTOMIZER -->
      <div id="subViewStoreBrand">
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🎨 White-Label Branding &amp; Visual Gateway Customizer</div>
              <div class="card-subtext">Customize every visual, textual, and brand asset of your customer checkout
                experience. Live reflection on smartphone mockup.</div>
            </div>
            <span class="badge badge-success">100% White-Label Capable</span>
          </div>

          <div
            style="display:grid; grid-template-columns:minmax(0, 1.4fr) minmax(340px, 1fr); gap:2rem; align-items:start;">

            <!-- LEFT COLUMN: CONTROLS & SETTINGS -->
            <div>
              <!-- SECTION 0: MERCHANT CREDENTIALS & INTEGRATION KEYS -->
              <div class="settings-group-box" style="border:1.5px solid var(--accent); background:rgba(37,99,235,0.03);">
                <div class="group-box-title" style="display:flex; justify-content:space-between; align-items:center;">
                  <span>🔑 Merchant ID &amp; API Integration Keys</span>
                  <button type="button" class="btn btn-primary" onclick="openNewMerchantModal()" style="font-size:0.75rem; padding:0.25rem 0.65rem;">+ New Merchant</button>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Active Merchant ID (UUID)</label>
                    <div style="display:flex; gap:0.4rem;">
                      <input id="settingDisplayMerchantId" type="text" readonly style="width:100%; font-family:monospace; font-size:0.8rem; background:var(--bg-main);" />
                      <button type="button" class="btn btn-secondary" onclick="copyMerchantId()" style="padding:0.3rem 0.6rem; font-size:0.75rem;" title="Copy Merchant ID">📋</button>
                    </div>
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Publishable Key (data-youpi-key)</label>
                    <div style="display:flex; gap:0.4rem;">
                      <input id="settingDisplayApiKey" type="text" readonly style="width:100%; font-family:monospace; font-size:0.8rem; background:var(--bg-main);" placeholder="Click Rotate to generate" />
                      <button type="button" class="btn btn-secondary" onclick="copyMerchantApiKey()" style="padding:0.3rem 0.6rem; font-size:0.75rem;" title="Copy API Key">📋</button>
                      <button type="button" class="btn btn-secondary" onclick="rotateMerchantApiKey()" style="padding:0.3rem 0.6rem; font-size:0.75rem;" title="Rotate / Generate New Key">🔄</button>
                    </div>
                  </div>
                </div>
                <div>
                  <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Universal 1-Script Integration Snippet</label>
                  <div style="display:flex; gap:0.4rem;">
                    <input id="settingIntegrationSnippet" type="text" readonly style="width:100%; font-family:monospace; font-size:0.75rem; background:var(--bg-main); color:var(--text-muted);" />
                    <button type="button" class="btn btn-secondary" onclick="copyIntegrationSnippet()" style="padding:0.3rem 0.65rem; font-size:0.75rem;">📋 Copy</button>
                  </div>
                  <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Paste this script tag into your storefront HTML &lt;head&gt; or &lt;body&gt; to connect YouPI checkout.</span>
                </div>
              </div>

              <!-- SECTION 1: CORE BRAND IDENTITY -->
              <div class="settings-group-box">
                <div class="group-box-title">
                  🏷️ 1. Core Brand Identity &amp; Title
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Merchant
                      Store / Business Name</label>
                    <input id="settingBusinessName" type="text" placeholder="e.g. YOUPI Store or MSPCARE"
                      style="width:100%;" oninput="updateLiveWhiteLabelPreview()" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Gateway
                      Title / App Name</label>
                    <input id="settingAppName" type="text" value="{{APP_NAME}}" placeholder="e.g. {{APP_NAME}}"
                      style="width:100%;" oninput="updateLiveWhiteLabelPreview()" />
                  </div>
                </div>
                <div>
                  <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Brand Logo
                    Image URL</label>
                  <input id="settingLogoUrl" type="url" placeholder="https://yourbrand.com/logo.png" style="width:100%;"
                    oninput="updateLiveWhiteLabelPreview()" />
                  <span
                    style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Transparent
                    PNG or SVG recommended. When left blank, your store initial letter is used.</span>
                </div>
              </div>

              <!-- SECTION 2: VISUAL THEME & COLOR PALETTE -->
              <div class="settings-group-box">
                <div class="group-box-title">
                  🎨 2. Visual Theme &amp; Color Palette
                </div>
                <div style="display:grid; grid-template-columns:1.2fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Primary
                      Brand Color (Hex)</label>
                    <div style="display:flex; gap:0.5rem; align-items:center;">
                      <input id="settingColorPicker" type="color" value="#0b63e5"
                        style="width:44px; height:40px; border:none; background:transparent; cursor:pointer; padding:0;"
                        oninput="syncColorPickerToText(this.value)" />
                      <input id="settingPrimaryColor" type="text" value="#0b63e5"
                        style="flex:1; font-family:monospace; font-weight:700;"
                        oninput="syncTextColorToPicker(this.value)" />
                    </div>
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Header
                      Styling Theme</label>
                    <select id="settingHeaderTheme" style="width:100%;" onchange="updateLiveWhiteLabelPreview()">
                      <option value="gradient">Dynamic Gradient (Brand to Deep Accent)</option>
                      <option value="solid">Solid Brand Color</option>
                      <option value="dark">Obsidian Dark Navy (#0b1329)</option>
                    </select>
                  </div>
                </div>
                <div>
                  <span
                    style="font-size:0.75rem; color:var(--text-muted); font-weight:700; display:block; margin-bottom:0.4rem;">Quick
                    FinTech Brand Palettes:</span>
                  <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#0b63e5', 'gradient')">🔵 Sapphire Blue</button>
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#10b981', 'gradient')">🟢 Emerald Green</button>
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#8b5cf6', 'gradient')">🟣 Violet Purple</button>
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#f43f5e', 'gradient')">🔴 Rose Crimson</button>
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#d97706', 'gradient')">🟡 Amber Gold</button>
                    <button type="button" class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;"
                      onclick="applyQuickPalette('#0f172a', 'dark')">⚫ Obsidian Dark</button>
                  </div>
                </div>
              </div>

              <!-- SECTION 3: TRUST BADGE & SUB-BANNER CONTROLS -->
              <div class="settings-group-box">
                <div class="group-box-title">
                  🛡️ 3. Badges &amp; Conversion Banners
                </div>
                <!-- Hidden inputs preserve existing trust badge settings without merchant UI access -->
                <input type="hidden" id="settingHideTrustBadge" />
                <input type="hidden" id="settingTrustBadgeText" />
                <div style="margin-bottom:1rem; padding-bottom:1rem; border-bottom:1px dashed var(--border);">
                  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.35rem;">
                    <label style="font-size:0.82rem; font-weight:700;">Header Sub-banner Text</label>
                    <label
                      style="font-size:0.78rem; color:var(--text-muted); display:flex; align-items:center; gap:0.35rem; cursor:pointer;">
                      <input type="checkbox" id="settingHideSubbanner" onchange="updateLiveWhiteLabelPreview()" />
                      <span>Hide Sub-banner</span>
                    </label>
                  </div>
                  <input id="settingSubbannerText" type="text" placeholder="e.g. 5-Second Instant UPI Activation"
                    style="width:100%;" oninput="updateLiveWhiteLabelPreview()" />
                </div>
                <div>
                  <label
                    style="font-size:0.78rem; color:var(--text-muted); display:flex; align-items:center; gap:0.35rem; cursor:pointer;">
                    <input type="checkbox" id="settingHideTimeSavingBanner" onchange="updateLiveWhiteLabelPreview()" />
                    <span>Hide Psychological Time-Saving Banner</span>
                  </label>
                </div>
              </div>

              <!-- SECTION 4: TRUST GUARANTEES & NOTICES -->
              <div class="settings-group-box">
                <div class="group-box-title">
                  🛡️ 4. Guarantees &amp; Conversion Notices
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Sidebar Trust Notice</label>
                    <input id="settingSidebarNotice" type="text" placeholder="e.g. Fast & Secure 256-Bit Encrypted Payments" style="width:100%;" oninput="updateLiveWhiteLabelPreview()" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Footer Guarantee Text</label>
                    <input id="settingFooterGuarantee" type="text" placeholder="e.g. 100% Payment Protection Guaranteed" style="width:100%;" oninput="updateLiveWhiteLabelPreview()" />
                  </div>
                </div>
              </div>

              <!-- SECTION 5: SUPPORT & LEGAL POLICIES -->
              <div class="settings-group-box">
                <div class="group-box-title">
                  📞 5. Support &amp; Legal Policies
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Customer
                      Support Email(s)</label>
                    <input id="settingSupportEmails" type="text" placeholder="[email protected], [email protected]"
                      style="width:100%;" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Customer
                      Support Mobile(s)</label>
                    <input id="settingSupportMobiles" type="text" placeholder="+91 9876543210, +91 9123456789"
                      style="width:100%;" />
                  </div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Privacy
                      Policy URL</label>
                    <input id="settingPrivacyPolicyUrl" type="url" placeholder="https://yourbrand.com/privacy-policy"
                      style="width:100%;" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Terms of
                      Service URL</label>
                    <input id="settingTermsUrl" type="url" placeholder="https://yourbrand.com/terms"
                      style="width:100%;" />
                  </div>
                </div>
              </div>

              <button class="btn btn-primary"
                style="padding:0.85rem 1.75rem; font-size:0.95rem; width:100%; justify-content:center;"
                onclick="saveMerchantBrandingAndToggles()">
                💾 Save &amp; Apply All White-Label Settings
              </button>
            </div>

            <!-- RIGHT COLUMN: INTERACTIVE SMARTPHONE CHECKOUT MOCKUP PREVIEW -->
            <div style="position:sticky; top:130px;">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem;">
                <div
                  style="font-size:0.82rem; font-weight:800; text-transform:uppercase; color:var(--text-muted); display:flex; align-items:center; gap:0.4rem;">
                  <span
                    style="display:inline-block; width:8px; height:8px; border-radius:50%; background:#10b981;"></span>
                  Live Gateway Mockup Preview
                </div>
                <span style="font-size:0.72rem; color:var(--text-muted);">Real-time reflection</span>
              </div>

              <!-- PHONE CHASSIS -->
              <div
                style="width:100%; max-width:380px; margin:0 auto; background:#ffffff; border-radius:36px; border:9px solid #1e293b; box-shadow:0 25px 50px -12px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.1); overflow:hidden; position:relative; min-height:580px; display:flex; flex-direction:column;">
                <!-- PHONE NOTCH -->
                <div
                  style="background:#0b0f19; height:24px; display:flex; align-items:center; justify-content:space-between; padding:0 16px; color:#ffffff; font-size:10px; font-weight:700;">
                  <span>9:41</span>
                  <div style="width:50px; height:4px; background:#334155; border-radius:4px;"></div>
                  <div style="display:flex; gap:4px; align-items:center;"><span>5G</span><span>100%</span></div>
                </div>

                <!-- LIVE CHECKOUT HEADER -->
                <div id="mockupHeader"
                  style="background:linear-gradient(180deg, #0b63e5 0%, #0747a6 100%); padding:12px 14px 10px 14px; color:#ffffff; transition:background 0.2s ease;">
                  <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:8px;">
                    <div style="display:flex; align-items:center; gap:10px;">
                      <div
                        style="width:36px; height:36px; border-radius:50%; background:#ffffff; display:flex; align-items:center; justify-content:center; overflow:hidden; box-shadow:0 2px 5px rgba(0,0,0,0.15); flex-shrink:0;">
                        <span id="mockupAvatarLetter" style="font-weight:900; color:#0b63e5; font-size:16px;">M</span>
                        <img id="mockupAvatarImg" alt="Logo"
                          style="display:none; width:100%; height:100%; object-fit:contain;" />
                      </div>
                      <div>
                        <div id="mockupHeaderMerchantName"
                          style="font-size:13.5px; font-weight:800; line-height:1.2; color:#ffffff;">Merchant Checkout
                        </div>
                        <div id="mockupTrustBadge"
                          style="display:inline-flex; align-items:center; gap:3px; margin-top:2px;">
                          <span style="font-size:11px;">🛡️</span>
                          <span id="mockupTrustBadgeText"
                            style="font-size:10px; font-weight:700; color:rgba(255,255,255,0.92);">YouPI PG Verified
                            Business</span>
                        </div>
                      </div>
                    </div>
                    <div
                      style="width:28px; height:28px; border-radius:50%; background:rgba(255,255,255,0.18); display:flex; align-items:center; justify-content:center; font-size:12px;">
                      👤</div>
                  </div>

                  <div id="mockupSubbanner"
                    style="background:rgba(255,255,255,0.15); border-radius:6px; padding:4px 8px; font-size:10.5px; font-weight:700; display:flex; align-items:center; gap:5px; backdrop-filter:blur(4px);">
                    <span>🛒</span>
                    <span id="mockupSubbannerText"
                      style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">Verified &amp; Protected by
                      {{APP_NAME}}</span>
                  </div>
                </div>

                <!-- BODY PREVIEW -->
                <div style="padding:12px; background:#f8fafc; flex:1; display:flex; flex-direction:column; gap:10px;">
                  <div id="mockupTimeSavingBanner"
                    style="background:#f0fdf4; border:1px solid #86efac; border-radius:8px; padding:7px 10px; display:flex; align-items:center; justify-content:space-between; gap:6px;">
                    <div style="font-size:10px; color:#14532d; font-weight:700; line-height:1.3;">⚡ Skip wait: Instant
                      billing counter checkout available</div>
                    <span
                      style="background:#10b981; color:#fff; font-size:9px; font-weight:800; padding:3px 7px; border-radius:5px; white-space:nowrap;">Switch</span>
                  </div>

                  <div
                    style="background:#ffffff; border:1px solid #e2e8f0; border-radius:10px; padding:10px; display:flex; justify-content:space-between; align-items:center;">
                    <div>
                      <div style="font-size:9.5px; color:#64748b; font-weight:700; text-transform:uppercase;">Order
                        #ORD-78921</div>
                      <div style="font-size:17px; font-weight:900; color:#0f172a; margin-top:2px;">₹1,500.00</div>
                    </div>
                    <span
                      style="background:#eff6ff; color:#0f766e; font-size:10px; font-weight:800; padding:3px 8px; border-radius:6px;">Direct
                      UPI</span>
                  </div>

                  <div
                    style="background:#ffffff; border:1px solid #e2e8f0; border-radius:10px; padding:12px; text-align:center;">
                    <div
                      style="width:110px; height:110px; margin:0 auto 8px auto; border-radius:8px; border:2px solid #0f172a; padding:4px; display:flex; align-items:center; justify-content:center; background:#ffffff;">
                      <div
                        style="width:100%; height:100%; background:repeating-linear-gradient(45deg, #0f172a, #0f172a 6px, #ffffff 6px, #ffffff 12px); border-radius:4px; opacity:0.85;">
                      </div>
                    </div>
                    <div style="font-size:10px; font-weight:700; color:#334155;">Scan with any UPI App (GPay, PhonePe,
                      Paytm)</div>
                  </div>
                </div>

                <!-- LIVE STICKY FOOTER -->
                <div style="background:#ffffff; border-top:1px solid #e2e8f0; padding:10px 14px; margin-top:auto;">
                  <div
                    style="display:flex; align-items:center; justify-content:center; gap:5px; font-size:10px; font-weight:700; color:#0b63e5; margin-bottom:5px;">
                    <span>🛡️</span>
                    <span id="mockupFooterGuarantee">100% Payment Protection by {{APP_NAME}}</span>
                  </div>
                  <div id="mockupLegalDisclaimer"
                    style="font-size:9px; color:#64748b; text-align:center; margin-bottom:8px;">
                    Secured by {{APP_NAME}} &amp; 256-Bit Bank Encryption &bull; Privacy Notice
                  </div>
                  <div
                    style="display:flex; justify-content:space-between; align-items:center; background:#0f172a; border-radius:8px; padding:8px 12px; color:#ffffff;">
                    <div>
                      <div style="font-size:8.5px; color:#94a3b8; font-weight:600;">Total Payable</div>
                      <div style="font-size:13px; font-weight:800; color:#ffffff;">₹1,500.00</div>
                    </div>
                    <span id="mockupCtaButton"
                      style="background:#0f766e; color:#ffffff; font-size:10.5px; font-weight:800; padding:5px 12px; border-radius:6px;">Continue
                      &rsaquo;</span>
                  </div>
                </div>

                <!-- PHONE HOME BAR -->
                <div style="background:#ffffff; height:14px; display:flex; align-items:center; justify-content:center;">
                  <div style="width:90px; height:4px; background:#cbd5e1; border-radius:4px;"></div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>

      <!-- SUB-VIEW 2.2: RECEIVING UPI ACCOUNTS (VPAS) -->
      <div id="subViewStoreVpa" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">⚡ Receiving UPI Accounts &amp; Multiple VPAs</div>
              <div class="card-subtext">Manage receiving VPAs. <strong>Only ONE VPA can be active at a time</strong> for
                gateway payments. Activating a VPA automatically rotates and deactivates all others.</div>
            </div>
            <span class="badge badge-success" id="activeVpaModeBadge">Active Gateway VPA</span>
          </div>

          <!-- Current Active VPA Callout Box -->
          <div id="activeVpaCallout"
            style="background:var(--bg-surface); border:1px solid var(--border); border-radius:0.75rem; padding:1.25rem; margin-bottom:1.5rem; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
            <div>
              <div style="font-size:0.75rem; font-weight:800; color:var(--text-muted); text-transform:uppercase;">
                Currently Active Gateway VPA</div>
              <div style="font-size:1.45rem; font-weight:900; color:var(--primary); margin:0.25rem 0;"
                id="activeVpaIdDisplay">Loading active VPA...</div>
              <div style="font-size:0.85rem; color:var(--text-muted);" id="activeVpaPayeeDisplay">Payee: -</div>
            </div>
            <div style="text-align:right;">
              <div style="font-size:0.75rem; color:var(--text-muted); margin-bottom:0.3rem;">Checkout Mode</div>
              <div style="font-size:0.9rem; font-weight:800; color:var(--success);">✓ Direct Dynamic UPI QR Gateway
              </div>
            </div>
          </div>

          <!-- Add New VPA Section -->
          <div class="settings-group-box">
            <h4 style="margin-bottom:0.85rem; font-size:0.95rem; color:var(--text-heading);">➕ Add New Receiving UPI VPA
            </h4>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
              <div>
                <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.3rem;">UPI ID /
                  VPA</label>
                <input id="newUpiVpa" type="text" placeholder="e.g. 9876543210@axl or merchant@okhdfcbank"
                  style="width:100%;" />
              </div>
              <div>
                <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.3rem;">Payee / Merchant
                  Display Name</label>
                <input id="newUpiPayee" type="text" placeholder="e.g. YOUPI Store or Store Name" style="width:100%;" />
              </div>
            </div>
            <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
              <label
                style="display:flex; align-items:center; gap:0.5rem; font-size:0.85rem; font-weight:600; cursor:pointer;">
                <input type="checkbox" id="newUpiActivateNow" checked style="width:16px; height:16px;" />
                <span>Set as active VPA for customer checkout immediately</span>
              </label>
              <button class="btn btn-primary" onclick="addNewUpiAccount()">➕ Save &amp; Add UPI Account</button>
            </div>
          </div>

          <!-- Saved VPAs Table -->
          <h4 style="margin-bottom:0.75rem; font-size:0.95rem; color:var(--text-heading);">📋 Saved Receiving UPI
            Accounts</h4>
          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>UPI ID (VPA)</th>
                  <th>Payee Name</th>
                  <th>Gateway Status</th>
                  <th>Slot State</th>
                  <th>Created</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody id="upiAccountsTableBody">
                <tr>
                  <td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">Loading UPI
                    accounts...</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 2.3: SELLING MODES & MODALITIES -->
      <div id="subViewStoreModes" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🏪 Store Selling Mode &amp; Payment Modalities</div>
              <div class="card-subtext">Toggle between <strong>Online Selling Mode</strong> (E-Commerce) or
                <strong>Offline Selling Mode</strong> (Physical till/POS desk). Reflects instantly on checkout.
              </div>
            </div>
            <span class="badge badge-info" id="currentSellingModeBadge">ONLINE SELLING MODE</span>
          </div>

          <!-- Mode Segmented Switch -->
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1.5rem;">
            <div id="cardModeOnline" onclick="setSellingMode('ONLINE', true)" class="selling-mode-card mode-selected-online">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.5rem;">
                <strong style="font-size:1rem; color:var(--text-heading);">🌐 Online Selling Mode</strong>
                <span class="badge badge-primary" id="badgeOnlineActive">ACTIVE</span>
              </div>
              <p style="font-size:0.82rem; color:var(--text-muted); line-height:1.45; margin:0;">
                For websites and courier deliveries. Supports <strong>UPI QR</strong> (always on) and optional
                <strong>Cash on Delivery (COD)</strong>.
              </p>
            </div>

            <div id="cardModeOffline" onclick="setSellingMode('OFFLINE', true)" class="selling-mode-card">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.5rem;">
                <strong style="font-size:1rem; color:var(--text-heading);">🏬 Offline Selling Mode</strong>
                <span class="badge badge-warning" id="badgeOfflineActive" style="display:none;">ACTIVE</span>
              </div>
              <p style="font-size:0.82rem; color:var(--text-muted); line-height:1.45; margin:0;">
                For retail stores and physical checkout desks. Supports <strong>UPI QR</strong> (always on),
                configurable <strong>Cash</strong>, and configurable <strong>Card POS</strong>.
              </p>
            </div>
          </div>

          <!-- ONLINE PAYMENT MODALITIES -->
          <div id="panelOnlineMode" class="settings-group-box">
            <div style="font-size:0.88rem; font-weight:700; color:var(--info); margin-bottom:0.75rem;">🌐 Online Payment
              Options</div>
            <div style="display:flex; flex-direction:column; gap:1rem;">
              <div
                style="display:flex; align-items:flex-start; justify-content:space-between; padding:0.85rem; background:var(--bg-card); border:1px solid var(--border); border-radius:0.5rem;">
                <div>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <strong style="font-size:0.9rem; color:var(--text-heading);">Digital UPI Payments (QR Code)</strong>
                    <span class="badge badge-success" style="font-size:0.72rem;">Default · Always Enabled</span>
                  </div>
                  <div style="font-size:0.8rem; color:var(--text-muted);">Direct QR code scan &amp; pay via any UPI app
                    (GPay, PhonePe, Paytm, CRED).</div>
                </div>
                <input type="checkbox" checked disabled style="width:20px; height:20px; opacity:0.85;" />
              </div>

              <label
                style="display:flex; align-items:flex-start; justify-content:space-between; padding:0.85rem; background:var(--bg-card); border:1px solid var(--border); border-radius:0.5rem; cursor:pointer;">
                <div>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <strong style="font-size:0.9rem; color:var(--text-heading);">Cash on Delivery (COD)</strong>
                    <span class="badge badge-info" style="font-size:0.72rem;">Doorstep Cash</span>
                  </div>
                  <div style="font-size:0.8rem; color:var(--text-muted);">Customers confirm order with pre-purchase
                    verification and pay cash upon package arrival.</div>
                </div>
                <input type="checkbox" id="toggleMethodCod" checked style="width:20px; height:20px; cursor:pointer;" />
              </label>
            </div>
          </div>

          <!-- OFFLINE PAYMENT MODALITIES -->
          <div id="panelOfflineMode" hidden class="settings-group-box">
            <div style="font-size:0.88rem; font-weight:700; color:var(--warning); margin-bottom:0.75rem;">🏬 Offline
              Counter Payment Options</div>
            <div style="display:flex; flex-direction:column; gap:1rem;">
              <div
                style="display:flex; align-items:flex-start; justify-content:space-between; padding:0.85rem; background:var(--bg-card); border:1px solid var(--border); border-radius:0.5rem;">
                <div>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <strong style="font-size:0.9rem; color:var(--text-heading);">Digital UPI Payments (QR Code)</strong>
                    <span class="badge badge-success" style="font-size:0.72rem;">Default · Always Enabled</span>
                  </div>
                  <div style="font-size:0.8rem; color:var(--text-muted);">Customer scans dynamic QR code on screen at
                    billing counter.</div>
                </div>
                <input type="checkbox" checked disabled style="width:20px; height:20px; opacity:0.85;" />
              </div>

              <label
                style="display:flex; align-items:flex-start; justify-content:space-between; padding:0.85rem; background:var(--bg-card); border:1px solid var(--border); border-radius:0.5rem; cursor:pointer;">
                <div>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <strong style="font-size:0.9rem; color:var(--text-heading);">Cash</strong>
                    <span class="badge badge-info" style="font-size:0.72rem;">Billing Till</span>
                  </div>
                  <div style="font-size:0.8rem; color:var(--text-muted);">Customer pays physical cash at till. Cashier
                    verifies note and approves in Cashier Dock.</div>
                </div>
                <input type="checkbox" id="toggleMethodCash" checked style="width:20px; height:20px; cursor:pointer;" />
              </label>

              <label
                style="display:flex; align-items:flex-start; justify-content:space-between; padding:0.85rem; background:var(--bg-card); border:1px solid var(--border); border-radius:0.5rem; cursor:pointer;">
                <div>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <strong style="font-size:0.9rem; color:var(--text-heading);">Card</strong>
                    <span class="badge badge-info" style="font-size:0.72rem;">Store POS Terminal</span>
                  </div>
                  <div style="font-size:0.8rem; color:var(--text-muted);">Customer swipes or taps card on physical store
                    POS machine.</div>
                </div>
                <input type="checkbox" id="toggleMethodCard" checked style="width:20px; height:20px; cursor:pointer;" />
              </label>
            </div>
          </div>

          <!-- Offline Instructions -->
          <div class="settings-group-box">
            <div style="font-size:0.88rem; font-weight:700; color:var(--text-heading); margin-bottom:1rem;">🏪 In-Store
              Till &amp; POS Instructions</div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
              <div>
                <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Cash at Till
                  Counter Instructions</label>
                <input id="settingCounterInstructions" type="text"
                  placeholder="e.g. Please proceed to Billing Counter and present this screen to Cashier"
                  style="width:100%;" />
              </div>
              <div>
                <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Card POS
                  Counter Instructions</label>
                <input id="settingCardCounterInstructions" type="text"
                  placeholder="e.g. Please swipe, insert, or tap your card on the store POS terminal."
                  style="width:100%;" />
              </div>
            </div>
          </div>

          <button class="btn btn-primary" style="width:100%; padding:0.75rem;"
            onclick="saveMerchantBrandingAndToggles()">
            💾 Save Selling Mode &amp; Payment Modalities
          </button>
        </div>
      </div>

          <!-- SUB-VIEW 2.4: PAYMENT QR STAND STUDIO -->
      <div id="subViewStoreStand" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🪧 Customized Payment QR Stand Studio &amp; Soundbox</div>
              <div class="card-subtext">Generate custom acrylic stands and smart counter displays. <strong>Accepts payments above ₹2,000</strong> without PhonePe gallery restrictions.</div>
            </div>
            <div style="display:flex; gap:0.5rem;">
              <a href="http://localhost:7000/stand" target="_blank" class="btn btn-secondary">⚡ Open Counter Stand</a>
              <button class="btn btn-primary" onclick="openPrintStandFromAdmin()">🖨️ Print Stand (Ctrl+P)</button>
            </div>
          </div>

          <div style="display:grid; grid-template-columns: minmax(0, 1.2fr) minmax(320px, 1fr); gap:2rem; align-items:start;">
            <!-- Left: Stand Customization Controls -->
            <div>
              <!-- Stand Identification -->
              <div class="settings-group-box">
                <div class="group-box-title">🏷️ 1. Merchant Identity &amp; PhonePe Integration</div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Customer UPI ID / VPA</label>
                    <input id="standInputVpa" type="text" placeholder="e.g. merchant@ybl or 9876543210@ybl" style="width:100%;" oninput="updateLiveStandPreview()" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">PhonePe Registered Mobile Number</label>
                    <input id="standInputMobile" type="tel" placeholder="e.g. 9876543210" style="width:100%;" oninput="updateLiveStandPreview()" />
                  </div>
                </div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Store / Business Name</label>
                    <input id="standInputBusinessName" type="text" placeholder="e.g. Sharma Sweets &amp; Bakers" style="width:100%;" oninput="updateLiveStandPreview()" />
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Payee Display Name</label>
                    <input id="standInputPayeeName" type="text" placeholder="e.g. Sharma Sweets" style="width:100%;" oninput="updateLiveStandPreview()" />
                  </div>
                </div>
              </div>

              <!-- Stand Layout & Appearance -->
              <div class="settings-group-box">
                <div class="group-box-title">🎨 2. Stand Layout &amp; Theme</div>
                <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1rem;">
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Physical Stand Size</label>
                    <select id="standSelectFormat" style="width:100%;" onchange="updateLiveStandPreview()">
                      <option value="table-tent" selected>4" x 6" Acrylic T-Stand (Portrait Table Tent)</option>
                      <option value="counter-stand">5" x 7" Countertop Stand (Large Display)</option>
                      <option value="desk-badge">3.5" x 3.5" Desk Sticker / POS Till Badge</option>
                    </select>
                  </div>
                  <div>
                    <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Primary Accent Color</label>
                    <div style="display:flex; gap:0.5rem; align-items:center;">
                      <input id="standInputColor" type="color" value="#5f259f" style="width:45px; height:38px; padding:2px; border-radius:6px; cursor:pointer;" onchange="document.getElementById('standInputColorText').value=this.value; updateLiveStandPreview()" />
                      <input id="standInputColorText" type="text" value="#5f259f" style="flex:1;" oninput="document.getElementById('standInputColor').value=this.value; updateLiveStandPreview()" />
                    </div>
                  </div>
                </div>
                <div>
                  <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Stand Subtitle / Tagline</label>
                  <input id="standInputTagline" type="text" value="Scan &amp; Pay with Any UPI App" style="width:100%;" oninput="updateLiveStandPreview()" />
                </div>
              </div>

              <!-- Educational Solution Notice Box -->
              <div style="background:rgba(16, 185, 129, 0.08); border:1px solid #10b981; border-radius:8px; padding:1rem; margin-bottom:1.5rem;">
                <div style="font-weight:700; color:#10b981; margin-bottom:0.3rem;">✨ Solution for PhonePe &gt; ₹2,000 Gallery Rejections</div>
                <div style="font-size:0.82rem; color:var(--text); line-height:1.5;">
                  When customers scan this physical stand or the counter screen with their PhonePe camera, NPCI processes it as an in-person present transaction (Camera Scan). This allows the customer to accept payments <strong>above ₹2,000 (up to ₹1,00,000 daily limit)</strong> without any gallery restriction.
                </div>
              </div>

              <!-- Action Buttons -->
              <div style="display:flex; gap:0.75rem; flex-wrap:wrap;">
                <button class="btn btn-primary" onclick="openPrintStandFromAdmin()">🖨️ Print Acrylic Stand (Ctrl+P)</button>
                <button class="btn btn-secondary" onclick="downloadStandSvgFromAdmin()">📥 Download Stand SVG</button>
                <a id="btnOpenDigitalStand" href="http://localhost:7000/stand" target="_blank" class="btn btn-secondary">⚡ Launch Digital Soundbox Stand</a>
              </div>
            </div>

            <!-- Right: Live Stand Mockup Preview -->
            <div>
              <div style="font-size:0.88rem; font-weight:700; margin-bottom:0.75rem; color:var(--text-heading);">Live Stand Artwork Preview</div>
              <div id="standPreviewWrapper" style="background:#ffffff; border-radius:12px; padding:12px; box-shadow:0 10px 25px rgba(0,0,0,0.15); border:1px solid var(--border); max-width:380px; margin:0 auto;">
                <div id="standSvgPreviewContainer" style="width:100%; height:auto;">
                  <!-- Live SVG inserted via JS -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>


    <!-- ========================================================================= -->
    <!-- SECTION 3: DEVELOPER & INFRASTRUCTURE HUB (Merged Control Center)          -->
    <!-- ========================================================================= -->
    <div id="sectionDeveloperHub" hidden>

      <!-- SUB-VIEW: DEVELOPER TOOLS -> PAYMENT SIMULATOR (FEATURE 65) -->
      <div id="subViewDevSimulator" hidden>
        <!-- Header Banner -->
        <div class="card"
          style="border:2px solid var(--primary); background:linear-gradient(135deg, rgba(20,184,166,0.12) 0%, var(--bg-card) 100%); margin-bottom:1.5rem;">
          <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
            <div>
              <div style="display:flex; align-items:center; gap:0.6rem; margin-bottom:0.35rem;">
                <span style="font-size:1.5rem;">🎮</span>
                <h2 style="margin:0; font-size:1.35rem; color:var(--text-heading); font-weight:800;">Developer Tools → Payment
                  Simulator</h2>
                <span class="badge"
                  style="background:#0f766e; color:#ffffff; font-size:0.75rem; padding:0.25rem 0.65rem;">DEVELOPER
                  TESTING ONLY</span>
              </div>
              <p
                style="font-size:0.86rem; color:var(--text-muted); margin:0.4rem 0 0 0; max-width:820px; line-height:1.5;">
                Simulate incoming bank SMS and Gmail payment notifications against real checkout sessions.
                The observation enters the <strong>REAL 6-stage verification engine</strong> without shortcuts.
                The real engine decides whether it passes, fails, or triggers fraud detection.
              </p>
            </div>
            <!-- Test Mode Quick Status / Enable -->
            <div
              style="background:var(--bg-surface); border:1px solid var(--border); border-radius:8px; padding:0.75rem 1rem; display:flex; align-items:center; gap:0.75rem;">
              <div style="font-size:0.8rem;">
                <div style="color:var(--text-muted); font-size:0.72rem; text-transform:uppercase;">Test Mode Status</div>
                <strong id="simTestModeStatus" style="color:var(--warning);">Checking...</strong>
              </div>
              <button id="simBtnEnableTestMode" class="btn btn-primary" onclick="simQuickEnableTestMode()"
                style="font-size:0.78rem; padding:0.4rem 0.8rem; background:#f59e0b; border-color:#d97706; color:#0f172a; font-weight:700;">
                Enable Test Mode
              </button>
            </div>
          </div>
        </div>

        <!-- Target Customer & Active Payment Session Card -->
        <div class="card" style="border:1px solid var(--border); background:var(--bg-box); margin-bottom:1.5rem;">
          <div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(320px, 1fr)); gap:1.5rem;">

            <!-- Column 1: Customer Selection -->
            <div>
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem;">
                <strong style="color:var(--text-heading); font-size:0.95rem; display:flex; align-items:center; gap:0.5rem;">
                  <span>👤</span> Target Customer
                </strong>
                <button class="btn btn-secondary" onclick="simFetchCustomers()"
                  style="font-size:0.72rem; padding:0.25rem 0.6rem;">
                  ↻ Reload
                </button>
              </div>
              <div style="margin-bottom:0.75rem;">
                <input type="text" id="simCustomerSearchInput" placeholder="Search customer (Name, Mobile, Email)..."
                  oninput="simFilterCustomers(this.value)"
                  style="width:100%; box-sizing:border-box; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.5rem 0.75rem; border-radius:6px; font-size:0.84rem;" />
              </div>
              <select id="simCustomerSelect" size="4" onchange="simSelectCustomer(this.value)"
                style="width:100%; box-sizing:border-box; background:var(--bg-input); color:var(--text-heading); border:1px solid var(--border); border-radius:6px; padding:0.5rem; font-size:0.82rem; min-height:110px;">
                <option value="" disabled selected>Loading existing customers...</option>
              </select>

              <!-- Selected Customer Details -->
              <div id="simSelectedCustomerBox"
                style="margin-top:0.75rem; padding:0.85rem; border-radius:8px; background:var(--bg-surface); border:1px solid var(--border); display:none;">
                <div style="font-size:0.74rem; color:var(--text-muted); text-transform:uppercase; margin-bottom:0.25rem;">Selected
                  Customer</div>
                <div style="display:flex; justify-content:space-between; align-items:baseline;">
                  <strong id="simCustName" style="color:var(--text-heading); font-size:1rem;">-</strong>
                  <span id="simCustPhone" style="color:var(--info); font-family:monospace; font-size:0.84rem;">-</span>
                </div>
                <div id="simCustEmail" style="color:var(--text-muted); font-size:0.8rem; margin-top:0.2rem;">-</div>
              </div>
            </div>

            <!-- Column 2: Active Payment Session Selection -->
            <div>
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem;">
                <strong style="color:var(--text-heading); font-size:0.95rem; display:flex; align-items:center; gap:0.5rem;">
                  <span>💳</span> Active Payment Sessions
                </strong>
                <button class="btn btn-secondary" onclick="simReloadSessions()"
                  style="font-size:0.72rem; padding:0.25rem 0.6rem;">
                  ↻ Refresh Sessions
                </button>
              </div>
              <div id="simSessionsList"
                style="min-height:160px; max-height:220px; overflow-y:auto; background:var(--bg-input); border:1px solid var(--border); border-radius:6px; padding:0.5rem;">
                <div style="color:var(--text-muted); font-size:0.82rem; text-align:center; padding:2rem 1rem;">
                  Please select a customer on the left to inspect their active payment sessions.
                </div>
              </div>

              <!-- Terminal Session Notice (Requirement 6) -->
              <div id="simTerminalNotice"
                style="display:none; margin-top:0.75rem; padding:0.75rem 1rem; border-radius:8px; background:rgba(239,68,68,0.15); border:1px solid #ef4444; color:var(--danger); font-size:0.84rem; font-weight:700;">
                ⚠️ SESSION NO LONGER ACTIVE — Observation injection disabled for terminal sessions.
              </div>

              <!-- Selected Session Details Bar -->
              <div id="simSelectedSessionBar"
                style="display:none; margin-top:0.75rem; padding:0.75rem 1rem; border-radius:8px; background:var(--bg-surface); border:1px solid var(--primary); display:flex; justify-content:space-between; align-items:center;">
                <div>
                  <span style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase;">Target Session</span>
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-top:0.15rem;">
                    <strong id="simSelectedSessionId"
                      style="color:var(--info); font-family:monospace; font-size:0.84rem;">-</strong>
                    <span id="simSelectedSessionOrder" style="color:var(--text-heading); font-size:0.82rem;">-</span>
                  </div>
                </div>
                <div style="text-align:right;">
                  <div id="simSelectedSessionAmount" style="color:var(--success); font-weight:800; font-size:1.05rem;">-</div>
                  <span id="simSelectedSessionBadge" class="badge"
                    style="font-size:0.7rem; padding:0.2rem 0.5rem; background:#22c55e; color:#0f172a;">ACTIVE</span>
                </div>
              </div>
            </div>

          </div>
        </div>

        <!-- Two Independent Streams: SMS & Gmail (Section 8-15) -->
        <div
          style="display:grid; grid-template-columns:repeat(auto-fit, minmax(360px, 1fr)); gap:1.5rem; margin-bottom:1.5rem;">

          <!-- SMS STREAM PANEL -->
          <div class="card" style="border:1px solid var(--primary); background:var(--bg-box);">
            <div
              style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
              <strong style="color:var(--info); font-size:1.05rem; display:flex; align-items:center; gap:0.5rem;">
                <span>📱</span> SMS STREAM
              </strong>
              <span style="font-size:0.74rem; color:var(--text-muted);">100% Customizable · Any String</span>
            </div>

            <div style="margin-bottom:1rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                Sender / Short Code
              </label>
              <input type="text" id="simSmsSender" value="HDFCBK"
                placeholder="e.g. HDFCBK, AXISBK, SBIN, arbitrary string..."
                style="width:100%; box-sizing:border-box; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.5rem 0.75rem; border-radius:6px; font-size:0.84rem; font-family:monospace;" />
            </div>

            <div style="margin-bottom:1rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                SMS Content (Free-Form Raw Text)
              </label>
              <textarea id="simSmsContent" rows="4"
                placeholder="e.g. A/C XX1234 credited with Rs 499.00 CR. Ref 123456789012"
                style="width:100%; box-sizing:border-box; background:var(--bg-input); color:var(--text-heading); border:1px solid var(--border); border-radius:6px; padding:0.75rem; font-size:0.84rem; font-family:monospace; resize:vertical;"></textarea>
              <div style="font-size:0.72rem; color:var(--text-muted); margin-top:0.25rem;">Exact text preserved verbatim as
                <code>raw</code>.
              </div>
            </div>

            <div style="margin-bottom:1.25rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                Received Time
              </label>
              <div style="display:flex; gap:0.5rem; margin-bottom:0.4rem;">
                <select id="simSmsTimeType" onchange="simToggleTimeInput('SMS')"
                  style="background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.4rem 0.65rem; border-radius:6px; font-size:0.82rem;">
                  <option value="CURRENT">Current Server Time</option>
                  <option value="CUSTOM">Custom Timestamp</option>
                </select>
              </div>
              <input type="text" id="simSmsCustomTime"
                placeholder="YYYY-MM-DDTHH:mm:ss.sssZ (e.g. 2026-10-04T11:45:21Z)"
                style="display:none; width:100%; box-sizing:border-box; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.45rem 0.75rem; border-radius:6px; font-size:0.82rem; font-family:monospace;" />
            </div>

            <button id="simBtnPushSms" class="btn btn-primary" onclick="simInjectObservation('SMS')"
              style="width:100%; background:#0f766e; border-color:#0b5f58; padding:0.65rem; font-size:0.92rem; font-weight:800; display:flex; justify-content:center; align-items:center; gap:0.5rem;">
              <span>🚀</span> PUSH SMS TO STREAM
            </button>
          </div>

          <!-- GMAIL STREAM PANEL -->
          <div class="card" style="border:1px solid #ec4899; background:var(--bg-box);">
            <div
              style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
              <strong style="color:#f472b6; font-size:1.05rem; display:flex; align-items:center; gap:0.5rem;">
                <span>✉️</span> GMAIL STREAM
              </strong>
              <span style="font-size:0.74rem; color:var(--text-muted);">100% Customizable · Any String</span>
            </div>

            <div style="margin-bottom:1rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                Sender Email Address
              </label>
              <input type="text" id="simGmailSender" value="[email protected]"
                placeholder="e.g. [email protected], [email protected], arbitrary email..."
                style="width:100%; box-sizing:border-box; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.5rem 0.75rem; border-radius:6px; font-size:0.84rem; font-family:monospace;" />
            </div>

            <div style="margin-bottom:1rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                Gmail Content (Free-Form Raw Text)
              </label>
              <textarea id="simGmailContent" rows="4"
                placeholder="e.g. Your account has been credited with ₹499.00 via UPI. Reference 123456789012."
                style="width:100%; box-sizing:border-box; background:var(--bg-input); color:var(--text-heading); border:1px solid var(--border); border-radius:6px; padding:0.75rem; font-size:0.84rem; font-family:monospace; resize:vertical;"></textarea>
              <div style="font-size:0.72rem; color:var(--text-muted); margin-top:0.25rem;">Exact text preserved verbatim as
                <code>raw</code>.
              </div>
            </div>

            <div style="margin-bottom:1.25rem;">
              <label style="display:block; font-size:0.8rem; color:var(--text-muted); margin-bottom:0.35rem; font-weight:600;">
                Received Time
              </label>
              <div style="display:flex; gap:0.5rem; margin-bottom:0.4rem;">
                <select id="simGmailTimeType" onchange="simToggleTimeInput('GMAIL')"
                  style="background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.4rem 0.65rem; border-radius:6px; font-size:0.82rem;">
                  <option value="CURRENT">Current Server Time</option>
                  <option value="CUSTOM">Custom Timestamp</option>
                </select>
              </div>
              <input type="text" id="simGmailCustomTime"
                placeholder="YYYY-MM-DDTHH:mm:ss.sssZ (e.g. 2026-10-04T11:45:21Z)"
                style="display:none; width:100%; box-sizing:border-box; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.45rem 0.75rem; border-radius:6px; font-size:0.82rem; font-family:monospace;" />
            </div>

            <button id="simBtnPushGmail" class="btn btn-primary" onclick="simInjectObservation('GMAIL')"
              style="width:100%; background:#db2777; border-color:#be185d; padding:0.65rem; font-size:0.92rem; font-weight:800; display:flex; justify-content:center; align-items:center; gap:0.5rem;">
              <span>🚀</span> PUSH GMAIL TO STREAM
            </button>
          </div>

        </div>

        <!-- PROCESSING RESULT INSPECTOR (Section 21 & 22) -->
        <div id="simResultInspectorCard" class="card"
          style="display:none; border:1px solid var(--border); background:var(--bg-input); margin-bottom:1.5rem;">
          <div
            style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; flex-wrap:wrap; gap:0.5rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
            <div style="display:flex; align-items:center; gap:0.75rem;">
              <span style="font-size:1.3rem;">🔬</span>
              <h3 style="margin:0; font-size:1.15rem; color:var(--text-heading); font-weight:800;">Processing Result Inspector</h3>
              <span id="simResultStatusBadge" class="badge"
                style="font-size:0.82rem; padding:0.3rem 0.75rem;">UNKNOWN</span>
            </div>
            <div id="simResultMessageId" style="font-size:0.78rem; color:var(--text-muted); font-family:monospace;"></div>
          </div>

          <!-- Target & Extracted Fields Grid -->
          <div
            style="display:grid; grid-template-columns:repeat(auto-fit, minmax(160px, 1fr)); gap:0.75rem; margin-bottom:1.25rem;">
            <div style="background:var(--bg-box); padding:0.65rem 0.85rem; border-radius:6px; border:1px solid var(--border);">
              <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Target Session</div>
              <div id="simResTargetSession"
                style="font-weight:700; color:var(--text-heading); font-size:0.85rem; font-family:monospace;">None</div>
            </div>
            <div style="background:var(--bg-box); padding:0.65rem 0.85rem; border-radius:6px; border:1px solid var(--border);">
              <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Source</div>
              <div id="simResSource" style="font-weight:700; color:var(--text-heading); font-size:0.85rem;">-</div>
            </div>
            <div style="background:var(--bg-box); padding:0.65rem 0.85rem; border-radius:6px; border:1px solid var(--border);">
              <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Amount</div>
              <div id="simResAmount" style="font-weight:700; color:var(--info); font-size:0.95rem;">-</div>
            </div>
            <div style="background:var(--bg-box); padding:0.65rem 0.85rem; border-radius:6px; border:1px solid var(--border);">
              <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Reference / UTR</div>
              <div id="simResRef" style="font-weight:700; color:var(--text-heading); font-size:0.82rem; font-family:monospace;">-
              </div>
            </div>
            <div style="background:var(--bg-box); padding:0.65rem 0.85rem; border-radius:6px; border:1px solid var(--border);">
              <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Failing Reason</div>
              <div id="simResReason" style="font-weight:700; color:var(--danger); font-size:0.82rem;">None</div>
            </div>
          </div>

          <!-- 6-Stage Execution Visualizer -->
          <div
            style="font-size:0.8rem; font-weight:700; color:var(--text-muted); margin-bottom:0.75rem; text-transform:uppercase; letter-spacing:0.04em;">
            Pipeline Stage Inspection (Stages 1 – 6)
          </div>
          <div id="simStagesContainer" style="display:flex; flex-direction:column; gap:0.5rem; margin-bottom:1rem;">
            <!-- Injected via JavaScript -->
          </div>

          <!-- Raw Text Verbatim -->
          <div style="background:var(--bg-box); padding:0.75rem 1rem; border-radius:6px; border:1px solid var(--border);">
            <div style="font-size:0.72rem; color:var(--text-muted); text-transform:uppercase; margin-bottom:0.25rem;">Exact Raw
              Payload (Preserved)</div>
            <pre id="simResRawText"
              style="margin:0; font-size:0.8rem; color:var(--text); font-family:monospace; white-space:pre-wrap; word-break:break-all;"></pre>
          </div>
        </div>

        <!-- SIMULATION HISTORY (Section 26 & 30) -->
        <div class="card" style="border:1px solid var(--border); background:var(--bg-box);">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.85rem;">
            <strong style="color:var(--text-heading); font-size:0.95rem; display:flex; align-items:center; gap:0.5rem;">
              <span>📜</span> Simulation History
            </strong>
            <button class="btn btn-secondary" onclick="simFetchHistory()"
              style="font-size:0.74rem; padding:0.25rem 0.65rem;">
              ↻ Refresh History
            </button>
          </div>
          <div style="overflow-x:auto;">
            <table style="width:100%; border-collapse:collapse; font-size:0.82rem; text-align:left;">
              <thead>
                <tr
                  style="border-bottom:1px solid var(--border); color:var(--text-muted); font-size:0.74rem; text-transform:uppercase;">
                  <th style="padding:0.6rem 0.75rem;">Timestamp</th>
                  <th style="padding:0.6rem 0.75rem;">Source</th>
                  <th style="padding:0.6rem 0.75rem;">Sender</th>
                  <th style="padding:0.6rem 0.75rem;">Session</th>
                  <th style="padding:0.6rem 0.75rem;">Result</th>
                  <th style="padding:0.6rem 0.75rem;">Message ID</th>
                  <th style="padding:0.6rem 0.75rem;">Reason</th>
                </tr>
              </thead>
              <tbody id="simHistoryTableBody">
                <tr>
                  <td colspan="7" style="padding:1.5rem; text-align:center; color:var(--text-muted);">Loading history...</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

      </div>

      <!-- SUB-VIEW 3.1: MERGED CONTROL CENTER & SYSTEM SUPERVISOR -->
      <div id="subViewDevSupervisor">

        <!-- CONFIRMATION MODAL: ENABLE TEST MODE (SECTION 11J) -->
        <div id="modalEnableTestMode"
          style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.8); z-index:999999; align-items:center; justify-content:center;">
          <div
            style="max-width:480px; width:92%; background:var(--bg-box); border:2px solid #f59e0b; border-radius:12px; padding:1.75rem; box-shadow:0 25px 50px -12px rgba(0,0,0,0.9);">
            <div style="display:flex; align-items:center; gap:0.75rem; margin-bottom:1rem;">
              <span style="font-size:1.8rem;">⚠️</span>
              <h3 style="margin:0; font-size:1.25rem; color:var(--warning); font-weight:800;">Enable Test Mode?</h3>
            </div>
            <p style="color:var(--text-heading); font-size:0.92rem; line-height:1.6; margin-bottom:1.5rem;">
              Test Mode disables automatic banning for 10 minutes and is intended only for development and testing.
            </p>
            <div style="display:flex; justify-content:flex-end; gap:0.75rem;">
              <button class="btn btn-secondary" onclick="closeTestModeModal()"
                style="font-size:0.88rem; padding:0.55rem 1.1rem;">
                Cancel
              </button>
              <button class="btn btn-primary" onclick="confirmEnableTestMode()"
                style="background:#f59e0b; border-color:#d97706; color:#0f172a; font-weight:800; font-size:0.88rem; padding:0.55rem 1.25rem;">
                Enable Test Mode
              </button>
            </div>
          </div>
        </div>

        <!-- DEVELOPER TEST MODE CARD (SECTIONS 11A - 11L) -->
        <div class="card" id="cardDeveloperTestMode"
          style="border:2px solid #f59e0b; background:linear-gradient(135deg, rgba(245,158,11,0.08) 0%, var(--bg-card) 100%); margin-bottom:1.5rem;">
          <!-- Card Header & Autoritative Server Toggle -->
          <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
            <div style="flex:1; min-width:280px;">
              <div style="display:flex; align-items:center; gap:0.6rem; margin-bottom:0.35rem;">
                <span style="font-size:1.35rem;">🧪</span>
                <strong style="font-size:1.15rem; color:var(--text-heading);">Developer Settings → Test Mode</strong>
                <span class="badge" id="testModeBadge"
                  style="font-size:0.75rem; padding:0.25rem 0.65rem; background:var(--bg-elevated); color:var(--text-muted);">[ OFF ] Test
                  Mode</span>
              </div>
              <p
                style="font-size:0.84rem; color:var(--text-muted); margin-top:0.4rem; max-width:760px; line-height:1.5;">
                This mode exists ONLY for development, debugging, QA, and verification-engine testing.
                While active, <strong>AUTOMATIC BAN SYSTEM = DISABLED</strong>.
                Automatically expires after 10 minutes (strictly enforced server-side).
              </p>
              <div
                style="display:flex; align-items:center; gap:0.75rem; margin-top:0.6rem; font-size:0.78rem; color:var(--text-muted); flex-wrap:wrap;">
                <span id="testModeBanStatusText">🛡️ Automatic Ban System: <strong style="color:var(--success);">ENABLED
                    (Normal)</strong></span>
                <span id="testModeCountdownWrap" style="display:none; color:var(--warning); font-weight:700;">⏱ Test Mode
                  Enabled · Remaining time: <span id="testModeTimerVal">10:00</span></span>
              </div>
            </div>
            <div style="display:flex; align-items:center; gap:1rem;">
              <label
                style="display:flex; align-items:center; gap:0.6rem; cursor:pointer; background:#1c1917; padding:0.6rem 1.1rem; border-radius:0.5rem; border:1px solid #d97706;">
                <input type="checkbox" id="toggleTestModeSwitch" onchange="handleTestModeToggle(this)"
                  style="width:20px; height:20px; accent-color:#f59e0b; cursor:pointer;" />
                <span style="font-size:0.88rem; font-weight:700; color:#fef3c7;" id="testModeLabelText">Test Mode</span>
              </label>
            </div>
          </div>

          <!-- Section 11J: Active Warning Banner -->
          <div id="testModeActiveBanner"
            style="display:none; margin-top:1.25rem; padding:1rem; border-radius:8px; background:rgba(245,158,11,0.14); border:1px solid rgba(245,158,11,0.4); color:#fef3c7;">
            <div
              style="display:flex; align-items:center; gap:0.6rem; font-weight:800; font-size:0.95rem; color:var(--warning); margin-bottom:0.25rem;">
              <span>⚠️</span> TEST MODE ACTIVE
            </div>
            <div style="font-size:0.84rem; color:#fed7aa; line-height:1.4;">
              Automatic banning is temporarily disabled. This mode will automatically turn off after 10 minutes.
            </div>
          </div>

          <!-- Section 11C: Test Payment Observation (Visible ONLY when Test Mode is Active) -->
          <div id="sectionTestObservation"
            style="display:none; margin-top:1.5rem; padding-top:1.25rem; border-top:1px solid rgba(245,158,11,0.25);">
            <div
              style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.75rem; margin-bottom:1rem;">
              <div>
                <h4 style="margin:0; font-size:1.05rem; color:var(--text-heading); display:flex; align-items:center; gap:0.5rem;">
                  <span>🎯</span> Test Payment Observation
                </h4>
                <span style="font-size:0.78rem; color:var(--text-muted);">Inject synthetic observations directly into the
                  canonical 6-stage production verification flow.</span>
              </div>
              <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
                <button class="btn btn-secondary" onclick="generateFakeSmsTemplate()"
                  style="font-size:0.8rem; padding:0.4rem 0.85rem; border-color:#d97706; color:var(--warning);">
                  📱 Create Fake SMS
                </button>
                <button class="btn btn-secondary" onclick="generateFakeGmailTemplate()"
                  style="font-size:0.8rem; padding:0.4rem 0.85rem; border-color:#d97706; color:var(--warning);">
                  ✉️ Create Fake Gmail
                </button>
              </div>
            </div>

            <!-- Section 11G: Timestamp Control -->
            <div
              style="background:var(--bg-box); padding:0.85rem; border-radius:8px; border:1px solid var(--border); margin-bottom:1.25rem; display:flex; align-items:center; gap:1rem; flex-wrap:wrap;">
              <span style="font-size:0.82rem; color:var(--text-muted); font-weight:600;">⏱ Test Timestamp Control:</span>
              <select id="selectTestTimestampControl" onchange="handleTestTimestampChange(this.value)"
                style="background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.35rem 0.75rem; border-radius:6px; font-size:0.82rem;">
                <option value="CURRENT">Current Server Timestamp (Normal)</option>
                <option value="BEFORE_SESSION">Message received before session creation (-5 mins)</option>
                <option value="AFTER_EXPIRY">Message received after session expiry (+30 mins)</option>
                <option value="CUSTOM">Custom ISO Timestamp</option>
              </select>
              <input type="text" id="inputCustomTimestamp" placeholder="YYYY-MM-DDTHH:mm:ss.sssZ"
                style="display:none; background:var(--bg-surface); color:var(--text-heading); border:1px solid var(--border-hover); padding:0.35rem 0.75rem; border-radius:6px; font-size:0.82rem; width:220px;" />
            </div>

            <!-- Sections 11D & 11E: Custom SMS & Custom Gmail Testing Grid -->
            <div
              style="display:grid; grid-template-columns:repeat(auto-fit, minmax(320px, 1fr)); gap:1.25rem; margin-bottom:1.5rem;">
              <!-- Custom SMS Input Area (Section 11D) -->
              <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:10px; padding:1.1rem;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.6rem;">
                  <strong style="color:var(--info); font-size:0.92rem; display:flex; align-items:center; gap:0.4rem;">
                    📱 SMS Test Message
                  </strong>
                  <input type="text" id="inputTestSmsSender" placeholder="Sender (e.g. VM-HDFCBK)" value="VM-HDFCBK"
                    style="background:var(--bg-surface); color:var(--text); border:1px solid var(--border); font-size:0.75rem; padding:0.25rem 0.5rem; border-radius:4px; width:130px;" />
                </div>
                <textarea id="inputTestSmsMessage" rows="4"
                  style="width:100%; box-sizing:border-box; background:var(--bg-input); color:var(--text-heading); border:1px solid var(--border); border-radius:6px; padding:0.75rem; font-family:monospace; font-size:0.82rem; resize:vertical;"
                  placeholder="Enter custom SMS content here...&#10;e.g. A/C XX1234 credited by Rs 499.00 CR. Ref 123456789012."></textarea>
                <div style="margin-top:0.75rem; display:flex; justify-content:space-between; align-items:center;">
                  <span style="font-size:0.72rem; color:var(--text-muted);">Preserved verbatim as <code>raw</code></span>
                  <button class="btn btn-primary" id="btnInjectSms" onclick="injectTestMessage('SMS')"
                    style="background:#0f766e; border-color:#0b5f58; font-size:0.82rem; padding:0.45rem 1rem;">
                    🚀 Inject Test SMS
                  </button>
                </div>
              </div>

              <!-- Custom Gmail Input Area (Section 11E) -->
              <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:10px; padding:1.1rem;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.6rem;">
                  <strong style="color:#f472b6; font-size:0.92rem; display:flex; align-items:center; gap:0.4rem;">
                    ✉️ Gmail Test Message
                  </strong>
                  <input type="text" id="inputTestGmailSender" placeholder="Sender (e.g. [email protected])"
                    value="[email protected]"
                    style="background:var(--bg-surface); color:var(--text); border:1px solid var(--border); font-size:0.75rem; padding:0.25rem 0.5rem; border-radius:4px; width:170px;" />
                </div>
                <textarea id="inputTestGmailMessage" rows="4"
                  style="width:100%; box-sizing:border-box; background:var(--bg-input); color:var(--text-heading); border:1px solid var(--border); border-radius:6px; padding:0.75rem; font-family:monospace; font-size:0.82rem; resize:vertical;"
                  placeholder="Enter custom email content here...&#10;e.g. Dear Customer, your account has been credited with INR 499.00 via UPI. UPI Ref No: 123456789012."></textarea>
                <div style="margin-top:0.75rem; display:flex; justify-content:space-between; align-items:center;">
                  <span style="font-size:0.72rem; color:var(--text-muted);">Preserved verbatim as <code>raw</code></span>
                  <button class="btn btn-primary" id="btnInjectGmail" onclick="injectTestMessage('GMAIL')"
                    style="background:#db2777; border-color:#be185d; font-size:0.82rem; padding:0.45rem 1rem;">
                    🚀 Inject Test Gmail
                  </button>
                </div>
              </div>
            </div>

            <!-- Section 11H: Test Results Display Inspector -->
            <div id="testResultContainer"
              style="display:none; background:var(--bg-input); border:1px solid var(--border); border-radius:10px; padding:1.25rem; margin-bottom:1.5rem;">
              <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; flex-wrap:wrap; gap:0.5rem;">
                <div style="display:flex; align-items:center; gap:0.75rem;">
                  <h4 style="margin:0; font-size:1rem; color:var(--text-heading);">🔬 Complete Processing Result</h4>
                  <span id="testResultStatusBadge" class="badge"
                    style="font-size:0.8rem; padding:0.3rem 0.75rem;">UNKNOWN</span>
                </div>
                <div id="testResultMeta" style="font-size:0.8rem; color:var(--text-muted); font-family:monospace;"></div>
              </div>

              <!-- Quick Metrics Summary -->
              <div
                style="display:grid; grid-template-columns:repeat(auto-fit, minmax(130px, 1fr)); gap:0.75rem; margin-bottom:1.25rem;">
                <div style="background:var(--bg-box); padding:0.6rem 0.8rem; border-radius:6px; border:1px solid var(--border);">
                  <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Source</div>
                  <div id="testResultSource" style="font-weight:700; color:var(--text-heading); font-size:0.9rem;">-</div>
                </div>
                <div style="background:var(--bg-box); padding:0.6rem 0.8rem; border-radius:6px; border:1px solid var(--border);">
                  <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Amount</div>
                  <div id="testResultAmount" style="font-weight:700; color:var(--info); font-size:0.9rem;">-</div>
                </div>
                <div style="background:var(--bg-box); padding:0.6rem 0.8rem; border-radius:6px; border:1px solid var(--border);">
                  <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Reference / UTR</div>
                  <div id="testResultRef"
                    style="font-weight:700; color:var(--text-heading); font-size:0.85rem; font-family:monospace;">-</div>
                </div>
                <div style="background:var(--bg-box); padding:0.6rem 0.8rem; border-radius:6px; border:1px solid var(--border);">
                  <div style="font-size:0.7rem; color:var(--text-muted); text-transform:uppercase;">Failing Reason</div>
                  <div id="testResultReason" style="font-weight:700; color:var(--danger); font-size:0.82rem;">None</div>
                </div>
              </div>

              <!-- 6-Stage Execution Visualizer -->
              <div
                style="font-size:0.8rem; font-weight:700; color:var(--text-muted); margin-bottom:0.6rem; text-transform:uppercase;">
                Verification Pipeline Stage Inspection
              </div>
              <div id="testResultStagesList" style="display:flex; flex-direction:column; gap:0.5rem;">
                <!-- Stages injected dynamically -->
              </div>
            </div>

            <!-- Section 11I: Test Mode Audit Log Table -->
            <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:10px; padding:1.1rem;">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem;">
                <strong style="color:var(--text-heading); font-size:0.88rem; display:flex; align-items:center; gap:0.4rem;">
                  📜 Test Mode Audit Log
                </strong>
                <button class="btn btn-secondary" onclick="fetchTestModeAuditLog()"
                  style="font-size:0.72rem; padding:0.25rem 0.6rem;">
                  ↻ Refresh Audit
                </button>
              </div>
              <div style="overflow-x:auto;">
                <table style="width:100%; border-collapse:collapse; font-size:0.78rem; text-align:left;">
                  <thead>
                    <tr style="border-bottom:1px solid var(--border); color:var(--text-muted);">
                      <th style="padding:0.4rem;">Time</th>
                      <th style="padding:0.4rem;">Action / Message ID</th>
                      <th style="padding:0.4rem;">Source</th>
                      <th style="padding:0.4rem;">Result</th>
                      <th style="padding:0.4rem;">Raw Message</th>
                    </tr>
                  </thead>
                  <tbody id="testAuditLogTableBody">
                    <tr>
                      <td colspan="5" style="padding:1rem; text-align:center; color:var(--text-muted);">Loading test audit
                        records...</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

          </div>
        </div>

        <!-- FALSE NARRATIVE DEV SWITCH (FEATURE 65 / DEV TOOLS) -->
        <div class="card"
          style="border:2px solid #8b5cf6; background:linear-gradient(135deg, rgba(139,92,246,0.1) 0%, var(--bg-card) 100%); margin-bottom:1.5rem;">
          <div style="display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:1rem;">
            <div style="flex:1; min-width:280px;">
              <div style="display:flex; align-items:center; gap:0.6rem; margin-bottom:0.35rem;">
                <span style="font-size:1.35rem;">🎭</span>
                <strong style="font-size:1.15rem; color:var(--text-heading);">UPI Server Health: False Narrative Switch</strong>
                <span class="badge badge-info" id="falseNarrativeBadge"
                  style="font-size:0.75rem; padding:0.25rem 0.65rem;">⚪ OFF · REAL SERVER STATUS</span>
              </div>
              <p
                style="font-size:0.84rem; color:var(--text-muted); margin-top:0.4rem; max-width:760px; line-height:1.5;">
                Override the live observer status to test checkout portal behavior under different UPI server health
                scenarios: <strong>Green</strong> (Healthy: Server Is Working), <strong>Yellow</strong> (Degraded: Extra
                processing seconds), or <strong>Red</strong> (Downtime: Server Facing Issues).
                <strong>Automatically turns off after 10 minutes</strong>.
              </p>
              <div
                style="display:flex; align-items:center; gap:0.75rem; margin-top:0.6rem; font-size:0.78rem; color:var(--text-muted); flex-wrap:wrap;">
                <span>⚡ <strong>QR Code Invariant:</strong> The dynamic UPI QR code always loads and displays whether
                  servers are UP, BUSY, or DOWN.</span>
                <span id="falseNarrativeCountdownWrap" style="display:none; color:#c084fc; font-weight:700;">⏱
                  Auto-expiry: <span id="falseNarrativeTimerVal">10:00</span></span>
              </div>
            </div>
            <div style="display:flex; flex-direction:column; gap:0.5rem; align-items:flex-end;">
              <div
                style="font-size:0.75rem; font-weight:700; color:#c4b5fd; text-transform:uppercase; letter-spacing:0.04em;">
                Select Narrative to Test:</div>
              <div style="display:flex; gap:6px; flex-wrap:wrap;">
                <button type="button" id="btnNarrativeGreen" onclick="handleFalseNarrativeSelect('GREEN')"
                  style="background:#064e3b; border:1px solid #059669; color:#6ee7b7; font-size:0.8rem; font-weight:700; padding:6px 12px; border-radius:6px; cursor:pointer; display:inline-flex; align-items:center; gap:5px; transition:all 0.15s;">
                  🟢 Green
                </button>
                <button type="button" id="btnNarrativeYellow" onclick="handleFalseNarrativeSelect('YELLOW')"
                  style="background:#78350f; border:1px solid #d97706; color:#fde68a; font-size:0.8rem; font-weight:700; padding:6px 12px; border-radius:6px; cursor:pointer; display:inline-flex; align-items:center; gap:5px; transition:all 0.15s;">
                  🟡 Yellow
                </button>
                <button type="button" id="btnNarrativeRed" onclick="handleFalseNarrativeSelect('RED')"
                  style="background:#7f1d1d; border:1px solid #dc2626; color:#fca5a5; font-size:0.8rem; font-weight:700; padding:6px 12px; border-radius:6px; cursor:pointer; display:inline-flex; align-items:center; gap:5px; transition:all 0.15s;">
                  🔴 Red
                </button>
                <button type="button" id="btnNarrativeOff" onclick="handleFalseNarrativeSelect('OFF')"
                  style="background:var(--bg-surface); border:1px solid var(--border-hover); color:var(--text); font-size:0.8rem; font-weight:700; padding:6px 12px; border-radius:6px; cursor:pointer; display:inline-flex; align-items:center; gap:5px; transition:all 0.15s;">
                  ⚪ Off (Live)
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- YOUPI SHOWCASE STORE PORT 5000 MASTER TOGGLE CARD -->
        <div class="card"
          style="border:2px solid #38bdf8; background:linear-gradient(135deg, rgba(56,189,248,0.06) 0%, var(--bg-card) 100%);">
          <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
            <div>
              <div style="display:flex; align-items:center; gap:0.6rem;">
                <span style="font-size:1.35rem;">🛍️</span>
                <strong style="font-size:1.15rem; color:var(--text-heading);">YOUPI Showcase Store (Port 5000)</strong>
                <span class="badge" id="cardStoreBadge"
                  style="font-size:0.8rem; padding:0.3rem 0.75rem;">CHECKING...</span>
              </div>
              <p
                style="font-size:0.84rem; color:var(--text-muted); margin-top:0.4rem; max-width:720px; line-height:1.5;">
                Toggle the public YOUPI Showcase Store on or off anytime. When disabled, the Node process is terminated
                and host port <code>5000</code> is freed. When enabled, it launches instantly.
              </p>
            </div>
            <div style="display:flex; align-items:center; gap:0.75rem;">
              <a href="http://localhost:5000" id="btnOpenStoreLink" target="_blank" class="btn btn-secondary"
                style="font-size:0.85rem; padding:0.6rem 1.1rem; text-decoration:none;">
                🌐 Open Store (5000) ↗
              </a>
              <button class="btn btn-primary" id="btnToggleYoupiStore"
                style="font-size:0.88rem; padding:0.65rem 1.4rem;" onclick="toggleYoupiStore()">
                ⚡ Toggle Port 5000
              </button>
            </div>
          </div>
        </div>

        <!-- MANAGED PROCESSES SUPERVISOR TABLE -->
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🖥️ Managed Host Processes (Unified Control Center)</div>
              <div class="card-subtext">Native child process supervisor. Zero external container dependencies. Start,
                stop, or restart any gateway service independently.</div>
            </div>
            <div style="display:flex; gap:0.5rem; align-items:center;">
              <button class="btn btn-success" onclick="startAllServices()">▶ Start All</button>
              <button class="btn btn-danger" onclick="stopAllServices()">⏹ Stop All</button>
              <button class="btn btn-secondary" onclick="loadServices()">🔄 Refresh</button>
            </div>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Service Name &amp; ID</th>
                  <th>Port</th>
                  <th>PID</th>
                  <th>Status</th>
                  <th>Uptime</th>
                  <th>Process Controls</th>
                </tr>
              </thead>
              <tbody id="servicesTableBody">
                <tr>
                  <td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">Loading managed
                    processes...</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- REAL-TIME AGGREGATE TERMINAL LOGS CONSOLE -->
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">📜 Real-Time Aggregate Terminal Console</div>
              <div class="card-subtext">Live SSE stdout/stderr broadcast stream from all active processes.</div>
            </div>
            <div style="display:flex; gap:0.6rem; align-items:center;">
              <select id="logServiceFilter" style="padding:0.4rem 0.75rem; font-size:0.78rem;" onchange="filterLogs()">
                <option value="ALL">All Services</option>
                <option value="payment-api">payment-api (6100)</option>
                <option value="checkout-portal">checkout-portal (7000)</option>
                <option value="merchant-admin">merchant-admin (6001)</option>
                <option value="coin-wallet-store">coin-wallet-store (5000)</option>
                <option value="sms-observer">sms-observer (6002)</option>
                <option value="gmail-observer">gmail-observer (6003)</option>
              </select>
              <button class="btn btn-secondary" style="padding:0.4rem 0.75rem; font-size:0.78rem;"
                onclick="clearLogsConsole()">Clear Console</button>
            </div>
          </div>

          <div class="terminal-container" id="terminalLogWindow">
            <div class="log-line log-system">
              <span class="log-ts">[Ready]</span> Unified Control Center operational. Awaiting log streams...
            </div>
          </div>
        </div>

      </div>

      <!-- SUB-VIEW 3.2: CLOUDFLARE TUNNEL CONFIGURATION (Canonical Single Source of Truth) -->
      <div id="subViewDevCloudflare" hidden>
        <div class="card" id="cardCloudflareConfig">
          <div class="card-header">
            <div>
              <div class="card-heading">☁️ Cloudflare Tunnel Configuration</div>
              <div class="card-subtext">Single canonical production gateway routing. Enter your domain and prefix; all
                routes, local service ports, and dashboard mappings are system-derived.</div>
            </div>
            <span class="badge badge-info" id="envModeDisplayBadge">💻 LOCALHOST MODE</span>
          </div>

          <!-- Mode Segmented Switch -->
          <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem; margin-bottom:1.5rem;">
            <div id="btnEnvLocalhost" onclick="setEnvMode('localhost')"
              style="background:var(--bg-box); border:2px solid #38bdf8; border-radius:0.75rem; padding:1.2rem; cursor:pointer; transition:all 0.2s;">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.4rem;">
                <strong style="font-size:1rem; color:var(--text-heading);">💻 Localhost Mode (Development)</strong>
                <span class="badge badge-primary" id="badgeLocalhostActive">ACTIVE</span>
              </div>
              <p style="font-size:0.8rem; color:var(--text-muted); margin:0; line-height:1.4;">
                Routes API, Checkout, and Observers directly over local developer ports (<code>7000</code>,
                <code>6100</code>, <code>6001</code>, <code>6003</code>, <code>5000</code>).
              </p>
            </div>

            <div id="btnEnvProduction" onclick="setEnvMode('production')"
              style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.75rem; padding:1.2rem; cursor:pointer; transition:all 0.2s;">
              <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.4rem;">
                <strong style="font-size:1rem; color:var(--text-heading);">🌍 Production Mode (Cloudflare Tunnel)</strong>
                <span class="badge badge-success" id="badgeProductionActive" style="display:none;">ACTIVE</span>
              </div>
              <p style="font-size:0.8rem; color:var(--text-muted); margin:0; line-height:1.4;">
                Authoritative production mode using deterministic Cloudflare public hostnames with SSL
                (<code>https://</code>).
              </p>
            </div>
          </div>

          <!-- Cloudflare Configuration Form -->
          <div
            style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.75rem; padding:1.25rem; margin-bottom:1.5rem;">
            <div style="font-size:0.88rem; font-weight:700; color:var(--info); margin-bottom:0.75rem;">☁️ Cloudflare Domain
              &amp; Prefix Setup</div>
            <div
              style="display:grid; grid-template-columns:2fr 1fr 1.3fr; gap:1rem; align-items:flex-end; margin-bottom:1rem;">
              <div>
                <label
                  style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-muted); margin-bottom:0.35rem;">1.
                  Cloudflare Domain</label>
                <input id="settingDomainTld" type="text" placeholder="example.com" value=""
                  oninput="updateCloudflarePreview()" style="width:100%;" />
              </div>
              <div>
                <label
                  style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-muted); margin-bottom:0.35rem;">2.
                  Deployment Prefix</label>
                <input id="settingDomainPrefix" type="text" placeholder="pay" value="pay"
                  oninput="updateCloudflarePreview()" style="width:100%;" />
              </div>
              <div>
                <button class="btn btn-primary" style="width:100%; padding:0.65rem; justify-content:center;"
                  onclick="saveDomainSettings()">💾 SAVE CONFIGURATION</button>
              </div>
            </div>
          </div>

          <!-- GENERATED ROUTES LIST -->
          <div style="margin-bottom:1.5rem;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.75rem;">
              <div>
                <div style="font-size:0.95rem; font-weight:800; color:var(--text-heading);">🛣️ CLOUDFLARE TUNNEL ROUTES</div>
                <div style="font-size:0.78rem; color:var(--text-muted);">Exact routes to create in Cloudflare Dashboard.
                  All ports and roles are system-defined.</div>
              </div>
              <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyAllMappings()">📋 COPY ALL
                MAPPINGS</button>
            </div>
            <div id="cloudflareRoutesContainer" style="display:flex; flex-direction:column; gap:0.75rem;">
              <!-- Dynamically populated route cards -->
            </div>
          </div>

          <!-- CLOUDFLARE DASHBOARD INSTRUCTIONS -->
          <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.75rem; padding:1.25rem;">
            <div style="font-size:0.88rem; font-weight:700; color:var(--info); margin-bottom:0.75rem;">📖 EXACT CLOUDFLARE
              DASHBOARD INSTRUCTIONS</div>
            <div
              style="display:flex; flex-wrap:wrap; align-items:center; gap:0.4rem; margin-bottom:1rem; font-size:0.8rem; font-family:monospace; background:var(--bg-input); padding:0.75rem; border-radius:0.5rem; border:1px solid var(--border);">
              <span style="color:var(--info); font-weight:700;">Cloudflare Dashboard</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Networking</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Tunnels</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Select YOUPI Tunnel</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Routes</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Add route</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Published application</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Enter Hostname</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--info); font-weight:700;">Enter Service URL</span>
              <span style="color:var(--text-muted);">↓</span>
              <span style="color:var(--success); font-weight:bold;">Save</span>
            </div>

            <div style="font-size:0.82rem; color:var(--text-muted); line-height:1.5;">
              <p style="margin:0 0 0.5rem 0;">• <strong>Public Hostname:</strong> The URL users and webhooks access from
                the internet.</p>
              <p style="margin:0 0 0.5rem 0;">• <strong>Service URL:</strong> The local service <code>cloudflared</code>
                forwards incoming traffic to on this host.</p>
              <p style="margin:0 0 0.5rem 0; color:var(--danger);">• <strong>DO NOT EXPOSE:</strong> SMS Observer
                (<code>localhost:6002</code>), Control Center (<code>localhost:8090</code>), and internal database
                endpoints must NEVER be published to Cloudflare.</p>
              <p style="margin:0;">• Android SMS observer connects to <strong>Payment API</strong>
                (<code>pay-api.example.com</code> / <code>6100</code>), not directly to internal observer ports.</p>
            </div>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 3.4: WEBHOOKS & SECURITY SECRETS -->
      <div id="subViewDevWebhooks" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🔑 Merchant API Keys, Webhook Endpoints &amp; Cryptographic Secrets</div>
              <div class="card-subtext">View, copy, or rotate your Publishable Merchant ID (<code>data-youpi-key</code> / <code>X-Merchant-Id</code>), Secret Merchant API Key (<code>X-Merchant-Key</code>), and HMAC-SHA256 Webhook Signing Secret.</div>
            </div>
          </div>

          <div style="display:flex; flex-direction:column; gap:1.25rem;">
            <div>
              <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Merchant ID / Publishable Key (<code>data-youpi-key</code> &amp; <code>X-Merchant-Id</code>)</label>
              <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">
                <input id="settingMerchantId" type="text" readonly
                  style="flex:1; min-width:260px; color:var(--info); font-family:monospace; font-weight:600;" />
                <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingMerchantId', 'Publishable Merchant ID')"
                  style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>
              </div>
              <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Safe to embed in frontend HTML (<code>&lt;script src=".../youpi.js" data-youpi-key="..."&gt;</code>) and pass as <code>X-Merchant-Id</code> in REST API calls.</span>
            </div>

            <div>
              <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Secret Merchant API Key (<code>X-Merchant-Key</code>)</label>
              <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">
                <input id="settingMerchantApiKey" type="text" readonly
                  style="flex:1; min-width:260px; color:var(--success); font-family:monospace; font-weight:600;" />
                <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingMerchantApiKey', 'Merchant API Key')"
                  style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>
                <button type="button" class="btn btn-secondary" onclick="rotateMerchantApiKey()"
                  style="padding:0.55rem 0.9rem; font-size:0.8rem; border-color:var(--info); color:var(--info);">🔄 Generate / Rotate Key</button>
              </div>
              <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Backend-only secret key used to authenticate server-to-server payment creation and status queries via the <code>X-Merchant-Key</code> header.</span>
            </div>

            <div>
              <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Webhook
                Destination URL</label>
              <input id="settingWebhookUrl" type="text" placeholder="https://yourstore.com/api/payment/webhook"
                style="width:100%;" />
              <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Server
                endpoint to receive instant signed transaction status notifications.</span>
            </div>

            <div>
              <label style="display:block; font-size:0.82rem; font-weight:700; margin-bottom:0.35rem;">Webhook Secret
                (HMAC-SHA256 Signing)</label>
              <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">
                <input id="settingWebhookSecret" type="text" readonly
                  style="flex:1; min-width:260px; color:var(--text-muted); font-family:monospace;" />
                <button type="button" class="btn btn-secondary" onclick="copyFieldValue('settingWebhookSecret', 'Webhook Secret')"
                  style="padding:0.55rem 0.9rem; font-size:0.8rem;">📋 Copy</button>
                <button type="button" class="btn btn-secondary" onclick="rotateWebhookSecret()"
                  style="padding:0.55rem 0.9rem; font-size:0.8rem;">🔄 Rotate Secret</button>
              </div>
              <span style="font-size:0.72rem; color:var(--text-muted); display:block; margin-top:0.25rem;">Used to verify <code>X-Gateway-Signature</code> on incoming server-to-server webhooks. Keep strictly on your backend.</span>
            </div>

            <button class="btn btn-primary" style="width:auto; align-self:flex-start;"
              onclick="saveMerchantBrandingAndToggles()">
              💾 Save Webhook Settings
            </button>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 3.5: ANDROID OBSERVER GATEWAY -->
      <div id="subViewDevAndroid" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">📱 Android SMS Companion App &amp; Device Pairing</div>
              <div class="card-subtext">Install the APK on your bank-linked phone and scan the pairing QR code to
                auto-forward incoming bank credit SMS.</div>
            </div>
            <span class="badge badge-info" id="smsDevBadge">STANDBY</span>
          </div>

          <div
            style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.75rem; padding:1.25rem; text-align:center; margin-bottom:1.5rem;">
            <div style="font-size:0.85rem; font-weight:800; color:var(--text); margin-bottom:0.75rem;">1. Scan to Pair Phone
            </div>
            <div id="smsPairQrBox"
              style="width:240px; height:240px; margin:0 auto; background:var(--bg-card); border-radius:0.75rem; padding:12px; display:flex; align-items:center; justify-content:center; box-shadow:0 4px 16px rgba(0,0,0,0.5);">
              Loading Pairing QR...
            </div>
            <div style="font-size:0.8rem; color:var(--text-muted); margin:0.75rem 0;">
              Enrollment Secret: <code id="smsTokenVal2" style="color:var(--info); font-weight:700;">Loading...</code>
              <button class="btn btn-secondary" style="font-size:0.7rem; padding:0.2rem 0.5rem; margin-left:0.5rem;"
                onclick="copySmsToken()">📋 Copy</button>
            </div>
            <div style="display:flex; justify-content:center; gap:0.5rem;">
              <button class="btn btn-secondary" onclick="fetchSmsPairQr()">🔄 Refresh QR</button>
              <a class="btn btn-success" href="/youpi-sms-gateway.apk" download="youpi-sms-gateway.apk">📲 Download
                Android APK</a>
            </div>
          </div>

          <div style="margin-bottom:1.5rem;">
            <div style="font-size:0.88rem; font-weight:700; color:var(--text-heading); margin-bottom:0.5rem;">Paired Mobile
              Observers</div>
            <div style="overflow-x:auto;">
              <table>
                <thead>
                  <tr>
                    <th>Device Name</th>
                    <th>Device ID</th>
                    <th>Paired At</th>
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody id="smsDevicesTableBody">
                  <tr>
                    <td colspan="4" style="text-align:center; color:var(--text-muted); padding:1rem;">No devices paired
                      yet. Scan QR above to pair.</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Interactive Test Bank SMS Sender -->
          <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.5rem; padding:1rem;">
            <div style="font-size:0.85rem; font-weight:700; color:var(--info); margin-bottom:0.5rem;">🧪 Test Bank SMS
              Parser</div>
            <div style="display:flex; gap:0.5rem; margin-bottom:0.5rem; flex-wrap:wrap;">
              <input type="text" id="testSmsSender" value="HDFCBK" placeholder="Sender (e.g. HDFCBK)"
                style="width:120px;" />
              <input type="text" id="testSmsBody"
                value="Dear Customer, A/C *1234 credited by Rs 500.00 on 30-Sep-26 by UPI/9876543210/REF987654321 - HDFC Bank"
                placeholder="SMS Body" style="flex:1; min-width:240px;" />
              <button class="btn btn-primary" onclick="sendTestBankSms()">Dispatch</button>
            </div>
            <div id="testSmsResult" style="font-size:0.78rem; color:var(--text-muted);"></div>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 3.6: GMAIL API & WHATSAPP PROTOCOLS -->
      <div id="subViewDevProtocols" hidden>
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:1.5rem;">
          <!-- Gmail Direct API -->
          <div class="card" id="gmailObserverCard">
            <div class="card-header">
              <div>
                <div class="card-heading">📧 Google Account & Gmail Direct API</div>
                <div class="card-subtext">Official Google OAuth 2.0 automated observation for real-time UPI credit
                  notifications.</div>
              </div>
              <span class="badge badge-info" id="gmailConfigBadge2">NOT CONFIGURED</span>
            </div>

            <!-- Hero Action Box: Automated One-Click Google Connect -->
            <div id="gmailConnectHeroBox"
              style="background:linear-gradient(135deg, rgba(37,99,235,0.1), var(--bg-card)); border:1px solid rgba(20,184,166,0.3); border-radius:0.75rem; padding:1.25rem; margin-bottom:1.25rem; display:flex; flex-direction:column; gap:0.75rem;">
              <div
                style="display:flex; justify-content:space-between; align-items:flex-start; flex-wrap:wrap; gap:0.75rem;">
                <div style="flex:1; min-width:260px;">
                  <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.25rem;">
                    <span id="gmailHeroStatusDot"
                      style="width:10px; height:10px; border-radius:50%; background:#ef4444; display:inline-block;"></span>
                    <strong id="gmailHeroStatusTitle" style="font-size:0.95rem; color:var(--text-heading);">Google Account
                      Disconnected</strong>
                  </div>
                  <div id="gmailHeroStatusDesc" style="font-size:0.82rem; color:var(--text-muted); line-height:1.4;">
                    Connect your bank-registered Google account with one click. When you click authorize, YouPI PG
                    handles the full OAuth flow, acquires persistent offline credentials, and activates 1-second UPI
                    credit polling.
                  </div>
                </div>

                <!-- Primary Google Action Button -->
                <div style="display:flex; gap:0.5rem; align-items:center;">
                  <button type="button" id="btnGooglePrimaryAuth" class="btn btn-primary"
                    onclick="startAutomatedGoogleAuth()"
                    style="display:inline-flex; align-items:center; gap:0.6rem; padding:0.65rem 1.25rem; font-size:0.9rem; font-weight:700; background:#0f766e; color:#fff; border:none; border-radius:0.5rem; cursor:pointer; box-shadow:0 4px 14px rgba(37,99,235,0.4);">
                    <svg width="18" height="18" viewBox="0 0 24 24">
                      <path fill="#ffffff"
                        d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                      <path fill="#ffffff"
                        d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                      <path fill="#ffffff"
                        d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z" />
                      <path fill="#ffffff"
                        d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z" />
                    </svg>
                    <span id="btnGooglePrimaryAuthLabel">Connect with Google (One-Click)</span>
                  </button>
                  <button type="button" id="btnGoogleDisconnect" class="btn btn-secondary"
                    onclick="disconnectGmailAccount()"
                    style="display:none; font-size:0.8rem; padding:0.65rem 0.9rem; color:var(--danger); border-color:#7f1d1d;">
                    ❌ Disconnect
                  </button>
                </div>
              </div>

              <!-- In-progress banner when popup is active -->
              <div id="gmailAuthInProgressBanner"
                style="display:none; background:rgba(20,184,166,0.15); border:1px solid var(--primary); border-radius:0.4rem; padding:0.6rem 0.85rem; font-size:0.82rem; color:var(--info); align-items:center; gap:0.5rem;">
                <span class="spinner"
                  style="width:14px; height:14px; border:2px solid var(--primary); border-top-color:transparent; border-radius:50%; display:inline-block; animation:spin 1s linear infinite;"></span>
                <span>Google Authorization Window Active. Select your account and grant permissions to complete
                  automatic setup...</span>
              </div>
            </div>

            <!-- Live Connection Status Details -->
            <div
              style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.5rem; padding:0.85rem; margin-bottom:1rem; font-size:0.8rem; display:grid; grid-template-columns:1fr 1fr; gap:0.6rem;">
              <div><span style="color:var(--text-muted);">OAuth Status:</span> <strong id="gmailOAuthStatusText"
                  style="color:var(--danger);">DISCONNECTED</strong></div>
              <div><span style="color:var(--text-muted);">Token Status:</span> <strong id="gmailTokenStatusText"
                  style="color:var(--text-muted);">NOT CONFIGURED</strong></div>
              <div style="grid-column: span 2; display:flex; align-items:center; gap:0.4rem;">
                <span style="color:var(--text-muted);">Connected Account:</span>
                <strong id="gmailConnectedAccountText" style="color:var(--info); font-family:monospace;">No account
                  authorized</strong>
              </div>
              <div><span style="color:var(--text-muted);">Last Successful Poll:</span> <span id="gmailLastPollText"
                  style="color:var(--text-muted);">Never</span></div>
              <div><span style="color:var(--text-muted);">Observer Pipeline:</span> <span id="gmailLastSentText"
                  style="color:var(--text-muted);">Standby</span></div>
            </div>

            <!-- Secondary Actions -->
            <div style="display:flex; gap:0.5rem; flex-wrap:wrap; margin-bottom:0.75rem;">
              <button type="button" class="btn btn-secondary" onclick="testGmailConnection()">🔑 Test Live
                Connection</button>
              <button type="button" class="btn btn-secondary" onclick="startAutomatedGoogleAuth()">🔄 Re-authorize
                Account</button>
              <button type="button" class="btn btn-secondary" onclick="openGmailGuideModal()">📖 Setup Guide</button>
            </div>

            <div id="gmailTestResultBox"
              style="display:none; padding:0.85rem; border-radius:0.5rem; font-size:0.82rem; margin-bottom:1rem;"></div>

            <!-- Advanced Collapsible Configuration -->
            <details
              style="background:var(--bg-surface); border:1px solid var(--border); border-radius:0.5rem; padding:0.6rem 0.85rem;">
              <summary style="cursor:pointer; font-size:0.78rem; font-weight:700; color:var(--text-muted); user-select:none;">
                ⚙️ Advanced OAuth Credentials &amp; Manual Override (Optional)
              </summary>
              <div style="display:flex; flex-direction:column; gap:0.75rem; margin-top:0.85rem;">
                <div>
                  <label
                    style="display:block; font-size:0.75rem; font-weight:700; color:var(--text-muted); margin-bottom:0.2rem;">Google
                    OAuth Client ID</label>
                  <input type="text" id="gmailClientIdInput" placeholder="your-client-id.apps.googleusercontent.com"
                    style="width:100%; font-family:monospace; font-size:0.8rem;" />
                </div>
                <div>
                  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.2rem;">
                    <label style="font-size:0.75rem; font-weight:700; color:var(--text-muted);">Google OAuth Client
                      Secret</label>
                    <button type="button" class="btn btn-secondary" style="font-size:0.68rem; padding:0.1rem 0.4rem;"
                      onclick="toggleSecretVisibility()">👁️ Show/Hide</button>
                  </div>
                  <input type="password" id="gmailClientSecretInput" placeholder="your-google-client-secret"
                    style="width:100%; font-family:monospace; font-size:0.8rem;" />
                </div>
                <div>
                  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.2rem;">
                    <label style="font-size:0.75rem; font-weight:700; color:var(--text-muted);">Exact Authorized
                      Redirect URI</label>
                    <button type="button" class="btn btn-secondary" style="font-size:0.68rem; padding:0.1rem 0.4rem;"
                      onclick="copyGmailRedirectUri()">📋 Copy</button>
                  </div>
                  <input type="text" id="gmailRedirectUriInput" readonly
                    style="width:100%; font-family:monospace; font-size:0.8rem; background:var(--bg-input); color:var(--info);" />
                </div>
                <div>
                  <label
                    style="display:block; font-size:0.75rem; font-weight:700; color:var(--text-muted); margin-bottom:0.2rem;">Google
                    Refresh Token</label>
                  <input type="password" id="gmailRefreshTokenInput" placeholder="your-google-refresh-token"
                    style="width:100%; font-family:monospace; font-size:0.8rem;" />
                </div>
                <div>
                  <button type="button" class="btn btn-primary" style="font-size:0.8rem; padding:0.4rem 0.8rem;"
                    onclick="saveGmailCredentials()">💾 Save Manual Credentials</button>
                </div>
              </div>
            </details>
          </div>

          <!-- WhatsApp Berry Protocol -->
          <div class="card">
            <div class="card-header">
              <div>
                <div class="card-heading">💬 WhatsApp Berry Protocol</div>
                <div class="card-subtext">Automated customer login OTP delivery at checkout.</div>
              </div>
              <span class="badge badge-warning" id="waHeaderBadge">CHECKING...</span>
            </div>

            <div
              style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.75rem; padding:1rem; margin-bottom:1rem;">
              <div id="waLiveStatusDisplay">
                <div style="display:flex; align-items:center; gap:0.5rem; margin-bottom:0.35rem;">
                  <span id="waDotIndicator" style="color:var(--warning);">●</span>
                  <strong id="waStateTitle" style="color:var(--text-heading);">Pairing Standby</strong>
                </div>
                <div id="waPhoneDisplay" style="font-size:0.85rem; color:var(--text-muted); font-family:monospace;">
                  Phone Number: Not Linked
                </div>
              </div>
            </div>

            <div id="waQrBox"
              style="background:var(--bg-card); border-radius:0.75rem; padding:1rem; display:inline-block; margin:0 auto 1rem auto; text-align:center;">
              <div id="waQrPlaceholder"
                style="width:240px; height:240px; display:flex; align-items:center; justify-content:center; color:var(--text-heading); font-size:0.85rem; text-align:center; padding:1rem;">
                Click "Connect / Refresh QR" to pair device
              </div>
              <img id="waQrImg" src="" alt="WhatsApp Pairing QR" style="width:240px; height:240px; display:none; image-rendering:pixelated;" onerror="this.style.display='none'; if(document.getElementById('waQrPlaceholder')){ document.getElementById('waQrPlaceholder').style.display='flex'; document.getElementById('waQrPlaceholder').innerText='QR preview unavailable. Click Refresh QR.'; }" />
            </div>

            <div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
              <button class="btn btn-primary" id="btnWaConnect" onclick="reconnectWhatsApp()">⚡ Connect / Refresh
                QR</button>
              <button class="btn btn-danger" id="btnWaDisconnect" onclick="disconnectWhatsApp()"
                style="display:none;">🔌 Disconnect</button>
              <button class="btn btn-secondary" onclick="fetchWhatsAppStatus(true)">🔄 Check Status</button>
            </div>
          </div>
        </div>
      </div>

    </div>

    <!-- ========================================================================= -->
    <!-- SECTION 4: SECURITY & BAN MANAGEMENT (Sections 4, 5, 6, 7, 9)              -->
    <!-- ========================================================================= -->
    <div id="sectionSecurity" hidden>

      <!-- SUB-VIEW 4.1: BANNED USERS -->
      <div id="subViewSecBanned">
        <div class="card">
          <div class="card-header" style="flex-wrap:wrap; gap:1rem;">
            <div>
              <div class="card-heading">🚫 Banned Customer Identities</div>
              <div class="card-subtext">Server-enforced access blocking. Positive identification of fraudulent payment
                injection or manual administrative bans.</div>
            </div>
            <div style="display:flex; gap:0.5rem; flex-wrap:wrap; align-items:center;">
              <input type="text" id="bannedSearchInput" placeholder="Search by name, email, or phone..."
                style="width:240px; font-size:0.82rem; padding:0.45rem 0.75rem;"
                oninput="filterBannedUsers(this.value)" />
              <button class="btn btn-secondary" onclick="fetchBannedUsers()">🔄 Refresh</button>
              <button class="btn btn-danger" onclick="openManualBanModal()">➕ Ban User</button>
            </div>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Phone</th>
                  <th>Ban Status</th>
                  <th>Ban Timestamp</th>
                  <th>Ban Reason</th>
                  <th>Payment Session</th>
                  <th>Last Device</th>
                  <th>Source</th>
                  <th style="text-align:right;">Actions</th>
                </tr>
              </thead>
              <tbody id="bannedUsersTableBody">
                <tr>
                  <td colspan="10" style="text-align:center; color:var(--text-muted); padding:2rem;">
                    Loading banned users...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 4.2: SECURITY EVENTS -->
      <div id="subViewSecEvents" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">🚨 Security &amp; Forensic Events Log</div>
              <div class="card-subtext">Real-time immutable security event records preserved with exact raw evidence
                verbatim.</div>
            </div>
            <button class="btn btn-secondary" onclick="fetchSecurityEvents()">🔄 Refresh</button>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Timestamp</th>
                  <th>Event Type</th>
                  <th>Customer</th>
                  <th>Source</th>
                  <th>Sender</th>
                  <th>Fraud Reason</th>
                  <th>Raw Evidence (Verbatim)</th>
                  <th style="text-align:right;">Action</th>
                </tr>
              </thead>
              <tbody id="securityEventsTableBody">
                <tr>
                  <td colspan="8" style="text-align:center; color:var(--text-muted); padding:2rem;">
                    Loading security events...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- SUB-VIEW 4.3: BAN HISTORY -->
      <div id="subViewSecHistory" hidden>
        <div class="card">
          <div class="card-header">
            <div>
              <div class="card-heading">📜 Ban &amp; Unban History Audit Trail</div>
              <div class="card-subtext">Historical chronological audit trail of all automatic bans, unbans, manual bans,
                and re-bans.</div>
            </div>
            <button class="btn btn-secondary" onclick="fetchSecurityHistory()">🔄 Refresh</button>
          </div>

          <div style="overflow-x:auto;">
            <table>
              <thead>
                <tr>
                  <th>Timestamp</th>
                  <th>Action</th>
                  <th>Actor</th>
                  <th>Customer Identity</th>
                  <th>Details &amp; Transitions</th>
                </tr>
              </thead>
              <tbody id="securityHistoryTableBody">
                <tr>
                  <td colspan="5" style="text-align:center; color:var(--text-muted); padding:2rem;">
                    Loading ban history...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>

  </main>

  <!-- Gmail Setup Guide Modal (Exact 15-Step Instructions & Refresh Token Guide) -->
  <div id="gmailGuideModal" class="modal-overlay" hidden>
    <div class="modal-box" style="max-width:720px; max-height:85vh; overflow-y:auto;">
      <div
        style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
        <h3 style="color:var(--text-heading); margin:0; font-size:1.15rem;">📖 Official Gmail API &amp; Refresh Token Guide</h3>
        <button class="btn btn-secondary" style="padding:0.25rem 0.5rem;" onclick="closeGmailGuideModal()">✕</button>
      </div>
      <div style="font-size:0.82rem; color:var(--text); line-height:1.6;">

        <div
          style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.5rem; padding:0.75rem 1rem; margin-bottom:1rem;">
          <strong style="color:var(--info); display:block; font-size:0.9rem; margin-bottom:0.25rem;">⚡ How to get your
            Google Refresh Token (Choose either method):</strong>
          <span style="color:var(--text-muted); font-size:0.78rem;">Both methods work 100% reliably. Method 1 is automated
            1-click; Method 2 uses Google's official OAuth Playground.</span>
        </div>

        <div
          style="border:1px solid var(--border); border-radius:0.5rem; padding:0.85rem; margin-bottom:1rem; background:var(--bg-box);">
          <h4 style="color:var(--success); margin:0 0 0.5rem 0; font-size:0.95rem;">Method 1: Direct 1-Click Authorize
            (Automatic)</h4>
          <ol style="padding-left:1.25rem; display:flex; flex-direction:column; gap:0.35rem; margin:0;">
            <li>In <strong>Google Cloud Console</strong> &gt; <em>Credentials</em>, add this exact redirect URI:
              <code
                style="color:var(--info); display:block; margin:0.2rem 0; background:var(--bg-input); padding:2px 6px; border-radius:4px;"
                id="guideProdUri">(loaded from your configured domain)</code>
            </li>
            <li>Under <em>OAuth consent screen</em> &gt; <em>Test users</em>, ensure your personal Gmail address is
              added.</li>
            <li>In YOUPI Admin Panel, enter your <strong>Client ID</strong> and <strong>Client Secret</strong>, then
              click <strong>💾 Save Credentials</strong>.</li>
            <li>Click the <strong>🔗 Authorize OAuth</strong> button. A Google sign-in window will open.</li>
            <li>Log into your Gmail account, grant read-only permissions, and complete consent.</li>
            <li>YOUPI will automatically capture and save the offline refresh token into your database!</li>
          </ol>
        </div>

        <div
          style="border:1px solid var(--border); border-radius:0.5rem; padding:0.85rem; margin-bottom:1rem; background:var(--bg-box);">
          <h4 style="color:var(--info); margin:0 0 0.5rem 0; font-size:0.95rem;">Method 2: Google OAuth 2.0 Playground
            (Manual — 60 Seconds)</h4>
          <ol style="padding-left:1.25rem; display:flex; flex-direction:column; gap:0.35rem; margin:0;">
            <li>Open <a href="https://developers.google.com/oauthplayground" target="_blank"
                style="color:var(--info); text-decoration:underline;">Google OAuth 2.0 Playground
                (developers.google.com/oauthplayground)</a> in a new tab.</li>
            <li>Click the <strong>⚙️ Gear Icon (OAuth 2.0 configuration)</strong> at the top right of the page.</li>
            <li>Check the box: <strong>"Use your own OAuth credentials"</strong>.</li>
            <li>Paste your <strong>OAuth Client ID</strong> and <strong>OAuth Client Secret</strong> into the fields
              that appear.</li>
            <li>In the main left pane under <strong>Step 1: Select &amp; authorize APIs</strong>:
              <div style="margin:0.25rem 0;">Scroll to <strong>Gmail API v1</strong> and check
                <code>https://www.googleapis.com/auth/gmail.readonly</code> (or type it in the text box).
              </div>
            </li>
            <li>Click the blue button: <strong>Authorize APIs</strong>. Sign in to your Google account and click
              <strong>Allow</strong>.
            </li>
            <li>Under <strong>Step 2: Exchange authorization code for tokens</strong>:
              <div style="margin:0.25rem 0;">Click the blue button: <strong>Exchange authorization code for
                  tokens</strong>.</div>
            </li>
            <li>Look at the response pane on the right: copy the <strong>Refresh token</strong> (starts with
              <code>1//...</code>).
            </li>
            <li>Paste the refresh token into the <strong>Google Refresh Token (Offline Access)</strong> box in YOUPI and
              click <strong>💾 Save Credentials</strong>!</li>
          </ol>
        </div>

        <div
          style="background:rgba(245,158,11,0.1); border:1px solid #d97706; border-radius:0.5rem; padding:0.75rem; font-size:0.75rem; color:var(--warning);">
          <strong>⚠️ Google Cloud Console Setup Note:</strong><br>
          Make sure the <strong>Gmail API</strong> is enabled in <em>APIs &amp; Services &gt; Library</em> and the OAuth
          consent screen publishing status is set to "Testing" with your Gmail added as a Test User.
        </div>
      </div>
      <div style="margin-top:1.25rem; text-align:right;">
        <button class="btn btn-primary" onclick="closeGmailGuideModal()">Got It</button>
      </div>
    </div>
  </div>

  <!-- ========================================================================= -->
  <!-- SECURITY & BAN MODALS (Section 9)                                         -->
  <!-- ========================================================================= -->

  <!-- 1. Ban Details Modal (Section 9.2: Complete Evidence & Verbatim Raw Message) -->
  <div id="banDetailsModal" class="modal-overlay" hidden>
    <div class="modal-box"
      style="max-width:850px; max-height:90vh; overflow-y:auto; background:var(--bg-box); border:1px solid var(--border); border-radius:12px; padding:1.75rem; box-shadow:0 25px 50px -12px rgba(0,0,0,0.7);">
      <div
        style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1.25rem; border-bottom:1px solid var(--border); padding-bottom:1rem;">
        <div style="display:flex; align-items:center; gap:0.6rem;">
          <span style="font-size:1.5rem;">🚨</span>
          <div>
            <h3 style="color:var(--danger); margin:0; font-size:1.25rem; font-weight:800; letter-spacing:-0.02em;">Forensic
              Security &amp; Ban Evidence Dossier</h3>
            <div style="color:var(--text-muted); font-size:0.78rem;">Immutable tamper-proof record of fraudulent payment injection
              attempt</div>
          </div>
        </div>
        <button class="btn btn-secondary" style="padding:0.35rem 0.65rem;" onclick="closeBanDetailsModal()">✕</button>
      </div>

      <div id="banDetailsModalBody">
        <div style="text-align:center; padding:2rem; color:var(--text-muted);">Loading ban evidence...</div>
      </div>

      <div
        style="margin-top:1.5rem; display:flex; justify-content:space-between; align-items:center; border-top:1px solid var(--border); padding-top:1rem;">
        <div style="font-size:0.75rem; color:var(--text-muted);">Security Engine v2 &bull; {{APP_NAME}}</div>
        <div style="display:flex; gap:0.75rem;">
          <button class="btn btn-secondary" onclick="closeBanDetailsModal()">Close</button>
          <button id="btnModalUnbanTrigger" class="btn btn-success"
            style="background:#059669; border-color:#059669; font-weight:700;" onclick="handleModalUnbanClick()">🔓
            Unban Customer</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 2. Unban Confirmation Modal (Section 9.3) -->
  <div id="unbanConfirmModal" class="modal-overlay" hidden>
    <div class="modal-box"
      style="max-width:540px; background:var(--bg-box); border:1px solid var(--border); border-radius:12px; padding:1.75rem;">
      <div
        style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
        <h3 style="color:var(--success); margin:0; display:flex; align-items:center; gap:0.5rem; font-size:1.15rem;">
          <span>🔓</span> Restore Customer Access (Unban)
        </h3>
        <button class="btn btn-secondary" style="padding:0.25rem 0.5rem;" onclick="closeUnbanModal()">✕</button>
      </div>

      <p style="font-size:0.88rem; color:var(--text); line-height:1.6; margin-bottom:1.25rem;">
        Are you sure you want to unban customer <strong id="unbanCustName" style="color:var(--text-heading);"></strong> (<span
          id="unbanCustPhone" style="color:var(--info); font-family:monospace;"></span>)?
        <br><span style="color:var(--text-muted); font-size:0.8rem; display:block; margin-top:0.4rem;">This will restore their
          status to <strong style="color:var(--success);">ACTIVE</strong> and immediately restore their ability to initiate
          payments on the gateway.</span>
      </p>

      <div style="margin-bottom:1.25rem;">
        <label style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-heading); margin-bottom:0.4rem;">
          Mandatory Reason for Unbanning <span style="color:var(--danger);">*</span>
        </label>
        <select id="unbanReasonSelect" class="form-control"
          style="width:100%; margin-bottom:0.5rem; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem;"
          onchange="handleUnbanReasonChange()">
          <option value="Customer verified via phone call">Customer verified via phone call</option>
          <option value="False positive investigated">False positive investigated</option>
          <option value="Testing override">Testing override</option>
          <option value="Dispute resolved with merchant">Dispute resolved with merchant</option>
          <option value="OTHER">Other custom reason...</option>
        </select>
        <input type="text" id="unbanReasonCustom" placeholder="Specify mandatory custom unban reason..."
          style="width:100%; display:none; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem;">
      </div>

      <div
        style="display:flex; justify-content:flex-end; gap:0.75rem; margin-top:1.5rem; border-top:1px solid var(--border); padding-top:1rem;">
        <button class="btn btn-secondary" onclick="closeUnbanModal()">Cancel</button>
        <button id="btnConfirmUnbanAction" class="btn btn-success"
          style="background:#059669; border-color:#059669; font-weight:700;" onclick="executeUnbanCustomer()">Confirm
          Unban</button>
      </div>
    </div>
  </div>

  <!-- 3. Manual Ban Modal (Section 9.4) -->
  <div id="manualBanModal" class="modal-overlay" hidden>
    <div class="modal-box"
      style="max-width:560px; background:var(--bg-box); border:1px solid var(--border); border-radius:12px; padding:1.75rem;">
      <div
        style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
        <h3 style="color:var(--danger); margin:0; display:flex; align-items:center; gap:0.5rem; font-size:1.15rem;">
          <span>🚫</span> Manually Ban Abusive Customer
        </h3>
        <button class="btn btn-secondary" style="padding:0.25rem 0.5rem;" onclick="closeManualBanModal()">✕</button>
      </div>

      <div style="margin-bottom:1rem;">
        <label style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-heading); margin-bottom:0.4rem;">
          Select Customer <span style="color:var(--danger);">*</span>
        </label>
        <select id="manualBanCustomerSelect"
          style="width:100%; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem;"
          onchange="handleManualBanCustomerChange()">
          <option value="">-- Choose Existing Customer --</option>
        </select>
      </div>

      <div id="manualBanCustomInputs" style="margin-bottom:1rem;">
        <label style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-heading); margin-bottom:0.4rem;">
          Or Enter Customer ID / Phone / Email
        </label>
        <input type="text" id="manualBanCustomerIdInput" placeholder="Customer UUID, mobile (+91...), or email"
          style="width:100%; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem;">
      </div>

      <div style="margin-bottom:1rem;">
        <label style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-heading); margin-bottom:0.4rem;">
          Mandatory Reason <span style="color:var(--danger);">*</span>
        </label>
        <input type="text" id="manualBanReasonInput" value="MANUAL_BAN"
          placeholder="e.g. Abusive behavior, chargeback dispute, manual fraud notice"
          style="width:100%; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem;">
      </div>

      <div style="margin-bottom:1.25rem;">
        <label style="display:block; font-size:0.8rem; font-weight:700; color:var(--text-heading); margin-bottom:0.4rem;">
          Optional Notes / Investigation Details
        </label>
        <textarea id="manualBanNotesInput" rows="3"
          placeholder="Additional merchant operator notes, reference ticket, etc."
          style="width:100%; background:var(--bg-input); border:1px solid var(--border); color:var(--text-heading); border-radius:6px; padding:0.55rem; font-size:0.85rem; resize:vertical;"></textarea>
      </div>

      <div style="display:flex; justify-content:flex-end; gap:0.75rem; border-top:1px solid var(--border); padding-top:1rem;">
        <button class="btn btn-secondary" onclick="closeManualBanModal()">Cancel</button>
        <button class="btn btn-danger" style="background:#dc2626; border-color:#dc2626; font-weight:700;"
          onclick="executeManualBan()">Confirm Ban</button>
      </div>
    </div>
  </div>

  <!-- Modal: Create / Onboard New Merchant -->
  <div id="newMerchantModal" class="modal-overlay" hidden>
    <div class="modal-box" style="max-width:540px;">
      <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; border-bottom:1px solid var(--border); padding-bottom:0.75rem;">
        <h3 style="color:var(--text-heading); margin:0; font-size:1.15rem;">🏪 Onboard New Merchant / Store</h3>
        <button class="btn btn-secondary" style="padding:0.25rem 0.5rem;" onclick="closeNewMerchantModal()">✕</button>
      </div>
      <div style="font-size:0.85rem; color:var(--text); line-height:1.6;">
        <div style="margin-bottom:1rem;">
          <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">Store / Business Name *</label>
          <input id="modalMerchantName" type="text" placeholder="e.g. Acme Supermart or Apex Retail" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" oninput="syncModalSlug(this.value)" />
        </div>
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem; margin-bottom:1rem;">
          <div>
            <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">Merchant Slug</label>
            <input id="modalMerchantSlug" type="text" placeholder="acme-supermart" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" />
          </div>
          <div>
            <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">UPI ID / VPA</label>
            <input id="modalMerchantVpa" type="text" placeholder="e.g. acme@okhdfcbank" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" />
          </div>
        </div>
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem; margin-bottom:1rem;">
          <div>
            <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">Contact Email</label>
            <input id="modalMerchantEmail" type="email" placeholder="[email protected]" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" />
          </div>
          <div>
            <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">Contact Phone</label>
            <input id="modalMerchantPhone" type="tel" placeholder="9876543210" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" />
          </div>
        </div>
        <div style="margin-bottom:1.25rem;">
          <label style="display:block; font-size:0.82rem; font-weight:700; color:var(--text-heading); margin-bottom:0.35rem;">Webhook Notification URL (Optional)</label>
          <input id="modalMerchantWebhook" type="url" placeholder="https://acme.com/api/webhook" style="width:100%; background:var(--bg-input); border:1px solid var(--border-hover); color:var(--text); border-radius:6px; padding:0.55rem; font-size:0.85rem;" />
        </div>
        <div style="display:flex; justify-content:flex-end; gap:0.75rem; border-top:1px solid var(--border); padding-top:1rem;">
          <button type="button" class="btn btn-secondary" onclick="closeNewMerchantModal()">Cancel</button>
          <button type="button" class="btn btn-primary" onclick="submitNewMerchant()">Create Merchant</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Global Cashier Floating Dock -->
  <div id="cashierFloatingDock" class="cashier-floating-dock"></div>

  <script>
    /* Emoji -> Heroicons (outline, 24px) swap. Sprite lives at the top of <body>.
       Runs once on load and on every DOM change, so JS-rendered text is covered too.
       Coloured circles become CSS dots (status state), not icons. */
    (function () {
      const MAP = {
        '🛡': 'shield-check', '☀': 'sun', '🌙': 'moon', '💻': 'computer-desktop', '🏪': 'building-storefront',
        '⚙': 'cog-6-tooth', '🛠': 'wrench-screwdriver', '⏳': 'clock', '⏱': 'clock', '⚠': 'exclamation-triangle',
        '📦': 'archive-box', '💳': 'credit-card', '📡': 'signal', '📱': 'device-phone-mobile', '📋': 'clipboard-document',
        '📲': 'arrow-down-tray', '📧': 'envelope', '✉': 'envelope', '🎨': 'swatch', '🏷': 'tag', '⚡': 'bolt',
        '👤': 'user', '🛒': 'shopping-cart', '🛍': 'shopping-bag', '➕': 'plus', '🌐': 'globe-alt',
        '🌍': 'globe-europe-africa', '🏬': 'building-office-2', '🎮': 'play-circle', '🖥': 'server-stack',
        '📜': 'document-text', '🚀': 'rocket-launch', '🔬': 'beaker', '🧪': 'beaker', '🎯': 'viewfinder-circle',
        '🎭': 'sparkles', '🎉': 'sparkles', '☁': 'cloud', '🛣': 'map', '🔐': 'lock-closed', '🔓': 'lock-open',
        '🔑': 'key', '🔗': 'link', '🔌': 'bolt-slash', '📖': 'book-open', '🔄': 'arrow-path', '↻': 'arrow-path',
        '💾': 'arrow-down-on-square', '💵': 'banknotes', '🚨': 'bell-alert', '🔔': 'bell', '🚫': 'no-symbol',
        '❌': 'x-circle', '✅': 'check-circle', '❓': 'question-mark-circle', '👁': 'eye', '🔍': 'magnifying-glass',
        '📞': 'phone', '💬': 'chat-bubble-left-right', '📊': 'chart-bar', '⚖': 'scale', 
        '✓': 'check', '✕': 'x-mark', '↗': 'arrow-top-right-on-square', '↓': 'arrow-down', '→': 'arrow-right',
        '▶': 'play', '⏹': 'stop', '▲': 'chevron-up',
        '🔴': 'dot-red', '🟢': 'dot-green', '🟡': 'dot-yellow', '🔵': 'dot-blue', '🟣': 'dot-purple',
        '⚫': 'dot-black', '⚪': 'dot-off'
      };
      const esc = k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      const RE = new RegExp('(' + Object.keys(MAP).sort((a, b) => b.length - a.length).map(esc).join('|') + ')\\uFE0F?', 'g');
      const SKIP = new Set(['SCRIPT', 'STYLE', 'TEXTAREA', 'SYMBOL']);
      const NS = 'http://www.w3.org/2000/svg';

      function node(name) {
        if (name.startsWith('dot-')) {
          const d = document.createElement('span');
          d.className = 'dot ' + name;
          return d;
        }
        const svg = document.createElementNS(NS, 'svg');
        svg.setAttribute('class', 'i');
        svg.setAttribute('aria-hidden', 'true');
        const use = document.createElementNS(NS, 'use');
        use.setAttribute('href', '#i-' + name);
        svg.appendChild(use);
        return svg;
      }

      function swapText(t) {
        const p = t.parentNode;
        if (!p || SKIP.has(p.nodeName) || !RE.test(t.nodeValue)) { RE.lastIndex = 0; return; }
        RE.lastIndex = 0;
        if (p.nodeName === 'OPTION') { t.nodeValue = t.nodeValue.replace(RE, '').replace(/^\s+/, ''); return; }
        const frag = document.createDocumentFragment();
        const s = t.nodeValue;
        let last = 0, m;
        while ((m = RE.exec(s))) {
          if (m.index > last) frag.appendChild(document.createTextNode(s.slice(last, m.index)));
          frag.appendChild(node(MAP[m[1]]));
          last = m.index + m[0].length;
        }
        if (last < s.length) frag.appendChild(document.createTextNode(s.slice(last)));
        p.replaceChild(frag, t);
      }

      function walk(root) {
        if (root.nodeType === 3) return swapText(root);
        if (root.nodeType !== 1 || SKIP.has(root.nodeName)) return;
        const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
        const hits = [];
        while (w.nextNode()) hits.push(w.currentNode);
        hits.forEach(swapText);
      }

      walk(document.body);
      new MutationObserver(muts => {
        for (const m of muts) {
          if (m.type === 'characterData') swapText(m.target);
          else m.addedNodes.forEach(walk);
        }
      }).observe(document.body, { childList: true, subtree: true, characterData: true });
    })();
  </script>

  <script>
    // --- Admin API authentication ---------------------------------------------------------
    // /api/v1/admin/* requires the admin token (ADMIN_API_TOKEN, or the generated file
    // data/.secrets/admin_api_token on the server). It is kept in sessionStorage for this tab only.
    window.__youpiAdminAuth = (function () {
      const KEY = 'youpi_admin_token';
      const nativeFetch = window.fetch.bind(window);
      let pending = null;

      const read = () => { try { return sessionStorage.getItem(KEY) || ''; } catch (e) { return ''; } };
      const write = (t) => { try { sessionStorage.setItem(KEY, t); } catch (e) {} };
      const clear = () => { try { sessionStorage.removeItem(KEY); } catch (e) {} };

      function isProtected(url) {
        return (/\/api\/v1\/admin\//.test(url) || /\/api\/services/.test(url) || /\/api\/admin\/tickets/.test(url)) && !/\/admin\/sms-gateway\/download-apk/.test(url);
      }

      function prompt(message) {
        if (pending) return pending;
        pending = new Promise((resolve) => {
          const overlay = document.createElement('div');
          overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,.85);display:flex;align-items:center;justify-content:center;padding:16px;font-family:system-ui,sans-serif';
          const box = document.createElement('form');
          box.style.cssText = 'background:var(--bg-card);color:var(--text-heading);border:1px solid var(--border);border-radius:12px;padding:24px;max-width:420px;width:100%;box-shadow:0 20px 50px rgba(0,0,0,.4)';
          const title = document.createElement('h3');
          title.textContent = 'Admin token required';
          title.style.margin = '0 0 8px';
          const hint = document.createElement('p');
          hint.textContent = message || 'Enter the admin API token (ADMIN_API_TOKEN, or the contents of data/.secrets/admin_api_token on the server).';
          hint.style.cssText = 'margin:0 0 12px;font-size:14px;color:var(--text-muted)';
          const input = document.createElement('input');
          input.type = 'password';
          input.autocomplete = 'off';
          input.required = true;
          input.style.cssText = 'width:100%;box-sizing:border-box;padding:10px;border:1px solid var(--border-hover);border-radius:8px;margin-bottom:12px';
          const btn = document.createElement('button');
          btn.type = 'submit';
          btn.textContent = 'Unlock';
          btn.style.cssText = 'width:100%;padding:10px;border:0;border-radius:8px;background:#0f766e;color:#fff;font-weight:600;cursor:pointer';
          box.append(title, hint, input, btn);
          overlay.appendChild(box);
          document.body.appendChild(overlay);
          input.focus();
          box.addEventListener('submit', (ev) => {
            ev.preventDefault();
            write(input.value.trim());
            overlay.remove();
            pending = null;
            resolve();
          });
        });
        return pending;
      }

      async function authedFetch(input, init) {
        const url = typeof input === 'string' ? input : (input && input.url) || '';
        if (!isProtected(url)) return nativeFetch(input, init);
        if (!read()) {
          await prompt();
          if (typeof connectAdminEventsSse === 'function') connectAdminEventsSse();
          if (typeof connectServicesLogsSse === 'function') connectServicesLogsSse();
        }
        const attempt = () => {
          const headers = new Headers((init && init.headers) || (input && input.headers) || {});
          headers.set('Authorization', 'Bearer ' + read());
          return nativeFetch(input, Object.assign({}, init, { headers }));
        };
        let res = await attempt();
        if (res.status === 401) {
          clear();
          await prompt('That token was rejected. Enter the admin API token again.');
          res = await attempt();
          if (res.ok && typeof connectAdminEventsSse === 'function') connectAdminEventsSse();
          if (res.ok && typeof connectServicesLogsSse === 'function') connectServicesLogsSse();
        }
        return res;
      }

      window.fetch = authedFetch;
      return { token: read, ensure: () => (read() ? Promise.resolve() : prompt()) };
    })();

    const API_BASE = "{{API_BASE_URL}}";
    let currentEnvMode = 'localhost';
    let currentDomainPrefix = 'pay';
    let currentDomainTld = '';
    let currentSellingMode = 'ONLINE';
    let currentMerchantId = '00000000-0000-0000-0000-000000000001';
    let currentMerchantBranding = {};
    let settingsLoaded = false;
    let pollingTimer = null;
    let waPollingTimer = null;
    let servicesLogsSse = null;
    let activeSection = 'operations';
    let activeSubTab = 'subViewOpsLive';
    let servicesList = [];

    // Helper to escape HTML safely
    function escapeHtml(str) {
      if (!str) return '';
      return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
    }

    // Helper to escape HTML safely while preserving falsy values such as 0
    function escapeHtmlValue(str) {
      if (str === null || str === undefined) return '';
      return escapeHtml(String(str));
    }

    // Escapes an attribute value that is delimited by double quotes.
    // Single quotes are deliberately left alone: they cannot terminate the
    // attribute, and the browser decodes entities before the inline handler
    // runs, so escaping them here would not prevent a break-out anyway.
    function escapeAttribute(str) {
      return escapeHtmlValue(str)
        .replace(/&#039;/g, "'");
    }

    // Builds a JavaScript literal that is safe to place inside a double-quoted
    // inline event handler attribute. Use instead of hand-written quotes:
    //   onclick="confirmCounterPayment(${jsArg(id)}, ${jsArg(method)})"
    function jsArg(value) {
      const literal = JSON.stringify(value === null || value === undefined ? '' : String(value));
      return escapeAttribute(literal);
    }

    function sanitizeImageUrl(url) {
      if (!url || typeof url !== 'string') return '';
      try {
        const parsed = new URL(url.trim(), window.location.href);
        if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
          return parsed.href;
        }
      } catch {}
      return '';
    }

    // --- REAL LIGHT / DARK THEME CONTROLLER ---
    const THEME_KEY = 'youpi-theme';
    const themeMQ = window.matchMedia('(prefers-color-scheme: dark)');

    function getThemePref() {
      try {
        const v = localStorage.getItem(THEME_KEY);
        return v === 'light' || v === 'dark' ? v : 'system';
      } catch (e) { return 'system'; }
    }

    function applyTheme(pref) {
      const theme = pref === 'system' ? (themeMQ.matches ? 'dark' : 'light') : pref;
      document.documentElement.setAttribute('data-theme', theme);
      document.querySelectorAll('[data-theme-pref]').forEach(b => {
        const on = b.dataset.themePref === pref;
        b.classList.toggle('active', on);
        b.setAttribute('aria-checked', on ? 'true' : 'false');
      });
    }

    function setThemePref(pref) {
      try {
        if (pref === 'system') localStorage.removeItem(THEME_KEY);
        else localStorage.setItem(THEME_KEY, pref);
      } catch (e) {}
      applyTheme(pref);
    }

    themeMQ.addEventListener('change', () => { if (getThemePref() === 'system') applyTheme('system'); });
    applyTheme(getThemePref());

    // --- NAVIGATION CONTROLLER: 3 HIGH-LEVEL SECTIONS ---
    function switchSection(sectionId, targetSubTab = null) {
      activeSection = sectionId;

      // Sync URL hash without jumping
      try {
        if (window.history && window.history.replaceState) {
          window.history.replaceState(null, '', `#${sectionId}`);
        } else {
          window.location.hash = sectionId;
        }
      } catch (e) { }

      // Update main nav buttons
      document.querySelectorAll('.main-nav-btn').forEach(b => b.classList.remove('active'));
      if (sectionId === 'operations') document.getElementById('mainNavOperations').classList.add('active');
      if (sectionId === 'storeSettings') document.getElementById('mainNavStoreSettings').classList.add('active');
      if (sectionId === 'developerHub') document.getElementById('mainNavDeveloperHub').classList.add('active');
      if (sectionId === 'security') document.getElementById('mainNavSecurity').classList.add('active');

      // Show/hide sections
      document.getElementById('sectionOperations').hidden = (sectionId !== 'operations');
      document.getElementById('sectionStoreSettings').hidden = (sectionId !== 'storeSettings');
      document.getElementById('sectionDeveloperHub').hidden = (sectionId !== 'developerHub');
      document.getElementById('sectionSecurity').hidden = (sectionId !== 'security');

      // Render sub-navigation bar
      renderSubNavBar(sectionId, targetSubTab);

      // Initial triggers
      if (sectionId === 'operations') {
        fetchLiveData();
      } else if (sectionId === 'storeSettings') {
        if (!settingsLoaded) fetchGatewaySettings();
      } else if (sectionId === 'developerHub') {
        loadServices();
        connectServicesLogsSse();
        fetchTunnelStatus();
      } else if (sectionId === 'security') {
        fetchBannedUsers();
      }
    }

    function renderSubNavBar(sectionId, targetSubTab = null) {
      const subNav = document.getElementById('subNavBar');
      subNav.innerHTML = '';

      let items = [];
      if (sectionId === 'operations') {
        items = [
          { id: 'subViewOpsLive', label: '📊 Live Monitor & Slots', viewId: 'subViewOpsLive' },
          { id: 'subViewOpsCounter', label: '🏪 Counter Desk (POS Cashier)', viewId: 'subViewOpsCounter' },
          { id: 'subViewOpsTransactions', label: '💳 Transactions Ledger', viewId: 'subViewOpsTransactions' },
          { id: 'subViewOpsObservers', label: '📡 Payment Observers Status', viewId: 'subViewOpsObservers' }
        ];
      } else if (sectionId === 'storeSettings') {
        items = [
          { id: 'subViewStoreBrand', label: '🎨 Brand Identity & Live Mockup', viewId: 'subViewStoreBrand' },
          { id: 'subViewStoreVpa', label: '⚡ Receiving Accounts (VPAs)', viewId: 'subViewStoreVpa' },
          { id: 'subViewStoreModes', label: '🏬 Selling Modes & Modalities', viewId: 'subViewStoreModes' },
          { id: 'subViewStoreStand', label: '🪧 Payment QR Stand Studio', viewId: 'subViewStoreStand' }
        ];
      } else if (sectionId === 'developerHub') {
        items = [
          { id: 'subViewDevSimulator', label: '🎮 Payment Simulator', viewId: 'subViewDevSimulator' },
          { id: 'subViewDevSupervisor', label: '🖥️ System Supervisor & Store (5000)', viewId: 'subViewDevSupervisor' },
          { id: 'subViewDevCloudflare', label: '☁️ Cloudflare Tunnel', viewId: 'subViewDevCloudflare' },
          { id: 'subViewDevWebhooks', label: '🔐 Webhooks & Secrets', viewId: 'subViewDevWebhooks' },
          { id: 'subViewDevAndroid', label: '📱 Android SMS Hub', viewId: 'subViewDevAndroid' },
          { id: 'subViewDevProtocols', label: '📧 Gmail & WhatsApp Protocols', viewId: 'subViewDevProtocols' }
        ];
      } else if (sectionId === 'security') {
        items = [
          { id: 'subViewSecBanned', label: '🚫 Banned Users', viewId: 'subViewSecBanned' },
          { id: 'subViewSecEvents', label: '🚨 Security Events', viewId: 'subViewSecEvents' },
          { id: 'subViewSecHistory', label: '📜 Ban History', viewId: 'subViewSecHistory' }
        ];
      }

      let defaultSub = targetSubTab || items[0].id;
      items.forEach(item => {
        const btn = document.createElement('button');
        btn.className = `sub-nav-pill ${item.id === defaultSub ? 'active' : ''}`;
        btn.textContent = item.label;
        btn.onclick = () => switchSubView(sectionId, item.id);
        subNav.appendChild(btn);
      });

      switchSubView(sectionId, defaultSub);
    }

    function switchSubView(sectionId, subViewId) {
      activeSubTab = subViewId;

      // Update pill styles
      document.querySelectorAll('.sub-nav-pill').forEach(p => {
        p.classList.remove('active');
        if (p.onclick.toString().includes(subViewId)) p.classList.add('active');
      });

      // Hide all sub-views in current section and show target
      const parent = document.getElementById(
        sectionId === 'operations' ? 'sectionOperations' :
          sectionId === 'storeSettings' ? 'sectionStoreSettings' :
            sectionId === 'developerHub' ? 'sectionDeveloperHub' : 'sectionSecurity'
      );
      Array.from(parent.children).forEach(child => {
        if (child.id && child.id.startsWith('subView')) {
          child.hidden = (child.id !== subViewId);
        }
      });

      if (subViewId === 'subViewDevSimulator') {
        initPaymentSimulator();
      }
      if (subViewId === 'subViewOpsCounter') {
        if (currentSellingMode === 'ONLINE') fetchCodOrders();
        else fetchCounterPayments();
      }
      if (subViewId === 'subViewOpsTransactions') fetchPaymentsLedger();
      if (subViewId === 'subViewOpsObservers') fetchObserversStatus();
      if (subViewId === 'subViewDevAndroid') {
        fetchObserversStatus();
        fetchSmsPairQr();
      }
      if (subViewId === 'subViewDevProtocols') {
        fetchWhatsAppStatus();
        fetchGmailCredentials();
      }
      if (subViewId === 'subViewDevSupervisor') {
        loadServices();
        fetchFalseNarrativeStatus();
      }
      if (subViewId === 'subViewSecBanned') fetchBannedUsers();
      if (subViewId === 'subViewSecEvents') fetchSecurityEvents();
      if (subViewId === 'subViewSecHistory') fetchSecurityHistory();
    }

    // --- MERGED CONTROL CENTER & SYSTEM SUPERVISOR ---
    async function loadServices() {
      try {
        const res = await fetch('/api/services');
        if (!res.ok) throw new Error('Supervisor unreachable');
        servicesList = await res.json();
        renderServicesTable(servicesList);
        updateYoupiStoreStatus(servicesList);
      } catch (e) {
        console.warn('loadServices error:', e);
        const tbody = document.getElementById('servicesTableBody');
        if (tbody) tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:var(--danger); padding:1.5rem;">⚠️ Supervisor API unavailable (Port 8090). Ensure services are running.</td></tr>`;
      }
    }

    function renderServicesTable(services) {
      const tbody = document.getElementById('servicesTableBody');
      if (!tbody) return;

      if (!services || services.length === 0) {
        tbody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No managed services registered.</td></tr>`;
        return;
      }

      tbody.innerHTML = services.map(s => {
        const isRunning = s.status === 'RUNNING';
        const isStarting = s.status === 'STARTING';
        const badgeClass = isRunning ? 'badge-success' : (isStarting ? 'badge-warning' : 'badge-danger');
        const statusIcon = isRunning ? '🟢' : (isStarting ? '🟡' : '🔴');

        const upSec = s.uptimeSeconds || 0;
        const uptimeStr = isRunning
          ? (upSec >= 3600 ? `${Math.floor(upSec / 3600)}h ${Math.floor((upSec % 3600) / 60)}m` : `${Math.floor(upSec / 60)}m ${upSec % 60}s`)
          : '-';

        const isStore = s.id === 'coin-wallet-store';

        return `
        <tr style="${isStore ? 'background:rgba(56,189,248,0.03);' : ''}">
          <td>
            <strong>${escapeHtml(s.name)}</strong>
            ${isStore ? '<span class="badge badge-info" style="font-size:0.68rem; margin-left:0.4rem;">Demo Store</span>' : ''}
            <div style="font-size:0.75rem; color:var(--text-muted); font-family:monospace;">${escapeHtml(s.id)}</div>
          </td>
          <td><code style="color:#f59e0b; background:#070c17; padding:2px 6px; border-radius:4px; font-weight:700;">${s.port}</code></td>
          <td><code style="color:var(--info);">${s.pid || '-'}</code></td>
          <td><span class="badge ${badgeClass}">${statusIcon} ${s.status}</span></td>
          <td style="font-size:0.8rem; color:var(--text-muted);">${uptimeStr}</td>
          <td>
            <div style="display:flex; gap:0.4rem;">
              ${!isRunning ? `
                <button class="btn btn-success" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="startService(${jsArg(s.id)})">▶ Start</button>
              ` : `
                <button class="btn btn-danger" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="stopService(${jsArg(s.id)})">⏹ Stop</button>
                <button class="btn btn-secondary" style="padding:0.3rem 0.65rem; font-size:0.75rem;" onclick="restartService(${jsArg(s.id)})">🔄 Restart</button>
              `}
              ${isRunning && s.port ? `
                <a href="http://localhost:${s.port}" target="_blank" class="btn btn-secondary" style="padding:0.3rem 0.55rem; font-size:0.75rem; text-decoration:none;" title="Open in browser">↗</a>
              ` : ''}
            </div>
          </td>
        </tr>
      `;
      }).join('');
    }

    // --- YOUPI SHOWCASE STORE (PORT 5000) MASTER SWITCH ---
    function updateYoupiStoreStatus(services) {
      const store = services.find(s => s.id === 'coin-wallet-store');
      const isRunning = store && store.status === 'RUNNING';

      // 1. Header Badge
      const hBadge = document.getElementById('headerStoreBadge');
      const hText = document.getElementById('headerStoreText');
      const hDot = document.getElementById('headerStoreDot');
      if (hBadge && hText) {
        if (isRunning) {
          hBadge.className = 'store-switch-badge is-online';
          hText.textContent = 'Store (5000): ONLINE';
          hDot.textContent = '🟢';
        } else {
          hBadge.className = 'store-switch-badge is-offline';
          hText.textContent = 'Store (5000): DISABLED';
          hDot.textContent = '🔴';
        }
      }

      // 2. Developer Card
      const cBadge = document.getElementById('cardStoreBadge');
      const btnToggle = document.getElementById('btnToggleYoupiStore') || document.getElementById('btnToggleGamerVaultStore');
      const btnLink = document.getElementById('btnOpenStoreLink');
      if (cBadge && btnToggle) {
        if (isRunning) {
          cBadge.className = 'badge badge-success';
          cBadge.textContent = '🟢 ONLINE & ACTIVE (PORT 5000)';
          btnToggle.className = 'btn btn-danger';
          btnToggle.innerHTML = '⏹ Disable YOUPI Store (Port 5000)';
          if (btnLink) btnLink.style.display = 'inline-flex';
        } else {
          cBadge.className = 'badge badge-danger';
          cBadge.textContent = '🔴 DISABLED (PORT 5000 FREE)';
          btnToggle.className = 'btn btn-success';
          btnToggle.innerHTML = '▶ Enable YOUPI Store (Port 5000)';
          if (btnLink) btnLink.style.display = 'none';
        }
      }
    }

    async function toggleYoupiStore() {
      const store = servicesList.find(s => s.id === 'coin-wallet-store');
      const isRunning = store && store.status === 'RUNNING';

      if (isRunning) {
        await stopService('coin-wallet-store');
        showAdminToast('YOUPI Showcase Store disabled. Port 5000 freed.');
      } else {
        await startService('coin-wallet-store');
        showAdminToast('YOUPI Showcase Store enabled on port 5000!');
      }
    }

    // Compatibility aliases
    window.updateGamerVaultStoreStatus = updateYoupiStoreStatus;
    window.toggleGamerVaultStore = toggleYoupiStore;

    async function startService(id) {
      try {
        const res = await fetch(`/api/services/${id}/start`, { method: 'POST' });
        const data = await res.json();
        if (!res.ok) alert(data.error || 'Failed to start service');
        loadServices();
      } catch (e) {
        alert('Network error starting service');
      }
    }

    async function stopService(id) {
      try {
        const res = await fetch(`/api/services/${id}/stop`, { method: 'POST' });
        const data = await res.json();
        if (!res.ok) alert(data.error || 'Failed to stop service');
        loadServices();
      } catch (e) {
        alert('Network error stopping service');
      }
    }

    async function restartService(id) {
      try {
        const res = await fetch(`/api/services/${id}/restart`, { method: 'POST' });
        const data = await res.json();
        if (!res.ok) alert(data.error || 'Failed to restart service');
        loadServices();
      } catch (e) {
        alert('Network error restarting service');
      }
    }

    async function startAllServices() {
      try {
        await fetch('/api/services/start-all', { method: 'POST' });
        showAdminToast('Starting all modular services...');
        setTimeout(loadServices, 1000);
      } catch (e) { }
    }

    async function stopAllServices() {
      if (!confirm('Are you sure you want to stop all background gateway services? (Control supervisor will remain online).')) return;
      try {
        await fetch('/api/services/stop-all', { method: 'POST' });
        showAdminToast('Stopping all services...');
        setTimeout(loadServices, 1000);
      } catch (e) { }
    }

    // --- LIVE AGGREGATE TERMINAL LOGS (SSE) ---
    let rawLogsBuffer = [];

    /**
     * Opens an SSE stream with an Authorization header.
     *
     * EventSource cannot send request headers, which is why the admin token used to be
     * passed as a `?token=` query parameter. That put a credential with write access into
     * the URL, so it landed in access logs, browser history and Referer headers. This uses
     * fetch() with a streaming body instead and keeps the token in the header only.
     *
     * @param {string} url
     * @param {string} token
     * @param {(event: string, data: string) => void} onEvent
     * @param {() => void} onError
     * @returns {{ close: () => void }}
     */
    function openAuthenticatedEventStream(url, token, onEvent, onError) {
      const controller = new AbortController();
      const listeners = new Map();
      let closed = false;

      const emit = (type, data) => {
        const handlers = listeners.get(type) || [];
        for (const handler of handlers) {
          try { handler({ data, type }); } catch (e) { }
        }
        if (onEvent) { try { onEvent(type, data); } catch (e) { } }
      };

      const run = async () => {
        try {
          const res = await fetch(url, {
            headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'text/event-stream' },
            signal: controller.signal
          });
          if (!res.ok || !res.body) throw new Error(`SSE failed: ${res.status}`);

          const reader = res.body.getReader();
          const decoder = new TextDecoder();
          let buffer = '';

          while (!closed) {
            const { value, done } = await reader.read();
            if (done) break;
            buffer += decoder.decode(value, { stream: true });

            let sep;
            while ((sep = buffer.indexOf('\n\n')) !== -1) {
              const raw = buffer.slice(0, sep);
              buffer = buffer.slice(sep + 2);

              let eventName = 'message';
              const dataLines = [];
              for (const line of raw.split('\n')) {
                if (line.startsWith('event:')) eventName = line.slice(6).trim();
                else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^ /, ''));
              }
              emit(eventName, dataLines.join('\n'));
            }
          }
        } catch (err) {
          if (!closed) {
            if (typeof apiSse.onerror === 'function') { try { apiSse.onerror(err); } catch (e) { } }
            if (onError) { try { onError(err); } catch (e) { } }
          }
        }
      };

      // Minimal EventSource-compatible surface so existing call sites keep working.
      const apiSse = {
        addEventListener(type, handler) {
          if (!listeners.has(type)) listeners.set(type, []);
          listeners.get(type).push(handler);
        },
        removeEventListener(type, handler) {
          const arr = listeners.get(type) || [];
          const i = arr.indexOf(handler);
          if (i !== -1) arr.splice(i, 1);
        },
        close() {
          closed = true;
          try { controller.abort(); } catch (e) { }
        },
        onerror: null
      };

      run();
      return apiSse;
    }

    function connectServicesLogsSse() {
      if (servicesLogsSse) return;
      const token = window.__youpiAdminAuth ? window.__youpiAdminAuth.token() : '';
      if (!token) return;
      try {
        servicesLogsSse = openAuthenticatedEventStream(
          '/api/logs/stream',
          token,
          (eventName, data) => {
            if (eventName === 'log') {
              try { appendLogEntry(JSON.parse(data)); } catch { }
            } else if (eventName === 'status_change') {
              loadServices();
            }
          },
          () => {
            servicesLogsSse.close();
            servicesLogsSse = null;
            setTimeout(connectServicesLogsSse, 5000);
          }
        );
      } catch (e) { }
    }

    function appendLogEntry(entry) {
      rawLogsBuffer.push(entry);
      if (rawLogsBuffer.length > 500) rawLogsBuffer.shift();

      const filterVal = document.getElementById('logServiceFilter')?.value || 'ALL';
      if (filterVal !== 'ALL' && entry.serviceId !== filterVal) return;

      const term = document.getElementById('terminalLogWindow');
      if (!term) return;

      const div = document.createElement('div');
      div.className = `log-line ${entry.stream === 'stderr' ? 'log-stderr' : (entry.stream === 'system' ? 'log-system' : '')}`;

      const timeStr = entry.timestamp ? new Date(entry.timestamp).toLocaleTimeString() : '';
      div.innerHTML = `<span class="log-ts">[${timeStr}]</span><span class="log-svc">[${escapeHtml(entry.serviceId)}]</span>${escapeHtml(entry.line)}`;

      term.appendChild(div);
      if (term.children.length > 300) term.removeChild(term.firstChild);
      term.scrollTop = term.scrollHeight;
    }

    function filterLogs() {
      const filterVal = document.getElementById('logServiceFilter')?.value || 'ALL';
      const term = document.getElementById('terminalLogWindow');
      if (!term) return;
      term.innerHTML = '';
      rawLogsBuffer.forEach(entry => {
        if (filterVal === 'ALL' || entry.serviceId === filterVal) {
          const div = document.createElement('div');
          div.className = `log-line ${entry.stream === 'stderr' ? 'log-stderr' : (entry.stream === 'system' ? 'log-system' : '')}`;
          const timeStr = entry.timestamp ? new Date(entry.timestamp).toLocaleTimeString() : '';
          div.innerHTML = `<span class="log-ts">[${timeStr}]</span><span class="log-svc">[${escapeHtml(entry.serviceId)}]</span>${escapeHtml(entry.line)}`;
          term.appendChild(div);
        }
      });
      term.scrollTop = term.scrollHeight;
    }

    function clearLogsConsole() {
      const term = document.getElementById('terminalLogWindow');
      if (term) term.innerHTML = `<div class="log-line log-system"><span class="log-ts">[Cleared]</span> Console cleared by merchant.</div>`;
    }

    // --- SELLING MODE & PAYMENT MODALITIES ---
    function setSellingMode(mode, save = false) {
      currentSellingMode = (mode === 'OFFLINE') ? 'OFFLINE' : 'ONLINE';
      const cardOnline = document.getElementById('cardModeOnline');
      const cardOffline = document.getElementById('cardModeOffline');
      const badgeOnline = document.getElementById('badgeOnlineActive');
      const badgeOffline = document.getElementById('badgeOfflineActive');
      const panelOnline = document.getElementById('panelOnlineMode');
      const panelOffline = document.getElementById('panelOfflineMode');
      const modeBadge = document.getElementById('currentSellingModeBadge');
      const codCard = document.getElementById('counterDeskCodCard');
      const offlineCard = document.getElementById('counterDeskOfflineCard');

      if (currentSellingMode === 'ONLINE') {
        if (cardOnline) {
          cardOnline.className = 'selling-mode-card mode-selected-online';
        }
        if (cardOffline) {
          cardOffline.className = 'selling-mode-card';
        }
        if (badgeOnline) badgeOnline.style.display = 'inline-block';
        if (badgeOffline) badgeOffline.style.display = 'none';
        if (panelOnline) panelOnline.hidden = false;
        if (panelOffline) panelOffline.hidden = true;
        if (modeBadge) { modeBadge.textContent = 'ONLINE SELLING MODE'; modeBadge.className = 'badge badge-info'; }
        if (codCard) codCard.style.display = 'block';
        if (offlineCard) offlineCard.style.display = 'none';
      } else {
        if (cardOffline) {
          cardOffline.className = 'selling-mode-card mode-selected-offline';
        }
        if (cardOnline) {
          cardOnline.className = 'selling-mode-card';
        }
        if (badgeOffline) badgeOffline.style.display = 'inline-block';
        if (badgeOnline) badgeOnline.style.display = 'none';
        if (panelOnline) panelOnline.hidden = true;
        if (panelOffline) panelOffline.hidden = false;
        if (modeBadge) { modeBadge.textContent = 'OFFLINE SELLING MODE'; modeBadge.className = 'badge badge-warning'; }
        if (codCard) codCard.style.display = 'none';
        if (offlineCard) offlineCard.style.display = 'block';
      }

      if (save) {
        saveMerchantBrandingAndToggles();
      }
    }

    // --- LIVE AUTO-POLLING (2.5s) ---
    async function fetchLiveData() {
      try {
        const qRes = await fetch(`${API_BASE}/api/v1/admin/queue`);
        const qData = await qRes.json();
        renderSlotActive(qData.currentSlot);
        renderSlotProcessing(qData.currentSlot);
        renderQueueTable(qData.queue || []);

        const pRes = await fetch(`${API_BASE}/api/v1/admin/payments`);
        const pData = await pRes.json();
        updateKpis(pData.payments || [], qData.queue || []);

        if (activeSection === 'operations' && activeSubTab === 'subViewOpsCounter') {
          if (currentSellingMode === 'ONLINE') fetchCodOrders();
          else renderCounterDesk(pData.payments || []);
        }
      } catch (e) { }
    }

    function renderSlotActive(currentSlot) {
      const box = document.getElementById('slotActiveBox');
      const content = document.getElementById('slotActiveContent');
      if (!box || !content) return;

      if (currentSlot && currentSlot.status === 'ACTIVE') {
        box.className = 'slot-card busy-active';
        const remainingSec = currentSlot.expiresAt ? Math.max(0, Math.ceil((new Date(currentSlot.expiresAt).getTime() - Date.now()) / 1000)) : 0;
        const m = Math.floor(remainingSec / 60);
        const s = remainingSec % 60;
        content.innerHTML = `
        <div style="font-size:1.75rem; font-weight:800; color:var(--info);">₹${(Number(currentSlot.amountPaise) / 100).toFixed(2)}</div>
        <div style="font-weight:700; margin:0.35rem 0;">Order #${escapeHtml(currentSlot.orderId)}</div>
        <div class="badge badge-info">ACTIVE (⏱ ${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')} remaining)</div>
      `;
      } else {
        box.className = 'slot-card';
        content.innerHTML = '<div style="color:var(--text-muted); padding:1rem 0;">No customer actively checking out.</div>';
      }
    }

    function renderSlotProcessing(currentSlot) {
      const box = document.getElementById('slotProcBox');
      const content = document.getElementById('slotProcContent');
      if (!box || !content) return;

      if (currentSlot && currentSlot.status === 'PROCESSING') {
        box.className = 'slot-card busy-proc';
        const remainingSec = currentSlot.processingExpiresAt ? Math.max(0, Math.ceil((new Date(currentSlot.processingExpiresAt).getTime() - Date.now()) / 1000)) : 0;
        content.innerHTML = `
        <div style="font-size:1.75rem; font-weight:800; color:var(--warning);">₹${(Number(currentSlot.amountPaise) / 100).toFixed(2)}</div>
        <div style="font-weight:700; margin:0.35rem 0;">Order #${escapeHtml(currentSlot.orderId)}</div>
        <div class="badge badge-warning">VERIFYING (⏳ ${remainingSec}s remaining)</div>
      `;
      } else {
        box.className = 'slot-card';
        content.innerHTML = '<div style="color:var(--text-muted); padding:1rem 0;">No payment in verification.</div>';
      }
    }

    function renderQueueTable(queue) {
      const tbody = document.getElementById('queueTableBody');
      if (!tbody) return;
      if (!queue || queue.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:1rem;">Waiting queue is empty.</td></tr>';
        return;
      }
      tbody.innerHTML = queue.map(q => `
      <tr>
        <td><strong>#${q.queuePosition}</strong></td>
        <td>Order #${escapeHtml(q.orderId)}</td>
        <td>₹${(Number(q.amountPaise) / 100).toFixed(2)}</td>
        <td><span class="badge badge-warning">QUEUED</span></td>
        <td>${escapeHtmlValue(new Date(q.createdAt).toLocaleTimeString())}</td>
      </tr>
    `).join('');
    }

    function updateKpis(payments, queue) {
      let successVol = 0;
      let successCount = 0;
      let pendingCounter = 0;
      let singleVerify = 0;
      let dualVerify = 0;

      payments.forEach(p => {
        if (p.status === 'RECONCILED' || p.status === 'SUCCESS') {
          successCount++;
          successVol += Number(p.amountPaise);
          if (p.verificationLevel >= 2) dualVerify++;
          else singleVerify++;
        }
        if (p.status === 'ACTIVE' && (p.method === 'CASH_COUNTER' || p.method === 'CARD_COUNTER')) {
          pendingCounter++;
        }
      });

      const kVol = document.getElementById('kpiVol');
      const kSuccess = document.getElementById('kpiSuccessCount');
      const kQueue = document.getElementById('kpiQueueCount');
      const kPending = document.getElementById('kpiPendingCounterCount');
      const kSingle = document.getElementById('kpiSingleVerify');
      const kDual = document.getElementById('kpiDualVerify');

      if (kVol) kVol.textContent = `₹${(successVol / 100).toFixed(2)}`;
      if (kSuccess) kSuccess.textContent = successCount;
      if (kQueue) kQueue.textContent = queue.length;
      if (kPending) kPending.textContent = pendingCounter;
      if (kSingle) kSingle.textContent = singleVerify;
      if (kDual) kDual.textContent = dualVerify;
    }

    async function promptClearAllQueue() {
      if (!confirm('Are you sure you want to clear the entire UPI waiting queue? All currently queued sessions will be expired automatically.')) return;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/queue/clear`, { method: 'POST' });
        const data = await res.json();
        if (res.ok) {
          showAdminToast(`UPI Queue Cleared! Expired ${data.clearedCount || 0} queued sessions.`);
          fetchLiveData();
        } else {
          alert(data.error || 'Failed to clear queue');
        }
      } catch (e) {
        alert('Network error clearing queue');
      }
    }

    // --- COUNTER DESK (POS CASHIER) ---
    async function fetchCounterPayments() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/payments`);
        const data = await res.json();
        renderCounterDesk(data.payments || []);
      } catch (e) { }
    }

    function renderCounterDesk(payments) {
      const pending = payments.filter(p => p.status === 'ACTIVE' && (p.method === 'CASH_COUNTER' || p.method === 'CARD_COUNTER'));
      const tbody = document.getElementById('counterTableBody');
      if (!tbody) return;

      if (!pending || pending.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No pending counter payments right now.</td></tr>';
        return;
      }

      tbody.innerHTML = pending.map(p => `
      <tr>
        <td><strong>Order #${escapeHtml(p.orderId)}</strong></td>
        <td><code style="font-size:0.75rem;">${p.id.substring(0, 16)}...</code></td>
        <td><strong style="color:var(--success); font-size:1.15rem;">₹${(Number(p.amountPaise) / 100).toFixed(2)}</strong></td>
        <td>
          <span class="badge ${p.method === 'CASH_COUNTER' ? 'badge-success' : 'badge-info'}">
            ${p.method === 'CASH_COUNTER' ? '💵 Cash at Till' : '💳 Card at POS'}
          </span>
        </td>
        <td>${new Date(p.createdAt).toLocaleTimeString()}</td>
        <td>
          <div style="display:flex; gap:0.4rem;">
            <button class="btn btn-success" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Approve</button>
            <button class="btn btn-danger" style="padding:0.35rem 0.75rem; font-size:0.78rem;" onclick="declineCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✕ Decline</button>
          </div>
        </td>
      </tr>
    `).join('');
    }

    async function confirmCounterPayment(paymentId, method) {
      const operatorId = document.getElementById('operatorDisplay')?.textContent || 'Cashier Desk #1';
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/counter-confirm`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paymentId, operatorId, method })
        });
        if (res.ok) {
          showAdminToast('Payment approved successfully!');
          pollGlobalCounterPending();
          fetchLiveData();
          fetchCounterPayments();
        } else {
          const err = await res.json();
          alert(err.error || 'Failed to approve payment');
        }
      } catch (e) {
        alert('Network error confirming payment');
      }
    }

    async function declineCounterPayment(paymentId, method) {
      const reason = prompt('Reason for declining this counter payment:', 'Payment note rejected at till');
      if (reason === null) return;
      const operatorId = document.getElementById('operatorDisplay')?.textContent || 'Cashier Desk #1';
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/counter-decline`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paymentId, operatorId, reason })
        });
        if (res.ok) {
          showAdminToast('Payment declined.');
          pollGlobalCounterPending();
          fetchLiveData();
          fetchCounterPayments();
        } else {
          const err = await res.json();
          alert(err.error || 'Failed to decline payment');
        }
      } catch (e) {
        alert('Network error declining payment');
      }
    }

    async function fetchCodOrders() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/cod-orders`);
        const data = await res.json();
        const tbody = document.getElementById('codOrdersTableBody');
        if (!tbody) return;
        const orders = data.codOrders || [];
        if (orders.length === 0) {
          tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No Cash on Delivery orders placed yet.</td></tr>';
          return;
        }
        tbody.innerHTML = orders.map(o => `
        <tr>
          <td><strong>Order #${escapeHtml(o.orderId)}</strong></td>
          <td><code style="font-size:0.75rem;">${o.paymentId.substring(0, 16)}...</code></td>
          <td><strong style="color:var(--success); font-size:1.15rem;">₹${(Number(o.amountPaise) / 100).toFixed(2)}</strong></td>
          <td>${escapeHtml(o.customerName || 'Customer')}</td>
          <td>${escapeHtml(o.customerPhone || '-')}</td>
          <td>${new Date(o.placedAt).toLocaleTimeString()}</td>
          <td>
            <button type="button" data-cod-order="${escapeHtml(o.orderId)}" class="btn btn-secondary" style="padding:0.25rem 0.5rem; font-size:0.75rem;">
              API ↗
            </button>
          </td>
        </tr>
      `).join('');
      } catch (e) { }
    }

    // The COD order API only returns the customer to an authenticated caller, and a plain
    // link would navigate without the admin token (authedFetch only covers /admin/ routes),
    // so fetch it with the bearer and show the JSON in a new tab.
    document.addEventListener('click', async (e) => {
      const btn = e.target.closest('[data-cod-order]');
      if (!btn) return;
      const tab = window.open('', '_blank');
      try {
        await window.__youpiAdminAuth.ensure();
        const res = await fetch(`${API_BASE}/api/v1/orders/${encodeURIComponent(btn.dataset.codOrder)}/cod`, {
          headers: { Authorization: 'Bearer ' + window.__youpiAdminAuth.token() }
        });
        const body = JSON.stringify(await res.json(), null, 2);
        const url = URL.createObjectURL(new Blob([body], { type: 'application/json' }));
        if (tab) tab.location.href = url; else window.open(url, '_blank');
      } catch (err) {
        if (tab) tab.close();
        alert('Could not load the COD order details.');
      }
    });

    // --- TRANSACTIONS LEDGER ---
    async function fetchPaymentsLedger() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/payments`);
        const data = await res.json();
        const tbody = document.getElementById('paymentsLedgerTbody');
        if (!tbody) return;

        tbody.innerHTML = (data.payments || []).map(p => {
          let verifyBadge = '<span style="color:var(--text-muted); font-size:0.75rem;">-</span>';
          if (p.status === 'SUCCESS' || p.status === 'OBSERVED_SUCCESS' || p.status === 'RECONCILED' || p.status === 'MANUAL_REVIEW') {
          const tag = p.verificationTag || (p.verificationLevel >= 2 ? 'Dual Verification' : 'Single Verification');
          if (p.verificationLevel >= 2) {
            verifyBadge = `<span class="badge badge-success">✓✓ ${escapeHtmlValue(tag)}</span>`;
          } else {
            verifyBadge = `<span class="badge badge-info">✓ ${escapeHtmlValue(tag)}</span>`;
          }
        }

          const sourcesChips = (p.verificationSources && p.verificationSources.length > 0)
            ? p.verificationSources.map(s => `<code style="font-size:0.7rem; background:var(--bg-box); padding:0.15rem 0.35rem; border-radius:0.25rem; margin-right:0.2rem; border:1px solid var(--border); color:var(--info);">${s === 'GOOGLE_MESSAGES' ? 'SMS' : escapeHtmlValue(s)}</code>`).join('')
            : '<span style="color:var(--text-muted); font-size:0.75rem;">-</span>';

          return `
          <tr>
            <td><strong>Order #${escapeHtml(p.orderId)}</strong></td>
            <td><code>${p.id}</code></td>
            <td>₹${(Number(p.amountPaise) / 100).toFixed(2)}</td>
            <td>${escapeHtmlValue(p.method)}</td>
            <td><span class="badge ${p.status === 'RECONCILED' || p.status === 'SUCCESS' ? 'badge-success' : (p.status === 'OBSERVED_SUCCESS' ? 'badge-warning' : (p.status === 'MANUAL_REVIEW' ? 'badge-danger' : (p.status === 'ACTIVE' ? 'badge-info' : 'badge-danger')))}">${escapeHtmlValue(p.status === 'OBSERVED_SUCCESS' ? 'Observed (not reconciled)' : p.status)}</span></td>
            <td>${verifyBadge}</td>
            <td>${sourcesChips}</td>
            <td>${escapeHtmlValue(new Date(p.createdAt).toLocaleTimeString())}</td>
            <td>${p.completedAt ? escapeHtmlValue(new Date(p.completedAt).toLocaleTimeString()) : '-'}</td>
          </tr>
        `;
        }).join('');
      } catch (e) { }
    }

    // --- WHITE-LABEL BRANDING & SMARTPHONE PREVIEW ---
    function syncColorPickerToText(val) {
      const txt = document.getElementById('settingPrimaryColor');
      if (txt) txt.value = val;
      updateLiveWhiteLabelPreview();
    }

    function syncTextColorToPicker(val) {
      if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
        const picker = document.getElementById('settingColorPicker');
        if (picker) picker.value = val;
      }
      updateLiveWhiteLabelPreview();
    }

    function applyQuickPalette(color, theme) {
      const colIn = document.getElementById('settingPrimaryColor');
      const pickIn = document.getElementById('settingColorPicker');
      const thmIn = document.getElementById('settingHeaderTheme');
      if (colIn) colIn.value = color;
      if (pickIn) pickIn.value = color;
      if (thmIn && theme) thmIn.value = theme;
      updateLiveWhiteLabelPreview();
    }

    function adjustHexColor(col, amt) {
      if (!col) return '#0957cb';
      try {
        let usePound = false;
        if (col[0] === '#') { col = col.slice(1); usePound = true; }
        if (col.length === 3) col = col[0] + col[0] + col[1] + col[1] + col[2] + col[2];
        const num = parseInt(col, 16);
        let r = (num >> 16) + amt;
        if (r > 255) r = 255; else if (r < 0) r = 0;
        let b = ((num >> 8) & 0x00FF) + amt;
        if (b > 255) b = 255; else if (b < 0) b = 0;
        let g = (num & 0x0000FF) + amt;
        if (g > 255) g = 255; else if (g < 0) g = 0;
        return (usePound ? '#' : '') + (g | (b << 8) | (r << 16)).toString(16).padStart(6, '0');
      } catch { return col; }
    }

    function updateLiveWhiteLabelPreview() {
      const bName = document.getElementById('settingBusinessName')?.value.trim() || 'Merchant Checkout';
      const appName = document.getElementById('settingAppName')?.value.trim() || '{{APP_NAME}}' || 'YOUPI PG';
      const logoUrl = document.getElementById('settingLogoUrl')?.value.trim() || '';
      const primaryColor = document.getElementById('settingPrimaryColor')?.value.trim() || '#0b63e5';
      const headerTheme = document.getElementById('settingHeaderTheme')?.value || 'gradient';
      const trustBadgeText = document.getElementById('settingTrustBadgeText')?.value.trim();
      const hideTrustBadge = document.getElementById('settingHideTrustBadge')?.checked;
      const subbannerText = document.getElementById('settingSubbannerText')?.value.trim();
      const hideSubbanner = document.getElementById('settingHideSubbanner')?.checked;
      const hideTimeSavingBanner = document.getElementById('settingHideTimeSavingBanner')?.checked;
      const hidePoweredBy = document.getElementById('settingHidePoweredBy')?.checked;
      const footerGuarantee = document.getElementById('settingFooterGuarantee')?.value.trim();

      const headerEl = document.getElementById('mockupHeader');
      if (headerEl) {
        if (headerTheme === 'solid') headerEl.style.background = primaryColor;
        else if (headerTheme === 'dark') headerEl.style.background = '#0b1329';
        else {
          const darkAccent = adjustHexColor(primaryColor, -25);
          headerEl.style.background = `linear-gradient(180deg, ${primaryColor} 0%, ${darkAccent} 100%)`;
        }
      }

      const avatarLetter = document.getElementById('mockupAvatarLetter');
      const avatarImg = document.getElementById('mockupAvatarImg');
      const safeLogoUrl = sanitizeImageUrl(logoUrl);
      if (safeLogoUrl && avatarImg && avatarLetter) {
        avatarImg.src = safeLogoUrl;
        avatarImg.style.display = 'block';
        avatarLetter.style.display = 'none';
        avatarImg.onerror = () => { avatarImg.style.display = 'none'; avatarLetter.style.display = 'block'; };
      } else if (avatarLetter && avatarImg) {
        avatarImg.style.display = 'none';
        avatarLetter.style.display = 'block';
        avatarLetter.textContent = bName.charAt(0).toUpperCase();
        avatarLetter.style.color = primaryColor;
      }

      const nameEl = document.getElementById('mockupHeaderMerchantName');
      if (nameEl) nameEl.textContent = bName;

      const trustBadgeBox = document.getElementById('mockupTrustBadge');
      const trustBadgeTextEl = document.getElementById('mockupTrustBadgeText');
      if (trustBadgeBox) {
        trustBadgeBox.style.display = hideTrustBadge ? 'none' : 'inline-flex';
        if (trustBadgeTextEl) trustBadgeTextEl.textContent = trustBadgeText || `${appName} Verified Business`;
      }

      const subbannerBox = document.getElementById('mockupSubbanner');
      const subbannerTextEl = document.getElementById('mockupSubbannerText');
      if (subbannerBox) {
        subbannerBox.style.display = hideSubbanner ? 'none' : 'flex';
        if (subbannerTextEl) subbannerTextEl.textContent = subbannerText || `Verified & Protected by ${appName}`;
      }

      const timeBanner = document.getElementById('mockupTimeSavingBanner');
      if (timeBanner) timeBanner.style.display = hideTimeSavingBanner ? 'none' : 'flex';

      const guaranteeEl = document.getElementById('mockupFooterGuarantee');
      if (guaranteeEl) {
        if (footerGuarantee) guaranteeEl.textContent = footerGuarantee;
        else if (hidePoweredBy) guaranteeEl.textContent = '100% Payment Protection & Security';
        else guaranteeEl.textContent = `100% Payment Protection by ${appName}`;
      }

      const legalEl = document.getElementById('mockupLegalDisclaimer');
      if (legalEl) {
        legalEl.textContent = hidePoweredBy
          ? 'Secured by 256-Bit Bank Encryption • Privacy & Terms'
          : `Secured by ${appName} & 256-Bit Bank Encryption • Privacy Notice`;
      }

      const ctaBtn = document.getElementById('mockupCtaButton');
      if (ctaBtn) ctaBtn.style.background = primaryColor;
    }

    // --- RECEIVING ACCOUNTS (VPAS) ---
    let currentUpiAccounts = [];

    function initStandInputs(accounts, mSettings) {
      const activeAcc = (accounts || []).find(a => a.isActive || a.is_active);
      const vpaInput = document.getElementById('standInputVpa');
      if (vpaInput && !vpaInput.value && activeAcc) {
        vpaInput.value = activeAcc.upiId || activeAcc.upi_id || '';
        document.getElementById('standInputPayeeName').value = activeAcc.payeeName || activeAcc.payee_name || '';
      }
      if (mSettings && document.getElementById('standInputBusinessName')) {
        if (!document.getElementById('standInputBusinessName').value) {
          document.getElementById('standInputBusinessName').value = mSettings.businessName || '';
        }
        if (!document.getElementById('standInputMobile').value && mSettings.contactPhone) {
          document.getElementById('standInputMobile').value = mSettings.contactPhone || '';
        }
      }
      updateLiveStandPreview();
    }

    function updateLiveStandPreview() {
      const vpa = document.getElementById('standInputVpa')?.value || 'customer@ybl';
      const mobile = document.getElementById('standInputMobile')?.value || '';
      const name = document.getElementById('standInputBusinessName')?.value || 'Merchant Store';
      const color = document.getElementById('standInputColor')?.value || '#5f259f';
      const format = document.getElementById('standSelectFormat')?.value || 'table-tent';
      const tagline = document.getElementById('standInputTagline')?.value || 'Scan & Pay with Any UPI App';

      const params = new URLSearchParams({ name, vpa, mobile, color, format, tagline });
      const previewUrl = `http://localhost:7000/stand/qr.svg?${params.toString()}`;
      const container = document.getElementById('standSvgPreviewContainer');
      if (container) {
        container.innerHTML = `<img src="${previewUrl}" style="width:100%; height:auto; display:block; border-radius:8px;" alt="Stand Artwork Preview" />`;
      }
    }

    function openPrintStandFromAdmin() {
      const vpa = document.getElementById('standInputVpa')?.value || '';
      const mobile = document.getElementById('standInputMobile')?.value || '';
      const name = document.getElementById('standInputBusinessName')?.value || '';
      const color = document.getElementById('standInputColor')?.value || '#5f259f';
      const format = document.getElementById('standSelectFormat')?.value || 'table-tent';
      const params = new URLSearchParams({ name, vpa, mobile, color, format });
      window.open(`http://localhost:7000/stand/print?${params.toString()}`, '_blank');
    }

    function downloadStandSvgFromAdmin() {
      const vpa = document.getElementById('standInputVpa')?.value || '';
      const mobile = document.getElementById('standInputMobile')?.value || '';
      const name = document.getElementById('standInputBusinessName')?.value || '';
      const color = document.getElementById('standInputColor')?.value || '#5f259f';
      const format = document.getElementById('standSelectFormat')?.value || 'table-tent';
      const params = new URLSearchParams({ name, vpa, mobile, color, format });
      window.open(`http://localhost:7000/stand/qr.svg?${params.toString()}`, '_blank');
    }

    async function fetchGatewaySettings() {
      try {
        const upiRes = await fetch(`${API_BASE}/api/v1/admin/upi-settings`);
        if (upiRes.ok) {
          const upiData = await upiRes.json();
          currentUpiAccounts = upiData.accounts || [];
          renderUpiAccountsTable(currentUpiAccounts);
          renderActiveVpaCallout(upiData);
        }

        const mRes = await fetch(`${API_BASE}/api/v1/admin/merchant-settings?merchantId=${encodeURIComponent(currentMerchantId)}`);
        if (mRes.ok) {
          const mData = await mRes.json();
          currentMerchantId = mData.merchantId || currentMerchantId || '00000000-0000-0000-0000-000000000001';

          const branding = mData.branding || {};
          currentMerchantBranding = branding;

          const setVal = (id, val) => {
            const el = document.getElementById(id);
            if (el) el.value = val ?? '';
          };
          const setCheck = (id, checked) => {
            const el = document.getElementById(id);
            if (el) el.checked = Boolean(checked);
          };

          setVal('settingMerchantId', mData.publishableKey || mData.merchantId || currentMerchantId);
          setVal('settingMerchantApiKey', mData.merchantKey || branding.merchantApiKey || '');
          setVal('settingBusinessName', mData.businessName);
          setVal('settingWebhookUrl', mData.webhookUrl);
          setVal('settingWebhookSecret', mData.webhookSecret);
          renderMerchantCredentials(mData);

          setVal('settingAppName', branding.appName || '{{APP_NAME}}' || 'YOUPI PG');
          setVal('settingLogoUrl', branding.logoUrl);
          setVal('settingSidebarNotice', branding.sidebarNotice);
          setVal('settingFooterGuarantee', branding.footerGuarantee);
          setVal('settingCounterInstructions', branding.counterInstructions);
          setVal('settingPrimaryColor', branding.primaryColor || '#0b63e5');
          setVal('settingColorPicker', branding.primaryColor || '#0b63e5');

          setVal('settingHeaderTheme', branding.headerTheme || 'gradient');
          setVal('settingTrustBadgeText', branding.trustBadgeText);
          setCheck('settingHideTrustBadge', branding.hideTrustBadge);
          setVal('settingSubbannerText', branding.subbannerText);
          setCheck('settingHideSubbanner', branding.hideSubbanner);
          setCheck('settingHideTimeSavingBanner', branding.hideTimeSavingBanner);
          setCheck('settingHidePoweredBy', branding.hidePoweredBy);
          setVal('settingCardCounterInstructions', branding.cardCounterInstructions);
          setVal('settingTermsUrl', branding.termsUrl);

          // Canonical Cloudflare Configuration & Environment
          currentEnvMode = branding.envMode || mData.envMode || 'localhost';
          currentDomainPrefix = branding.deploymentPrefix || branding.domainPrefix || mData.deploymentPrefix || mData.domainPrefix || 'pay';
          currentDomainTld = branding.cloudflareDomain || branding.domainTld || mData.cloudflareDomain || mData.domainTld || '';

          setVal('settingDomainPrefix', currentDomainPrefix);
          setVal('settingDomainTld', currentDomainTld);

          setEnvMode(currentEnvMode, false);
          updateCloudflarePreview();

          // Selling Mode
          const sellingMode = mData.sellingMode || branding.sellingMode || 'ONLINE';
          setSellingMode(sellingMode, false);

          const codOn = mData.codEnabled !== undefined
            ? Boolean(mData.codEnabled)
            : (branding.codEnabled !== undefined
              ? Boolean(branding.codEnabled)
              : (branding.enabledPaymentMethods ? branding.enabledPaymentMethods.includes('COD') : false));
          const cashOn = mData.cashEnabled !== undefined ? mData.cashEnabled : (branding.cashEnabled !== undefined ? branding.cashEnabled : true);
          const cardOn = mData.cardEnabled !== undefined ? mData.cardEnabled : (branding.cardEnabled !== undefined ? branding.cardEnabled : true);

          setCheck('toggleMethodCod', codOn);
          setCheck('toggleMethodCash', cashOn);
          setCheck('toggleMethodCard', cardOn);

          const supportEmails = mData.supportEmails || branding.supportEmails || (mData.contactEmail ? [mData.contactEmail] : []);
          setVal('settingSupportEmails', Array.isArray(supportEmails) ? supportEmails.join(', ') : (supportEmails || ''));

          const supportMobiles = mData.supportMobiles || branding.supportMobiles || (mData.contactPhone ? [mData.contactPhone] : []);
          setVal('settingSupportMobiles', Array.isArray(supportMobiles) ? supportMobiles.join(', ') : (supportMobiles || ''));

          setVal('settingPrivacyPolicyUrl', mData.privacyPolicyUrl || branding.privacyPolicyUrl || '');

          updateLiveWhiteLabelPreview();
        }
      } catch (e) {
        console.error('Error fetching gateway settings:', e);
      } finally {
        settingsLoaded = true;
      }
    }

    function renderActiveVpaCallout(activeData) {
      const idEl = document.getElementById('activeVpaIdDisplay');
      const payeeEl = document.getElementById('activeVpaPayeeDisplay');
      const headerVpa = document.getElementById('accountVpaDisplay');

      if (activeData && activeData.upiId && activeData.isActive) {
        if (idEl) idEl.textContent = activeData.upiId;
        if (payeeEl) payeeEl.textContent = `Payee: ${activeData.payeeName || 'Store'}`;
        if (headerVpa) headerVpa.textContent = `VPA: ${activeData.upiId}`;
      } else {
        if (idEl) idEl.textContent = 'No VPA currently active';
        if (payeeEl) payeeEl.textContent = 'Add or activate a VPA below to accept payments';
        if (headerVpa) headerVpa.textContent = 'NO ACTIVE VPA';
      }
    }

    function renderUpiAccountsTable(accounts) {
      const tbody = document.getElementById('upiAccountsTableBody');
      if (!tbody) return;
      if (!accounts || accounts.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:1.5rem;">No UPI accounts saved yet. Add your first VPA above.</td></tr>';
        return;
      }

      tbody.innerHTML = accounts.map(a => {
        const statusBadge = a.isActive
          ? '<span class="badge badge-info" style="font-weight:800; font-size:0.78rem;">● ACTIVE</span>'
          : '<span class="badge badge-neutral" style="font-size:0.75rem;">Disabled</span>';

        const slotBadge = a.isSlotBusy
          ? '<span class="badge badge-warning" style="font-size:0.7rem;">Slot Busy</span>'
          : '<span style="color:var(--text-muted); font-size:0.75rem;">Available</span>';

        let actionBtns = '';
        if (!a.isActive) {
          actionBtns += `<button class="btn btn-primary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="activateVpa(${jsArg(a.id)})">Activate</button>`;
        } else {
          actionBtns += `<button class="btn btn-secondary" style="padding:0.35rem 0.65rem; font-size:0.78rem; margin-right:0.4rem;" onclick="toggleVpa(${jsArg(a.id)})">Deactivate</button>`;
        }
        actionBtns += `<button class="btn btn-danger" style="padding:0.35rem 0.65rem; font-size:0.78rem;" onclick="deleteVpa(${jsArg(a.id)}, ${jsArg(a.upiId)})">Delete</button>`;

        return `
        <tr style="${a.isActive ? 'background:var(--primary-light);' : ''}">
          <td><strong style="color:var(--text-heading);">${escapeHtml(a.upiId)}</strong></td>
          <td>${escapeHtml(a.payeeName)}</td>
          <td>${statusBadge}</td>
          <td>${slotBadge}</td>
          <td style="font-size:0.75rem; color:var(--text-muted);">${new Date(a.createdAt).toLocaleDateString()}</td>
          <td>${actionBtns}</td>
        </tr>
      `;
      }).join('');
    }

    async function addNewUpiAccount() {
      const upiId = document.getElementById('newUpiVpa').value.trim();
      const payeeName = document.getElementById('newUpiPayee').value.trim();
      const isActive = document.getElementById('newUpiActivateNow').checked;
      if (!upiId) return alert('Please enter a valid UPI VPA.');

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/upi-accounts`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ upiId, payeeName: payeeName || document.getElementById('settingBusinessName').value, isActive })
        });
        const data = await res.json();
        if (res.ok) {
          showAdminToast(`UPI account "${data.account.upiId}" added successfully!`);
          document.getElementById('newUpiVpa').value = '';
          document.getElementById('newUpiPayee').value = '';
          fetchGatewaySettings();
        } else {
          alert(data.error || 'Failed to add UPI account');
        }
      } catch (e) {
        alert('Network error adding UPI account');
      }
    }

    async function activateVpa(accountId) {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/upi-accounts/${accountId}/activate`, { method: 'POST' });
        const data = await res.json();
        if (res.ok) {
          showAdminToast(`VPA "${data.activeAccount.upiId}" is now the active gateway VPA!`);
          fetchGatewaySettings();
        } else {
          alert(data.error || 'Failed to activate UPI account');
        }
      } catch (e) {
        alert('Network error activating UPI account');
      }
    }

    async function toggleVpa(accountId) {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/upi-accounts/${accountId}/toggle`, { method: 'POST' });
        if (res.ok) fetchGatewaySettings();
      } catch (e) { }
    }

    async function deleteVpa(accountId, upiId) {
      if (!confirm(`Are you sure you want to delete VPA "${upiId}"?`)) return;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/upi-accounts/${accountId}`, { method: 'DELETE' });
        if (res.ok) {
          showAdminToast(`VPA "${upiId}" deleted.`);
          fetchGatewaySettings();
        }
      } catch (e) { }
    }

    async function saveMerchantBrandingAndToggles() {
      settingsLoaded = true;
      const businessName = document.getElementById('settingBusinessName')?.value.trim() || '';
      const appName = document.getElementById('settingAppName')?.value.trim() || '{{APP_NAME}}' || 'YOUPI PG';
      const logoUrl = document.getElementById('settingLogoUrl')?.value.trim() || '';
      const primaryColor = document.getElementById('settingPrimaryColor')?.value.trim() || '#0b63e5';
      const sidebarNotice = document.getElementById('settingSidebarNotice')?.value.trim() || (currentMerchantBranding?.sidebarNotice || '');
      const footerGuarantee = document.getElementById('settingFooterGuarantee')?.value.trim() || (currentMerchantBranding?.footerGuarantee || '');
      const counterInstructions = document.getElementById('settingCounterInstructions')?.value.trim() || '';
      const webhookUrl = document.getElementById('settingWebhookUrl')?.value.trim() || '';

      const supportEmails = (document.getElementById('settingSupportEmails')?.value || '').split(/[,\n]+/).map(s => s.trim()).filter(Boolean);
      const supportMobiles = (document.getElementById('settingSupportMobiles')?.value || '').split(/[,\n]+/).map(s => s.trim()).filter(Boolean);
      const privacyPolicyUrl = document.getElementById('settingPrivacyPolicyUrl')?.value.trim() || '';

      const headerTheme = document.getElementById('settingHeaderTheme')?.value || 'gradient';
      const trustBadgeText = (document.getElementById('settingTrustBadgeText')?.value || '').trim() || (currentMerchantBranding?.trustBadgeText || '');
      const hideTrustBadge = document.getElementById('settingHideTrustBadge')?.type === 'checkbox'
        ? (document.getElementById('settingHideTrustBadge')?.checked || false)
        : Boolean(currentMerchantBranding?.hideTrustBadge);
      const subbannerText = document.getElementById('settingSubbannerText')?.value.trim() || '';
      const hideSubbanner = document.getElementById('settingHideSubbanner')?.checked || false;
      const hideTimeSavingBanner = document.getElementById('settingHideTimeSavingBanner')?.checked || false;
      const hidePoweredBy = document.getElementById('settingHidePoweredBy')?.checked || false;
      const cardCounterInstructions = document.getElementById('settingCardCounterInstructions')?.value.trim() || '';
      const termsUrl = document.getElementById('settingTermsUrl')?.value.trim() || '';

      const codChecked = document.getElementById('toggleMethodCod')?.checked ?? true;
      const cashChecked = document.getElementById('toggleMethodCash')?.checked ?? true;
      const cardChecked = document.getElementById('toggleMethodCard')?.checked ?? true;

      const enabledMethods = ['UPI'];
      if (currentSellingMode === 'ONLINE') {
        if (codChecked) enabledMethods.push('COD');
      } else {
        if (cashChecked) enabledMethods.push('CASH_COUNTER');
        if (cardChecked) enabledMethods.push('CARD_COUNTER');
      }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchant-settings`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            merchantId: currentMerchantId || '00000000-0000-0000-0000-000000000001',
            businessName,
            webhookUrl,
            supportEmails,
            supportMobiles,
            privacyPolicyUrl: privacyPolicyUrl || null,
            termsUrl: termsUrl || null,
            sellingMode: currentSellingMode,
            enabledPaymentMethods: enabledMethods,
            codEnabled: codChecked,
            cashEnabled: cashChecked,
            cardEnabled: cardChecked,
            envMode: currentEnvMode,
            domainPrefix: (document.getElementById('settingDomainPrefix')?.value || 'pay').trim().toLowerCase(),
            domainTld: (document.getElementById('settingDomainTld')?.value || '').trim().toLowerCase(),
            customDomain: getCalculatedDomainUrl(),
            branding: {
              appName,
              logoUrl: logoUrl || null,
              primaryColor,
              headerTheme,
              trustBadgeText: trustBadgeText || null,
              hideTrustBadge,
              subbannerText: subbannerText || null,
              hideSubbanner,
              hideTimeSavingBanner,
              hidePoweredBy,
              sidebarNotice: sidebarNotice || null,
              footerGuarantee: footerGuarantee || null,
              counterInstructions: counterInstructions || null,
              cardCounterInstructions: cardCounterInstructions || null,
              termsUrl: termsUrl || null,
              sellingMode: currentSellingMode,
              enabledPaymentMethods: enabledMethods,
              codEnabled: codChecked,
              cashEnabled: cashChecked,
              cardEnabled: cardChecked,
              supportEmails,
              supportMobiles,
              privacyPolicyUrl: privacyPolicyUrl || null,
              envMode: currentEnvMode,
              domainPrefix: (document.getElementById('settingDomainPrefix')?.value || 'pay').trim().toLowerCase(),
              domainTld: (document.getElementById('settingDomainTld')?.value || '').trim().toLowerCase(),
              customDomain: getCalculatedDomainUrl()
            }
          })
        });
        const data = await res.json();
        if (res.ok) {
          if (data.branding) currentMerchantBranding = data.branding;
          showAdminToast('Store settings & branding saved successfully! Live on checkout.');
          updateLiveWhiteLabelPreview();
        } else {
          showAdminToast(data.error || 'Failed to save merchant settings', false);
        }
      } catch (e) {
        showAdminToast('Network error saving merchant settings.', false);
      }
    }

    function copyFieldValue(inputId, label) {
      const el = document.getElementById(inputId);
      const val = el ? el.value.trim() : '';
      if (!val) {
        showAdminToast(`No ${label || 'value'} available to copy.`, false);
        return;
      }
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(val).then(() => {
          showAdminToast(`${label || 'Value'} copied to clipboard!`);
        }).catch(() => {
          el.select();
          document.execCommand('copy');
          showAdminToast(`${label || 'Value'} copied to clipboard!`);
        });
      } else {
        el.select();
        document.execCommand('copy');
        showAdminToast(`${label || 'Value'} copied to clipboard!`);
      }
    }

    async function rotateMerchantApiKey() {
      if (!confirm('Generate a new Secret Merchant API Key (X-Merchant-Key)? Any backend scripts using the previous key will need to be updated.')) {
        return;
      }
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchant-key/rotate`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ merchantId: currentMerchantId || '00000000-0000-0000-0000-000000000001' })
        });
        const data = await res.json();
        if (res.ok && data.merchantKey) {
          const el = document.getElementById('settingMerchantApiKey');
          if (el) el.value = data.merchantKey;
          showAdminToast('New Secret Merchant API Key generated!');
        } else {
          showAdminToast(data.error || 'Failed to rotate Merchant API Key', false);
        }
      } catch (e) {
        showAdminToast('Network error rotating Merchant API Key.', false);
      }
    }

    async function rotateWebhookSecret() {
      if (!confirm('Rotate the Webhook HMAC Signing Secret? Make sure to update YOUPI_WEBHOOK_SECRET on your backend server.')) {
        return;
      }
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/webhook-secret/rotate`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ merchantId: currentMerchantId || '00000000-0000-0000-0000-000000000001' })
        });
        const data = await res.json();
        if (res.ok && data.webhookSecret) {
          const el = document.getElementById('settingWebhookSecret');
          if (el) el.value = data.webhookSecret;
          showAdminToast('New Webhook Secret generated!');
        } else {
          showAdminToast(data.error || 'Failed to rotate Webhook Secret', false);
        }
      } catch (e) {
        showAdminToast('Network error rotating Webhook Secret.', false);
      }
    }

    // --- CANONICAL CLOUDFLARE TUNNEL ROUTING ---
    function getCalculatedDomainUrl() {
      const prefix = (document.getElementById('settingDomainPrefix')?.value || currentDomainPrefix || 'pay').trim().toLowerCase();
      const tld = (document.getElementById('settingDomainTld')?.value || currentDomainTld || '').trim().toLowerCase();
      if (currentEnvMode === 'production' && tld) {
        return `https://${prefix}.${tld}`;
      }
      return 'http://localhost:7000';
    }

    function setEnvMode(mode, save = true) {
      currentEnvMode = mode;
      const btnLoc = document.getElementById('btnEnvLocalhost');
      const btnProd = document.getElementById('btnEnvProduction');
      const badgeLoc = document.getElementById('badgeLocalhostActive');
      const badgeProd = document.getElementById('badgeProductionActive');
      const badgeDisplay = document.getElementById('envModeDisplayBadge');
      const headerBadge = document.getElementById('headerEnvBadge');

      if (mode === 'production') {
        if (btnLoc) { btnLoc.style.borderColor = 'var(--border)'; btnLoc.style.background = 'var(--bg-box)'; }
        if (btnProd) { btnProd.style.borderColor = '#10b981'; btnProd.style.background = 'var(--bg-box)'; }
        if (badgeLoc) badgeLoc.style.display = 'none';
        if (badgeProd) badgeProd.style.display = 'inline-block';
        if (badgeDisplay) { badgeDisplay.textContent = '🌍 PRODUCTION MODE'; badgeDisplay.className = 'badge badge-success'; }
        if (headerBadge) { headerBadge.textContent = '🌍 PRODUCTION'; headerBadge.className = 'badge badge-success'; }
      } else {
        if (btnLoc) { btnLoc.style.borderColor = '#38bdf8'; btnLoc.style.background = 'var(--bg-box)'; }
        if (btnProd) { btnProd.style.borderColor = 'var(--border)'; btnProd.style.background = 'var(--bg-box)'; }
        if (badgeLoc) badgeLoc.style.display = 'inline-block';
        if (badgeProd) badgeProd.style.display = 'none';
        if (badgeDisplay) { badgeDisplay.textContent = '💻 LOCALHOST MODE'; badgeDisplay.className = 'badge badge-info'; }
        if (headerBadge) { headerBadge.textContent = '💻 LOCALHOST'; headerBadge.className = 'badge badge-info'; }
      }

      updateCloudflarePreview();
      if (save && settingsLoaded) saveDomainSettings(false);
    }

    function updateCloudflarePreview() {
      const prefix = (document.getElementById('settingDomainPrefix')?.value || currentDomainPrefix || 'pay').trim().toLowerCase();
      const tld = (document.getElementById('settingDomainTld')?.value || currentDomainTld || '').trim().toLowerCase();
      renderCloudflareRoutes(prefix, tld);
    }

    function renderCloudflareRoutes(prefix, domain) {
      const container = document.getElementById('cloudflareRoutesContainer');
      if (!container) return;

      const cleanDomain = (domain || '').trim().replace(/^https?:\/\//, '').replace(/\/+$/, '');
      const cleanPrefix = (prefix || 'pay').trim().toLowerCase();

      const mkHost = (sub) => cleanDomain ? (sub ? `${sub}.${cleanDomain}` : cleanDomain) : '';

      const routes = [
        {
          key: 'checkout',
          serviceName: '1. Checkout',
          hostname: mkHost(cleanPrefix),
          serviceUrl: 'http://localhost:7000',
          purpose: 'Customer checkout / checkout portal',
          optional: false
        },
        {
          key: 'api',
          serviceName: '2. Payment API',
          hostname: mkHost(`${cleanPrefix}-api`),
          serviceUrl: 'http://localhost:6100',
          purpose: 'Payment API / merchant API / SSE / observer ingestion',
          optional: false
        },
        {
          key: 'admin',
          serviceName: '3. Merchant Admin',
          hostname: mkHost(`${cleanPrefix}-admin`),
          serviceUrl: 'http://localhost:6001',
          purpose: 'Merchant/Admin panel',
          optional: false
        },
        {
          key: 'gmail',
          serviceName: '4. Gmail OAuth / Gmail Observer',
          hostname: mkHost(`${cleanPrefix}-gmail`),
          serviceUrl: 'http://localhost:6003',
          purpose: 'Gmail OAuth callback and Gmail observation service',
          optional: false
        },
        {
          key: 'store',
          serviceName: '5. Demo Store',
          hostname: mkHost(`${cleanPrefix}-store`),
          serviceUrl: 'http://localhost:5000',
          purpose: 'Reference/demo store',
          optional: true
        }
      ];

      container.innerHTML = routes.map(r => `
      <div style="background:var(--bg-box); border:1px solid var(--border); border-radius:0.5rem; padding:1rem; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:1rem;">
        <div>
          <div style="display:flex; align-items:center; gap:0.5rem;">
            <span style="font-weight:700; color:var(--text-heading); font-size:0.95rem;">${escapeHtml(r.serviceName)}</span>
            ${r.optional ? '<span class="badge badge-warning" style="font-size:0.68rem; font-weight:700;">OPTIONAL — DEMO STORE</span>' : ''}
          </div>
          <div style="font-size:0.8rem; color:var(--text-muted); margin-top:0.25rem;">${escapeHtml(r.purpose)}</div>
          <div style="margin-top:0.5rem; display:flex; flex-direction:column; gap:0.3rem; font-size:0.82rem;">
            <div>
              <span style="color:var(--text-muted);">Public Hostname:</span>
              <strong style="color:var(--info); font-family:monospace; margin-left:0.3rem;">${escapeHtml(r.hostname || 'None (configure domain above)')}</strong>
            </div>
            <div>
              <span style="color:var(--text-muted);">Service URL:</span>
              <code style="color:var(--warning); background:var(--bg-input); padding:2px 6px; border-radius:4px; font-family:monospace; margin-left:0.3rem;">${escapeHtml(r.serviceUrl)}</code>
            </div>
          </div>
        </div>
        <div style="display:flex; gap:0.5rem;">
          <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText(${jsArg(r.hostname || '')}, 'Hostname copied to clipboard!')" ${!r.hostname ? 'disabled' : ''}>📋 Copy Hostname</button>
          <button class="btn btn-secondary" style="font-size:0.75rem;" onclick="copyText(${jsArg(r.serviceUrl)}, 'Service URL copied to clipboard!')">📋 Copy Service URL</button>
        </div>
      </div>
    `).join('');
    }

    function copyText(text, msg) {
      if (!text) return;
      navigator.clipboard.writeText(text).then(() => {
        showAdminToast(msg || 'Copied to clipboard!');
      });
    }

    function copyAllMappings() {
      const prefix = (document.getElementById('settingDomainPrefix')?.value || currentDomainPrefix || 'pay').trim().toLowerCase();
      const tld = (document.getElementById('settingDomainTld')?.value || currentDomainTld || '').trim().toLowerCase();
      const domain = tld || 'example.com';

      const text = `CLOUDFLARE TUNNEL ROUTES

1. Checkout
   Public Hostname:
       ${prefix}.${domain}
   Service URL:
       http://localhost:7000
   Purpose:
       Customer checkout / checkout portal

2. Payment API
   Public Hostname:
       ${prefix}-api.${domain}
   Service URL:
       http://localhost:6100
   Purpose:
       Payment API / merchant API / SSE / observer ingestion

3. Merchant Admin
   Public Hostname:
       ${prefix}-admin.${domain}
   Service URL:
       http://localhost:6001
   Purpose:
       Merchant/Admin panel

4. Gmail OAuth / Gmail Observer
   Public Hostname:
       ${prefix}-gmail.${domain}
   Service URL:
       http://localhost:6003
   Purpose:
       Gmail OAuth callback and Gmail observation service

5. Demo Store (OPTIONAL)
   Public Hostname:
       ${prefix}-store.${domain}
   Service URL:
       http://localhost:5000
   Purpose:
       Reference/demo store`;

      navigator.clipboard.writeText(text).then(() => {
        showAdminToast('All 5 Cloudflare mappings copied to clipboard!');
      }).catch(() => {
        showAdminToast('Clipboard copy failed.', false);
      });
    }

    async function saveDomainSettings(notify = true) {
      const prefix = (document.getElementById('settingDomainPrefix')?.value || 'pay').trim().toLowerCase();
      const tld = (document.getElementById('settingDomainTld')?.value || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
      const customDomain = tld ? `https://${prefix}.${tld}` : '';

      currentDomainPrefix = prefix;
      currentDomainTld = tld;

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchant-settings`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            envMode: currentEnvMode,
            domainPrefix: prefix,
            domainTld: tld,
            cloudflareDomain: tld,
            deploymentPrefix: prefix,
            customDomain,
            branding: {
              envMode: currentEnvMode,
              domainPrefix: prefix,
              domainTld: tld,
              cloudflareDomain: tld,
              deploymentPrefix: prefix,
              customDomain
            }
          })
        });
        if (res.ok && notify) {
          showAdminToast(`Cloudflare configuration saved!\nEnvironment: ${currentEnvMode.toUpperCase()}`);
          fetchGatewaySettings();
          fetchGmailCredentials();
        }
      } catch (e) {
        if (notify) showAdminToast('Failed to save Cloudflare configuration.', false);
      }
    }

    // --- CLOUDFLARE TUNNEL RUNNER ---
    async function fetchTunnelStatus() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/tunnel/status`);
        if (!res.ok) return;
        const status = await res.json();
        renderTunnelStatus(status);
      } catch (e) { }
    }

    function renderTunnelStatus(status) {
      const badge = document.getElementById('tunnelStatusBadge');
      const pidInfo = document.getElementById('tunnelPidInfo');
      const logsEl = document.getElementById('tunnelLogsConsole');
      const btnStart = document.getElementById('btnStartTunnel');
      const btnStop = document.getElementById('btnStopTunnel');
      if (!badge) return;

      if (status.running) {
        badge.textContent = '🟢 RUNNING';
        badge.style.background = '#065f46';
        badge.style.color = 'var(--success)';
        if (btnStart) btnStart.style.display = 'none';
        if (btnStop) btnStop.style.display = 'inline-flex';
        const upSec = Math.floor((status.uptimeMs || 0) / 1000);
        const upStr = upSec >= 60 ? `${Math.floor(upSec / 60)}m ${upSec % 60}s` : `${upSec}s`;
        if (pidInfo) pidInfo.textContent = `PID: ${status.pid} | Uptime: ${upStr}`;
      } else {
        badge.textContent = '⚪ STOPPED';
        badge.style.background = 'var(--bg-elevated)';
        badge.style.color = 'var(--text-muted)';
        if (btnStart) btnStart.style.display = 'inline-flex';
        if (btnStop) btnStop.style.display = 'none';
        if (pidInfo) pidInfo.textContent = `PID: - | Uptime: -`;
      }

      if (logsEl && status.logs && status.logs.length > 0) {
        logsEl.textContent = status.logs.join('\n');
        logsEl.scrollTop = logsEl.scrollHeight;
      }
    }

    async function startTunnelFromInput() {
      const cmd = (document.getElementById('settingTunnelCommand')?.value || '').trim();
      if (!cmd) return alert('Please paste your Cloudflare tunnel command.');
      await saveTunnelSettings(cmd);
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/tunnel/start`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ command: cmd })
        });
        const data = await res.json();
        if (!res.ok) alert(`Failed to start tunnel: ${data.error || 'Unknown error'}`);
        else {
          showAdminToast('Cloudflare Tunnel command executed!');
          fetchTunnelStatus();
        }
      } catch (e) {
        alert('Network error connecting to tunnel runner');
      }
    }

    async function stopTunnelFromInput() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/tunnel/stop`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        });
        const data = await res.json();
        showAdminToast(data.message || 'Tunnel stopped.');
        fetchTunnelStatus();
      } catch (e) {
        alert('Network error stopping tunnel');
      }
    }

    async function saveTunnelSettings(cmd) {
      try {
        await fetch(`${API_BASE}/api/v1/admin/merchant-settings`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ cloudflareTunnelCommand: cmd, branding: { cloudflareTunnelCommand: cmd } })
        });
      } catch (e) { }
    }

    // --- ANDROID SMS OBSERVER FUNCTIONS ---
    async function fetchObserversStatus() {
      fetchSmsGatewayDevices();
      fetchSmsPairQr();
      fetchGmailCredentials();
    }

    async function fetchSmsGatewayDevices() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/sms-gateway/devices`);
        if (!res.ok) return;
        const data = await res.json();
        const tbody = document.getElementById('smsDevicesTableBody');
        const badge = document.getElementById('smsGatewayBadge');
        const devBadge = document.getElementById('smsDevBadge');

        const devices = data.devices || [];
        if (badge) {
          badge.className = devices.length > 0 ? 'badge badge-success' : 'badge badge-info';
          badge.innerText = devices.length > 0 ? `${devices.length} PAIRED` : 'STANDBY';
        }
        if (devBadge) {
          devBadge.className = devices.length > 0 ? 'badge badge-success' : 'badge badge-info';
          devBadge.innerText = devices.length > 0 ? `${devices.length} PAIRED` : 'STANDBY';
        }

        if (!tbody) return;
        if (devices.length === 0) {
          tbody.innerHTML = '<tr><td colspan="4" style="text-align:center; color:var(--text-muted); font-size:0.8rem; padding:1rem;">No devices paired yet. Scan QR above to pair.</td></tr>';
          return;
        }

        tbody.innerHTML = devices.map(d => {
          const name = d.deviceName || d.device_name || d.deviceModel || 'Android Observer';
          const id = d.deviceId || d.id || '-';
          const rawTime = d.pairedAt || d.createdAt || d.created_at;
          const timeStr = rawTime ? new Date(rawTime).toLocaleTimeString() : 'Active';
          return `
        <tr>
          <td><strong>${escapeHtml(name)}</strong></td>
          <td><code style="font-size:0.75rem; color:var(--info);">${escapeHtml(id)}</code></td>
          <td><span style="font-size:0.75rem; color:var(--text-muted);">${timeStr}</span></td>
          <td>
            <button class="btn btn-danger" style="padding:0.25rem 0.6rem; font-size:0.72rem;" onclick="unpairSmsDevice(${jsArg(id)})">Unpair</button>
          </td>
        </tr>
      `;
        }).join('');
      } catch (e) { }
    }

    async function fetchSmsPairQr() {
      const box = document.getElementById('smsPairQrBox');
      if (!box) return;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/sms-gateway/pair-qr`);
        if (!res.ok) throw new Error();
        const data = await res.json();
        const qrSvg = data.pairingQrSvg || data.qrSvg;
        if (qrSvg) {
          box.innerHTML = qrSvg;
          const svgEl = box.querySelector('svg');
          if (svgEl) {
            svgEl.setAttribute('width', '100%');
            svgEl.setAttribute('height', '100%');
            svgEl.style.width = '100%';
            svgEl.style.height = '100%';
          }
        }
        const tok1 = document.getElementById('smsTokenVal');
        const tok2 = document.getElementById('smsTokenVal2');
        if (tok1 && data.enrollmentToken) tok1.textContent = data.enrollmentToken;
        if (tok2 && data.enrollmentToken) tok2.textContent = data.enrollmentToken;
      } catch (e) {
        box.innerHTML = '<span style="font-size:0.75rem; color:var(--danger);">Failed to load QR</span>';
      }
    }

    function copySmsToken() {
      const el = document.getElementById('smsTokenVal') || document.getElementById('smsTokenVal2');
      if (el && el.textContent) {
        navigator.clipboard.writeText(el.textContent.trim()).then(() => {
          showAdminToast('Pairing enrollment token copied!');
        });
      }
    }

    async function unpairSmsDevice(deviceId) {
      if (!confirm(`Are you sure you want to unpair device "${deviceId}"?`)) return;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/sms-gateway/devices/${deviceId}`, { method: 'DELETE' });
        if (res.ok) {
          showAdminToast('Device unpaired.');
          fetchSmsGatewayDevices();
        }
      } catch (e) { }
    }

    async function sendTestBankSms() {
      const sender = (document.getElementById('testSmsSender')?.value || 'HDFCBK').trim();
      const body = (document.getElementById('testSmsBody')?.value || '').trim();
      const resBox = document.getElementById('testSmsResult');
      if (!body) return alert('Please enter SMS text.');

      if (resBox) resBox.textContent = 'Dispatching test SMS...';
      try {
        const res = await fetch(`${API_BASE}/api/v1/observers/sms`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ sender, body, timestamp: Date.now() })
        });
        const data = await res.json();
        if (resBox) {
          if (res.ok) {
            resBox.style.color = 'var(--success)';
            resBox.textContent = `✅ Parsed successfully! Amount: ₹${data.event?.amountPaise ? (data.event.amountPaise / 100) : 'N/A'}, Ref: ${data.event?.refId || 'N/A'}`;
          } else {
            resBox.style.color = 'var(--danger)';
            resBox.textContent = `⚠️ Error: ${data.error || 'Failed to parse'}`;
          }
        }
      } catch (e) {
        if (resBox) { resBox.style.color = 'var(--danger)'; resBox.textContent = 'Network error.'; }
      }
    }

    // --- GMAIL DIRECT API & AUTOMATED GOOGLE LOGIN ---
    function copyGmailRedirectUri() {
      const uri = document.getElementById('gmailRedirectUriInput')?.value || 'http://localhost:6003/oauth/callback';
      navigator.clipboard.writeText(uri).then(() => {
        showAdminToast('Redirect URI copied to clipboard!');
      });
    }

    function toggleSecretVisibility() {
      const el = document.getElementById('gmailClientSecretInput');
      if (!el) return;
      el.type = el.type === 'password' ? 'text' : 'password';
    }

    let googleAuthPopup = null;
    let googleAuthPollInterval = null;

    async function startAutomatedGoogleAuth() {
      const banner = document.getElementById('gmailAuthInProgressBanner');
      if (banner) banner.style.display = 'flex';

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/gmail/oauth/start`);
        const data = await res.json();
        if (!res.ok || !data.authUrl) {
          throw new Error(data.error || 'Failed to generate Google Authorization URL');
        }

        const w = 560;
        const h = 680;
        const left = window.screen.width ? (window.screen.width - w) / 2 : 100;
        const top = window.screen.height ? (window.screen.height - h) / 2 : 100;

        if (googleAuthPopup && !googleAuthPopup.closed) {
          googleAuthPopup.focus();
        } else {
          googleAuthPopup = window.open(
            data.authUrl,
            'youpi_google_oauth',
            `width=${w},height=${h},top=${top},left=${left},menubar=no,toolbar=no,location=no,status=no`
          );
        }

        const cleanup = (email) => {
          if (googleAuthPollInterval) {
            clearInterval(googleAuthPollInterval);
            googleAuthPollInterval = null;
          }
          window.removeEventListener('message', onMessage);
          window.removeEventListener('storage', onStorage);
          if (banner) banner.style.display = 'none';

          fetchGmailCredentials().then(() => {
            showAdminToast(`🎉 Google Account Connected: ${email || 'Verified'}! Live UPI observer active.`);
          });
        };

        const onMessage = (event) => {
          if (!event.data || event.data.type !== 'GMAIL_OAUTH_SUCCESS') return;
          // Only the OAuth popup we opened may report a successful link.
          if (event.source !== googleAuthPopup) return;
          if (event.origin !== window.location.origin) return;
          cleanup(event.data.email);
        };
        window.addEventListener('message', onMessage);

        const onStorage = (event) => {
          if (event.key === 'youpi_gmail_oauth_result') {
            try {
              const parsed = JSON.parse(event.newValue);
              if (parsed && parsed.type === 'GMAIL_OAUTH_SUCCESS') {
                cleanup(parsed.email);
              }
            } catch (e) { }
          }
        };
        window.addEventListener('storage', onStorage);

        googleAuthPollInterval = setInterval(() => {
          if (!googleAuthPopup || googleAuthPopup.closed) {
            clearInterval(googleAuthPollInterval);
            googleAuthPollInterval = null;
            if (banner) banner.style.display = 'none';
            // Check state after popup close
            setTimeout(() => {
              fetchGmailCredentials();
            }, 800);
          }
        }, 1000);

      } catch (err) {
        if (banner) banner.style.display = 'none';
        alert('Error initiating Google Login: ' + err.message);
      }
    }

    async function disconnectGmailAccount() {
      if (!confirm('Are you sure you want to disconnect this Google Account? Automated email-based UPI verification will be paused until re-authorized.')) {
        return;
      }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/gmail/disconnect`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ merchantId: currentMerchantId })
        });
        if (res.ok) {
          showAdminToast('Google Account disconnected successfully.');
          const box = document.getElementById('gmailTestResultBox');
          if (box) box.style.display = 'none';
          await fetchGmailCredentials();
        } else {
          const d = await res.json();
          alert(d.error || 'Failed to disconnect account');
        }
      } catch (e) {
        alert('Network error disconnecting Google Account');
      }
    }

    async function fetchGmailCredentials() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/gmail/credentials`);
        if (!res.ok) return;
        const data = await res.json();
        const cfg = data.gmailConfig || {};
        const isConnected = data.oauthStatus === 'CONNECTED' && Boolean(cfg.refreshToken);

        // Manual configuration inputs inside collapsible
        if (document.getElementById('gmailClientIdInput')) document.getElementById('gmailClientIdInput').value = cfg.clientId || data.clientId || '';
        if (document.getElementById('gmailClientSecretInput')) document.getElementById('gmailClientSecretInput').value = cfg.clientSecret || data.clientSecret || '';
        if (document.getElementById('gmailRefreshTokenInput')) document.getElementById('gmailRefreshTokenInput').value = cfg.refreshToken || '';

        const redirectUri = data.redirectUri || 'http://localhost:6003/oauth/callback';
        if (document.getElementById('gmailRedirectUriInput')) document.getElementById('gmailRedirectUriInput').value = redirectUri;
        if (document.getElementById('guideProdUri')) document.getElementById('guideProdUri').textContent = redirectUri;

        // Status badges
        const badge1 = document.getElementById('gmailConfigBadge');
        const badge2 = document.getElementById('gmailConfigBadge2');
        [badge1, badge2].forEach(b => {
          if (b) {
            b.className = isConnected ? 'badge badge-success' : 'badge badge-info';
            b.innerText = isConnected ? 'CONFIGURED' : 'NOT CONFIGURED';
          }
        });

        // Hero Box Dynamic State
        const heroDot = document.getElementById('gmailHeroStatusDot');
        const heroTitle = document.getElementById('gmailHeroStatusTitle');
        const heroDesc = document.getElementById('gmailHeroStatusDesc');
        const authBtnLabel = document.getElementById('btnGooglePrimaryAuthLabel');
        const disconnectBtn = document.getElementById('btnGoogleDisconnect');
        const connectedEmail = data.connectedEmail || cfg.connectedEmail || null;

        if (isConnected) {
          if (heroDot) heroDot.style.background = '#10b981';
          if (heroTitle) heroTitle.textContent = 'Google Account Connected & Active';
          if (heroDesc) {
            heroDesc.innerHTML = `✅ Authenticated as <strong style="color:var(--info); font-family:monospace;">${escapeHtml(connectedEmail || 'Authorized Account')}</strong>. Zero-delay mailbox polling active for incoming UPI payment notifications.`;
          }
          if (authBtnLabel) authBtnLabel.textContent = '🔄 Re-authorize Account';
          if (disconnectBtn) disconnectBtn.style.display = 'inline-flex';
        } else {
          if (heroDot) heroDot.style.background = '#ef4444';
          if (heroTitle) heroTitle.textContent = 'Google Account Disconnected';
          if (heroDesc) {
            heroDesc.textContent = 'Connect your bank-registered Google account with one click. When you click authorize, YouPI PG handles the full OAuth flow, acquires persistent offline credentials, and activates 1-second UPI credit polling.';
          }
          if (authBtnLabel) authBtnLabel.textContent = 'Connect with Google (One-Click)';
          if (disconnectBtn) disconnectBtn.style.display = 'none';
        }

        // Detailed Status Grid
        if (document.getElementById('gmailOAuthStatusText')) {
          document.getElementById('gmailOAuthStatusText').textContent = isConnected ? 'CONNECTED' : 'DISCONNECTED';
          document.getElementById('gmailOAuthStatusText').style.color = isConnected ? '#34d399' : '#f87171';
        }
        if (document.getElementById('gmailTokenStatusText')) {
          document.getElementById('gmailTokenStatusText').textContent = isConnected ? 'ACTIVE (OFFLINE READY)' : 'NOT CONFIGURED';
          document.getElementById('gmailTokenStatusText').style.color = isConnected ? '#34d399' : '#64748b';
        }
        if (document.getElementById('gmailConnectedAccountText')) {
          document.getElementById('gmailConnectedAccountText').textContent = connectedEmail || 'No account authorized';
          document.getElementById('gmailConnectedAccountText').style.color = isConnected ? '#38bdf8' : '#94a3b8';
        }
        if (document.getElementById('gmailLastPollText')) {
          document.getElementById('gmailLastPollText').textContent = data.lastTestedAt ? new Date(data.lastTestedAt).toLocaleTimeString() : (isConnected ? 'Active' : 'Never');
        }
        if (document.getElementById('gmailLastSentText')) {
          document.getElementById('gmailLastSentText').textContent = isConnected ? 'Active (Live Ingestion)' : 'Standby';
          document.getElementById('gmailLastSentText').style.color = isConnected ? '#34d399' : '#94a3b8';
        }
      } catch (e) { }
    }

    async function saveGmailCredentials() {
      const clientId = document.getElementById('gmailClientIdInput')?.value.trim() || '';
      const clientSecret = document.getElementById('gmailClientSecretInput')?.value.trim() || '';
      const refreshToken = document.getElementById('gmailRefreshTokenInput')?.value.trim() || '';

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/gmail/credentials`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ clientId, clientSecret, refreshToken, merchantId: currentMerchantId })
        });
        if (res.ok) {
          showAdminToast('Gmail API credentials saved successfully!');
          fetchGmailCredentials();
        } else {
          const d = await res.json();
          alert(d.error || 'Failed to save Gmail credentials');
        }
      } catch (e) {
        alert('Network error saving Gmail credentials');
      }
    }

    async function testGmailConnection() {
      const clientId = document.getElementById('gmailClientIdInput')?.value.trim() || '';
      const clientSecret = document.getElementById('gmailClientSecretInput')?.value.trim() || '';
      const refreshToken = document.getElementById('gmailRefreshTokenInput')?.value.trim() || '';
      const box = document.getElementById('gmailTestResultBox');

      if (box) {
        box.style.display = 'block';
        box.style.background = 'var(--bg-box)';
        box.style.border = '1px solid #1e293b';
        box.style.color = 'var(--info)';
        box.textContent = '⏳ Testing live Google API connection & mailbox indexing...';
      }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/gmail/test`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ clientId, clientSecret, refreshToken, merchantId: currentMerchantId })
        });
        const data = await res.json();
        if (box) {
          if (res.ok && data.success) {
            box.style.background = 'rgba(16, 185, 129, 0.1)';
            box.style.border = '1px solid #059669';
            box.style.color = 'var(--success)';
            box.innerHTML = `
            <div style="font-weight:700; margin-bottom:0.35rem; color:var(--success);">✅ GOOGLE API VERIFICATION SUCCESSFUL</div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.25rem; font-size:0.78rem; font-family:monospace;">
              <div><strong>AUTHENTICATED:</strong> <span style="color:var(--success);">YES</span></div>
              <div><strong>ACCOUNT:</strong> ${escapeHtml(data.emailAddress || 'Authorized')}</div>
              <div><strong>LAST POLL:</strong> ${new Date(data.lastPoll || Date.now()).toLocaleTimeString()}</div>
              <div><strong>MAILBOX INDEX:</strong> ${escapeHtml(data.lastMessageFetched || 'Mailbox active')}</div>
              <div style="grid-column: span 2;"><strong>STATUS:</strong> <span style="color:var(--success);">100% OPERATIONAL • INCOMING UPI NOTIFICATIONS MONITORED</span></div>
            </div>
          `;
            fetchGmailCredentials();
          } else {
            box.style.background = 'rgba(239, 68, 68, 0.1)';
            box.style.border = '1px solid #dc2626';
            box.style.color = 'var(--danger)';
            box.innerHTML = `⚠️ <strong>Connection Test Notice:</strong> ${escapeHtml(data.error || 'Token expired or invalid. Please click Connect with Google to re-authorize.')}`;
          }
        }
      } catch (e) {
        if (box) {
          box.style.background = 'rgba(239, 68, 68, 0.1)';
          box.style.border = '1px solid #dc2626';
          box.style.color = 'var(--danger)';
          box.textContent = 'Network error testing Gmail connection: ' + e.message;
        }
      }
    }

    function openGmailGuideModal() { document.getElementById('gmailGuideModal').hidden = false; }
    function closeGmailGuideModal() { document.getElementById('gmailGuideModal').hidden = true; }

    // --- WHATSAPP BERRY PROTOCOL ---
    async function fetchWhatsAppStatus(isManual = false) {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/whatsapp/status`);
        if (!res.ok) return;
        const data = await res.json();

        const badge = document.getElementById('waHeaderBadge');
        const dot = document.getElementById('waDotIndicator');
        const title = document.getElementById('waStateTitle');
        const phoneDisplay = document.getElementById('waPhoneDisplay');
        const qrBox = document.getElementById('waQrBox');
        const qrImg = document.getElementById('waQrImg');
        const qrPlaceholder = document.getElementById('waQrPlaceholder');
        const btnDisconnect = document.getElementById('btnWaDisconnect');
        const btnConnect = document.getElementById('btnWaConnect');

        if (data.status === 'CONNECTED') {
          if (badge) { badge.className = 'badge badge-success'; badge.innerText = 'CONNECTED'; }
          if (dot) dot.style.color = 'var(--success)';
          if (title) title.innerText = 'WhatsApp Connected & Active';
          if (phoneDisplay) phoneDisplay.innerHTML = `Linked Phone: <strong style="color:var(--success);">${data.phoneNumber || 'Linked Device'}</strong>`;
          if (qrBox) qrBox.style.display = 'none';
          if (btnDisconnect) btnDisconnect.style.display = 'inline-block';
          if (btnConnect) btnConnect.innerText = '🔄 Re-Pair Device';
        } else if (data.status === 'QR_READY') {
          if (badge) { badge.className = 'badge badge-warning'; badge.innerText = 'QR READY'; }
          if (dot) dot.style.color = 'var(--warning)';
          if (title) title.innerText = 'Scan QR Code with WhatsApp';
          if (phoneDisplay) phoneDisplay.innerText = 'Awaiting pairing scan from merchant WhatsApp handset';
          if (qrBox) qrBox.style.display = 'inline-block';
          if (btnDisconnect) btnDisconnect.style.display = 'none';
          if (btnConnect) btnConnect.innerText = '🔄 Refresh QR Code';

          if (data.qrCode && qrImg && qrPlaceholder) {
            let qrSrc = data.qrCode;
            if (typeof qrSrc === 'string' && !qrSrc.startsWith('data:image/') && !qrSrc.startsWith('http')) {
              if (qrSrc.startsWith('<svg')) {
                qrSrc = 'data:image/svg+xml;utf8,' + encodeURIComponent(qrSrc);
              }
            }

            if (qrSrc && (qrSrc.startsWith('data:image/') || qrSrc.startsWith('http'))) {
              qrImg.src = qrSrc;
              qrImg.style.display = 'block';
              qrPlaceholder.style.display = 'none';
            } else {
              qrImg.style.display = 'none';
              qrPlaceholder.style.display = 'flex';
              qrPlaceholder.innerText = 'Preparing pairing QR... Click "Refresh QR Code"';
            }
          }
        } else if (data.status === 'CONNECTING') {
          if (badge) { badge.className = 'badge badge-info'; badge.innerText = 'CONNECTING'; }
          if (dot) dot.style.color = 'var(--info)';
          if (title) title.innerText = 'Connecting to WhatsApp...';
          if (phoneDisplay) phoneDisplay.innerText = 'Establishing secure WhatsApp pairing session...';
          if (qrBox) qrBox.style.display = 'inline-block';
          if (qrImg) qrImg.style.display = 'none';
          if (qrPlaceholder) {
            qrPlaceholder.style.display = 'flex';
            qrPlaceholder.innerText = 'Generating official WhatsApp pairing QR...';
          }
          if (btnDisconnect) btnDisconnect.style.display = 'none';
          if (btnConnect) btnConnect.innerText = '⏳ Connecting...';
        } else {
          if (badge) { badge.className = 'badge badge-danger'; badge.innerText = 'DISCONNECTED'; }
          if (dot) dot.style.color = 'var(--danger)';
          if (title) title.innerText = 'Session Disconnected';
          if (phoneDisplay) phoneDisplay.innerText = 'No WhatsApp session active';
          if (qrBox) qrBox.style.display = 'inline-block';
          if (qrImg) qrImg.style.display = 'none';
          if (qrPlaceholder) {
            qrPlaceholder.style.display = 'flex';
            qrPlaceholder.innerText = 'Click "Connect WhatsApp" to pair device';
          }
          if (btnDisconnect) btnDisconnect.style.display = 'none';
          if (btnConnect) btnConnect.innerText = '⚡ Connect WhatsApp';
        }

        if (isManual) showAdminToast('WhatsApp session status: ' + data.status);
      } catch (e) { }
    }

    async function reconnectWhatsApp() {
      const btn = document.getElementById('btnWaConnect');
      const oldText = btn.innerText;
      btn.disabled = true;
      btn.innerText = '⏳ Initializing Pairing...';

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/whatsapp/reconnect`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' }
        });
        await fetchWhatsAppStatus();
      } catch (e) {
        alert('Network error initiating WhatsApp pairing');
      } finally {
        btn.disabled = false;
        btn.innerText = oldText;
      }
    }

    async function disconnectWhatsApp() {
      if (!confirm('Disconnect WhatsApp session and wipe credentials?')) return;
      try {
        await fetch(`${API_BASE}/api/v1/admin/whatsapp/disconnect`, { method: 'POST' });
        await fetchWhatsAppStatus();
        showAdminToast('WhatsApp session disconnected.');
      } catch (e) { }
    }

    // --- FLOATING CASHIER MODALS DOCK ---
    let minimizedCounterIds = new Set();
    let cachedPendingPayments = [];
    let isInitialCounterPollDone = false;
    async function pollGlobalCounterPending() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/counter-pending`);
        if (!res.ok) return;
        const data = await res.json();
        const payments = data.payments || [];

        const kpiEl = document.getElementById('kpiPendingCounterCount');
        if (kpiEl) kpiEl.textContent = payments.length;

        const prevIds = new Set((cachedPendingPayments || []).map(p => p.id));
        const newlyAdded = payments.filter(p => !prevIds.has(p.id));
        if (newlyAdded.length > 0 && isInitialCounterPollDone) {
          newlyAdded.forEach(p => {
            const isCash = p.method === 'CASH_COUNTER';
            showAdminToast(`🔔 Counter Payment Request: ${isCash ? '💵 Cash at Till' : '💳 Card at POS'} for ₹${p.amount} (Order #${p.orderId})`);
          });
        }
        isInitialCounterPollDone = true;

        if (typeof renderCounterDesk === 'function') renderCounterDesk(payments);
        renderFloatingCashierModals(payments);
      } catch (e) { }
    }

    function connectAdminEventsSse() {
      try {
        const adminToken = window.__youpiAdminAuth.token();
        if (!adminToken) return; // reconnected right after the token is entered
        if (window.__adminSse) { try { window.__adminSse.close(); } catch (e) {} }
        const adminSse = window.__adminSse = openAuthenticatedEventStream(
          `${API_BASE}/api/v1/admin/stream`,
          adminToken,
          (eventName, data) => {
            if (eventName !== 'counter_payment_requested') return;
            const event = { data };
            pollGlobalCounterPending();
            fetchLiveData();
            if (typeof fetchCounterPayments === 'function') fetchCounterPayments();
            try {
              const payload = event.data ? JSON.parse(event.data) : null;
              const isCash = payload?.method === 'CASH_COUNTER';
              const amt = (payload?.amountPaise) ? `₹${(Number(payload.amountPaise) / 100).toFixed(2)}` : '';
              const ord = (payload?.orderId) ? `(Order #${payload.orderId})` : '';
              showAdminToast(`🔔 Cashier Prompt: Customer requested ${isCash ? '💵 Cash at Till' : '💳 Card at POS'} ${amt} ${ord}!`);
            } catch (e) {
              showAdminToast('🔔 Cashier Prompt: In-store customer selected Cash/Card payment!');
            }
          },
          () => { /* the caller reconnects */ }
        );
        adminSse.addEventListener('status_change', () => {
          pollGlobalCounterPending();
          fetchLiveData();
          if (typeof fetchCounterPayments === 'function') fetchCounterPayments();
        });
        adminSse.onerror = () => {
          adminSse.close();
          setTimeout(connectAdminEventsSse, 3000);
        };
      } catch (e) { }
    }

    function toggleMinimizeCard(paymentId) {
      if (minimizedCounterIds.has(paymentId)) minimizedCounterIds.delete(paymentId);
      else minimizedCounterIds.add(paymentId);
      if (cachedPendingPayments) renderFloatingCashierModals(cachedPendingPayments);
    }

    function renderFloatingCashierModals(payments) {
      cachedPendingPayments = payments;
      const dock = document.getElementById('cashierFloatingDock');
      if (!dock) return;
      if (!payments || payments.length === 0) {
        dock.innerHTML = '';
        return;
      }

      dock.innerHTML = payments.map(p => {
        const isMinimized = minimizedCounterIds.has(p.id);
        const isCash = p.method === 'CASH_COUNTER';
        const methodLabel = isCash ? '💵 Cash at Till' : '💳 Card at Counter';
        const badgeClass = isCash ? 'cashier-badge-cash' : 'cashier-badge-card';
        const orderIdStr = p.orderId ? (String(p.orderId).startsWith('#') ? p.orderId : `#${p.orderId}`) : `#${p.id.slice(0, 8)}`;
        const amountStr = `₹${p.amount}`;
        const customerText = p.customer && p.customer.name ? `${p.customer.name}` : 'Customer at Till';

        if (isMinimized) {
          return `
          <div class="cashier-modal-card is-minimized ${!isCash ? 'is-card-terminal' : ''}">
            <div class="cashier-modal-header">
              <div style="display:flex; align-items:center; gap:6px;">
                <span class="cashier-modal-badge ${badgeClass}">${methodLabel}</span>
                <strong style="color:#ffffff; font-size:12px; font-family:monospace;">${escapeHtmlValue(orderIdStr)}</strong>
                <span style="color:var(--warning); font-size:12px; font-weight:700;">${escapeHtmlValue(amountStr)}</span>
              </div>
              <div style="display:flex; align-items:center; gap:4px;">
                <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard(${jsArg(p.id)})">▲</button>
                <button type="button" class="cashier-btn-accept" style="padding:4px 8px; font-size:11px;" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Accept</button>
              </div>
            </div>
          </div>
        `;
        }

        return `
        <div class="cashier-modal-card ${!isCash ? 'is-card-terminal' : ''}">
          <div class="cashier-modal-header">
            <div style="display:flex; align-items:center; gap:8px;">
              <span class="cashier-modal-badge ${badgeClass}">${methodLabel}</span>
              <strong style="color:#ffffff; font-size:13px; font-family:monospace;">${escapeHtmlValue(orderIdStr)}</strong>
            </div>
            <button type="button" class="cashier-btn-minimize" onclick="toggleMinimizeCard(${jsArg(p.id)})">—</button>
          </div>
          <div class="cashier-modal-body">
            <div class="cashier-modal-amount-row">
              <div>
                <div style="font-size:11px; font-weight:700; color:var(--text-muted); text-transform:uppercase;">Payable at Desk</div>
                <div style="font-size:1.35rem; font-weight:900; color:${isCash ? '#22c55e' : '#38bdf8'};">${escapeHtmlValue(amountStr)}</div>
              </div>
              <div style="text-align:right;">
                <div style="font-size:11px; color:var(--text-muted);">${escapeHtmlValue(customerText)}</div>
                <div style="font-size:11px; color:var(--text-muted); margin-top:2px;">Requested at counter</div>
              </div>
            </div>
            <div class="cashier-modal-actions">
              <button type="button" class="cashier-btn-accept" onclick="confirmCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✓ Confirm &amp; Accept</button>
              <button type="button" class="cashier-btn-decline" onclick="declineCounterPayment(${jsArg(p.id)}, ${jsArg(p.method)})">✕ Decline</button>
            </div>
          </div>
        </div>
      `;
      }).join('');
    }

    // --- ADMIN LIVE TOAST ---
    function showAdminToast(msg, isSuccess = true) {
      let t = document.getElementById('adminLiveToast');
      if (!t) {
        t = document.createElement('div');
        t.id = 'adminLiveToast';
        t.style.cssText = 'position:fixed; bottom:24px; right:24px; z-index:999999; padding:12px 20px; border-radius:8px; font-weight:700; font-size:13.5px; box-shadow:0 8px 24px rgba(0,0,0,0.5); display:flex; align-items:center; gap:8px; transition:all 0.25s ease; transform:translateY(100px); opacity:0; pointer-events:none;';
        document.body.appendChild(t);
      }
      t.style.background = isSuccess ? '#065f46' : '#991b1b';
      t.style.color = '#ffffff';
      t.style.border = isSuccess ? '1px solid #10b981' : '1px solid #ef4444';
      t.innerHTML = `${isSuccess ? '✓' : '⚠️'} ${escapeHtml(msg)}`;
      t.style.transform = 'translateY(0)';
      t.style.opacity = '1';
      clearTimeout(t._timer);
      t._timer = setTimeout(() => {
        t.style.transform = 'translateY(100px)';
        t.style.opacity = '0';
      }, 4000);
    }

    // --- DEVELOPER SETTINGS: FALSE NARRATIVE LOGIC (AUTO-EXPIRES IN 10 MINUTES) ---
    let falseNarrativeExpiry = null;
    let falseNarrativeTimer = null;
    let currentFalseNarrativeMode = 'OFF';

    async function fetchFalseNarrativeStatus() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/false-narrative`);
        if (res.ok) {
          const data = await res.json();
          updateFalseNarrativeUI(data.enabled, data.falseNarrativeUntil, data.narrative || data.mode);
        }
      } catch (e) {
        console.warn('fetchFalseNarrativeStatus error:', e);
      }
    }

    function updateFalseNarrativeUI(isEnabled, untilTimestamp, mode = 'GREEN') {
      const badge = document.getElementById('falseNarrativeBadge');
      const wrap = document.getElementById('falseNarrativeCountdownWrap');
      const timerVal = document.getElementById('falseNarrativeTimerVal');

      if (falseNarrativeTimer) {
        clearInterval(falseNarrativeTimer);
        falseNarrativeTimer = null;
      }

      const now = Date.now();
      const isActive = Boolean(isEnabled && untilTimestamp && Number(untilTimestamp) > now);
      currentFalseNarrativeMode = isActive ? (mode || 'GREEN').toUpperCase() : 'OFF';

      const btnG = document.getElementById('btnNarrativeGreen');
      const btnY = document.getElementById('btnNarrativeYellow');
      const btnR = document.getElementById('btnNarrativeRed');
      const btnOff = document.getElementById('btnNarrativeOff');

      [btnG, btnY, btnR, btnOff].forEach(b => { if (b) { b.style.outline = 'none'; b.style.transform = ''; } });

      if (isActive) {
        falseNarrativeExpiry = Number(untilTimestamp);
        if (wrap) wrap.style.display = 'inline-block';

        if (currentFalseNarrativeMode === 'GREEN' && btnG) {
          btnG.style.outline = '2px solid #34d399';
          btnG.style.transform = 'scale(1.05)';
        } else if (currentFalseNarrativeMode === 'YELLOW' && btnY) {
          btnY.style.outline = '2px solid #fbbf24';
          btnY.style.transform = 'scale(1.05)';
        } else if (currentFalseNarrativeMode === 'RED' && btnR) {
          btnR.style.outline = '2px solid #f87171';
          btnR.style.transform = 'scale(1.05)';
        }

        const updateTimer = () => {
          const remMs = falseNarrativeExpiry - Date.now();
          if (remMs <= 0) {
            clearInterval(falseNarrativeTimer);
            falseNarrativeTimer = null;
            updateFalseNarrativeUI(false, null, 'OFF');
            showAdminToast('False narrative 10-minute window elapsed. Automatically reverted to live server status.');
            return;
          }
          const remSec = Math.floor(remMs / 1000);
          const m = String(Math.floor(remSec / 60)).padStart(2, '0');
          const s = String(remSec % 60).padStart(2, '0');
          const timeStr = `${m}:${s}`;
          if (timerVal) timerVal.textContent = timeStr;
          if (badge) {
            if (currentFalseNarrativeMode === 'GREEN') {
              badge.className = 'badge badge-success';
              badge.textContent = `🟢 GREEN (WORKING) · EXPIRES IN ${timeStr}`;
            } else if (currentFalseNarrativeMode === 'YELLOW') {
              badge.className = 'badge badge-warning';
              badge.textContent = `🟡 YELLOW (EXTRA PROCESSING) · EXPIRES IN ${timeStr}`;
            } else {
              badge.className = 'badge badge-danger';
              badge.textContent = `🔴 RED (DOWN) · EXPIRES IN ${timeStr}`;
            }
          }
        };

        updateTimer();
        falseNarrativeTimer = setInterval(updateTimer, 1000);
      } else {
        falseNarrativeExpiry = null;
        if (wrap) wrap.style.display = 'none';
        if (btnOff) {
          btnOff.style.outline = '2px solid #94a3b8';
        }
        if (badge) {
          badge.className = 'badge badge-info';
          badge.textContent = '⚪ OFF · REAL SERVER STATUS';
        }
      }
    }

    async function handleFalseNarrativeSelect(mode) {
      const isEnabling = mode !== 'OFF';
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/false-narrative`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ enabled: isEnabling, narrative: mode, mode })
        });
        if (res.ok) {
          const data = await res.json();
          updateFalseNarrativeUI(data.enabled, data.falseNarrativeUntil, data.narrative || data.mode);
          if (isEnabling) {
            const desc = mode === 'GREEN'
              ? 'Green (Server Is Working)'
              : (mode === 'YELLOW' ? 'Yellow (Extra processing seconds)' : 'Red (Server Facing Issues)');
            showAdminToast(`False narrative enabled for 10 minutes: ${desc}`);
          } else {
            showAdminToast('False narrative turned off. Reverted to live server status.');
          }
        } else {
          showAdminToast('Failed to update false narrative state', 'error');
          fetchFalseNarrativeStatus();
        }
      } catch (e) {
        showAdminToast('Network error updating false narrative', 'error');
        fetchFalseNarrativeStatus();
      }
    }

    async function handleFalseNarrativeToggle(checked) {
      return handleFalseNarrativeSelect(checked ? 'GREEN' : 'OFF');
    }

    // --- DEVELOPER SETTINGS: TEST MODE (10-MINUTE SERVER-ENFORCED AUTO-EXPIRY & INJECTION) ---
    let testModeExpiry = null;
    let testModeTimer = null;

    function openTestModeModal() {
      const modal = document.getElementById('modalEnableTestMode');
      if (modal) modal.style.display = 'flex';
    }

    function closeTestModeModal() {
      const modal = document.getElementById('modalEnableTestMode');
      if (modal) modal.style.display = 'none';
      const sw = document.getElementById('toggleTestModeSwitch');
      if (sw) sw.checked = Boolean(testModeExpiry && testModeExpiry > Date.now());
    }

    function confirmEnableTestMode() {
      closeTestModeModal();
      setTestMode(true);
    }

    function handleTestModeToggle(checkbox) {
      if (checkbox.checked) {
        // Require explicit confirmation before enabling (Section 11J)
        checkbox.checked = false;
        openTestModeModal();
      } else {
        setTestMode(false);
      }
    }

    async function setTestMode(enabled) {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ enabled })
        });
        if (res.ok) {
          const data = await res.json();
          updateTestModeUI(data.enabled, data.testModeUntil, data.remainingSeconds);
          showAdminToast(enabled
            ? '🧪 Test Mode Enabled (10-minute window). Automatic banning is disabled.'
            : 'Test Mode disabled. Automatic ban system restored.');
        } else {
          showAdminToast('Failed to update Test Mode state', false);
          fetchTestModeStatus();
        }
      } catch (e) {
        showAdminToast('Network error updating Test Mode', false);
        fetchTestModeStatus();
      }
    }

    async function fetchTestModeStatus() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode`);
        if (res.ok) {
          const data = await res.json();
          updateTestModeUI(data.enabled, data.testModeUntil, data.remainingSeconds);
        }
      } catch (e) {
        console.warn('fetchTestModeStatus error:', e);
      }
    }

    function updateTestModeUI(isEnabled, untilTimestamp, remSec) {
      const sw = document.getElementById('toggleTestModeSwitch');
      const badge = document.getElementById('testModeBadge');
      const wrap = document.getElementById('testModeCountdownWrap');
      const timerVal = document.getElementById('testModeTimerVal');
      const label = document.getElementById('testModeLabelText');
      const banner = document.getElementById('testModeActiveBanner');
      const section = document.getElementById('sectionTestObservation');
      const banText = document.getElementById('testModeBanStatusText');

      if (testModeTimer) {
        clearInterval(testModeTimer);
        testModeTimer = null;
      }

      const now = Date.now();
      const isActive = Boolean(isEnabled && untilTimestamp && Number(untilTimestamp) > now);

      if (sw) sw.checked = isActive;
      if (label) label.textContent = isActive ? 'Active (Testing)' : 'Test Mode';

      if (isActive) {
        testModeExpiry = Number(untilTimestamp);
        if (wrap) wrap.style.display = 'inline-block';
        if (banner) banner.style.display = 'block';
        if (section) section.style.display = 'block';
        if (banText) {
          banText.innerHTML = '🛡️ Automatic Ban System: <strong style="color:var(--danger);">DISABLED (Test Mode Active)</strong>';
        }

        const updateTimer = () => {
          const remMs = testModeExpiry - Date.now();
          if (remMs <= 0) {
            clearInterval(testModeTimer);
            testModeTimer = null;
            updateTestModeUI(false, null, 0);
            showAdminToast('Test Mode 10-minute window elapsed. Test Mode = OFF. Automatic ban system restored.');
            return;
          }
          const rem = Math.floor(remMs / 1000);
          const m = String(Math.floor(rem / 60)).padStart(2, '0');
          const s = String(rem % 60).padStart(2, '0');
          const timeStr = `${m}:${s}`;
          if (timerVal) timerVal.textContent = timeStr;
          if (badge) {
            badge.style.background = '#b45309';
            badge.style.color = '#fef3c7';
            badge.textContent = `🔴 [ ON ] TEST MODE (${timeStr})`;
          }
        };

        updateTimer();
        testModeTimer = setInterval(updateTimer, 1000);
        fetchTestModeAuditLog();
      } else {
        testModeExpiry = null;
        if (wrap) wrap.style.display = 'none';
        if (banner) banner.style.display = 'none';
        if (section) section.style.display = 'none';
        if (badge) {
          badge.style.background = 'var(--bg-elevated)';
          badge.style.color = 'var(--text-muted)';
          badge.textContent = '[ OFF ] Test Mode';
        }
        if (banText) {
          banText.innerHTML = '🛡️ Automatic Ban System: <strong style="color:var(--success);">ENABLED (Normal)</strong>';
        }
      }
    }

    function handleTestTimestampChange(val) {
      const customInput = document.getElementById('inputCustomTimestamp');
      if (customInput) {
        customInput.style.display = (val === 'CUSTOM') ? 'inline-block' : 'none';
        if (val === 'CUSTOM' && !customInput.value) {
          customInput.value = new Date().toISOString();
        }
      }
    }

    function generateFakeSmsTemplate() {
      const smsInput = document.getElementById('inputTestSmsMessage');
      const senderInput = document.getElementById('inputTestSmsSender');
      if (senderInput) senderInput.value = 'VM-HDFCBK';
      if (smsInput) {
        const randomRef = '123' + Math.floor(100000000 + Math.random() * 900000000);
        smsInput.value = `A/C XX1234 credited by Rs 499.00 CR. Ref ${randomRef}.`;
      }
      showAdminToast('Generated standard valid Indian Bank SMS template');
    }

    function generateFakeGmailTemplate() {
      const gmailInput = document.getElementById('inputTestGmailMessage');
      const senderInput = document.getElementById('inputTestGmailSender');
      if (senderInput) senderInput.value = '[email protected]';
      if (gmailInput) {
        const randomRef = '123' + Math.floor(100000000 + Math.random() * 900000000);
        gmailInput.value = `Dear Customer, your account has been credited with INR 499.00 via UPI. UPI Ref No: ${randomRef}.`;
      }
      showAdminToast('Generated standard valid Indian Bank Gmail template');
    }

    async function injectTestMessage(channel) {
      const isSms = channel === 'SMS';
      const textElem = document.getElementById(isSms ? 'inputTestSmsMessage' : 'inputTestGmailMessage');
      const senderElem = document.getElementById(isSms ? 'inputTestSmsSender' : 'inputTestGmailSender');
      const timeControl = document.getElementById('selectTestTimestampControl');
      const customTimeInput = document.getElementById('inputCustomTimestamp');

      const raw = (textElem?.value || '').trim();
      if (!raw) {
        showAdminToast(`Please enter test ${channel} message content first`, false);
        return;
      }

      const sender = senderElem?.value?.trim() || (isSms ? 'VM-HDFCBK' : '[email protected]');

      let receivedAt = new Date().toISOString();
      const mode = timeControl?.value || 'CURRENT';
      if (mode === 'BEFORE_SESSION') {
        receivedAt = new Date(Date.now() - 300000).toISOString(); // 5 minutes in past
      } else if (mode === 'AFTER_EXPIRY') {
        receivedAt = new Date(Date.now() + 1800000).toISOString(); // 30 minutes in future
      } else if (mode === 'CUSTOM' && customTimeInput?.value) {
        receivedAt = customTimeInput.value.trim();
      }

      const btn = document.getElementById(isSms ? 'btnInjectSms' : 'btnInjectGmail');
      if (btn) btn.disabled = true;

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode/inject`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            source: channel,
            message: raw,
            sender,
            receivedAt
          })
        });

        const data = await res.json();
        if (res.status === 403) {
          showAdminToast(data.error || 'Test Mode has expired. Injections blocked.', false);
          fetchTestModeStatus();
          return;
        }

        displayTestResults(data);
        fetchTestModeAuditLog();

        if (data.status === 'VERIFIED') {
          showAdminToast(`Observation VERIFIED! Attributed to Order #${data.session?.orderId || 'Active'}`);
        } else if (data.status === 'REJECTED' && (data.reason === 'FRAUDULENT_PAYMENT_INJECTION' || data.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION' || data.stages?.stage5?.reason === 'FRAUDULENT_PAYMENT_INJECTION')) {
          showAdminToast('🚨 FRAUD DETECTED! Customer automatically BANNED and session terminated.', false);
          if (typeof fetchBannedUsers === 'function') fetchBannedUsers();
        } else if (data.status === 'SUSPICIOUS') {
          showAdminToast('Observation flagged as SUSPICIOUS!', false);
        } else {
          showAdminToast(`Observation REJECTED: ${data.reason || 'Verification failed'}`, false);
        }
      } catch (e) {
        showAdminToast(`Error injecting test message: ${e.message}`, false);
      } finally {
        if (btn) btn.disabled = false;
      }
    }

    function displayTestResults(res) {
      const container = document.getElementById('testResultContainer');
      if (!container) return;
      container.style.display = 'block';

      const badge = document.getElementById('testResultStatusBadge');
      const meta = document.getElementById('testResultMeta');
      const sourceElem = document.getElementById('testResultSource');
      const amountElem = document.getElementById('testResultAmount');
      const refElem = document.getElementById('testResultRef');
      const reasonElem = document.getElementById('testResultReason');
      const stagesList = document.getElementById('testResultStagesList');

      const isFraudBan = res.reason === 'FRAUDULENT_PAYMENT_INJECTION' ||
        res.failingCondition === 'FRAUDULENT_PAYMENT_INJECTION' ||
        res.stages?.stage5?.autoBanApplied ||
        res.stages?.stage5?.reason === 'FRAUDULENT_PAYMENT_INJECTION';

      if (badge) {
        badge.textContent = isFraudBan ? 'FRAUD BANNED' : res.status;
        if (res.status === 'VERIFIED') {
          badge.className = 'badge badge-success';
          badge.style.background = '#059669';
        } else if (isFraudBan) {
          badge.className = 'badge badge-danger';
          badge.style.background = '#dc2626';
        } else if (res.status === 'SUSPICIOUS') {
          badge.className = 'badge badge-warning';
          badge.style.background = '#d97706';
        } else {
          badge.className = 'badge badge-danger';
          badge.style.background = '#dc2626';
        }
      }

      if (meta) {
        meta.textContent = `ID: ${res.messageId || 'TEST'} · ${new Date(res.receivedAt).toLocaleTimeString()}`;
      }

      if (sourceElem) sourceElem.textContent = res.source || '-';
      if (amountElem) amountElem.textContent = res.amount || 'None';
      if (refElem) refElem.textContent = res.reference || 'None';
      if (reasonElem) {
        reasonElem.textContent = res.reason || 'None (Passed)';
        reasonElem.style.color = res.reason ? '#f87171' : '#4ade80';
      }

      if (stagesList && res.stages) {
        const stageDefs = [
          { key: 'stage1', num: 1, title: 'Stage 1: Raw Evidence Loader' },
          { key: 'stage2', num: 2, title: 'Stage 2: Source / Sender Filtering' },
          { key: 'stage3', num: 3, title: 'Stage 3: Payment Parser' },
          { key: 'stage4', num: 4, title: 'Stage 4: Payment Verification' },
          { key: 'stage5', num: 5, title: 'Stage 5: Security Engine' },
          { key: 'stage6', num: 6, title: 'Stage 6: Attribution' }
        ];

        stagesList.innerHTML = stageDefs.map(def => {
          const st = res.stages[def.key] || { status: 'UNKNOWN' };
          let statusColor = '#94a3b8';
          let statusBadge = 'PENDING';
          let bg = 'rgba(15,23,42,0.6)';

          if (st.status === 'LOADED' || st.status === 'PASSED' || st.status === 'PARSED' || st.status === 'VERIFIED' || st.status === 'ATTRIBUTED') {
            statusColor = '#34d399';
            statusBadge = st.status;
            bg = 'rgba(6,95,70,0.15)';
          } else if (st.status === 'FAILED') {
            statusColor = '#f87171';
            statusBadge = (def.key === 'stage5' && st.autoBanApplied) ? 'FAILED (CUSTOMER BANNED)' : `FAILED (${st.reason || 'REJECTED'})`;
            bg = 'rgba(153,27,27,0.2)';
          } else if (st.status === 'SUSPICIOUS_FLAGGED' || st.status === 'FLAGGED_SUSPICIOUS') {
            statusColor = '#fbbf24';
            statusBadge = 'SUSPICIOUS (BAN SUPPRESSED)';
            bg = 'rgba(180,83,9,0.2)';
          }

          const detailsText = st.details ? (typeof st.details === 'object' ? JSON.stringify(st.details) : st.details) : (st.diagnostic || '');

          return `
          <div style="background:${bg}; border:1px solid #334155; border-radius:6px; padding:0.6rem 0.85rem; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:0.5rem;">
            <div>
              <strong style="color:#ffffff; font-size:0.83rem;">${def.title}</strong>
              ${detailsText ? `<div style="font-size:0.75rem; color:var(--text); margin-top:0.2rem; font-family:monospace;">${escapeHtml(detailsText)}</div>` : ''}
            </div>
            <span style="font-weight:700; font-size:0.75rem; color:${statusColor};">${statusBadge}</span>
          </div>
        `;
        }).join('');
      }
    }

    async function fetchTestModeAuditLog() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode/audit`);
        if (res.ok) {
          const data = await res.json();
          const tbody = document.getElementById('testAuditLogTableBody');
          if (!tbody) return;

          if (!data.logs || data.logs.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" style="padding:1rem; text-align:center; color:var(--text-muted);">No test records recorded yet.</td></tr>';
            return;
          }

          tbody.innerHTML = data.logs.map(log => {
            const d = log.details || {};
            const time = new Date(log.createdAt).toLocaleTimeString();
            const actionText = log.action === 'TEST_OBSERVATION_INJECTED' ? (d.testMessageId || 'INJECTION') : log.action;
            const rawSnippet = d.raw ? (d.raw.length > 50 ? d.raw.substring(0, 48) + '...' : d.raw) : '-';
            const outcome = d.outcomeStatus || '-';
            let outcomeColor = '#94a3b8';
            if (outcome === 'VERIFIED' || outcome === 'SUCCESS') outcomeColor = '#34d399';
            else if (outcome === 'REJECTED' || outcome === 'FAILED') outcomeColor = '#f87171';
            else if (outcome === 'SUSPICIOUS') outcomeColor = '#fbbf24';

            return `
            <tr style="border-bottom:1px solid var(--border);">
              <td style="padding:0.4rem; color:var(--text-muted);">${time}</td>
              <td style="padding:0.4rem; font-family:monospace; color:var(--text-heading);">${escapeHtml(actionText)}</td>
              <td style="padding:0.4rem; color:var(--info);">${escapeHtml(d.source || '-')}</td>
              <td style="padding:0.4rem; font-weight:700; color:${outcomeColor};">${escapeHtml(outcome)}</td>
              <td style="padding:0.4rem; color:var(--text); font-family:monospace; font-size:0.75rem;">${escapeHtml(rawSnippet)}</td>
            </tr>
          `;
          }).join('');
        }
      } catch (e) {
        console.warn('fetchTestModeAuditLog error:', e);
      }
    }

    // =========================================================================
    // DEVELOPER TOOLS -> PAYMENT SIMULATOR CONTROLLER (FEATURE 65)
    // =========================================================================

    let simCustomersCache = [];
    let simSelectedCustomer = null;
    let simSelectedSession = null;
    let currentSimulatorMerchantId = null;

    async function simGetMerchantId() {
      if (currentSimulatorMerchantId) return currentSimulatorMerchantId;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchant-settings`);
        if (res.ok) {
          const d = await res.json();
          if (d && d.merchantId) {
            currentSimulatorMerchantId = d.merchantId;
            return currentSimulatorMerchantId;
          }
        }
      } catch { }
      return '00000000-0000-0000-0000-000000000001';
    }

    async function simGetHeaders(extraHeaders = {}) {
      const mId = await simGetMerchantId();
      return {
        'x-merchant-id': mId,
        ...extraHeaders
      };
    }

    async function initPaymentSimulator() {
      await simCheckTestMode();
      await simFetchCustomers();
      await simFetchHistory();
    }

    async function simCheckTestMode() {
      try {
        const headers = await simGetHeaders();
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode`, { headers });
        if (res.ok) {
          const data = await res.json();
          const statusEl = document.getElementById('simTestModeStatus');
          const btnEnable = document.getElementById('simBtnEnableTestMode');
          if (data.enabled) {
            if (statusEl) {
              statusEl.innerHTML = `<span style="color:var(--success);">● ACTIVE</span> (${Math.floor(data.remainingSeconds / 60)}m ${data.remainingSeconds % 60}s)`;
            }
            if (btnEnable) btnEnable.style.display = 'none';
          } else {
            if (statusEl) {
              statusEl.innerHTML = `<span style="color:var(--danger);">● OFF / EXPIRED</span>`;
            }
            if (btnEnable) {
              btnEnable.style.display = 'inline-block';
              btnEnable.textContent = 'Enable Test Mode';
            }
          }
        }
      } catch (e) {
        console.warn('simCheckTestMode error:', e);
      }
    }

    async function simQuickEnableTestMode() {
      try {
        const headers = await simGetHeaders({ 'Content-Type': 'application/json' });
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/test-mode`, {
          method: 'POST',
          headers,
          body: JSON.stringify({ enabled: true })
        });
        if (res.ok) {
          showAdminToast('Developer Test Mode Enabled (10 minutes)');
          await simCheckTestMode();
        }
      } catch (e) {
        showAdminToast('Failed to enable Test Mode: ' + e.message, 'error');
      }
    }

    async function simFetchCustomers(searchQuery = '') {
      const select = document.getElementById('simCustomerSelect');
      if (select) {
        select.innerHTML = '<option value="" disabled selected>Loading existing customers...</option>';
      }

      try {
        const url = searchQuery
          ? `${API_BASE}/api/v1/admin/dev/simulator/customers?q=${encodeURIComponent(searchQuery)}`
          : `${API_BASE}/api/v1/admin/dev/simulator/customers`;
        const headers = await simGetHeaders();
        const res = await fetch(url, { headers });
        if (!res.ok) throw new Error('Failed to load customers');
        const data = await res.json();
        simCustomersCache = data.customers || [];

        if (!select) return;

        if (simCustomersCache.length === 0) {
          select.innerHTML = '<option value="" disabled selected>No existing customers found.</option>';
          return;
        }

        select.innerHTML = simCustomersCache.map(c => {
          return `<option value="${c.id}">${escapeHtml(c.name)} (${escapeHtml(c.phone || c.email)})</option>`;
        }).join('');

        // If already selected, re-select
        if (simSelectedCustomer) {
          select.value = simSelectedCustomer.id;
        }
      } catch (e) {
        if (select) select.innerHTML = `<option value="" disabled selected>Error: ${escapeHtml(e.message)}</option>`;
      }
    }

    function simFilterCustomers(q) {
      simFetchCustomers(q);
    }

    async function simSelectCustomer(customerId) {
      if (!customerId) return;
      const cust = simCustomersCache.find(c => c.id === customerId);
      if (!cust) return;

      simSelectedCustomer = cust;
      simSelectedSession = null;

      // Display customer details
      const box = document.getElementById('simSelectedCustomerBox');
      if (box) box.style.display = 'block';
      const nameEl = document.getElementById('simCustName');
      const phoneEl = document.getElementById('simCustPhone');
      const emailEl = document.getElementById('simCustEmail');
      if (nameEl) nameEl.textContent = cust.name;
      if (phoneEl) phoneEl.textContent = cust.phone || cust.mobileNumber || 'No phone';
      if (emailEl) emailEl.textContent = cust.email || 'No email';

      // Fetch sessions
      await simReloadSessions();
    }

    async function simReloadSessions() {
      if (!simSelectedCustomer) return;
      const container = document.getElementById('simSessionsList');
      if (container) {
        container.innerHTML = '<div style="padding:1.5rem; text-align:center; color:var(--text-muted);">Loading payment sessions...</div>';
      }

      // Hide session bar and terminal notice
      const bar = document.getElementById('simSelectedSessionBar');
      if (bar) bar.style.display = 'none';
      const notice = document.getElementById('simTerminalNotice');
      if (notice) notice.style.display = 'none';

      try {
        const headers = await simGetHeaders();
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/simulator/customers/${simSelectedCustomer.id}/sessions`, { headers });
        if (!res.ok) throw new Error('Failed to load customer sessions');
        const data = await res.json();
        const sessions = data.sessions || [];

        if (!container) return;

        if (sessions.length === 0) {
          container.innerHTML = `
          <div style="padding:1.5rem; text-align:center; color:var(--text-muted); font-size:0.84rem;">
            No payment sessions found for ${escapeHtml(simSelectedCustomer.name)}.<br/>
            <span style="font-size:0.75rem; color:#475569;">Initiate a payment via checkout or Coin Store to test.</span>
          </div>
        `;
          return;
        }

        container.innerHTML = sessions.map(s => {
          const isProcessable = s.isProcessable;
          let badgeColor = '#94a3b8';
          let badgeBg = '#1e293b';
          if (s.status === 'ACTIVE') { badgeColor = '#0f172a'; badgeBg = '#22c55e'; }
          else if (s.status === 'PROCESSING') { badgeColor = '#0f172a'; badgeBg = '#fbbf24'; }
          else if (s.status === 'RECONCILED' || s.status === 'SUCCESS') { badgeColor = '#ffffff'; badgeBg = '#059669'; }
          else if (s.status === 'OBSERVED_SUCCESS') { badgeColor = '#78350f'; badgeBg = '#fcd34d'; }
          else if (s.status === 'MANUAL_REVIEW') { badgeColor = '#ffffff'; badgeBg = '#b45309'; }
          else if (s.status === 'CANCELLED' || s.status === 'EXPIRED' || s.status === 'FAILED') { badgeColor = '#ffffff'; badgeBg = '#ef4444'; }

          return `
          <div class="sim-session-row" onclick="simPickSession(${jsArg(s.id)})" style="cursor:pointer; display:flex; justify-content:space-between; align-items:center; padding:0.5rem 0.65rem; border-radius:6px; margin-bottom:0.35rem; background:var(--bg-box); border:1px solid var(--border); transition:all 0.15s ease;" id="simSessItem_${escapeAttribute(s.id)}">
            <div>
              <div style="display:flex; align-items:center; gap:0.4rem;">
                <input type="radio" name="simSessionRadio" id="radio_${s.id}" style="accent-color:var(--primary); cursor:pointer;" />
                <strong style="color:var(--text-heading); font-size:0.84rem; font-family:monospace;">${escapeHtml(s.id.slice(0, 14))}...</strong>
                <span style="color:var(--text-muted); font-size:0.78rem;">#${escapeHtml(s.orderId)}</span>
              </div>
              <div style="font-size:0.72rem; color:var(--text-muted); margin-left:1.4rem;">
                Device: <code>${escapeHtml(s.deviceId ? s.deviceId.slice(0, 16) : 'None')}</code>
              </div>
            </div>
            <div style="text-align:right;">
              <strong style="color:var(--info); font-size:0.88rem;">₹${escapeHtml(s.amount)}</strong>
              <div style="margin-top:0.15rem;">
                <span class="badge" style="font-size:0.68rem; padding:0.15rem 0.45rem; background:${badgeBg}; color:${badgeColor}; font-weight:700;">
                  ${escapeHtml(s.status)}
                </span>
              </div>
            </div>
          </div>
        `;
        }).join('');

        // Store sessions
        container._sessions = sessions;

        // Auto-select the first processable session if available, else first session
        const firstActive = sessions.find(s => s.isProcessable) || sessions[0];
        if (firstActive) {
          simPickSession(firstActive.id);
        }
      } catch (e) {
        if (container) container.innerHTML = `<div style="padding:1rem; color:var(--danger); font-size:0.8rem;">Error: ${escapeHtml(e.message)}</div>`;
      }
    }

    function simPickSession(sessionId) {
      const container = document.getElementById('simSessionsList');
      const sessions = container?._sessions || [];
      const sess = sessions.find(s => s.id === sessionId);
      if (!sess) return;

      simSelectedSession = sess;

      // Highlight row
      document.querySelectorAll('.sim-session-row').forEach(r => {
        r.style.borderColor = '#1e293b';
        r.style.background = 'var(--bg-box)';
      });
      const item = document.getElementById(`simSessItem_${sessionId}`);
      if (item) {
        item.style.borderColor = 'var(--primary)';
        item.style.background = 'rgba(20,184,166,0.12)';
      }
      const radio = document.getElementById(`radio_${sessionId}`);
      if (radio) radio.checked = true;

      // Update session details bar
      const bar = document.getElementById('simSelectedSessionBar');
      if (bar) bar.style.display = 'flex';
      const idEl = document.getElementById('simSelectedSessionId');
      const ordEl = document.getElementById('simSelectedSessionOrder');
      const amtEl = document.getElementById('simSelectedSessionAmount');
      const badgeEl = document.getElementById('simSelectedSessionBadge');

      if (idEl) idEl.textContent = sess.id;
      if (ordEl) ordEl.textContent = `#${sess.orderId}`;
      if (amtEl) amtEl.textContent = `₹${sess.amount}`;
      if (badgeEl) {
        badgeEl.textContent = sess.status;
        badgeEl.style.background = sess.isProcessable ? '#22c55e' : '#ef4444';
        badgeEl.style.color = sess.isProcessable ? '#0f172a' : '#ffffff';
      }

      // Terminal session enforcement (Section 6)
      const notice = document.getElementById('simTerminalNotice');
      const btnSms = document.getElementById('simBtnPushSms');
      const btnGmail = document.getElementById('simBtnPushGmail');

      const isTerminal = ['SUCCESS', 'OBSERVED_SUCCESS', 'RECONCILED', 'MANUAL_REVIEW', 'FAILED', 'EXPIRED', 'CANCELLED'].includes(sess.status);
      if (isTerminal) {
        if (notice) notice.style.display = 'block';
        if (btnSms) { btnSms.disabled = true; btnSms.style.opacity = '0.5'; btnSms.style.cursor = 'not-allowed'; }
        if (btnGmail) { btnGmail.disabled = true; btnGmail.style.opacity = '0.5'; btnGmail.style.cursor = 'not-allowed'; }
      } else {
        if (notice) notice.style.display = 'none';
        if (btnSms) { btnSms.disabled = false; btnSms.style.opacity = '1'; btnSms.style.cursor = 'pointer'; }
        if (btnGmail) { btnGmail.disabled = false; btnGmail.style.opacity = '1'; btnGmail.style.cursor = 'pointer'; }

        // Fill in sample amounts matching session
        const randRef = Math.floor(100000000000 + Math.random() * 900000000000);
        const smsContent = document.getElementById('simSmsContent');
        if (smsContent && (!smsContent.value || smsContent.value.includes('credited with'))) {
          smsContent.value = `A/C XX1234 credited with Rs ${sess.amount} CR. Ref ${randRef}`;
        }
        const gmailContent = document.getElementById('simGmailContent');
        if (gmailContent && (!gmailContent.value || gmailContent.value.includes('credited with'))) {
          gmailContent.value = `Your account has been credited with ₹${sess.amount} via UPI. Reference ${randRef}`;
        }
      }
    }

    function simToggleTimeInput(stream) {
      const isSms = stream === 'SMS';
      const typeSelect = document.getElementById(isSms ? 'simSmsTimeType' : 'simGmailTimeType');
      const customInput = document.getElementById(isSms ? 'simSmsCustomTime' : 'simGmailCustomTime');
      if (!typeSelect || !customInput) return;

      if (typeSelect.value === 'CUSTOM') {
        customInput.style.display = 'block';
        if (!customInput.value) customInput.value = new Date().toISOString();
      } else {
        customInput.style.display = 'none';
      }
    }

    async function simInjectObservation(stream) {
      await simCheckTestMode();

      const isSms = stream === 'SMS';
      const senderInput = document.getElementById(isSms ? 'simSmsSender' : 'simGmailSender');
      const contentInput = document.getElementById(isSms ? 'simSmsContent' : 'simGmailContent');
      const timeTypeSelect = document.getElementById(isSms ? 'simSmsTimeType' : 'simGmailTimeType');
      const customTimeInput = document.getElementById(isSms ? 'simSmsCustomTime' : 'simGmailCustomTime');

      const sender = senderInput ? senderInput.value : '';
      const content = contentInput ? contentInput.value : '';
      let receivedAt = undefined;
      if (timeTypeSelect && timeTypeSelect.value === 'CUSTOM' && customTimeInput) {
        receivedAt = customTimeInput.value;
      }

      const payload = {
        source: stream,
        sender,
        content,
        receivedAt,
        paymentSessionId: simSelectedSession ? simSelectedSession.id : undefined,
        customerId: simSelectedCustomer ? simSelectedCustomer.id : undefined
      };

      const btn = document.getElementById(isSms ? 'simBtnPushSms' : 'simBtnPushGmail');
      const originalText = btn ? btn.innerHTML : '';
      if (btn) {
        btn.disabled = true;
        btn.innerHTML = '<span>⏳</span> Processing via Real Pipeline...';
      }

      try {
        const headers = await simGetHeaders({ 'Content-Type': 'application/json' });
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/simulator/inject`, {
          method: 'POST',
          headers,
          body: JSON.stringify(payload)
        });

        const data = await res.json();

        if (!res.ok) {
          showAdminToast(data.error || 'Simulation rejected by engine', 'error');
          if (data.error === 'SESSION NO LONGER ACTIVE') {
            const notice = document.getElementById('simTerminalNotice');
            if (notice) notice.style.display = 'block';
          }
        } else {
          showAdminToast(`Observation Processed: ${data.status}`);
        }

        // Display results in Result Inspector
        simRenderResultInspector(data, stream);

        // Refresh customer sessions & history
        if (simSelectedCustomer) {
          await simReloadSessions();
        }
        await simFetchHistory();
      } catch (e) {
        showAdminToast('Injection Network Error: ' + e.message, 'error');
      } finally {
        if (btn) {
          btn.disabled = false;
          btn.innerHTML = originalText;
        }
      }
    }

    function simRenderResultInspector(data, stream) {
      const card = document.getElementById('simResultInspectorCard');
      if (!card) return;
      card.style.display = 'block';
      card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });

      // Status Badge
      const badge = document.getElementById('simResultStatusBadge');
      if (badge) {
        badge.textContent = data.status || 'UNKNOWN';
        if (data.status === 'VERIFIED') {
          badge.style.background = '#22c55e';
          badge.style.color = '#0f172a';
        } else if (data.status === 'REJECTED') {
          badge.style.background = '#ef4444';
          badge.style.color = '#ffffff';
        } else if (data.status === 'SUSPICIOUS') {
          badge.style.background = '#f59e0b';
          badge.style.color = '#0f172a';
        } else {
          badge.style.background = '#64748b';
          badge.style.color = '#ffffff';
        }
      }

      const msgIdEl = document.getElementById('simResultMessageId');
      if (msgIdEl) msgIdEl.textContent = `ID: ${data.messageId || '-'}`;

      const tgtEl = document.getElementById('simResTargetSession');
      if (tgtEl) {
        tgtEl.textContent = (simSelectedSession ? `${simSelectedSession.id.slice(0, 10)}... (#${simSelectedSession.orderId})` : 'Auto-Resolved');
      }

      const srcEl = document.getElementById('simResSource');
      if (srcEl) srcEl.textContent = stream;

      const amtEl = document.getElementById('simResAmount');
      if (amtEl) amtEl.textContent = data.amount || '-';

      const refEl = document.getElementById('simResRef');
      if (refEl) refEl.textContent = data.reference || '-';

      const reasonEl = document.getElementById('simResReason');
      if (reasonEl) {
        reasonEl.textContent = data.reason || data.failingCondition || 'None (Passed)';
        reasonEl.style.color = (data.reason || data.failingCondition) ? '#f87171' : '#22c55e';
      }

      // Exact Raw Text
      const rawEl = document.getElementById('simResRawText');
      if (rawEl) rawEl.textContent = data.raw || data.syntheticObservation?.raw || '';

      // Stages 1 through 6 Visualizer
      const stagesContainer = document.getElementById('simStagesContainer');
      if (stagesContainer) {
        const stages = data.stages || {};
        const stageDefs = [
          { key: 'stage1', num: 1, name: 'Stage 1: Observation Loaded & Evidence Preserved', desc: 'Normalized and preserved verbatim raw text evidence.' },
          { key: 'stage2', num: 2, name: 'Stage 2: Source / Sender Filtering', desc: 'Validates bank institutional shortcodes or authorized email domains.' },
          { key: 'stage3', num: 3, name: 'Stage 3: Payment Notification Parser', desc: 'Parses currency indicators (Rs, Rs., ₹, INR), credit indicators, 12-digit UTR.' },
          { key: 'stage4', num: 4, name: 'Stage 4: Payment Verification Engine', desc: 'Verifies active session match, timestamp window, amount equality, deduplication.' },
          { key: 'stage5', num: 5, name: 'Stage 5: Security & Fraud Pattern Engine', desc: 'Scans for injection patterns and checks customer ban status.' },
          { key: 'stage6', num: 6, name: 'Stage 6: Attribution & State Machine Transition', desc: 'Attributes payment, promotes next queued customer, and emits webhooks & SSE.' }
        ];

        stagesContainer.innerHTML = stageDefs.map(def => {
          const s = stages[def.key] || { status: 'PENDING' };
          let icon = '⚪';
          let statusColor = '#94a3b8';
          let bgColor = '#0f172a';
          let borderCol = '#1e293b';

          if (s.status === 'LOADED' || s.status === 'PASSED' || s.status === 'PARSED' || s.status === 'VERIFIED' || s.status === 'ATTRIBUTED') {
            icon = '✅';
            statusColor = '#22c55e';
            borderCol = 'rgba(34,197,94,0.3)';
          } else if (s.status === 'FAILED') {
            icon = '❌';
            statusColor = '#ef4444';
            borderCol = 'rgba(239,68,68,0.4)';
            bgColor = 'rgba(239,68,68,0.06)';
          } else if (s.status === 'FLAGGED_CUSTOMER_SENDER' || s.status === 'FLAGGED_SUSPICIOUS' || s.status === 'SUSPICIOUS') {
            icon = '⚠️';
            statusColor = '#f59e0b';
            borderCol = 'rgba(245,158,11,0.4)';
          } else if (s.status === 'UNRESOLVED') {
            icon = '❓';
            statusColor = '#cbd5e1';
          }

          const detailText = s.details ? (typeof s.details === 'string' ? s.details : JSON.stringify(s.details)) : def.desc;
          const reasonBadge = s.reason ? `<span class="badge" style="background:#ef4444; color:#fff; font-size:0.7rem; margin-left:0.5rem;">${escapeHtml(s.reason)}</span>` : '';

          return `
          <div style="background:${bgColor}; border:1px solid ${borderCol}; border-radius:8px; padding:0.6rem 0.85rem; display:flex; justify-content:space-between; align-items:center;">
            <div>
              <div style="display:flex; align-items:center; gap:0.5rem;">
                <span style="font-size:1.05rem;">${icon}</span>
                <strong style="color:#ffffff; font-size:0.86rem;">${escapeHtml(def.name)}</strong>
                ${reasonBadge}
              </div>
              <div style="font-size:0.75rem; color:var(--text-muted); margin-left:1.85rem; margin-top:0.15rem;">
                ${escapeHtml(detailText)}
              </div>
            </div>
            <div>
              <span style="font-size:0.75rem; font-weight:800; color:${statusColor}; font-family:monospace;">
                ${escapeHtml(s.status || 'PENDING')}
              </span>
            </div>
          </div>
        `;
        }).join('');
      }
    }

    async function simFetchHistory() {
      try {
        const headers = await simGetHeaders();
        const res = await fetch(`${API_BASE}/api/v1/admin/dev/simulator/history`, { headers });
        if (res.ok) {
          const data = await res.json();
          const tbody = document.getElementById('simHistoryTableBody');
          if (!tbody) return;

          if (!data.history || data.history.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="padding:1.5rem; text-align:center; color:var(--text-muted);">No simulations recorded yet.</td></tr>';
            return;
          }

          tbody.innerHTML = data.history.map(item => {
            const time = new Date(item.timestamp).toLocaleTimeString();
            let resColor = '#94a3b8';
            if (item.result === 'VERIFIED') resColor = '#22c55e';
            else if (item.result === 'REJECTED') resColor = '#ef4444';
            else if (item.result === 'SUSPICIOUS') resColor = '#f59e0b';

            return `
            <tr style="border-bottom:1px solid var(--border);">
              <td style="padding:0.6rem 0.75rem; color:var(--text-muted); font-size:0.78rem;">${time}</td>
              <td style="padding:0.6rem 0.75rem; color:var(--info); font-weight:700;">${escapeHtml(item.source)}</td>
              <td style="padding:0.6rem 0.75rem; color:var(--text-heading); font-family:monospace; font-size:0.78rem;">${escapeHtml(item.sender || '-')}</td>
              <td style="padding:0.6rem 0.75rem; color:var(--text-heading); font-family:monospace; font-size:0.75rem;">${escapeHtml(item.sessionId ? item.sessionId.slice(0, 10) + '...' : '-')}</td>
              <td style="padding:0.6rem 0.75rem; font-weight:800; color:${resColor};">${escapeHtml(item.result)}</td>
              <td style="padding:0.6rem 0.75rem; font-family:monospace; color:var(--text-muted); font-size:0.72rem;">${escapeHtml(item.messageId || '-')}</td>
              <td style="padding:0.6rem 0.75rem; color:var(--danger); font-size:0.75rem;">${escapeHtml(item.failingReason || '-')}</td>
            </tr>
          `;
          }).join('');
        }
      } catch (e) {
        console.warn('simFetchHistory error:', e);
      }
    }

    // =========================================================================
    // SECURITY & BAN MANAGEMENT CONTROLLER (Section 9)
    // =========================================================================

    let bannedUsersCache = [];
    let currentModalCustomerId = null;
    let currentUnbanCustomerId = null;

    async function fetchBannedUsers() {
      const tbody = document.getElementById('bannedUsersTableBody');
      if (tbody) {
        tbody.innerHTML = '<tr><td colspan="10" style="text-align:center; color:var(--text-muted); padding:2rem;">Loading banned users...</td></tr>';
      }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/banned-users`);
        if (!res.ok) throw new Error('Failed to fetch banned users');
        const data = await res.json();
        bannedUsersCache = data.bannedUsers || [];
        renderBannedUsersTable(bannedUsersCache);
      } catch (e) {
        console.warn('fetchBannedUsers error:', e);
        if (tbody) {
          tbody.innerHTML = `<tr><td colspan="10" style="text-align:center; color:var(--danger); padding:1.5rem;">⚠️ Failed to load banned users: ${escapeHtml(e.message)}</td></tr>`;
        }
      }
    }

    function renderBannedUsersTable(users) {
      const tbody = document.getElementById('bannedUsersTableBody');
      if (!tbody) return;

      if (!users || users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="10" style="text-align:center; color:var(--text-muted); padding:2rem;">No customers currently banned.</td></tr>';
        return;
      }

      tbody.innerHTML = users.map(u => {
        const bannedTime = u.bannedAt ? new Date(u.bannedAt).toLocaleString() : '-';
        const reasonBadge = u.banReason === 'MANUAL_BAN'
          ? '<span class="badge badge-warning" style="font-size:0.75rem;">MANUAL_BAN</span>'
          : `<span class="badge badge-danger" style="font-size:0.75rem;">${escapeHtml(u.banReason || 'FRAUDULENT_PAYMENT_INJECTION')}</span>`;

        return `
        <tr style="border-bottom:1px solid var(--border);">
          <td><strong style="color:#ffffff;">${escapeHtml(u.name || 'Anonymous')}</strong><div style="font-size:0.72rem; color:var(--text-muted); font-family:monospace;">${u.id}</div></td>
          <td style="color:var(--text); font-size:0.83rem;">${escapeHtml(u.email || '-')}</td>
          <td style="color:var(--info); font-family:monospace; font-size:0.83rem;">${escapeHtml(u.phone || u.mobileNumber || '-')}</td>
          <td><span class="badge badge-danger" style="font-weight:800; font-size:0.75rem; letter-spacing:0.04em;">BANNED</span></td>
          <td style="color:var(--text-muted); font-size:0.8rem;">${bannedTime}</td>
          <td>${reasonBadge}</td>
          <td><code style="font-size:0.75rem; color:var(--text-muted);">${u.lastSessionId ? u.lastSessionId.substring(0, 14) + '...' : '-'}</code></td>
          <td style="color:var(--text-muted); font-size:0.78rem;">${escapeHtml(u.lastDevice || 'android-gateway')}</td>
          <td><span class="badge badge-info" style="font-size:0.7rem;">${escapeHtml(u.source || 'SMS')}</span></td>
          <td style="text-align:right;">
            <div style="display:inline-flex; gap:0.4rem;">
              <button class="btn btn-secondary" style="padding:0.3rem 0.6rem; font-size:0.75rem;" onclick="viewBanDetails(${jsArg(u.id)})">🔍 Details</button>
              <button class="btn btn-success" style="padding:0.3rem 0.6rem; font-size:0.75rem; background:#059669; border-color:#059669;" onclick="promptUnbanCustomer(${jsArg(u.id)}, ${jsArg(u.name || '')}, ${jsArg(u.phone || u.mobileNumber || '')})">🔓 Unban</button>
            </div>
          </td>
        </tr>
      `;
      }).join('');
    }

    function filterBannedUsers(query) {
      const q = (query || '').toLowerCase().trim();
      if (!q) {
        renderBannedUsersTable(bannedUsersCache);
        return;
      }
      const filtered = bannedUsersCache.filter(u =>
        (u.name && u.name.toLowerCase().includes(q)) ||
        (u.email && u.email.toLowerCase().includes(q)) ||
        (u.phone && u.phone.toLowerCase().includes(q)) ||
        (u.mobileNumber && u.mobileNumber.toLowerCase().includes(q)) ||
        (u.id && u.id.toLowerCase().includes(q))
      );
      renderBannedUsersTable(filtered);
    }

    async function viewBanDetails(customerId) {
      currentModalCustomerId = customerId;
      const modal = document.getElementById('banDetailsModal');
      const modalBody = document.getElementById('banDetailsModalBody');
      if (!modal || !modalBody) return;

      modalBody.innerHTML = '<div style="text-align:center; padding:2rem; color:var(--text-muted);">Loading comprehensive forensic evidence...</div>';
      modal.hidden = false;

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/banned-users/${customerId}`);
        if (!res.ok) throw new Error('Failed to retrieve ban evidence dossier');
        const data = await res.json();

        const c = data.customer || {};
        const b = data.banDetails || {};
        const meta = data.observationMetadata || {};
        const disc = data.discrepancyAnalysis || {};
        const timeline = data.timeline || {};
        const rawEvidence = data.rawEvidence || 'NO_RAW_PAYLOAD_AVAILABLE';

        modalBody.innerHTML = `
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:1.25rem; margin-bottom:1.25rem;">
          <!-- 1. Customer Profile -->
          <div style="background:var(--bg-input); border:1px solid var(--border); border-radius:8px; padding:1rem;">
            <div style="font-weight:700; color:var(--info); font-size:0.85rem; margin-bottom:0.75rem; text-transform:uppercase; letter-spacing:0.05em;">👤 Customer Profile</div>
            <div style="display:grid; grid-template-columns:auto 1fr; gap:0.4rem 0.8rem; font-size:0.82rem;">
              <span style="color:var(--text-muted);">Name:</span><strong style="color:#ffffff;">${escapeHtml(c.name || '-')}</strong>
              <span style="color:var(--text-muted);">Phone:</span><span style="color:var(--info); font-family:monospace;">${escapeHtml(c.phone || '-')}</span>
              <span style="color:var(--text-muted);">Email:</span><span style="color:var(--text);">${escapeHtml(c.email || '-')}</span>
              <span style="color:var(--text-muted);">Customer ID:</span><code style="color:var(--text-muted); font-size:0.72rem;">${c.id || '-'}</code>
              <span style="color:var(--text-muted);">Created At:</span><span style="color:var(--text);">${c.createdAt ? new Date(c.createdAt).toLocaleString() : '-'}</span>
              <span style="color:var(--text-muted);">Total Orders:</span><strong style="color:#ffffff;">${c.totalOrders || 0}</strong>
              <span style="color:var(--text-muted);">Total Spent:</span><strong style="color:var(--success);">₹${c.totalSpentRupees || '0.00'}</strong>
            </div>
          </div>

          <!-- 2. Ban & Trigger Details -->
          <div style="background:var(--bg-input); border:1px solid var(--border); border-radius:8px; padding:1rem;">
            <div style="font-weight:700; color:var(--danger); font-size:0.85rem; margin-bottom:0.75rem; text-transform:uppercase; letter-spacing:0.05em;">⚖️ Enforcement Attributes</div>
            <div style="display:grid; grid-template-columns:auto 1fr; gap:0.4rem 0.8rem; font-size:0.82rem;">
              <span style="color:var(--text-muted);">Ban Type:</span><span class="badge ${b.banType === 'AUTOMATIC' ? 'badge-danger' : 'badge-warning'}">${escapeHtml(b.banType)}</span>
              <span style="color:var(--text-muted);">Trigger Event:</span><strong style="color:var(--danger);">${escapeHtml(b.triggerEvent)}</strong>
              <span style="color:var(--text-muted);">Timestamp:</span><span style="color:var(--text);">${b.triggerTimestamp ? new Date(b.triggerTimestamp).toLocaleString() : '-'}</span>
              <span style="color:var(--text-muted);">Session ID:</span><code style="color:var(--text-muted); font-size:0.72rem;">${b.paymentSessionId || '-'}</code>
              <span style="color:var(--text-muted);">Order ID:</span><strong style="color:#ffffff;">#${escapeHtml(b.orderId || '-')}</strong>
              <span style="color:var(--text-muted);">Session Amount:</span><strong style="color:var(--info);">₹${b.sessionAmountRupees || '-'}</strong>
            </div>
          </div>
        </div>

        <!-- 3. VERBATIM RAW EVIDENCE (PRESERVED WORD-FOR-WORD) -->
        <div style="margin-bottom:1.25rem;">
          <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.5rem;">
            <div style="font-weight:700; color:var(--danger); font-size:0.85rem; text-transform:uppercase; letter-spacing:0.05em;">
              📜 Verbatim Raw Message Evidence (Exact Word-For-Word Payload)
            </div>
            <span class="badge badge-danger" style="font-size:0.68rem;">UNTOUCHED RAW STRING</span>
          </div>
          <pre style="background:var(--bg-input); border:1px solid #dc2626; color:var(--danger); padding:1.1rem; border-radius:8px; font-family:Consolas, Monaco, monospace; white-space:pre-wrap; word-break:break-all; font-size:0.85rem; line-height:1.55; margin:0; box-shadow:inset 0 2px 4px rgba(0,0,0,0.5);"><code>${escapeHtml(rawEvidence)}</code></pre>
          <div style="font-size:0.74rem; color:var(--text-muted); margin-top:0.35rem; font-style:italic;">
            * Stored verbatim without parsing truncation or database mutation. Exact fake message sent by the customer.
          </div>
        </div>

        <!-- 4. Observation Metadata & Discrepancy Analysis -->
        <div style="display:grid; grid-template-columns:1fr 1fr; gap:1.25rem; margin-bottom:1.25rem;">
          <!-- Metadata -->
          <div style="background:var(--bg-input); border:1px solid var(--border); border-radius:8px; padding:1rem;">
            <div style="font-weight:700; color:var(--text-muted); font-size:0.85rem; margin-bottom:0.75rem; text-transform:uppercase; letter-spacing:0.05em;">📡 Observation Metadata</div>
            <div style="display:grid; grid-template-columns:auto 1fr; gap:0.4rem 0.8rem; font-size:0.82rem;">
              <span style="color:var(--text-muted);">Source Channel:</span><strong style="color:#ffffff;">${escapeHtml(meta.source || 'SMS')}</strong>
              <span style="color:var(--text-muted);">Sender Identity:</span><code style="color:var(--info);">${escapeHtml(meta.sender || '-')}</code>
              <span style="color:var(--text-muted);">Receiver Identity:</span><span style="color:var(--text);">${escapeHtml(meta.receiver || '-')}</span>
              <span style="color:var(--text-muted);">Observer Device ID:</span><code style="color:var(--text); font-size:0.72rem;">${escapeHtml(meta.deviceId || '-')}</code>
            </div>
          </div>

          <!-- Discrepancy Analysis -->
          <div style="background:var(--bg-input); border:1px solid var(--border); border-radius:8px; padding:1rem;">
            <div style="font-weight:700; color:var(--warning); font-size:0.85rem; margin-bottom:0.75rem; text-transform:uppercase; letter-spacing:0.05em;">🔍 Discrepancy Forensic Audit</div>
            <div style="display:grid; grid-template-columns:auto 1fr; gap:0.35rem 0.8rem; font-size:0.8rem;">
              <span style="color:var(--text-muted);">Customer Phone:</span><span style="color:var(--info); font-family:monospace;">${escapeHtml(disc.customerPhone || '-')}</span>
              <span style="color:var(--text-muted);">Sender Number:</span><span style="color:var(--danger); font-family:monospace;">${escapeHtml(disc.observationSender || '-')}</span>
              <span style="color:var(--text-muted);">Legitimate Bank:</span><strong style="color:var(--danger);">${escapeHtml(disc.registeredBankHeader || 'NO')}</strong>
              <span style="color:var(--text-muted);">Session Amount:</span><span style="color:#ffffff;">${escapeHtml(disc.sessionAmount || '-')}</span>
              <span style="color:var(--text-muted);">Fraud Engine Verdict:</span><strong style="color:var(--danger);">${escapeHtml(disc.result || 'FRAUDULENT_PAYMENT_INJECTION')}</strong>
            </div>
          </div>
        </div>

        <!-- 5. Forensic Timeline -->
        <div style="background:var(--bg-input); border:1px solid var(--border); border-radius:8px; padding:1rem;">
          <div style="font-weight:700; color:var(--text); font-size:0.85rem; margin-bottom:0.6rem; text-transform:uppercase; letter-spacing:0.05em;">⏱️ Immutable Incident Timeline</div>
          <div style="display:flex; flex-direction:column; gap:0.4rem; font-size:0.8rem;">
            <div style="display:flex; gap:0.75rem;"><span style="color:var(--text-muted); width:170px;">1. Payment Session Created:</span><span style="color:#ffffff;">${timeline.sessionCreated ? new Date(timeline.sessionCreated).toLocaleString() : '-'}</span></div>
            <div style="display:flex; gap:0.75rem;"><span style="color:var(--text-muted); width:170px;">2. Fake Observation Injected:</span><span style="color:var(--danger); font-weight:700;">${timeline.fakeObservationReceived ? new Date(timeline.fakeObservationReceived).toLocaleString() : '-'}</span></div>
            <div style="display:flex; gap:0.75rem;"><span style="color:var(--text-muted); width:170px;">3. Confirmation Blocked:</span><span style="color:var(--danger); font-weight:700;">${timeline.paymentRejected ? new Date(timeline.paymentRejected).toLocaleString() : '-'} (DO NOT PAY)</span></div>
            <div style="display:flex; gap:0.75rem;"><span style="color:var(--text-muted); width:170px;">4. Customer Identity Banned:</span><span style="color:var(--danger); font-weight:700;">${timeline.autoBanExecuted ? new Date(timeline.autoBanExecuted).toLocaleString() : '-'} (AUTO BAN)</span></div>
          </div>
        </div>
      `;
      } catch (e) {
        modalBody.innerHTML = `<div style="text-align:center; padding:2rem; color:var(--danger);">⚠️ Error retrieving ban details: ${escapeHtml(e.message)}</div>`;
      }
    }

    function closeBanDetailsModal() {
      const modal = document.getElementById('banDetailsModal');
      if (modal) modal.hidden = true;
      currentModalCustomerId = null;
    }

    function handleModalUnbanClick() {
      if (!currentModalCustomerId) return;
      const user = bannedUsersCache.find(u => u.id === currentModalCustomerId);
      promptUnbanCustomer(currentModalCustomerId, user?.name || '', user?.phone || user?.mobileNumber || '');
    }

    function promptUnbanCustomer(customerId, name, phone) {
      currentUnbanCustomerId = customerId;
      const nameEl = document.getElementById('unbanCustName');
      const phoneEl = document.getElementById('unbanCustPhone');
      const reasonSelect = document.getElementById('unbanReasonSelect');
      const reasonCustom = document.getElementById('unbanReasonCustom');

      if (nameEl) nameEl.textContent = name || 'Customer';
      if (phoneEl) phoneEl.textContent = phone || customerId;
      if (reasonSelect) reasonSelect.value = 'Customer verified via phone call';
      if (reasonCustom) { reasonCustom.style.display = 'none'; reasonCustom.value = ''; }

      const modal = document.getElementById('unbanConfirmModal');
      if (modal) modal.hidden = false;
    }

    function handleUnbanReasonChange() {
      const select = document.getElementById('unbanReasonSelect');
      const custom = document.getElementById('unbanReasonCustom');
      if (!select || !custom) return;
      if (select.value === 'OTHER') {
        custom.style.display = 'block';
        custom.focus();
      } else {
        custom.style.display = 'none';
      }
    }

    function closeUnbanModal() {
      const modal = document.getElementById('unbanConfirmModal');
      if (modal) modal.hidden = true;
      currentUnbanCustomerId = null;
    }

    async function executeUnbanCustomer() {
      if (!currentUnbanCustomerId) return;
      const select = document.getElementById('unbanReasonSelect');
      const custom = document.getElementById('unbanReasonCustom');
      let reason = select ? select.value : 'Administrative Override';
      if (reason === 'OTHER') {
        reason = custom ? custom.value.trim() : '';
      }

      if (!reason) {
        return alert('A mandatory reason is required to unban a customer.');
      }

      const btn = document.getElementById('btnConfirmUnbanAction');
      if (btn) { btn.disabled = true; btn.textContent = 'Unbanning...'; }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/unban`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            customerId: currentUnbanCustomerId,
            reason
          })
        });

        const data = await res.json();
        if (res.ok) {
          showAdminToast(data.message || 'Customer unbanned successfully! Access restored.');
          closeUnbanModal();
          closeBanDetailsModal();
          fetchBannedUsers();
          fetchSecurityEvents();
          fetchSecurityHistory();
        } else {
          alert(data.error || 'Failed to unban customer');
        }
      } catch (e) {
        alert('Network error unbanning customer');
      } finally {
        if (btn) { btn.disabled = false; btn.textContent = 'Confirm Unban'; }
      }
    }

    async function openManualBanModal() {
      const modal = document.getElementById('manualBanModal');
      const select = document.getElementById('manualBanCustomerSelect');
      const inputId = document.getElementById('manualBanCustomerIdInput');
      const reasonInput = document.getElementById('manualBanReasonInput');
      const notesInput = document.getElementById('manualBanNotesInput');

      if (inputId) inputId.value = '';
      if (reasonInput) reasonInput.value = 'MANUAL_BAN';
      if (notesInput) notesInput.value = '';

      if (select) {
        select.innerHTML = '<option value="">-- Choose Existing Customer --</option>';
        try {
          const res = await fetch(`${API_BASE}/api/v1/admin/customers`);
          if (res.ok) {
            const data = await res.json();
            (data.customers || []).forEach(c => {
              const opt = document.createElement('option');
              opt.value = c.id;
              opt.textContent = `${c.name || 'Anonymous'} (${c.phone || c.email || c.id}) - Status: ${c.status}`;
              select.appendChild(opt);
            });
          }
        } catch (e) { }
      }

      if (modal) modal.hidden = false;
    }

    function handleManualBanCustomerChange() {
      const select = document.getElementById('manualBanCustomerSelect');
      const input = document.getElementById('manualBanCustomerIdInput');
      if (select && input && select.value) {
        input.value = select.value;
      }
    }

    function closeManualBanModal() {
      const modal = document.getElementById('manualBanModal');
      if (modal) modal.hidden = true;
    }

    async function executeManualBan() {
      const select = document.getElementById('manualBanCustomerSelect');
      const inputId = document.getElementById('manualBanCustomerIdInput');
      const reasonInput = document.getElementById('manualBanReasonInput');
      const notesInput = document.getElementById('manualBanNotesInput');

      const customerId = (inputId?.value || select?.value || '').trim();
      const reason = (reasonInput?.value || '').trim();
      const notes = (notesInput?.value || '').trim();

      if (!customerId) {
        return alert('Please select a customer or enter a Customer ID / Phone / Email.');
      }
      if (!reason) {
        return alert('Mandatory ban reason is required.');
      }

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/manual-ban`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ customerId, reason, notes })
        });
        const data = await res.json();
        if (res.ok) {
          showAdminToast(data.message || 'Customer manually banned.');
          closeManualBanModal();
          fetchBannedUsers();
          fetchSecurityEvents();
          fetchSecurityHistory();
        } else {
          alert(data.error || 'Failed to ban customer');
        }
      } catch (e) {
        alert('Network error executing manual ban');
      }
    }

    async function fetchSecurityEvents() {
      const tbody = document.getElementById('securityEventsTableBody');
      if (!tbody) return;
      tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:2rem;">Loading security events...</td></tr>';

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/events`);
        if (!res.ok) throw new Error('Failed to fetch events');
        const data = await res.json();
        const events = data.events || [];

        if (events.length === 0) {
          tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:2rem;">No security events recorded yet.</td></tr>';
          return;
        }

        tbody.innerHTML = events.map(e => {
          const time = e.createdAt ? new Date(e.createdAt).toLocaleString() : '-';
          const rawSnippet = e.rawMessage ? (e.rawMessage.length > 55 ? e.rawMessage.substring(0, 52) + '...' : e.rawMessage) : '-';
          let eventBadge = '<span class="badge badge-info">' + escapeHtml(e.eventType) + '</span>';
          if (e.eventType === 'FRAUDULENT_PAYMENT_INJECTION') eventBadge = '<span class="badge badge-danger">FRAUD_INJECTION</span>';
          else if (e.eventType === 'USER_UNBANNED') eventBadge = '<span class="badge badge-success">USER_UNBANNED</span>';
          else if (e.eventType === 'MANUAL_BAN') eventBadge = '<span class="badge badge-warning">MANUAL_BAN</span>';

          return `
          <tr style="border-bottom:1px solid var(--border);">
            <td style="color:var(--text-muted); font-size:0.8rem;">${time}</td>
            <td>${eventBadge}</td>
            <td><code style="color:var(--text); font-size:0.75rem;">${escapeHtml(e.customerId || '-')}</code></td>
            <td><span class="badge badge-secondary" style="font-size:0.7rem;">${escapeHtml(e.source || 'SMS')}</span></td>
            <td style="color:var(--info); font-family:monospace; font-size:0.8rem;">${escapeHtml(e.sender || '-')}</td>
            <td style="color:var(--danger); font-size:0.8rem;">${escapeHtml(e.fraudReason || '-')}</td>
            <td><code style="color:var(--danger); font-size:0.75rem; background:var(--bg-input); padding:2px 6px; border-radius:4px;">${escapeHtml(rawSnippet)}</code></td>
            <td style="text-align:right;">
              ${e.customerId ? `<button class="btn btn-secondary" style="padding:0.25rem 0.5rem; font-size:0.75rem;" onclick="viewBanDetails(${jsArg(e.customerId)})">View Dossier</button>` : '-'}
            </td>
          </tr>
        `;
        }).join('');
      } catch (e) {
        tbody.innerHTML = `<tr><td colspan="8" style="text-align:center; color:var(--danger); padding:1.5rem;">⚠️ Failed to load events: ${escapeHtml(e.message)}</td></tr>`;
      }
    }

    async function fetchSecurityHistory() {
      const tbody = document.getElementById('securityHistoryTableBody');
      if (!tbody) return;
      tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:2rem;">Loading ban history...</td></tr>';

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/security/history`);
        if (!res.ok) throw new Error('Failed to fetch security history');
        const data = await res.json();
        const logs = data.history || [];

        if (logs.length === 0) {
          tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; color:var(--text-muted); padding:2rem;">No historical ban actions logged.</td></tr>';
          return;
        }

        tbody.innerHTML = logs.map(l => {
          const time = l.createdAt ? new Date(l.createdAt).toLocaleString() : '-';
          const d = l.details || {};
          const detailsStr = JSON.stringify(d);
          let actionBadge = '<span class="badge badge-info">' + escapeHtml(l.action) + '</span>';
          if (l.action === 'CUSTOMER_AUTOMATICALLY_BANNED') actionBadge = '<span class="badge badge-danger">AUTO_BANNED</span>';
          else if (l.action === 'USER_UNBANNED') actionBadge = '<span class="badge badge-success">UNBANNED</span>';
          else if (l.action === 'CUSTOMER_MANUALLY_BANNED') actionBadge = '<span class="badge badge-warning">MANUAL_BAN</span>';

          return `
          <tr style="border-bottom:1px solid var(--border);">
            <td style="color:var(--text-muted); font-size:0.8rem;">${time}</td>
            <td>${actionBadge}</td>
            <td style="color:var(--text); font-size:0.82rem;">${escapeHtml(l.actorId || l.actorType || 'SYSTEM')}</td>
            <td><code style="color:var(--info); font-size:0.75rem;">${escapeHtml(l.entityId || '-')}</code></td>
            <td style="color:var(--text); font-size:0.75rem; font-family:monospace; max-width:320px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${escapeHtml(detailsStr)}">
              ${escapeHtml(detailsStr)}
            </td>
          </tr>
        `;
        }).join('');
      } catch (e) {
        tbody.innerHTML = `<tr><td colspan="5" style="text-align:center; color:var(--danger); padding:1.5rem;">⚠️ Failed to load history: ${escapeHtml(e.message)}</td></tr>`;
      }
    }

    // --- MERCHANT MANAGEMENT & CREDENTIALS ---
    let merchantsList = [];

    async function fetchMerchantsList() {
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchants`);
        if (!res.ok) return;
        const data = await res.json();
        merchantsList = data.merchants || [];
        renderMerchantSelector();
      } catch (err) {
        console.warn('[Admin] Failed to fetch merchants list:', err);
      }
    }

    function renderMerchantSelector() {
      const sel = document.getElementById('headerMerchantSelector');
      if (!sel) return;
      if (merchantsList.length === 0) {
        sel.innerHTML = `<option value="${escapeHtml(currentMerchantId)}">Default Store</option>`;
        return;
      }
      sel.innerHTML = merchantsList.map(m => `
        <option value="${escapeHtml(m.id)}" ${m.id === currentMerchantId ? 'selected' : ''}>
          ${escapeHtml(m.businessName || 'Store')} (${escapeHtml(m.id.substring(0, 8))}...)
        </option>
      `).join('');
    }

    async function onMerchantSwitch(merchantId) {
      if (!merchantId || merchantId === currentMerchantId) return;
      currentMerchantId = merchantId;
      showAdminToast(`Switched store context.`, true);
      await loadMerchantSettings();
      renderMerchantCredentials();
    }

    function renderMerchantCredentials(mData = null) {
      const idEl = document.getElementById('settingDisplayMerchantId');
      const keyEl = document.getElementById('settingDisplayApiKey');
      const snippetEl = document.getElementById('settingIntegrationSnippet');
      if (idEl) idEl.value = currentMerchantId || '';

      const currentM = merchantsList.find(m => m.id === currentMerchantId);
      const host = window.location.origin;
      const snippet = `<script src="${host}/youpi.js" data-youpi-key="${currentMerchantId}"><\/script>`;
      if (snippetEl) snippetEl.value = snippet;

      if (keyEl) {
        if (mData && mData.apiKey) {
          keyEl.value = mData.apiKey;
        } else if (currentM && currentM.apiKeyConfigured) {
          keyEl.value = 'yp_live_••••••••••••••••';
        } else {
          keyEl.value = currentMerchantId;
        }
      }
    }

    function openNewMerchantModal() {
      const modal = document.getElementById('newMerchantModal');
      if (modal) modal.hidden = false;
      const nameInp = document.getElementById('modalMerchantName');
      if (nameInp) { nameInp.value = ''; nameInp.focus(); }
      const slugInp = document.getElementById('modalMerchantSlug');
      if (slugInp) slugInp.value = '';
      const vpaInp = document.getElementById('modalMerchantVpa');
      if (vpaInp) vpaInp.value = '';
      const emailInp = document.getElementById('modalMerchantEmail');
      if (emailInp) emailInp.value = '';
      const phoneInp = document.getElementById('modalMerchantPhone');
      if (phoneInp) phoneInp.value = '';
      const hookInp = document.getElementById('modalMerchantWebhook');
      if (hookInp) hookInp.value = '';
    }

    function closeNewMerchantModal() {
      const modal = document.getElementById('newMerchantModal');
      if (modal) modal.hidden = true;
    }

    function syncModalSlug(val) {
      const slugInp = document.getElementById('modalMerchantSlug');
      if (slugInp && !slugInp.dataset.manual) {
        slugInp.value = String(val || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
      }
    }

    async function submitNewMerchant() {
      const name = document.getElementById('modalMerchantName')?.value?.trim();
      if (!name) {
        showAdminToast('Store / Business Name is required.', false);
        return;
      }
      const slug = document.getElementById('modalMerchantSlug')?.value?.trim() || undefined;
      const vpa = document.getElementById('modalMerchantVpa')?.value?.trim() || undefined;
      const contactEmail = document.getElementById('modalMerchantEmail')?.value?.trim() || '';
      const contactPhone = document.getElementById('modalMerchantPhone')?.value?.trim() || '';
      const webhookUrl = document.getElementById('modalMerchantWebhook')?.value?.trim() || undefined;

      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchants`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ businessName: name, slug, vpa, contactEmail, contactPhone, webhookUrl })
        });
        const data = await res.json();
        if (!res.ok) {
          showAdminToast(data.error || 'Failed to create merchant.', false);
          return;
        }

        closeNewMerchantModal();
        showAdminToast(`Merchant '${name}' onboarded successfully!`, true);
        await fetchMerchantsList();
        currentMerchantId = data.merchant.id;
        renderMerchantSelector();
        await loadMerchantSettings();
        renderMerchantCredentials(data.merchant);
      } catch (err) {
        showAdminToast(`Network error: ${err.message}`, false);
      }
    }

    async function rotateMerchantApiKey() {
      if (!confirm('Are you sure you want to rotate this merchant API key? Existing integrations using the old key will need to be updated.')) return;
      try {
        const res = await fetch(`${API_BASE}/api/v1/admin/merchants/${encodeURIComponent(currentMerchantId)}/rotate-key`, {
          method: 'POST'
        });
        const data = await res.json();
        if (!res.ok) {
          showAdminToast(data.error || 'Failed to rotate key.', false);
          return;
        }
        showAdminToast('API key rotated successfully!', true);
        renderMerchantCredentials(data);
        await fetchMerchantsList();
      } catch (err) {
        showAdminToast(`Error rotating key: ${err.message}`, false);
      }
    }

    function copyMerchantId() {
      const val = document.getElementById('settingDisplayMerchantId')?.value || currentMerchantId;
      navigator.clipboard?.writeText(val);
      showAdminToast('Merchant ID copied to clipboard!', true);
    }

    function copyMerchantApiKey() {
      const val = document.getElementById('settingDisplayApiKey')?.value;
      if (!val || val.includes('•')) {
        navigator.clipboard?.writeText(currentMerchantId);
        showAdminToast('Merchant ID copied as public key!', true);
      } else {
        navigator.clipboard?.writeText(val);
        showAdminToast('API key copied to clipboard!', true);
      }
    }

    function copyIntegrationSnippet() {
      const val = document.getElementById('settingIntegrationSnippet')?.value;
      if (val) {
        navigator.clipboard?.writeText(val);
        showAdminToast('Script snippet copied to clipboard!', true);
      }
    }

    // --- INITIALIZATION ---
    const validSections = ['operations', 'storeSettings', 'developerHub', 'security'];
    const hashSec = (window.location.hash || '').replace('#', '').trim();
    const searchSec = new URLSearchParams(window.location.search).get('section');
    const initialSec = validSections.includes(hashSec) ? hashSec : (validSections.includes(searchSec) ? searchSec : 'operations');
    switchSection(initialSec);

    window.addEventListener('hashchange', () => {
      const h = (window.location.hash || '').replace('#', '').trim();
      if (validSections.includes(h) && h !== activeSection) {
        switchSection(h);
      }
    });

    fetchMerchantsList();
    fetchGatewaySettings();
    fetchObserversStatus();
    fetchWhatsAppStatus();
    loadServices();
    fetchFalseNarrativeStatus();
    fetchTestModeStatus();
    connectServicesLogsSse();
    connectAdminEventsSse();
    pollGlobalCounterPending();

    pollingTimer = setInterval(fetchLiveData, 2500);
    setInterval(pollGlobalCounterPending, 4000);
    setInterval(fetchTunnelStatus, 4000);
    setInterval(fetchWhatsAppStatus, 4000);
    setInterval(fetchSmsGatewayDevices, 3500);
    setInterval(loadServices, 5000);
    setInterval(fetchFalseNarrativeStatus, 15000);
    setInterval(fetchTestModeStatus, 15000);
  </script>

</body>

</html>