Subversion Repositories SmartDukaan

Rev

Rev 37783 | Blame | Compare with Previous | Last modification | View Log | RSS feed

## LMS Dashboard — STANDALONE full page. Faithful copy of sts-mockup.html design (app bar + tabs + hand-drawn
## funnel/heat-map, NO charts), wired to REAL lead data. Rendered as a complete HTML doc (layout.vm = $screen_content).
## Served at GET /lms/dashboard. Seeds: regions[], summaryJson, stateFunnelJson, slaHeatmapJson, ageingJson, fromDate, toDate,
## viewerName / viewerRole / viewerInitials (signed-in user for the app bar, pre-escaped).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LMS — Lead Dashboard</title>
<style>
  :root{
    --bg:#eef1f7; --card:#ffffff; --ink:#1d2433; --muted:#69748c; --soft:#97a1b5;
    --line:#e6e9f1; --line2:#eef1f6;
    --navy:#1f2a5e; --navy2:#2f3d78;
    --brand:#3b5bdb; --brand2:#5c7cfa; --teal:#0ca678; --cyan:#1098ad;
    --amber:#f59f00; --orange:#e8590c; --red:#e03131; --coral:#f0483e; --violet:#7048e8; --pink:#d6336c;
    --good:#2f9e44; --warn:#f08c00; --bad:#e03131;
  }
  *{box-sizing:border-box}
  html,body{margin:0;background:var(--bg);color:var(--ink);
    font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;font-size:14px}
  .wrap{max-width:1340px;margin:0 auto;padding:0 24px 90px}
  a{color:var(--brand);text-decoration:none}
  code,.mono{font-family:ui-monospace,Menlo,Consolas,monospace}

  /* ===== app bar ===== */
  .appbar{position:sticky;top:0;z-index:40;background:var(--navy);color:#fff;margin:0;padding:0 24px}
  .appbar .inner{max-width:1340px;margin:0 auto;display:flex;align-items:center;gap:18px;height:58px}
  .logo{display:flex;align-items:center;gap:10px;font-weight:800;letter-spacing:-.01em;font-size:16px}
  .logo .mk{width:30px;height:30px;border-radius:8px;background:linear-gradient(135deg,var(--coral),#ff7a5c);display:flex;align-items:center;justify-content:center;font-size:15px;font-weight:800}
  .logo small{display:block;font-size:10px;font-weight:600;color:#aab3d6;letter-spacing:.06em}
  .search{flex:1;max-width:560px;position:relative}
  .search input{width:100%;background:#2b3768;border:1px solid #3a488a;color:#fff;border-radius:9px;padding:9px 12px 9px 34px;font-size:13px;font-weight:500}
  .search input::placeholder{color:#9aa4cc}
  .search .si{position:absolute;left:11px;top:9px;color:#9aa4cc;font-size:14px}
  .search .hint{position:absolute;right:10px;top:8px;font-size:10px;color:#9aa4cc;border:1px solid #3a488a;border-radius:5px;padding:2px 6px}
  .abtn{background:#2b3768;border:1px solid #3a488a;color:#fff;border-radius:9px;padding:8px 11px;font-size:13px;font-weight:600;cursor:pointer;display:inline-flex;align-items:center;gap:7px}
  .abtn.coral{background:var(--coral);border-color:var(--coral)}
  .role{display:flex;align-items:center;gap:9px}
  .role .av{width:31px;height:31px;border-radius:50%;background:#3a488a;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:12px}
  .role .who{font-size:12px;line-height:1.25}
  .role .who b{font-weight:700}
  .role .who span{color:#aab3d6}

  /* ===== tabs ===== */
  .tabbar{position:sticky;top:58px;z-index:39;background:var(--card);border-bottom:1px solid var(--line);margin:0 0 20px;padding:0 24px;box-shadow:0 1px 2px rgba(20,30,60,.03)}
  .tabbar .inner{max-width:1340px;margin:0 auto;display:flex;gap:2px;overflow-x:auto}
  .tab{padding:13px 4px;margin-right:24px;font-size:13.5px;font-weight:650;color:var(--muted);cursor:pointer;border:0;background:transparent;border-bottom:2.5px solid transparent;margin-bottom:-1px;white-space:nowrap}
  .tab:hover{color:var(--ink)}
  .tab.active{color:var(--navy);border-bottom-color:var(--coral)}

  /* ===== generic ===== */
  .crumb{font-size:12px;color:var(--soft);font-weight:600}
  h1.page{margin:2px 0 2px;font-size:23px;font-weight:760;letter-spacing:-.01em}
  /* Title block and filters share one line: the title block shrinks (its subtitle wraps) rather than
     pushing the filters onto a second row. Only a narrow viewport is allowed to wrap. */
  .pagehead{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;flex-wrap:nowrap;margin-bottom:18px}
  .pagehead > div:first-child{min-width:0;flex:1 1 auto}
  .pagehead .hd-right{flex:0 0 auto}
  .pagehead .hd-right select.ctl{max-width:200px;text-overflow:ellipsis}
  @media (max-width:1100px){ .pagehead{flex-wrap:wrap} }
  .pagehead .sub{color:var(--muted);font-size:13px;margin-top:2px}
  /* When the filter row wraps under the title it must still hug the right edge, not restart at the left. */
  .hd-right{display:flex;align-items:center;gap:9px;flex-wrap:wrap;justify-content:flex-end;margin-left:auto}
  .ctl{background:var(--card);border:1px solid var(--line);border-radius:9px;padding:8px 12px;font-size:13px;color:var(--ink);font-weight:600}
  .ctl .lbl{color:var(--soft);font-weight:500;margin-right:5px}
  select.ctl{appearance:none;cursor:pointer;padding-right:26px;background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6'><path d='M1 1l4 4 4-4' stroke='%2369748c' fill='none' stroke-width='1.5'/></svg>");background-repeat:no-repeat;background-position:right 10px center}
  .btn{background:var(--navy);border:0;color:#fff;font-weight:650;padding:9px 15px;border-radius:9px;cursor:pointer;font-size:13px}
  .btn.coral{background:var(--coral)}
  .btn.ghost{background:#fff;color:var(--ink);border:1px solid var(--line)}
  .btn.sm{padding:6px 11px;font-size:12px}

  .sectionlabel{font-size:11.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--soft);font-weight:700;margin:24px 2px 12px}
  .grid{display:grid;gap:16px}
  .g2{grid-template-columns:1fr 1fr}
  .g3{grid-template-columns:1.6fr 1fr}
  .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:17px 19px;margin-bottom:16px;box-shadow:0 1px 2px rgba(20,30,60,.04)}
  .card h2{margin:0 0 3px;font-size:15px;font-weight:720;letter-spacing:-.01em}
  .card .desc{color:var(--muted);font-size:12.5px;margin:0 0 14px}

  /* kpis */
  .kpis{display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:8px}
  .kpi{background:var(--card);border:1px solid var(--line);border-radius:13px;padding:14px 15px;box-shadow:0 1px 2px rgba(20,30,60,.04)}
  .kpi .top{display:flex;align-items:center;gap:8px}
  .kpi .ic{width:28px;height:28px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
  .kpi .label{font-size:11.5px;color:var(--muted);font-weight:600;line-height:1.2}
  .kpi .val{font-size:26px;font-weight:760;margin-top:9px;letter-spacing:-.02em;line-height:1}
  .kpi .val small{font-size:13px;color:var(--soft);font-weight:600}
  .kpi .foot{font-size:11.5px;color:var(--soft);margin-top:7px}

  /* funnel */
  .funnel{display:flex;gap:8px;align-items:stretch;flex-wrap:wrap}
  .fstep{flex:1;min-width:118px;border:1px solid var(--line);border-radius:11px;padding:12px 11px;position:relative;text-align:center;background:#fbfcfe}
  .fstep .fn{font-size:10.5px;text-transform:uppercase;letter-spacing:.03em;color:var(--muted);font-weight:700}
  .fstep .fv{font-size:24px;font-weight:770;margin-top:6px}
  .fstep .fbar{height:5px;border-radius:3px;margin-top:9px;background:linear-gradient(90deg,var(--navy),var(--brand))}
  .fstep .drop{font-size:10.5px;color:var(--red);margin-top:6px;font-weight:600}
  .fstep .keep{font-size:10.5px;color:var(--good);margin-top:6px;font-weight:600}
  .fstep .fcap[data-drop]{cursor:pointer;text-decoration:underline dotted;text-underline-offset:2px}
  .fstep .fcap[data-drop]:hover{text-decoration-style:solid}
  .fstep .arrow{position:absolute;right:-11px;top:50%;transform:translateY(-50%);z-index:2;color:#c5cce0;font-size:14px}

  /* table */
  table{width:100%;border-collapse:collapse;font-size:13px}
  th,td{text-align:left;padding:9px 9px;border-bottom:1px solid var(--line2)}
  th{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:700;white-space:nowrap}
  th.num,td.num{text-align:right}
  tbody tr:hover{background:#f7f9fd}
  .clickrow{cursor:pointer}
  .rowwarn{background:#fff9f0}
  .rowbad{background:#fff5f5}
  .warnflag{color:var(--orange);font-weight:700}
  .badflag{color:var(--red);font-weight:700}

  /* pills / stages */
  .idpill{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;font-weight:700;color:var(--navy);background:#eef1fb;border:1px solid #dfe4f7;border-radius:6px;padding:2px 7px;white-space:nowrap}
  .stage{display:inline-flex;align-items:center;gap:6px;font-weight:700;font-size:11px;padding:3px 9px;border-radius:999px;text-transform:uppercase;letter-spacing:.02em}
  .st-new{background:#eef1fb;color:#3b5bdb}
  .st-assigned{background:#e7f5ff;color:#1971c2}
  .st-contacted{background:#e3fafc;color:#0c8599}
  .st-qualified{background:#e6fcf5;color:#0ca678}
  .st-beat{background:#f3f0ff;color:#7048e8}
  .st-visited{background:#fff0f6;color:#c2255c}
  .st-onboarded{background:#ebfbee;color:#2f9e44}
  .st-active{background:#d3f9d8;color:#2b8a3e}
  .st-ni{background:#fff4e6;color:#e8590c}
  .st-dead{background:#f1f3f5;color:#868e96}
  .tag{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 7px;border-radius:5px}
  .tag.a{background:#fff0ef;color:var(--coral)}
  .tag.b{background:#e6fcf5;color:var(--teal)}

  /* SLA pills */
  .sla{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:700}
  .sla .clk{font-family:ui-monospace,Menlo,Consolas,monospace}
  .sla.ok{color:var(--good)} .sla.warn{color:var(--orange)} .sla.bad{color:var(--red)}
  .slabar{display:inline-block;width:52px;height:6px;border-radius:4px;background:#eef1f6;overflow:hidden;vertical-align:middle}
  .slabar>i{display:block;height:100%}

  /* attention */
  .att{display:flex;align-items:center;gap:12px;padding:11px 12px;border:1px solid var(--line);border-radius:11px;margin-bottom:9px}
  /* Across the top rather than down a narrow column, so the nine-column table gets the full width. */
  .attstrip{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px}
  .attstrip .att{margin-bottom:0}
  .attstrip .atitle{font-size:12.5px;line-height:1.25}
  .attstrip .adet{font-size:11.5px;margin-top:1px}
  /* Wide content scrolls inside its own card, never the page body. */
  .pipewrap{overflow-x:auto}
  /* table-layout:fixed + a colgroup so the columns keep sane proportions on a wide screen instead
     of the browser handing City and Created-by a third of the table each. Business/Retailer takes
     the slack because it is the column people actually read. */
  .pipewrap table{min-width:1040px;table-layout:fixed}
  .pipewrap td{vertical-align:middle;overflow:hidden;text-overflow:ellipsis}
  .pipewrap td.wrapok{white-space:normal}
  .pipewrap td.nowrap{white-space:nowrap}
  .att .ic{width:30px;height:30px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px;flex:none}
  .att .ab{flex:1}
  .att .atitle{font-size:13px;font-weight:650}
  .att .adet{font-size:12px;color:var(--muted);margin-top:2px}
  .att .acount{font-size:18px;font-weight:780}

  /* tiles */
  .tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:11px}
  .tile{background:#f8f9fc;border:1px solid var(--line2);border-radius:11px;padding:12px}
  .tile .t{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:600}
  .tile .v{font-size:21px;font-weight:760;margin-top:5px}
  .tile .v small{font-size:12px;color:var(--soft);font-weight:600}

  .hide{display:none !important}
  /* Liveness reads better as a ticking clock than as a boxed date field: the board is always
     today, and a timestamp that never visibly moves looks stale rather than live. */
  .liveclock{display:inline-flex;align-items:center;gap:7px;font-size:12.5px;color:var(--soft);font-weight:600}
  /* A readout, not a control: the dates are picked on the Command Center filter bar. */
  .periodtag{display:inline-flex;align-items:baseline;gap:7px;font-size:12.5px;color:var(--soft);font-weight:600}
  .periodtag .pl{font-size:10.5px;letter-spacing:.09em;text-transform:uppercase;color:var(--muted);font-weight:700}
  .periodtag #dashPeriod{color:var(--ink);font-weight:650;white-space:nowrap}
  .livedot{width:7px;height:7px;border-radius:50%;background:#2f9e44;flex:none}
  .livedot.beat{animation:livePulse .9s ease-out}
  .livedot.stalled{background:#e03131}
  @keyframes livePulse{0%{box-shadow:0 0 0 0 rgba(47,158,68,.55)}100%{box-shadow:0 0 0 7px rgba(47,158,68,0)}}
  @media (prefers-reduced-motion:reduce){ .livedot.beat{animation:none} }
  .callbar{position:fixed;right:18px;bottom:18px;z-index:88;width:280px;background:#fff;border:1px solid var(--line);
    border-radius:14px;box-shadow:0 18px 44px rgba(10,15,40,.22);padding:14px 16px}
  .callbar .cb-head{display:flex;align-items:center;gap:8px;font-weight:700;color:var(--brand)}
  .callbar .cb-dot{width:9px;height:9px;border-radius:50%;background:#e03131;flex:none;animation:cbPulse 1.4s infinite}
  .callbar .cb-time{margin-left:auto;color:var(--soft);font-weight:600;font-size:12.5px}
  .callbar .cb-state{margin-top:6px;font-size:12.5px;color:var(--soft);text-transform:capitalize}
  .callbar .cb-acts{margin-top:11px;display:flex;gap:7px}
  .callbar .cb-err{margin-top:8px;color:#e03131;font-size:12px}
  @keyframes cbPulse{0%{opacity:1}50%{opacity:.35}100%{opacity:1}}
  @media (prefers-reduced-motion:reduce){ .callbar .cb-dot{animation:none} }
  /* Call button on a pipeline row. */
  .chkq{padding:12px 0;border-bottom:1px solid var(--line2)}
  .chkq:last-child{border-bottom:0}
  .chkq .qp{font-size:13px;font-weight:600;color:var(--ink);margin-bottom:7px}
  .chkq .qp .req{color:#e03131;margin-left:3px}
  .chkq .opts{display:flex;gap:7px;flex-wrap:wrap}
  .chkopt{border:1px solid var(--line);background:#fff;border-radius:999px;padding:5px 13px;font-size:12.5px;
    cursor:pointer;font-weight:600;color:var(--soft)}
  .chkopt.sel{background:#1f2a5e;border-color:#1f2a5e;color:#fff}
  .rowcall{border:1px solid var(--line);background:#fff;color:#e03131;border-radius:8px;padding:4px 9px;
    cursor:pointer;font-size:13px;line-height:1.1}
  .rowcall:hover{background:#fff0f0;border-color:#ffc9c9}
  .rowcall[disabled]{opacity:.45;cursor:not-allowed}
  .rowedit{border:1px solid var(--line);background:#fff;color:var(--brand2);border-radius:8px;padding:4px 9px;
    cursor:pointer;font-size:13px;line-height:1.1}
  .rowedit:hover{background:#eef1fb;border-color:#c7d2fe}
  .rowassign{border:1px solid var(--line);background:#fff;color:#0ca678;border-radius:8px;padding:4px 9px;
    cursor:pointer;font-size:13px;line-height:1.1}
  .rowassign:hover{background:#e6fcf5;border-color:#96f2d7}
  .tierpill{display:inline-block;min-width:26px;text-align:center;padding:2px 7px;border-radius:6px;
    background:#eef1fb;color:#3b5bdb;font-size:11px;font-weight:700;margin-right:8px}
  .asgrow{display:flex;align-items:center;gap:10px;padding:9px 10px;border:1px solid var(--line);
    border-radius:10px;margin-bottom:6px;cursor:pointer}
  .asgrow:hover{background:#f8f9fc;border-color:var(--brand2)}
  .asgrow.covers{border-color:#96f2d7;background:#f4fffb}
  .asgrow .nm{font-weight:650;font-size:13px}
  .asgrow .rg{margin-left:auto;font-size:11px;color:var(--soft)}
  .lstat{display:inline-block;padding:3px 9px;border-radius:999px;font-size:11px;font-weight:700;letter-spacing:.02em}
  .lstat.oncall{background:#e6fcf5;color:#0ca678}
  .lstat.wrap{background:#eef1f6;color:#69748c}
  .lstat.idle{background:#fff4e6;color:#e8590c}
  .lstat.avail{background:#eef1fb;color:#3b5bdb}
  .lstat.off{background:#f1f3f5;color:#97a1b5}
  .lstale{color:#e03131;font-size:11px;margin-left:6px}
  th.sortable{cursor:pointer;user-select:none;white-space:nowrap}
  th.sortable:hover{color:var(--brand2)}
  th.sortable.on{color:var(--brand2)}
  /* Triangle drawn with borders — no glyph, so it cannot fall back to a tofu box the way U+2195 did. */
  th.sortable .arrow{display:inline-block;width:0;height:0;margin-left:5px;vertical-align:middle;
    border-left:4px solid transparent;border-right:4px solid transparent}
  th.sortable .arrow.up{border-bottom:5px solid currentColor}
  th.sortable .arrow.down{border-top:5px solid currentColor}
  /* Generic table search + sort, attached to every list table that does not sort server-side.
     Deliberately NOT the .sortable class: renderPipeHead() rewrites every th.sortable in the
     document, so sharing it would have the pipeline stamping its arrows onto these headers. */
  th.tsort{cursor:pointer;user-select:none;white-space:nowrap}
  th.tsort:hover{color:var(--brand2)}
  th.tsort.on{color:var(--brand2)}
  th.tsort .arrow{display:inline-block;width:0;height:0;margin-left:5px;vertical-align:middle;
    border-left:4px solid transparent;border-right:4px solid transparent}
  th.tsort .arrow.up{border-bottom:5px solid currentColor}
  th.tsort .arrow.down{border-top:5px solid currentColor}
  .tstools{display:flex;align-items:center;gap:9px;margin:0 0 10px;flex-wrap:wrap}
  .tstools .inp{width:210px;font-size:12.5px;padding:7px 10px}
  .tstools .tscount{font-size:11.5px;color:var(--soft);font-weight:600;font-variant-numeric:tabular-nums}
  .tsempty{font-size:12.5px;color:var(--soft);font-style:italic;padding:14px 0;text-align:center}

  /* Field label outside the filter bar (.ctl .lbl is scoped to it) + the record-action modals. */
  .lbl{display:block;font-size:12px;font-weight:600;color:var(--soft);margin:10px 0 4px}
  .modal{position:fixed;inset:0;z-index:90;background:rgba(14,18,40,.44);display:flex;align-items:flex-start;
         justify-content:center;padding:6vh 16px;overflow:auto}
  .modal .box{background:#fff;border-radius:14px;width:min(640px,100%);box-shadow:0 26px 70px rgba(10,15,40,.3)}
  .modal .mh{padding:18px 22px 0}
  .modal .mh h2{margin:0;font-size:17px;color:var(--brand)}
  .modal .mb{padding:4px 22px 18px}
  .modal .mf{padding:14px 22px;border-top:1px solid var(--line);display:flex;justify-content:flex-end;gap:8px}
  .dispgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin-top:6px}

  /* interactivity */
  .kpi,.fstep,.att,#dash tbody tr,.heat td{cursor:pointer}
  .kpi,.fstep{transition:transform .12s,box-shadow .12s}
  .kpi:hover,.fstep:hover{box-shadow:0 4px 14px rgba(20,30,60,.10);transform:translateY(-1px)}
  .att:hover{border-color:#c7d0e8}

  .drawer-ov{position:fixed;inset:0;background:rgba(20,26,50,.42);z-index:70;opacity:0;pointer-events:none;transition:opacity .2s}
  .drawer-ov.open{opacity:1;pointer-events:auto}
  .drawer{position:fixed;top:0;right:0;height:100%;width:min(680px,96vw);background:#f7f8fc;z-index:71;box-shadow:-14px 0 46px rgba(10,15,40,.22);transform:translateX(100%);transition:transform .26s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column}
  .drawer.open{transform:none}
  .drawer .dh{padding:17px 20px;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:flex-start;gap:12px;flex:none}
  .drawer .crumb2{font-size:10.5px;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:var(--coral)}
  .drawer h3{margin:2px 0 1px;font-size:18px;font-weight:770;letter-spacing:-.01em}
  .drawer .dsub{color:var(--muted);font-size:12.5px}
  /* The title block takes the slack, so the tools slot and the close button sit against the right
     edge instead of two competing auto margins splitting the gap between them. */
  .drawer .dhmain{flex:1;min-width:0}
  .drawer .dtools{flex:none;align-self:center}
  .drawer .dtools .tstools{margin:0}
  .drawer .dtools .tstools .inp{width:190px}
  .drawer .x{margin-left:auto;cursor:pointer;font-size:22px;line-height:1;color:var(--soft);background:none;border:0;padding:0 2px}
  .drawer .dbody{padding:16px 18px 40px;overflow:auto;flex:1}
  .drawer .card{margin-bottom:12px}
  .dstat{display:grid;grid-template-columns:repeat(3,1fr);gap:9px;margin-bottom:12px}
  .dstat .box{background:#fff;border:1px solid var(--line);border-radius:11px;padding:11px 12px}
  .dstat .t{font-size:10px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:700}
  .dstat .v{font-size:20px;font-weight:770;margin-top:3px}
  .dnote{font-size:12px;color:var(--muted);line-height:1.55;margin-top:8px}

  .toastwrap{position:fixed;bottom:22px;left:50%;transform:translateX(-50%);z-index:90;display:flex;flex-direction:column;gap:8px;align-items:center}
  .toast{background:#1f2a5e;color:#fff;padding:11px 16px;border-radius:11px;font-size:13px;font-weight:600;box-shadow:0 10px 34px rgba(10,15,40,.32);display:flex;align-items:center;gap:10px;animation:tin .18s ease-out}
  .toast .ok{color:#69db7c;font-weight:800}
  @keyframes tin{from{opacity:0;transform:translateY(10px)}}

  /* heatmap */
  .heat td{width:34px;height:30px;text-align:center;font-size:11px;font-weight:700;color:#fff;border:2px solid #fff;border-radius:6px}

  /* callout */
  .callout{background:linear-gradient(180deg,#fbfcff,#f4f7ff);border:1px solid #dfe6fb;border-radius:14px;padding:18px 20px;margin-top:6px}
  .callout h2{margin:0 0 3px;font-size:16px}
  .fix{display:flex;gap:13px;padding:13px 0;border-bottom:1px solid #e6ebf8}
  .fix:last-child{border-bottom:0}
  .fix .sev{width:6px;border-radius:4px;flex:none}
  .fix .fb{flex:1}
  .fix .ft{font-size:14px;font-weight:700}
  .fix .fd{font-size:13px;color:#3a4459;margin-top:4px;line-height:1.5}
  .fix .fd b{color:var(--ink)}
  .fix .act{font-size:12.5px;color:var(--good);margin-top:6px;font-weight:650}

  .note{font-size:11.5px;color:var(--soft);margin-top:10px;line-height:1.6}
  .ph{font-size:12.5px;color:var(--soft);font-style:italic;padding:16px 0;text-align:center}
  .rbadge{font-size:9.5px;font-weight:700;padding:1px 6px;border-radius:10px;margin-left:6px;vertical-align:middle}
  .rbadge.live{background:#e6f7ee;color:var(--good)}.rbadge.partial{background:#fff3dc;color:var(--warn)}.rbadge.soon{background:#eef0f5;color:var(--soft)}

  /* record / kv / trail */
  .kv{display:grid;grid-template-columns:130px 1fr;gap:7px 12px;font-size:13px}
  .kv .k{color:var(--soft);font-weight:600}
  .kv .v{font-weight:600}
  .divider{height:1px;background:var(--line);margin:14px 0}
  .recordHost{min-height:120px}
  .lookup{display:flex;gap:8px;align-items:center;margin-bottom:14px}
  .lookup input{border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13px;width:280px}

  /* form */
  .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px 16px}
  .fld{display:flex;flex-direction:column;gap:5px}
  .fld.full{grid-column:1/3}
  .fld label{font-size:11.5px;font-weight:700;color:var(--muted)}
  .fld label .m{color:var(--red)}
  .fld label .auto{float:right;font-size:10px;font-weight:700;color:var(--brand);background:#eef1fb;border-radius:5px;padding:1px 6px;text-transform:uppercase;letter-spacing:.03em}
  .inp{border:1px solid var(--line);border-radius:9px;padding:9px 11px;font-size:13px;font-weight:500;background:#fff;color:var(--ink);width:100%}
  .inp:focus{outline:none;border-color:var(--brand2);box-shadow:0 0 0 3px #eaefff}
  .inp[readonly],.inp.ro{background:#f5f6fa;color:var(--muted);font-weight:600}
  select.inp{appearance:none;cursor:pointer;background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6'><path d='M1 1l4 4 4-4' stroke='%2369748c' fill='none' stroke-width='1.5'/></svg>");background-repeat:no-repeat;background-position:right 11px center}
  .hinttext{font-size:11px;color:var(--soft)}
  /* Brand-wise value capture. auto-fill keeps it compact on a laptop and collapses to one column
     on a phone, which is where Path B (field encounter) is actually used. */
  .brandgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(148px,1fr));gap:8px;margin-top:2px}
  .brandcell{display:flex;align-items:center;gap:6px;background:#f7f8fc;border:1px solid var(--line);
    border-radius:8px;padding:4px 8px}
  .brandcell .bname{font-size:11.5px;font-weight:700;color:var(--ink);white-space:nowrap;min-width:58px}
  .brandcell .bval{border:0;background:transparent;padding:3px 0;height:auto;font-size:12.5px;text-align:right}
  .brandcell .bval:focus{outline:0;box-shadow:none}
  .brandcell:focus-within{border-color:var(--brand);background:#fff}
  .resolvebox{background:#f5f7ff;border:1px solid #dfe4f7;border-radius:11px;padding:13px 15px;display:flex;align-items:center;gap:13px}
  .resolvebox .ra{width:38px;height:38px;border-radius:10px;background:var(--navy);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;flex:none}
  .resolvebox .rt{font-size:11px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.04em}
  .resolvebox .rn{font-size:15px;font-weight:750;margin-top:1px}
  .resolvebox .rc{font-size:11.5px;color:var(--muted);margin-top:2px}
  .trail{position:relative;padding-left:22px}
  /* When the trail scrolls, bleed it out to the card's edge (.card padding is 17px 19px) and put
     that 19px back as padding — the scrollbar then sits flush against the card border instead of
     floating in a gutter, and the entries stay where they were. */
  .trail.scrolls{margin-right:-19px;padding-right:19px}
  .trail:before{content:"";position:absolute;left:7px;top:4px;bottom:4px;width:2px;background:var(--line)}
  .tevt{position:relative;padding:0 0 14px}
  .tevt:last-child{padding-bottom:0}
  .tevt .tdot{position:absolute;left:-22px;top:2px;width:16px;height:16px;border-radius:50%;background:#fff;border:2px solid var(--brand);display:flex;align-items:center;justify-content:center;font-size:8px;color:var(--brand)}
  .tevt.sys .tdot{border-color:var(--soft);color:var(--soft)}
  .tevt.win .tdot{border-color:var(--good);color:var(--good)}
  .tevt.call .tdot{border-color:var(--coral);color:var(--coral)}
  .tevt .tt{font-size:13px;font-weight:650}
  .tevt .tm{font-size:11.5px;color:var(--soft);margin-top:1px}
  .tevt .td{font-size:12.5px;color:var(--muted);margin-top:4px;background:#f8f9fc;border:1px solid var(--line2);border-radius:8px;padding:8px 10px}
  .tevt .trec{display:flex;align-items:center;gap:8px;margin-top:6px}
  .tevt .trec audio{height:30px;max-width:230px}

  /* record stepper */
  .rec-stepper{display:flex;align-items:center;gap:0;margin:2px 0 4px;flex-wrap:wrap}
  .rec-step{display:flex;align-items:center;gap:8px;flex:1;min-width:96px;position:relative}
  .rec-step .dot{width:26px;height:26px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex:none;border:2px solid var(--line);background:#fff;color:var(--soft)}
  .rec-step.done .dot{background:var(--good);border-color:var(--good);color:#fff}
  .rec-step.cur .dot{background:var(--navy);border-color:var(--navy);color:#fff;box-shadow:0 0 0 4px #e7ebfa}
  .rec-step .sl{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.02em;color:var(--muted)}
  .rec-step.cur .sl{color:var(--navy)}
  .rec-step .bar{position:absolute;left:26px;right:0;top:13px;height:2px;background:var(--line);z-index:-1}
  .rec-step.done .bar{background:var(--good)}

  /* matrix */
  .matrix{width:100%;border-collapse:separate;border-spacing:0;font-size:12.5px}
  .matrix th,.matrix td{padding:9px 8px;border-bottom:1px solid var(--line2);text-align:center}
  .matrix th:first-child,.matrix td:first-child{text-align:left;font-weight:650}
  .matrix thead th{background:#f8f9fc;color:var(--muted);font-size:10.5px;text-transform:uppercase;letter-spacing:.03em}
  .mk-y{color:var(--good);font-weight:800}
  .mk-n{color:#ccd2e0}
  .mk-s{color:var(--orange);font-weight:800;font-size:11px}

  @media (max-width:1040px){
    .kpis{grid-template-columns:repeat(3,1fr)}
    .g2,.g3{grid-template-columns:1fr}
    .form-grid{grid-template-columns:1fr}.fld.full{grid-column:1}
    .search{display:none}
  }
</style>
</head>
<body>

<!-- ============ APP BAR ============ -->
<div class="appbar">
  <div class="inner">
    <div class="logo"><span class="mk">SD</span><div>SmartDukaan · LMS<small>LEAD MANAGEMENT SYSTEM</small></div></div>
    <div class="search">
      <span class="si">&#128269;</span>
      <input id="lmsSearch" placeholder="Search LMS ID, business, phone, retailer…  e.g. LMS-UPW-26-000123">
      <span class="hint">/ to focus</span>
    </div>
    #if($canCreateLead)
    <button class="abtn coral" onclick="window.open(CTX+'/getOpenLead','_blank')">+ New Lead</button>
    #end
    <div class="role">
      <div class="av" title="Signed in as $!viewerName">$!viewerInitials</div>
      <div class="who"><b>$!viewerName</b><br><span>$!viewerRole</span></div>
    </div>
  </div>
</div>

<!-- ============ TABS ============ -->
<div class="tabbar">
  <div class="inner">
    <button class="tab active" data-screen="cmd" onclick="go('cmd',this)">Command Center</button>
    <button class="tab" data-screen="record" onclick="go('record',this)">Lead Record</button>
    #if($canCreateLead)
    <button class="tab" data-screen="create" onclick="go('create',this)">Create Lead</button>
    #end
    <button class="tab" data-screen="assign" onclick="go('assign',this)">Auto-Assignment</button>
    <button class="tab" data-screen="live" onclick="go('live',this)">Live Calls</button>
    <button class="tab" data-screen="dash" onclick="go('dash',this)">Dashboards</button>
    <button class="tab" data-screen="chk" onclick="go('chk',this)">Checklist</button>
    <button class="tab" data-screen="audit" onclick="go('audit',this)">Recordings &amp; Audit</button>
  </div>
</div>

<div class="wrap">

  <!-- ======================= COMMAND CENTER ========================= -->
  <div id="cmd">
    <div class="pagehead">
      <div>
        <div class="crumb">Sales · Lead Pipeline</div>
        <h1 class="page">Command Center</h1>
        <div class="sub">Every lead you own or oversee — from creation to onboarding. SLA clock runs on all NEW records.</div>
      </div>
      <div class="hd-right">
        <select class="ctl" id="fAgent" title="Call Center user — every number below narrows to leads they created or currently own">
          <option value="">All Call Center users</option>
        </select>
        <select class="ctl" id="fRegion">
          <option value="">All regions</option>
          #foreach($r in $regions)
            <option value="$r.getId()">$!r.getName()#if($r.getRegionCode()) ($r.getRegionCode())#end</option>
          #end
        </select>
        <input type="date" class="ctl" id="fFrom" value="$!fromDate">
        <input type="date" class="ctl" id="fTo" value="$!toDate">
      </div>
    </div>

    <div class="kpis" id="ccKpis"></div>

    <div class="sectionlabel">Lifecycle Funnel — selected period · beat, visit &amp; onboarding read from source tables</div>
    <div class="card"><div class="funnel" id="ccFunnel"></div></div>

    <div class="card">
      <h2>Needs attention now</h2>
      <p class="desc">Actionable queues for the selected period &amp; region · click to work them.</p>
      <div id="ccAttention" class="attstrip"></div>
    </div>

    <div class="card">
        <h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">Lead pipeline
          <span style="display:flex;gap:6px;align-items:center">
            <input id="pipeQ" class="inp" style="width:210px;font-size:12.5px;padding:7px 10px"
                   placeholder="Name, outlet, mobile, city, created by">
            <button class="btn ghost sm" onclick="pipeSearch()">Search</button>
            <button class="btn ghost sm hide" id="pipeClear" onclick="pipeClearSearch()">Clear</button>
          </span>
        </h2>
        <p class="desc" id="pipeDesc">Click any row &rarr; full LMS record &amp; trail. Rows shaded by SLA urgency.</p>
        <div class="pipewrap">
        <table>
          <colgroup>
            <col style="width:132px"><col><col style="width:64px"><col style="width:112px">
            <col style="width:130px"><col style="width:130px"><col style="width:130px">
            <col style="width:104px"><col style="width:84px"><col style="width:124px">
          </colgroup>
          <thead><tr>
            <th class="sortable" data-sort="created">LMS ID</th>
            <th class="sortable" data-sort="name">Business / Retailer</th>
            <th>Path</th>
            <th class="sortable" data-sort="stage">Stage</th>
            <th>Owner</th>
            <th class="sortable" data-sort="city">City</th>
            <th class="sortable" data-sort="createdBy">Created by</th>
            <th class="sortable" data-sort="sla">SLA</th>
            <th class="sortable num" data-sort="value">Value</th>
            <th></th>
          </tr></thead>
          <tbody id="ccPipeline"><tr><td colspan="10"><div class="ph">Loading…</div></td></tr></tbody>
        </table>
        </div>
        <div id="pipeFoot" style="display:flex;align-items:center;justify-content:space-between;gap:10px;
             margin-top:10px;flex-wrap:wrap">
          <span class="note" id="pipeCount"></span>
          <span style="display:flex;gap:6px;align-items:center">
            <button class="btn ghost sm" id="pipePrev" onclick="pipePage(-1)">&larr; Prev</button>
            <span class="note" id="pipePageLbl"></span>
            <button class="btn ghost sm" id="pipeNext" onclick="pipePage(1)">Next &rarr;</button>
          </span>
        </div>
    </div>
  </div>

  <!-- ======================= LEAD RECORD ========================= -->
  <div id="record" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Command Center · Lead Record</div>
        <h1 class="page">Lead Record</h1>
        <div class="sub">The single source of truth for a lead — stepper, immutable trail, SLA &amp; disposition. Loads the real record.</div>
      </div>
      <div class="hd-right">
        <div class="lookup">
          <input id="recLookup" placeholder="Lead # (e.g. 123)" inputmode="numeric">
          <button class="btn sm" onclick="loadRecord()">Load</button>
        </div>
      </div>
    </div>
    <div class="recordHost" id="recordHost"><div class="card"><div class="ph">Loading the most recent lead…</div></div></div>
    <div class="note" style="margin-left:2px">Acts on the real record: edit, call, disposition and stage moves all write here, and every change lands in the trail.</div>
  </div>

  <!-- ======================= CREATE LEAD ========================= -->
  <div id="create" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Create · New Lead</div>
        <h1 class="page">Create Lead</h1>
        <div class="sub">What an agent can know on a first call, plus the shop details the Leads screen captures. LMS ID is generated on submit and the lead is auto-assigned from region. Address, store photo and geo-pin come from the capture link, which is created automatically and copied to your clipboard.</div>
      </div>
      <div class="hd-right">
        <div class="ctl" style="padding:4px;display:flex;gap:4px">
          <button class="btn coral sm" id="pathA" style="border-radius:7px" onclick="setPath('A',this)">Path A · BGC outbound</button>
          <button class="btn ghost sm" id="pathB" style="border-radius:7px" onclick="setPath('B',this)">Path B · Field encounter</button>
        </div>
      </div>
    </div>

    <div class="grid g3">
      <div class="card">
        <h2>Lead details</h2>
        <p class="desc" id="createDesc">Path A — captured by BGC agent during an outbound call, after consent.</p>
        <div class="form-grid">
          <div class="fld"><label>Retailer name <span class="m">*</span></label><input class="inp" id="cRetailer" placeholder="Contact person"></div>
          <div class="fld"><label>Business name <span class="m">*</span></label><input class="inp" id="cBusiness" placeholder="Shop / trade name"></div>
          <div class="fld"><label>Contact number <span class="m">*</span></label><input class="inp mono" id="cContact" placeholder="10-digit mobile" inputmode="numeric"></div>
          <div class="fld full">
            <label>Monthly business value — brand wise <span class="auto" id="cValueTotal">total ₹0</span></label>
            <div class="brandgrid" id="cBrandGrid">
              #foreach($b in $leadBrands)
                <div class="brandcell">
                  <span class="bname">$b</span>
                  <input class="inp bval mono" data-brand="$b" placeholder="0" inputmode="numeric"
                         oninput="brandTotal()">
                </div>
              #end
            </div>
            <div class="hinttext">Type in rupees per month — 100000 or 1L, 50k both work. Leave a brand blank if it is not stocked.</div>
          </div>
          <div class="fld"><label>Interest status</label><select class="inp" id="cInterest"><option>Interested</option><option>Callback</option><option>Not Interested</option></select></div>
          <div class="fld"><label>Source</label>
            <select class="inp" id="cSource">
              <option value="LMS Dashboard" selected>LMS Dashboard</option>
              <option value="SELF">SELF</option><option value="NEWSPAPER">NEWSPAPER</option><option value="INTERNET">INTERNET</option>
              <option value="PARTNER">PARTNER</option><option value="WEBINAR">WEBINAR</option><option value="TRIAL">TRIAL</option>
              <option value="WHATSAPP_CAMPAIGN">WHATSAPP CAMPAIGN</option><option value="RETAILER_MEET">RETAILER MEET</option>
              <option value="AI Assistant">AI Assistant</option>
            </select></div>
          <div class="fld full"><label>Address</label><input class="inp" id="cAddress" placeholder="Shop address" maxlength="128"></div>
          <div class="fld"><label>City</label><input class="inp" id="cCity" placeholder="City" maxlength="30"></div>
          <div class="fld"><label>State</label>
            <select class="inp" id="cState">
              <option value="">Select a state…</option>
              #foreach($sn in $stateNames)
                <option value="$sn">$sn</option>
              #end
            </select></div>
          <div class="fld"><label>Conversion probability</label>
            <select class="inp" id="cConversion"><option value="false" selected>Low</option><option value="true">High</option></select></div>
          <div class="fld"><label>Counter size <span class="auto" id="cCounterHint">= brand total, editable</span></label>
            <input class="inp mono" id="cCounter" placeholder="₹ per month" inputmode="numeric" oninput="counterEdited()"></div>
          <div class="fld full"><label>Remark</label><input class="inp" id="cRemark" placeholder="Anything the BM should know before the first call" maxlength="500"></div>
          <div class="fld full">
            <label>Store photos <span class="auto">optional — same five shots as the Leads screen</span></label>
            <div class="brandgrid" id="cPhotoGrid">
              <div class="brandcell"><span class="bname">Front</span><input type="file" accept="image/*" class="inp cphoto" data-photo="frontp"></div>
              <div class="brandcell"><span class="bname">Internal with market</span><input type="file" accept="image/*" class="inp cphoto" data-photo="frontWithMarket"></div>
              <div class="brandcell"><span class="bname">Internal long shot</span><input type="file" accept="image/*" class="inp cphoto" data-photo="internalLongShot"></div>
              <div class="brandcell"><span class="bname">Internal left wall</span><input type="file" accept="image/*" class="inp cphoto" data-photo="internalLeftWall"></div>
              <div class="brandcell"><span class="bname">Internal right wall</span><input type="file" accept="image/*" class="inp cphoto" data-photo="internalRightWall"></div>
            </div>
            <div class="hinttext">Photos upload when you submit. Skip them on a call — the capture link collects them from the retailer.</div>
          </div>
          <div class="fld full">
            <label>Region / State <span class="m">*</span> <span class="auto">drives auto-assignment</span></label>
            <select class="inp" id="cRegion" onchange="resolveBM(this.value)">
              <option value="">Select a region…</option>
              #foreach($r in $regions)
                <option value="$r.getId()">$!r.getName()#if($r.getRegionCode()) ($r.getRegionCode())#end</option>
              #end
            </select>
          </div>
        </div>
        <div style="display:flex;gap:9px;margin-top:16px;justify-content:flex-end">
          <button class="btn coral" onclick="submitLead()">Submit &amp; generate LMS ID</button>
        </div>
      </div>

      <div>
        <div class="card">
          <h2>Auto-assignment preview</h2>
          <p class="desc">On Region select, the engine resolves the BM/RSM and shows it for confirmation before submit.</p>
          <div class="resolvebox" id="resolveBox">
            <div class="ra" id="raAv">—</div>
            <div>
              <div class="rt">Resolved BM / RSM · <span id="rRegion">—</span></div>
              <div class="rn" id="rName">Pick a region…</div>
              <div class="rc" id="rEsc">The owning BM/RSM is resolved from the region (cs.position).</div>
            </div>
          </div>
          <div class="note">If a region has no active BM/RSM, the LMS enters a <b>HOLD queue</b> and the Sales Head is notified.</div>
        </div>
        <div class="card">
          <h2>What happens on submit</h2>
          <div class="trail" style="margin-top:4px">
            <div class="tevt win"><div class="tdot">1</div><div class="tt">Validate fields &amp; generate LMS ID</div><div class="tm">immutable, searchable</div></div>
            <div class="tevt sys"><div class="tdot">2</div><div class="tt">Set stage = Assigned</div><div class="tm">BM/RSM resolved from region</div></div>
            <div class="tevt sys"><div class="tdot">3</div><div class="tt">Dispatch assignment email</div><div class="tm">BM/RSM + CC Reporting Mgr</div></div>
            <div class="tevt call"><div class="tdot">4</div><div class="tt">Start 5 hr SLA timer</div><div class="tm">first-contact clock begins</div></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ======================= AUTO-ASSIGNMENT ========================= -->
  <div id="assign" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Sales Ops · Routing</div>
        <h1 class="page">Auto-Assignment Engine</h1>
        <div class="sub">Region &rarr; BM/RSM mapping resolves ownership at submit — from the live cs.position table. HOLD when a region has no active BM.</div>
      </div>
    </div>

    <div class="kpis" style="grid-template-columns:repeat(4,1fr)" id="assignKpis"></div>

    <div class="grid g3">
      <div class="card">
        <h2>Region &rarr; BM/RSM mapping</h2>
        <p class="desc">The live routing table — resolved for each region right now.</p>
        <table>
          <thead><tr><th>Region / State</th><th>Assigned BM / RSM</th><th>Status</th><th></th></tr></thead>
          <tbody id="assignMap"><tr><td colspan="4"><div class="ph">Resolving…</div></td></tr></tbody>
        </table>
      </div>
      <div>
        <div class="card">
          <h2>Engine rules</h2>
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#eef1fb;color:#3b5bdb">1</div><div class="ab"><div class="atitle">Resolve at submit</div><div class="adet">Region drives ownership; BM/RSM shown for confirmation.</div></div></div>
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff4e6;color:#e8590c">2</div><div class="ab"><div class="atitle">Tier fallback</div><div class="adet">L4 → L5 → L3 within the region (cs.position).</div></div></div>
          <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff0f0;color:#e03131">3</div><div class="ab"><div class="atitle">HOLD queue</div><div class="adet">No active BM/RSM &rarr; LMS held; Sales Head notified.</div></div></div>
          <div class="att" style="margin-bottom:0"><div class="ic" style="background:#f3f0ff;color:#7048e8">4</div><div class="ab"><div class="atitle">Manual reassignment</div><div class="adet">BM/RSM/Sales Head can override — always logged.</div></div></div>
        </div>
        <div class="card" style="background:#fff5f5;border-color:#ffd9d5">
          <h2 style="color:#c92a2a">HOLD queue</h2>
          <p class="desc" style="margin-bottom:8px">LMS with no active BM — waiting until one is mapped.</p>
          <div id="holdQueue"><div class="ph">Loading…</div></div>
        </div>
      </div>
    </div>
  </div>

  <!-- ======================= DASHBOARDS ========================= -->
  <!-- ======================= LIVE CALLS ========================= -->
  <div id="live" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Floor &middot; Live</div>
        <h1 class="page">Live Calls</h1>
        <div class="sub">Who is on a call right now, and how the day is going per agent &mdash; from the
          call log. Refreshes every 10 seconds.</div>
      </div>
      <div class="hd-right">
        <span class="liveclock"><span class="livedot" id="liveDot"></span><span id="liveAsOf">connecting&hellip;</span></span>
        <button class="btn ghost sm" onclick="exportLive()">Export CSV</button>
      </div>
    </div>

    <div class="kpis" id="liveKpis"></div>

    <div class="card">
      <h2>Agents</h2>
      <p class="desc">Roster is everyone with a dialer mapping &mdash; an agent without one cannot place
        a call. Click a row for their calls today.</p>
      <div class="pipewrap">
        <table>
          <colgroup>
            <col style="width:170px"><col style="width:104px"><col style="width:96px">
            <col style="width:70px"><col style="width:82px"><col style="width:84px">
            <col style="width:88px"><col style="width:90px"><col style="width:86px">
            <col style="width:92px"><col style="width:96px">
          </colgroup>
          <thead><tr>
            <th>Agent</th><th>Status</th><th>In status</th>
            <th class="num">Calls</th><th class="num">Conn.</th><th class="num">Conn%</th>
            <th class="num">Talk</th><th class="num">Longest</th>
            <th class="num">Assigned</th><th class="num">Touched</th><th class="num">SLA breach</th>
          </tr></thead>
          <tbody id="liveBody"><tr><td colspan="11"><div class="ph">Loading&hellip;</div></td></tr></tbody>
        </table>
      </div>
      <div class="note">Status is derived from call activity &mdash; the Vonage softphone reports no
        presence, so there is deliberately no Login or Break here rather than a guess.</div>
    </div>

    <div class="card">
      <h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">Call log
        <span style="display:flex;gap:6px;align-items:center">
          <input type="date" class="ctl" id="clFrom">
          <input type="date" class="ctl" id="clTo">
          <button class="btn ghost sm" onclick="loadCallLog(1)">Apply</button>
          <button class="btn ghost sm" onclick="exportCallLog()">Export CSV</button>
        </span>
      </h2>
      <p class="desc">Every call placed in the window &mdash; ring time, talk time, outcome and recording.
        Click a row to open its lead.</p>
      <div class="pipewrap">
        <table>
          <colgroup>
            <col style="width:132px"><col style="width:140px"><col style="width:190px">
            <col style="width:124px"><col style="width:104px"><col style="width:74px">
            <col style="width:74px"><col style="width:120px"><col>
          </colgroup>
          <thead><tr>
            <th>Started</th><th>Agent</th><th>Lead</th><th>Number</th><th>Status</th>
            <th class="num">Ring</th><th class="num">Talk</th><th>Recording</th><th>Disposition</th>
          </tr></thead>
          <tbody id="clBody"><tr><td colspan="9"><div class="ph">Loading&hellip;</div></td></tr></tbody>
        </table>
      </div>
      <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:10px;flex-wrap:wrap">
        <span class="note" id="clCount"></span>
        <span style="display:flex;gap:6px;align-items:center">
          <button class="btn ghost sm" id="clPrev" onclick="clPage(-1)">&larr; Prev</button>
          <span class="note" id="clPageLbl"></span>
          <button class="btn ghost sm" id="clNext" onclick="clPage(1)">Next &rarr;</button>
        </span>
      </div>
      <div class="note">Ring is dial &rarr; answer; Talk is answer &rarr; hangup. A call that was never
        answered has a ring time but no talk time.</div>
    </div>
  </div>

  <div id="dash" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Management · Cross-region roll-up</div>
        <h1 class="page">Dashboards</h1>
        <div class="sub">Funnel, SLA compliance, ageing &amp; servicing across all regions — derived from the lead record.</div>
      </div>
      <div class="hd-right">
        <span class="periodtag"><span class="pl">Period</span><span id="dashPeriod">&mdash;</span></span>
        <button class="btn ghost sm" onclick="exportPipeline()">Export CSV</button>
      </div>
    </div>

    <div class="kpis" id="dashKpis"></div>

    <div class="sectionlabel">State funnel — NEW &rarr; ONBOARDED by region</div>
    <div class="card">
      <table>
        <thead><tr><th>Region</th><th class="num">Leads</th><th class="num">Contacted</th><th class="num">Qualified</th><th class="num">Beat</th><th class="num">Visited</th><th class="num">Onboarded</th><th class="num">Conv%</th><th class="num">SLA%</th></tr></thead>
        <tbody id="dashState"></tbody>
      </table>
    </div>

    <div class="grid g2">
      <div class="card">
        <h2>SLA compliance — owner heat-map</h2>
        <p class="desc">% first contact within SLA, by BM (rows) across recent weeks (cols). Red = chronic breach.</p>
        <div id="dashHeat"></div>
        <div class="note">SLA = first contact within 5 hrs of creation (SOP §11). Reminder T-1h; escalation to BM at T+5h.</div>
      </div>
      <div class="card">
        <h2>Standard dashboards</h2>
        <p class="desc">SOP §18.2 report suite — click any row to open it. Live = measured from real data; Pending = its source system does not exist yet.</p>
        <table><tbody style="font-size:12.5px">
          <tr class="clickrow" data-rep="State Funnel"><td>&#128200; <b>State Funnel</b><span class="rbadge live">Live</span></td><td style="color:#69748c">New &rarr; onboarded by region, BM, ASM</td></tr>
          <tr class="clickrow" data-rep="SLA Compliance"><td>&#9878; <b>SLA Compliance</b><span class="rbadge live">Live</span></td><td style="color:#69748c">% within SLA, owner heat-map</td></tr>
          <tr class="clickrow" data-rep="Ageing"><td>&#8987; <b>Ageing</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Stuck by stage, days-since-action</td></tr>
          <tr class="clickrow" data-rep="Management Roll-up"><td>&#128081; <b>Management Roll-up</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Cross-region leads, onboardings, value</td></tr>
          <tr class="clickrow" data-rep="BGC Daily"><td>&#128202; <b>BGC Daily</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Calls, connect rate &amp; talk time per agent per day</td></tr>
          <tr class="clickrow" data-rep="Audit Hygiene"><td>&#129529; <b>Audit Hygiene</b><span class="rbadge live">Live</span></td><td style="color:#69748c">Dispositions, SLA, HOLD, DND breaches, recording access</td></tr>
          <tr class="clickrow" data-rep="RBM Servicing"><td>&#128260; <b>RBM Servicing</b><span class="rbadge soon">Pending data</span></td><td style="color:#69748c">Repeat-order / complaint / TAT need order data</td></tr>
        </tbody></table>
      </div>
    </div>

    <div class="sectionlabel">What to fix</div>
    <div class="callout">
      <h2>Recommended actions — from this period's data</h2>
      <p class="desc">Each links to the section above.</p>
      <div id="dashFix"></div>
    </div>
  </div>

  <!-- ======================= CHECKLIST ADMIN ========================= -->
  <div id="chk" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Setup &middot; In-call script</div>
        <h1 class="page">Checklist questions</h1>
        <div class="sub">What agents are asked while a call is connected. Questions show at the stages
          you pick, and carry points towards a lead's score.</div>
      </div>
      <div class="hd-right">
        <button class="btn coral sm" onclick="editQuestion(null)">+ New question</button>
      </div>
    </div>

    <div class="card">
      <div class="pipewrap">
        <table>
          <colgroup>
            <col style="width:54px"><col><col style="width:96px"><col style="width:66px">
            <col style="width:70px"><col style="width:220px"><col style="width:74px"><col style="width:132px">
          </colgroup>
          <thead><tr>
            <th class="num">Order</th><th>Question</th><th>Type</th><th class="num">Points</th>
            <th>Required</th><th>Shows at</th><th>Status</th><th></th>
          </tr></thead>
          <tbody id="qBody"><tr><td colspan="8"><div class="ph">Loading&hellip;</div></td></tr></tbody>
        </table>
      </div>
      <div class="note">A question that has been answered can be switched off but not deleted &mdash;
        the answers reference it.</div>
    </div>
  </div>

  <!-- ======================= RECORDINGS & AUDIT ========================= -->
  <div id="audit" class="hide">
    <div class="pagehead">
      <div>
        <div class="crumb">Audit · Access Control</div>
        <h1 class="page">Recordings &amp; Audit</h1>
        <div class="sub">Recordings are gated by role + reporting hierarchy; every open is logged. Hygiene flags are live; the recording repo is a pending source system.</div>
      </div>
    </div>

    <div class="kpis" style="grid-template-columns:repeat(5,1fr)" id="auditKpis"></div>

    <div class="grid g2">
      <div class="card">
        <h2>Access &amp; recording visibility matrix</h2>
        <p class="desc">What each role can open. Recording access is scoped by role + reporting hierarchy (SOP §15).</p>
        <table class="matrix">
          <thead><tr><th>Role</th><th>Own LMS</th><th>Reports'</th><th>State-wide</th><th>All records</th><th>Recordings</th></tr></thead>
          <tbody>
            <tr><td>Individual (BGC/ASM)</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-s">own only</td></tr>
            <tr><td>Reporting Manager</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-n">&mdash;</td><td class="mk-s">reports'</td></tr>
            <tr><td>BM / RSM</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-n">&mdash;</td><td class="mk-s">state-wide</td></tr>
            <tr><td>Audit Team</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-s">all · read-only</td></tr>
            <tr><td>Upper Management</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-y">&#10003;</td><td class="mk-s">via BI drill</td></tr>
          </tbody>
        </table>
        <div class="note">Recording repository (signed URLs, DND enforcement, 24-mo retention) is a Phase-2 source system — not yet wired to real data.</div>
      </div>

      <div class="card">
        <h2>Weekly hygiene flags <span style="color:#97a1b5;font-weight:500;font-size:12px">· live</span></h2>
        <p class="desc">Derived from the lead record — click to list the leads.</p>
        <div id="auditHygiene"><div class="ph">Loading…</div></div>
      </div>
    </div>

    <div class="grid g2">
      <div class="card">
        <h2>Audit &amp; compliance program (SOP §17)</h2>
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#e6fcf5;color:#0ca678">&#127925;</div><div class="ab"><div class="atitle">Weekly recording sampling</div><div class="adet">Across BGC, ASM &amp; RBM for quality &amp; process adherence.</div></div></div>
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#e6fcf5;color:#0ca678">&#129529;</div><div class="ab"><div class="atitle">5% deep audit of onboarded</div><div class="adet">Verify data integrity &amp; process compliance.</div></div></div>
        <div class="att" style="margin-bottom:8px"><div class="ic" style="background:#fff0f0;color:#e03131">&#128683;</div><div class="ab"><div class="atitle">DND enforcement</div><div class="adet">Audit maintains the list; repeat calls auto-flag the user.</div></div></div>
        <div class="att" style="margin-bottom:0"><div class="ic" style="background:#eef1f6;color:#69748c">&#128451;</div><div class="ab"><div class="atitle">Retention policy</div><div class="adet">24 months for recordings · 5 years for LMS records.</div></div></div>
      </div>
      <div class="card">
        <h2>Recording repository <span style="color:#97a1b5;font-weight:500;font-size:12px">· pending source</span></h2>
        <p class="desc">Each recording would be tagged with LMS ID, user, timestamp, duration &amp; disposition.</p>
        <div class="ph">No recording repository connected yet — this arrives with the C2C telephony bridge (Phase 2/3).</div>
      </div>
    </div>
  </div>

</div>

<!-- drawer + toast -->
<div class="drawer-ov" id="ov" onclick="closeDrawer()"></div>
<div class="drawer" id="drawer">
  <div class="dh"><div class="dhmain"><div class="crumb2" id="dCrumb"></div><h3 id="dTitle"></h3><div class="dsub" id="dSub"></div></div><div class="dtools" id="dTools"></div><button class="x" onclick="closeDrawer()">&times;</button></div>
  <div class="dbody" id="dBody"></div>
</div>
<!-- Record actions: edit the record, and log a call outcome. Both write to the same endpoints
     the in-app lead record uses. -->
<div class="modal hide" id="editModal">
  <div class="box">
    <div class="mh"><h2>Edit record</h2>
      <p class="desc">Every change is written to the trail against your name.</p></div>
    <div class="mb" id="editBody"></div>
    <div class="mf"><button class="btn ghost" onclick="closeEdit()">Cancel</button>
      <button class="btn" style="background:#1f2a5e;color:#fff" onclick="saveEdit()">Save changes</button></div>
  </div>
</div>

<div class="modal hide" id="dispModal">
  <div class="box">
    <div class="mh"><h2>Call disposition</h2>
      <p class="desc">Structured outcome on every interaction (SOP &sect;12.2).</p></div>
    <div class="mb">
      <label class="lbl">Outcome (required)</label>
      <div class="dispgrid" id="dispGrid"></div>
      <div id="dispExtra"></div>
      <label class="lbl">Note (attaches to the trail)</label>
      <textarea id="dispNote" class="inp" rows="2" style="width:100%;resize:vertical"></textarea>
    </div>
    <div class="mf"><button class="btn ghost" onclick="closeDisp()">Cancel</button>
      <button class="btn coral" onclick="saveDisp()">Save disposition</button></div>
  </div>
</div>

<!-- Manual geo verification (SOP §6: geo-pin). Same endpoints the Leads screen uses:
     /lead-geo/geocode-address, /lead-geo/upload-image, /lead-geo/manual-verify. -->
<div class="modal hide" id="geoModal">
  <div class="box">
    <div class="mh"><h2>Verify location manually</h2>
      <p class="desc">For when the retailer will not tap the capture link — confirm the coordinates
        over the phone, or read them off a Maps link they shared. Saved as approved, against your name.</p></div>
    <div class="mb">
      <label class="lbl">Address</label>
      <div style="display:flex;gap:6px">
        <input id="geoAddress" class="inp" style="flex:1" placeholder="Shop address with city, state, pincode">
        <button class="btn ghost sm" id="geoFindBtn" onclick="geoGeocode()">Find on map</button>
      </div>
      <label class="lbl">Latitude, longitude</label>
      <div style="display:flex;gap:6px">
        <input id="geoLatLng" class="inp" style="flex:1" placeholder="28.6139,77.2090 — or paste a Google Maps link">
        <button class="btn ghost sm" onclick="geoPreview()">Show on map</button>
      </div>
      <div id="geoMapWrap" class="hide" style="margin-top:10px">
        <iframe id="geoMapFrame" style="width:100%;height:220px;border:1px solid var(--line);border-radius:10px" loading="lazy"></iframe>
        <a id="geoOpenMap" class="note" target="_blank" rel="noopener" href="#">Open in Google Maps &rarr;</a>
      </div>
      <label class="lbl">Store-board photo (required)</label>
      <input id="geoPhoto" type="file" accept="image/jpeg,image/png" class="inp" onchange="geoPickPhoto()">
      <div class="note">The only evidence that someone actually saw the store-board.</div>
      <img id="geoPhotoImg" class="hide" style="margin-top:8px;max-height:130px;border-radius:8px;border:1px solid var(--line)">
      <label class="lbl">Remark</label>
      <input id="geoRemark" class="inp" placeholder="Optional — how the location was confirmed">
      <div id="geoErr" class="hide" style="margin-top:10px;color:#e03131;font-size:12.5px"></div>
    </div>
    <div class="mf"><button class="btn ghost" onclick="closeGeo()">Cancel</button>
      <button class="btn" style="background:#1f2a5e;color:#fff" id="geoSaveBtn" onclick="geoSave()">Save &amp; verify</button></div>
  </div>
</div>

<!-- One call bar for the whole console. It used to live inside the lead-record card, which meant a
     call started from anywhere else had nowhere to report progress, and switching tabs mid-call
     hid the hang-up button. -->
<div class="callbar hide" id="gCallBar">
  <div class="cb-head">
    <span class="cb-dot"></span>
    <span id="gCallWho">&mdash;</span>
    <span class="cb-time mono" id="gCallTimer">00:00</span>
  </div>
  <div class="cb-state" id="gCallState">Starting&hellip;</div>
  <div class="cb-acts">
    <button class="btn ghost sm" onclick="endCall()">Hang up</button>
    <button class="btn coral sm" onclick="openDisp()">Disposition&hellip;</button>
  </div>
  <div class="cb-err hide" id="gCallErr"></div>
</div>

<!-- First-call checklist. Opens by itself the moment the first call to a lead is ANSWERED — the
     questions are worth asking while the retailer is on the line, not reconstructed afterwards. -->
<div class="modal hide" id="chkModal">
  <div class="box">
    <div class="mh"><h2>First call &middot; <span id="chkWho">&mdash;</span></h2>
      <p class="desc">Ask these while you have them on the line. Saved against the call and the trail.</p></div>
    <div class="mb" id="chkBody"></div>
    <div class="mf">
      <span class="note" id="chkNote" style="margin-right:auto"></span>
      <button class="btn ghost" onclick="closeChk()">Later</button>
      <button class="btn" style="background:#1f2a5e;color:#fff" id="chkSaveBtn" onclick="saveChk()">Save answers</button>
    </div>
  </div>
</div>

<div class="modal hide" id="qModal">
  <div class="box">
    <div class="mh"><h2 id="qTitle">New question</h2>
      <p class="desc">Shows while a call is connected, at the stages you choose.</p></div>
    <div class="mb">
      <label class="lbl">Question (required)</label>
      <input id="qPrompt" class="inp" style="width:100%" placeholder="What should the agent ask?">
      <div class="grid g2" style="gap:12px">
        <div>
          <label class="lbl">Answer type</label>
          <select id="qType" class="inp" style="width:100%" onchange="qTypeChanged()">
            <option value="TEXT">Text</option><option value="NUMBER">Number</option>
            <option value="YESNO">Yes / No</option><option value="CHOICE">Choice</option>
          </select>
        </div>
        <div>
          <label class="lbl">Points</label>
          <input id="qPoints" type="number" min="0" step="1" class="inp" style="width:100%" value="0">
        </div>
      </div>
      <div id="qChoicesWrap" class="hide">
        <label class="lbl">Options &mdash; separate with |</label>
        <input id="qChoices" class="inp" style="width:100%" placeholder="Yes|No|Not sure">
      </div>
      <label class="lbl">Show at these stages</label>
      <div class="opts" id="qStages"></div>
      <div class="note">None selected means every stage.</div>
      <div class="grid g2" style="gap:12px">
        <div>
          <label class="lbl">Sort order</label>
          <input id="qOrder" type="number" step="10" class="inp" style="width:100%" value="0">
        </div>
        <div>
          <label class="lbl">&nbsp;</label>
          <div style="display:flex;gap:14px;align-items:center;padding-top:8px">
            <label style="font-size:13px"><input type="checkbox" id="qRequired"> Required</label>
            <label style="font-size:13px"><input type="checkbox" id="qActive" checked> Active</label>
          </div>
        </div>
      </div>
      <div id="qErr" class="hide" style="margin-top:10px;color:#e03131;font-size:12.5px"></div>
    </div>
    <div class="mf">
      <button class="btn ghost" id="qDelBtn" onclick="deleteQuestion()" style="margin-right:auto">Delete</button>
      <button class="btn ghost" onclick="closeQ()">Cancel</button>
      <button class="btn" style="background:#1f2a5e;color:#fff" id="qSaveBtn" onclick="saveQuestion()">Save</button>
    </div>
  </div>
</div>

<div class="modal hide" id="asgModal">
  <div class="box">
    <div class="mh"><h2>Assign lead</h2>
      <p class="desc" id="asgWho">&mdash;</p></div>
    <div class="mb">
      <input id="asgSearch" class="inp" style="width:100%" placeholder="Filter by name or tier…"
             oninput="renderAssignList()">
      <div style="display:flex;gap:6px;margin:10px 0 4px;flex-wrap:wrap" id="asgTiers"></div>
      <div id="asgList" style="max-height:340px;overflow-y:auto;margin-top:6px"></div>
    </div>
    <div class="mf"><button class="btn ghost" onclick="closeAssign()">Cancel</button></div>
  </div>
</div>

<div class="modal hide" id="rgnModal">
  <div class="box">
    <div class="mh"><h2>Region owner</h2>
      <p class="desc" id="rgnWho">&mdash;</p></div>
    <div class="mb">
      <p class="desc" style="margin-bottom:8px">Pick the BM/RSM who should own this region. This writes the region's Sales L4 position, which the engine reads first; leads already assigned keep their owner.</p>
      <input id="rgnSearch" class="inp" style="width:100%" placeholder="Filter by name, tier or region…" oninput="renderRegionOwnerList()">
      <div id="rgnList" style="max-height:340px;overflow-y:auto;margin-top:10px"></div>
    </div>
    <div class="mf"><button class="btn ghost" onclick="closeRegionOwner()">Cancel</button></div>
  </div>
</div>

<div class="toastwrap" id="toasts"></div>

<script>
  var CTX = "${rc.contextPath}";
  var SEED = { summary:$summaryJson, state:$stateFunnelJson, heat:$slaHeatmapJson, ageing:$ageingJson };
  var STATE = { regionId:'', agentId:'', from:'$!fromDate', to:'$!toDate' };
  var DATA = { summary:null, state:null, heat:null, ageing:null };

  function byId(x){ return document.getElementById(x); }
  function esc(s){ if(s==null) return ''; return (''+s).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
  function fmtInt(n){ if(n==null) return '0'; return (''+n).replace(/\B(?=(\d{3})+(?!\d))/g,','); }
  /**
   * Business value in lakhs.
   *
   * Two conventions live in user.lead.potential: the form captures LAKHS (rows hold 1–99), but
   * ~1,355 older rows were entered in RUPEES (1,000 – 2,00,00,000). Nothing between 100 and 999
   * exists, so the gap is a safe separator: 1000 and above is read as rupees and brought onto the
   * lakh scale. Normalised on read only — no stored value is rewritten.
   */
  var LAKH_CUTOFF=1000;
  function toLakh(v){ v=Number(v); return v>=LAKH_CUTOFF ? v/100000 : v; }
  function inrShort(v){ if(v==null||isNaN(v)||Number(v)<=0) return '&#8377;0';
    var l=toLakh(v);
    // Under a lakh needs two decimals: a ₹1,000 lead is 0.01L, and one decimal would print it as
    // ₹0L — the same information loss the old scaling caused, just at the other end.
    var n=l<1?Math.round(l*100)/100:Math.round(l*10)/10;
    return '&#8377;'+(n%1===0?n:n.toFixed(l<1?2:1))+'L'; }

  /**
   * "1 - 21 Sep 2026" / "28 Aug - 21 Sep 2026" / "21 Dec 2025 - 3 Jan 2026".
   * ISO on both ends made the reader parse two 10-character strings to see it was one month.
   */
  function periodLabel(from,to){
    if(!from||!to) return (from||to||'\u2014');
    var a=new Date(from), b=new Date(to);
    if(isNaN(a)||isNaN(b)) return from+' \u2192 '+to;
    var M=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var sameY=a.getFullYear()===b.getFullYear(), sameM=sameY&&a.getMonth()===b.getMonth();
    if(sameM)  return a.getDate()+' \u2013 '+b.getDate()+' '+M[b.getMonth()]+' '+b.getFullYear();
    if(sameY)  return a.getDate()+' '+M[a.getMonth()]+' \u2013 '+b.getDate()+' '+M[b.getMonth()]+' '+b.getFullYear();
    return a.getDate()+' '+M[a.getMonth()]+' '+a.getFullYear()+' \u2013 '+b.getDate()+' '+M[b.getMonth()]+' '+b.getFullYear();
  }

  function setDashPeriod(){ byId('dashPeriod').textContent=periodLabel(STATE.from,STATE.to); }

  // ---- tabs
  var SCREENS=['cmd','record','create','assign','live','dash','chk','audit'];
  var LOADED={};
  function go(id,btn){ SCREENS.forEach(function(s){ byId(s).classList.toggle('hide',s!==id); });
    // Leaving the live tab must stop its poll; entering it starts a fresh one.
    if(id==='live'){ startLive(); } else { stopLive(); }
    if(id==='chk') loadQuestions();
    document.querySelectorAll('.tab').forEach(function(t){ t.classList.remove('active'); }); if(btn) btn.classList.add('active');
    if(id==='dash'){ setDashPeriod(); loadBgc(); }
    if(id==='record' && !LOADED.record){ LOADED.record=true; loadRecentRecord(); }
    if(id==='assign' && !LOADED.assign){ LOADED.assign=true; buildAssign(); }
    if(id==='audit'){ buildAudit(); } }

  // ---- toast
  function toast(msg,ok){ var w=byId('toasts'); var t=document.createElement('div'); t.className='toast';
    t.innerHTML=(ok?'<span class="ok">&#10003;</span>':'')+esc(msg); w.appendChild(t);
    setTimeout(function(){ t.style.opacity='0'; t.style.transition='opacity .3s'; setTimeout(function(){ t.remove(); },300); },2600); }

  // ---- filters + fetch
  function qs(){ var q=''; if(STATE.regionId)q+='&regionId='+encodeURIComponent(STATE.regionId);
    if(STATE.agentId)q+='&agentId='+encodeURIComponent(STATE.agentId);
    if(STATE.from)q+='&from='+encodeURIComponent(STATE.from); if(STATE.to)q+='&to='+encodeURIComponent(STATE.to); return q; }
  function getJSON(path,cb,onErr){ fetch(CTX+path,{credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(function(j){ cb((j&&j.response!==undefined)?j.response:j); })
    .catch(function(e){ console.error('LMS fetch failed',path,e);
      if(typeof onErr==='function'){ onErr(e); } else { toast('Could not load data'); } }); }

  // ---- stage helpers
  var STCLASS={NEW:'st-new',ASSIGNED:'st-assigned',CONTACTED:'st-contacted',QUALIFIED:'st-qualified',
    BEAT_PLANNED:'st-beat',VISITED:'st-visited',ONBOARDED:'st-onboarded',ACTIVE:'st-active',NOT_INTERESTED:'st-ni',DROPPED:'st-dead'};
  function stagePill(st,lb){ if(!st) return '<span class="stage st-new">—</span>'; return '<span class="stage '+(STCLASS[st]||'st-new')+'">'+esc(lb||st)+'</span>'; }
  function slaCell(state){ switch(state){
    case'MET': return '<span class="sla ok"><span class="slabar"><i style="width:100%;background:#2f9e44"></i></span><span class="clk">met</span></span>';
    case'RUNNING': return '<span class="sla ok"><span class="slabar"><i style="width:50%;background:#1f2a5e"></i></span><span class="clk">running</span></span>';
    case'AT_RISK': return '<span class="sla warn"><span class="slabar"><i style="width:85%;background:#f08c00"></i></span><span class="clk">&lt; 1 hr</span></span>';
    case'BREACHED': return '<span class="sla bad"><span class="slabar"><i style="width:100%;background:#e03131"></i></span><span class="clk">breached</span></span>';
    default: return '<span style="color:#97a1b5;font-size:12px">&mdash;</span>'; } }

  // ---- COMMAND CENTER
  var CC_KPI={ 'new':{i:'&#128229;',bg:'#eef1fb',fg:'#3b5bdb'}, awaiting:{i:'&#9203;',bg:'#fff4e6',fg:'#f08c00',v:'#f08c00'},
    sla:{i:'&#9888;',bg:'#fff0f0',fg:'#e03131',v:'#e03131'}, contacted:{i:'&#128222;',bg:'#e3fafc',fg:'#0c8599'},
    qualified:{i:'&#10003;',bg:'#e6fcf5',fg:'#0ca678'}, onboarded:{i:'&#127942;',bg:'#ebfbee',fg:'#2f9e44'} };
  var ATT_META={ BREACHED_NO_CONTACT:{i:'&#9888;',bg:'#fff0f0',fg:'#e03131',c:'badflag'}, HOLD:{i:'&#128100;',bg:'#fff0f0',fg:'#e03131',c:'badflag'},
    SLA_UNDER_1H:{i:'&#9203;',bg:'#fff4e6',fg:'#e8590c',c:'warnflag'}, MISSING_DISP:{i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',c:'warnflag'},
    QUALIFIED_NO_BEAT:{i:'&#128337;',bg:'#eef1f6',fg:'#69748c',c:''}, ONBOARDED_PENDING:{i:'&#128260;',bg:'#f3f0ff',fg:'#7048e8',c:''} };

  function renderSummary(d){ DATA.summary=d;
    var kh=''; (d.kpis||[]).forEach(function(k){ var m=CC_KPI[k.key]||{i:'&#128202;',bg:'#eef1f6',fg:'#69748c'};
      kh+='<div class="kpi" data-kpi="'+esc(k.key)+'"><div class="top"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
        '<div class="label">'+esc(k.label)+'</div></div><div class="val"'+(m.v?' style="color:'+m.v+'"':'')+'>'+fmtInt(k.value)+'</div>'+
        '<div class="foot">'+esc(k.foot)+'</div></div>'; });
    byId('ccKpis').innerHTML=kh;
    renderFunnel(d.funnel||[]);
    var ah=''; (d.attention||[]).forEach(function(a){ var m=ATT_META[a.key]||{i:'&#128202;',bg:'#eef1f6',fg:'#69748c',c:''};
      ah+='<div class="att" data-att="'+esc(a.key)+'" data-attt="'+esc(a.title)+'"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
        '<div class="ab"><div class="atitle">'+esc(a.title)+'</div><div class="adet">'+esc(a.detail)+'</div></div>'+
        '<div class="acount '+m.c+'">'+fmtInt(a.count)+'</div></div>'; });
    byId('ccAttention').innerHTML=ah;
    buildDashKpis(); buildFix();
  }

  function renderFunnel(funnel){
    var byStage={}; funnel.forEach(function(s){ byStage[s.stage]=s; });
    // First box is every lead created in the period (server key ALL) -- not the NEW stage, which is
    // the "New" KPI card. BEAT_PLANNED / VISITED / ONBOARDED are evidence-derived on the server.
    var seq=[['ALL','All leads'],['ASSIGNED','Assigned'],['CONTACTED','Contacted'],['QUALIFIED','Qualified'],['BEAT_PLANNED','Beat planned'],['VISITED','Visited'],['ONBOARDED','Onboarded']];
    var h=''; var prev=null, prevKey=null;
    seq.forEach(function(p,idx){ var s=byStage[p[0]]; if(!s) return; var last=(idx===seq.length-1);
      // Leads that fell out between the previous box and this one: at the previous stage exactly,
      // or -- for the first gap -- anything in scope that never reached ASSIGNED (still NEW, or
      // closed as NOT_INTERESTED / DROPPED). Same buckets the drill endpoint already understands.
      var dropKey = prevKey===null ? '' : (prevKey==='ALL' ? 'NEW,NOT_INTERESTED,DROPPED' : prevKey);
      var dropAttr = dropKey ? ' data-drop="'+esc(dropKey)+'" data-droplabel="'+esc('Dropped before '+p[1])+'" title="Open the leads that did not reach '+esc(p[1])+'"' : '';
      var cap; if(idx===0){ cap='<div class="keep">created</div>'; }
      else if(last){ var dropL=prev?prev.count-s.count:0;
        cap='<div class="keep"><span class="fcap"'+dropAttr+'>'+s.pct+'% conversion'+(dropL>0?(' · &minus;'+fmtInt(dropL)):'')+'</span></div>'; }
      else { var drop=prev?prev.count-s.count:0;
        cap=drop>0?('<div class="drop"><span class="fcap"'+dropAttr+'>&minus;'+fmtInt(drop)+'</span></div>')
                  :('<div class="keep"><span class="fcap"'+dropAttr+'>'+s.pct+'%</span></div>'); }
      h+='<div class="fstep" data-stage="'+p[0]+'" data-label="'+esc(p[1])+'"><div class="fn">'+esc(p[1])+'</div><div class="fv">'+fmtInt(s.count)+'</div>'+
        '<div class="fbar" style="width:'+Math.max(s.pct,3)+'%"></div>'+cap+(last?'':'<span class="arrow">&#10148;</span>')+'</div>';
      prev=s; prevKey=p[0]; });
    byId('ccFunnel').innerHTML=h||'<div class="ph">No leads in scope.</div>';
  }

  // ---- Lead pipeline: filtered, sorted and paged on the server ------------------------------
  // PIPE.q is the search term. While it is set the date filter does not apply — a search hunts for
  // one known retailer, and quietly scoping it to the selected month would report "not found" for a
  // lead that exists. The caption says which mode is in force so that is never a surprise.
  var PIPE = { q:'', sort:'created', dir:'desc', page:1, pageSize:50, pages:1, total:0 };
  // Call Center users for the page-level agent filter (header). "Their" leads = created by them OR
  // owned by them; qs() carries it, so cards, funnel, attention queue, pipeline and every drawer
  // narrow together.
  function loadCallCenterUsers(){
    getJSON('/lms/dashboard/callcenter-users', function(d){
      var sel=byId('fAgent'); if(!sel) return; var keep=sel.value;
      var users=(d&&d.users)||[];
      var h='<option value="">'+(users.length?'All Call Center users':'No Call Center users found')+'</option>';
      users.forEach(function(u){ h+='<option value="'+u.authId+'">'+esc(u.name)+'</option>'; });
      sel.innerHTML=h; sel.value=keep||'';
    }, function(){ var sel=byId('fAgent'); if(sel) sel.innerHTML='<option value="">Call Center list unavailable</option>'; });
  }
  // Search mode ignores the date window but keeps the scope filters (region + agent).
  function scopeQs(){ var q=''; if(STATE.regionId) q+='&regionId='+encodeURIComponent(STATE.regionId);
    if(STATE.agentId) q+='&agentId='+encodeURIComponent(STATE.agentId); return q; }

  function loadPipeline(){
    byId('ccPipeline').innerHTML='<tr><td colspan="10"><div class="ph">Loading…</div></td></tr>';
    var p='/lms/dashboard/pipeline?page='+PIPE.page+'&pageSize='+PIPE.pageSize+
          '&sort='+encodeURIComponent(PIPE.sort)+'&dir='+encodeURIComponent(PIPE.dir);
    if(PIPE.q){ p+='&q='+encodeURIComponent(PIPE.q)+scopeQs(); }
    else { p+=qs(); }
    getJSON(p,function(d){
      d=d||{}; var rows=d.rows||[];
      PIPE.total=d.total||0; PIPE.pages=d.pages||1; PIPE.page=d.page||1;
      renderPipeHead();
      if(!rows.length){
        byId('ccPipeline').innerHTML='<tr><td colspan="10"><div class="ph">'+
          (PIPE.q?('No lead matches “'+esc(PIPE.q)+'”.'):'No leads in scope.')+'</div></td></tr>';
      } else {
        var h='';
        rows.forEach(function(l){
          var rc=l.slaState==='BREACHED'?'rowbad':(l.slaState==='AT_RISK'?'rowwarn':'');
          h+='<tr class="clickrow '+rc+'" data-leadid="'+l.id+'">'+
            '<td class="nowrap"><span class="idpill">'+esc(l.lmsCode)+'</span></td>'+
            '<td class="wrapok"><b>'+esc(l.name||'—')+'</b>'+(l.outlet?'<br><span style="color:#97a1b5;font-size:11px">'+esc(l.outlet)+'</span>':'')+'</td>'+
            '<td class="nowrap">'+(l.path==='B'?'<span class="tag b">B · Field</span>':'<span class="tag a">A · BGC</span>')+'</td>'+
            '<td class="nowrap">'+stagePill(l.stage,l.stageLabel)+'</td>'+
            // title= so a name clipped by the fixed width is still readable on hover.
            '<td class="nowrap" title="'+esc(l.owner||'')+'">'+esc(l.owner||'—')+'</td>'+
            '<td class="nowrap" title="'+esc(l.city||'')+'">'+esc(l.city||'—')+'</td>'+
            '<td class="nowrap" title="'+esc(l.createdBy||'')+'">'+esc(l.createdBy||'—')+'</td>'+
            '<td class="nowrap">'+slaCell(l.slaState)+'</td>'+
            '<td class="num nowrap">'+inrShort(l.value)+'</td>'+
            // data-call carries the lead so the handler needs nothing from the row's other cells.
            '<td class="nowrap" style="display:flex;gap:5px">'+
              '<button class="rowcall" data-call="'+l.id+'" data-callname="'+esc(l.name||'')+'"'+
                ' title="Call '+esc(l.name||('lead #'+l.id))+'">&#9742;</button>'+
              '<button class="rowedit" data-editlead="'+l.id+'"'+
                ' title="Edit '+esc(l.name||('lead #'+l.id))+'">&#9998;</button>'+
              '<button class="rowassign" data-assign="'+l.id+'" data-assignname="'+esc(l.name||'')+'"'+
                ' data-assignowner="'+esc(l.owner||'')+'" data-assignregion="'+esc(l.regionId||'')+'"'+
                ' title="Assign '+esc(l.name||('lead #'+l.id))+'">&#128100;</button>'+
            '</td></tr>';
        });
        byId('ccPipeline').innerHTML=h;
      }
      // Say how many there actually are, not how many were drawn.
      var shown=rows.length, first=(PIPE.page-1)*PIPE.pageSize+(shown?1:0), last=(PIPE.page-1)*PIPE.pageSize+shown;
      byId('pipeCount').textContent=PIPE.total
        ? ('Showing '+first+'–'+last+' of '+fmtInt(PIPE.total)+(PIPE.q?' matching leads (all dates)':' leads in the selected period'))
        : '';
      byId('pipePageLbl').textContent='Page '+PIPE.page+' / '+Math.max(PIPE.pages,1);
      byId('pipePrev').disabled=(PIPE.page<=1);
      byId('pipeNext').disabled=(PIPE.page>=PIPE.pages);
      byId('pipeDesc').innerHTML=PIPE.q
        ? 'Searching every lead for “<b>'+esc(PIPE.q)+'</b>” — the date filter is ignored while a search is active.'
        : 'Click any row &rarr; full LMS record &amp; trail. Rows shaded by SLA urgency.';
      byId('pipeClear').classList.toggle('hide', !PIPE.q);
    });
  }

  /**
   * Mark the active column and its direction.
   *
   * The label is captured once into data-label and re-read from there. Deriving it from
   * textContent instead re-read the arrow this function had just appended, so every sort click
   * stacked another one onto the header.
   */
  function renderPipeHead(){
    document.querySelectorAll('th.sortable').forEach(function(th){
      if(!th.hasAttribute('data-label')) th.setAttribute('data-label', th.textContent.trim());
      var on=(th.getAttribute('data-sort')===PIPE.sort);
      th.classList.toggle('on',on);
      th.innerHTML=esc(th.getAttribute('data-label'))+
        (on?'<span class="arrow '+(PIPE.dir==='asc'?'up':'down')+'"></span>':'');
    });
  }

  function pipeSort(col){
    // Same column toggles direction; a new column starts descending, which is what people expect
    // from value and dates and is harmless for the text columns.
    if(PIPE.sort===col){ PIPE.dir=(PIPE.dir==='asc'?'desc':'asc'); }
    else { PIPE.sort=col; PIPE.dir='desc'; }
    PIPE.page=1; loadPipeline();
  }
  function pipeSearch(){
    var v=(byId('pipeQ').value||'').trim();
    if(v && v.length<2){ toast('Type at least 2 characters'); return; }
    PIPE.q=v; PIPE.page=1; loadPipeline();
  }
  function pipeClearSearch(){ byId('pipeQ').value=''; PIPE.q=''; PIPE.page=1; loadPipeline(); }
  function pipePage(step){
    var n=PIPE.page+step;
    if(n<1||n>PIPE.pages) return;
    PIPE.page=n; loadPipeline();
  }

  function kpiBucket(k){ switch(k){case'new':return['STAGE','NEW'];case'awaiting':return['STAGE','ASSIGNED'];
    case'sla':return['ATTENTION','BREACHED_NO_CONTACT'];case'contacted':return['STAGE','CONTACTED'];
    case'qualified':return['STAGE','QUALIFIED'];
    // The Onboarded tile counts ONBOARDED + ACTIVE, so its drill has to as well.
    case'onboarded':return['STAGE_IN','ONBOARDED,ACTIVE'];default:return['ALL','']; } }

  // ---- DASHBOARDS
  var DASH_KPI=[ {i:'&#128229;',bg:'#eef1fb',fg:'#3b5bdb'}, {i:'&#128200;',bg:'#e6fcf5',fg:'#0ca678',v:'#0ca678'},
    {i:'&#9878;',bg:'#fff4e6',fg:'#f08c00',v:'#f08c00'}, {i:'&#128222;',bg:'#e3fafc',fg:'#0c8599'},
    {i:'&#8987;',bg:'#fff0f0',fg:'#e03131',v:'#e03131'}, {i:'&#128176;',bg:'#ebfbee',fg:'#2f9e44'} ];
  function pctColor(p){ return p>=25?'#2f9e44':(p>=18?'#f08c00':(p>=10?'#e8590c':'#e03131')); }
  function slaColor(p){ return p>=85?'#2f9e44':(p>=70?'#f08c00':'#e03131'); }

  function renderState(d){ DATA.state=d; var rows=(d&&d.rows)?d.rows:[];
    var h=''; rows.forEach(function(r){ var cls=r.convPct<15?'rowbad':(r.slaPct<60?'rowwarn':'');
      h+='<tr class="clickrow '+cls+'" data-region="'+esc(r.regionCode)+'" data-rn="'+esc(r.regionName)+'">'+
        '<td><b>'+esc(r.regionName)+'</b> <span class="idpill">'+esc(r.regionCode)+'</span></td>'+
        '<td class="num">'+fmtInt(r.newCount)+'</td><td class="num">'+fmtInt(r.contacted)+'</td><td class="num">'+fmtInt(r.qualified)+'</td>'+
        '<td class="num">'+fmtInt(r.beatPlanned)+'</td><td class="num">'+fmtInt(r.visited)+'</td><td class="num">'+fmtInt(r.onboarded)+'</td>'+
        '<td class="num"><b style="color:'+pctColor(r.convPct)+'">'+r.convPct+'%</b></td>'+
        '<td class="num"><b style="color:'+slaColor(r.slaPct)+'">'+r.slaPct+'%</b></td></tr>'; });
    byId('dashState').innerHTML=h||'<tr><td colspan="9"><div class="ph">No regional data.</div></td></tr>';
    buildDashKpis(); buildFix();
  }

  function renderHeat(d){ DATA.heat=d; var weeks=(d&&d.weeks)?d.weeks:[],bms=(d&&d.bms)?d.bms:[];
    if(!bms.length){ byId('dashHeat').innerHTML='<div class="ph">No SLA data for the selected period.</div>'; return; }
    function hc(p){ if(p>=90)return'#40c057';if(p>=80)return'#82c91e';if(p>=70)return'#fab005';if(p>=60)return'#fd7e14';if(p>=50)return'#fa5252';return'#e03131'; }
    var h='<table class="heat"><thead><tr><td style="background:none;border:0"></td>';
    weeks.forEach(function(w){ h+='<td style="background:none;border:0;color:#97a1b5;font-size:10px;font-weight:700">'+esc(w)+'</td>'; });
    h+='</tr></thead><tbody>';
    bms.forEach(function(bm){ h+='<tr><td style="background:none;color:#69748c;font-size:11px;text-align:left;width:auto;border:0">'+esc(bm.bmName)+'</td>';
      (bm.cells||[]).forEach(function(c){ if(c.pct==null){ h+='<td style="background:#eef1f6;color:#97a1b5">–</td>'; }
        else { var col=hc(c.pct),tc=(c.pct>=70&&c.pct<80)?'#333':'#fff'; h+='<td style="background:'+col+';color:'+tc+'">'+c.pct+'</td>'; } }); h+='</tr>'; });
    h+='</tbody></table>'; byId('dashHeat').innerHTML=h;
  }

  function renderAgeing(d){ DATA.ageing=d; buildDashKpis(); buildFix(); }

  /** Telephony totals for the calls/day tile. Failure leaves the tile honest rather than zeroed. */
  function loadBgc(){
    getJSON('/lms/dashboard/bgc-daily'+qsDates(), function(d){ DATA.bgc=d||null; buildDashKpis(); },
      function(){ DATA.bgc=null; buildDashKpis(); });
  }

  /** Days in the selected period — the calls/day tile divided by a hardcoded 90 regardless of it. */
  function periodDays(){
    if(!STATE.from || !STATE.to) return 1;
    var a=new Date(STATE.from), b=new Date(STATE.to);
    if(isNaN(a)||isNaN(b)) return 1;
    return Math.max(1, Math.round((b-a)/86400000)+1);
  }

  function buildDashKpis(){ var s=DATA.summary; if(!s) return;
    var tot=0,acc=0; ((DATA.state&&DATA.state.rows)||[]).forEach(function(r){ tot+=r.newCount; acc+=r.slaPct*r.newCount; });
    var sla=tot>0?Math.round(acc/tot):0;

    // Calls/day from the real call log. It used to be CONTACTED ÷ 90 labelled "proxy · no
    // telephony" — a stage count divided by a constant that stopped matching the period the moment
    // the default window became the current month. Now: calls placed ÷ days in the selected period,
    // with the connect rate underneath, or an honest dash when the telephony data has not loaded.
    var callsTile='—', callsFoot='no calls in period';
    if(DATA.bgc){
      var days=periodDays();
      callsTile=fmtInt(Math.round((DATA.bgc.calls||0)/days));
      callsFoot=(DATA.bgc.calls||0)+' calls · '+(DATA.bgc.connectPct||0)+'% connected';
    }

    var ageDays=(DATA.ageing&&DATA.ageing.days)?DATA.ageing.days:7;
    var vals=[ {v:fmtInt(s.total),f:'in period'}, {v:s.conversionPct+'<small>%</small>',f:'new &rarr; onboarded'},
      {v:sla+'<small>%</small>',f:'first contact ≤ 5h'}, {v:callsTile,f:callsFoot},
      {v:DATA.ageing?fmtInt(DATA.ageing.total):'—',f:'stuck by stage'},
      // inrShort, not fmtInr: business value is stored in lakhs and every other figure on the page
      // renders it that way. fmtInr printed a bare ₹139 for what is ₹139 lakh.
      {v:inrShort(s.onboardedValue),f:'est. potential'} ];
    var labels=['LMS created','Conversion','SLA compliance','Calls / day (BGC)',
                'Ageing &gt; '+ageDays+' days','Onboarded value'];
    var h=''; vals.forEach(function(x,i){ var m=DASH_KPI[i];
      h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.i+'</div>'+
        '<div class="label">'+labels[i]+'</div></div><div class="val"'+(m.v?' style="color:'+m.v+'"':'')+'>'+x.v+'</div><div class="foot">'+x.f+'</div></div>'; });
    byId('dashKpis').innerHTML=h;
  }

  function buildFix(){ var rows=((DATA.state&&DATA.state.rows)||[]).slice();
    var out='';
    if(rows.length){ var worst=rows.slice().sort(function(a,b){return a.convPct-b.convPct;})[0];
      out+='<div class="fix"><div class="sev" style="background:#e03131"></div><div class="fb"><div class="ft">'+esc(worst.regionName)+' is leaking at the top</div>'+
        '<div class="fd"><b>'+fmtInt(worst.newCount)+' created, only '+worst.convPct+'% onboarded and '+worst.slaPct+'% SLA</b> — the weakest region this period.</div>'+
        '<div class="act">&rarr; Review its stuck leads; check BM mapping / HOLD queue.</div></div></div>';
      var lowSla=rows.slice().sort(function(a,b){return a.slaPct-b.slaPct;})[0];
      if(lowSla && lowSla.regionCode!==worst.regionCode){ out+='<div class="fix"><div class="sev" style="background:#f59f00"></div><div class="fb"><div class="ft">'+esc(lowSla.regionName)+' SLA slipping</div>'+
        '<div class="fd"><b>'+lowSla.slaPct+'% on-time first contact</b> — first-contact discipline is breaking down.</div>'+
        '<div class="act">&rarr; Enforce ASM mapping (≤2h) + coaching.</div></div></div>'; } }
    var age=DATA.ageing?DATA.ageing.total:0;
    out+='<div class="fix"><div class="sev" style="background:#f59f00"></div><div class="fb"><div class="ft">'+fmtInt(age)+' leads ageing &gt; 7 days</div>'+
      '<div class="fd"><b>Stuck open leads by stage</b> — qualified leads not being added to beats lose revival odds.</div>'+
      '<div class="act">&rarr; Nudge ASMs to beat-plan qualified LMS within 48h.</div></div></div>';
    byId('dashFix').innerHTML=out;
  }

  // ---- drill drawer
  function openDrawer(crumb,title,sub,html){ byId('dCrumb').textContent=crumb||''; byId('dTitle').textContent=title||'';
    byId('dSub').textContent=sub||'';
    // The filter for a drawer table lives in the drawer header, so it has to go when the body it
    // belongs to is replaced — otherwise the next drawer opens wearing the last one's filter.
    byId('dTools').innerHTML='';
    byId('dBody').innerHTML=html||''; byId('ov').classList.add('open'); byId('drawer').classList.add('open'); }
  function closeDrawer(){ byId('ov').classList.remove('open'); byId('drawer').classList.remove('open'); }
  document.addEventListener('keydown',function(e){ if(e.key==='Escape')closeDrawer();
    if(e.key==='/'&&document.activeElement.tagName!=='INPUT'){ e.preventDefault(); byId('lmsSearch').focus(); } });

  // No SLA column: the drawer lists leads by stage, region or search term, and the first-contact
  // clock only ever ran on leads created through the LMS -- so the column was a wall of em-dashes
  // with the occasional breach, carrying no information the drawer was opened to find. SLA lives
  // where it is the subject: the pipeline, the attention queue, and the SLA Compliance report.
  function drawerLeadTable(leads){ if(!leads||!leads.length) return '<div class="ph">No leads in this bucket.</div>';
    var h='<div class="card"><table><thead><tr><th>LMS ID</th><th>Business</th><th>Stage</th><th>Owner</th><th class="num">Value</th></tr></thead><tbody>';
    leads.forEach(function(l){ h+='<tr class="clickrow" data-leadid="'+l.id+'"><td><span class="idpill">'+esc(l.lmsCode)+'</span></td>'+
      '<td><b>'+esc(l.name||'—')+'</b>'+(l.outlet?'<br><span style="color:#97a1b5;font-size:11px">'+esc(l.outlet)+'</span>':'')+'</td>'+
      '<td>'+stagePill(l.stage,l.stageLabel)+'</td><td>'+esc(l.owner||'—')+'</td>'+
      '<td class="num">'+inrShort(l.value)+'</td></tr>'; });
    return h+'</tbody></table></div>'; }
  // The drill drawer pages server-side (100 per page), so a bar reading 501 can be walked in full
  // instead of stopping at the first 100. The header filter box only filters the page on screen.
  var DRILL={crumb:'',title:'',sub:'',bt:'',bk:'',page:1,pageSize:100,pages:1,total:0};
  function drill(crumb,title,sub,bt,bk){ DRILL={crumb:crumb,title:title,sub:sub,bt:bt,bk:bk,page:1,pageSize:100,pages:1,total:0}; loadDrill(); }
  function drillPage(delta){ var n=DRILL.page+delta; if(n<1||n>DRILL.pages) return; DRILL.page=n; loadDrill(); }
  function loadDrill(){ var D=DRILL; openDrawer(D.crumb,D.title,'Loading…','<div class="ph">Loading…</div>');
    var q='?bucketType='+encodeURIComponent(D.bt)+(D.bk?'&bucketKey='+encodeURIComponent(D.bk):'')+
      '&page='+D.page+'&pageSize='+D.pageSize+qs();
    getJSON('/lms/dashboard/leads'+q,function(d){ var leads=(d&&d.leads)?d.leads:[];
      D.total=(d&&d.total!=null)?d.total:leads.length; D.pages=Math.max((d&&d.pages)||1,1); D.page=(d&&d.page)||D.page;
      var count=fmtInt(D.total)+' lead(s)';
      if(D.pages>1){ var first=(D.page-1)*D.pageSize+(leads.length?1:0), last=(D.page-1)*D.pageSize+leads.length;
        count+=' · showing '+first+'–'+last; }
      openDrawer(D.crumb,D.title,(D.sub||'')+' · '+count,drawerLeadTable(leads)+drillPager());
      byId('dBody').scrollTop=0; }); }
  function drillPager(){ if(DRILL.pages<=1) return '';
    return '<div style="display:flex;justify-content:flex-end;align-items:center;gap:6px;margin-top:10px;flex-wrap:wrap">'+
      '<button class="btn ghost sm" onclick="drillPage(-1)"'+(DRILL.page<=1?' disabled':'')+'>&larr; Prev</button>'+
      '<span class="note">Page '+DRILL.page+' / '+DRILL.pages+'</span>'+
      '<button class="btn ghost sm" onclick="drillPage(1)"'+(DRILL.page>=DRILL.pages?' disabled':'')+'>Next &rarr;</button></div>'; }

  // ---- app-bar search: LMS id / retailer / business / phone / city -> results in the drawer
  var searchTimer=null, searchSeq=0;
  function runSearch(){ var q=(byId('lmsSearch').value||'').trim();
    if(q.length<2){ toast('Type at least 2 characters'); return; }
    var seq=++searchSeq;
    openDrawer('Search','\u201c'+q+'\u201d','Searching…','<div class="ph">Searching…</div>');
    getJSON('/lms/dashboard/search?q='+encodeURIComponent(q),function(d){
      if(seq!==searchSeq) return;                       // a newer search already won
      var leads=(d&&d.leads)?d.leads:[];
      openDrawer('Search','\u201c'+q+'\u201d',leads.length+' match(es)',drawerLeadTable(leads)); },
      function(){ if(seq!==searchSeq) return;
        openDrawer('Search','\u201c'+q+'\u201d','Search failed','<div class="ph">Could not run the search.</div>'); }); }
  byId('pipeQ').addEventListener('keydown',function(e){
    if(e.key==='Enter'){ e.preventDefault(); pipeSearch(); }
    else if(e.key==='Escape'){ pipeClearSearch(); } });

  byId('lmsSearch').addEventListener('keydown',function(e){
    if(e.key==='Enter'){ e.preventDefault(); clearTimeout(searchTimer); runSearch(); }
    else if(e.key==='Escape'){ this.blur(); closeDrawer(); } });
  byId('lmsSearch').addEventListener('input',function(){ clearTimeout(searchTimer);
    var v=(this.value||'').trim(); if(v.length<2) return;
    searchTimer=setTimeout(runSearch,400); });

  var REPORT_NOTE={ 'State Funnel':'Live from the lead record — grouped by region, BM and ASM.',
    'SLA Compliance':'Live — first_contacted_at vs first_contact_due, owner heat-map.',
    'Ageing':'Live — open leads untouched > 7 days, by stage.',
    'Management Roll-up':'Live — cross-region leads, onboardings and estimated value.',
    'BGC Daily':'Partial — created + dispositions are real; call volume is a PROXY (contacted ÷ days). No telephony bridge yet.',
    'Audit Hygiene':'Partial — missing-disposition & HOLD are shown; DND breaches & recording flags need the call/recording log.',
    'RBM Servicing':'Pending data — repeat-order / complaint / resolution-TAT need order + ticket data outside the lead record.' };

  // ---- delegated clicks
  document.addEventListener('click',function(e){
    var eq=e.target.closest('[data-editq]');
    if(eq){ editQuestion(parseInt(eq.getAttribute('data-editq'),10)); return; }
    // Stage chips are multi-select; the in-call answer chips are single-select.
    var qs=e.target.closest('.qstage');
    if(qs){ qs.classList.toggle('sel'); return; }
    var tf=e.target.closest('.trailf');
    if(tf){ setTrailFilter(tf.getAttribute('data-trailtype')); return; }
    var tp=e.target.closest('#asgTiers .chkopt');
    if(tp){ byId('asgTiers').querySelectorAll('.chkopt').forEach(function(x){ x.classList.remove('sel'); });
      tp.classList.add('sel'); ASG.tier=tp.getAttribute('data-tier'); renderAssignList(); return; }
    // The assign-modal tier pills share the .chkopt class for styling, so they are handled above
    // and excluded here: this generic branch only picks an answer chip, and letting it swallow a
    // tier click selected the pill visually while never applying the filter.
    var co=e.target.closest('.chkopt');
    if(co && !co.closest('#asgTiers') && !co.classList.contains('trailf')){ var wrap=co.parentNode;
      wrap.querySelectorAll('.chkopt').forEach(function(x){ x.classList.remove('sel'); });
      co.classList.add('sel'); return; }
    var asg=e.target.closest('[data-assign]');
    if(asg){ e.preventDefault(); e.stopPropagation();
      openAssign(parseInt(asg.getAttribute('data-assign'),10), asg.getAttribute('data-assignname'),
                 asg.getAttribute('data-assignowner'), asg.getAttribute('data-assignregion')); return; }
    var pick=e.target.closest('[data-assignto]');
    if(pick){ assignTo(parseInt(pick.getAttribute('data-assignto'),10)); return; }
    var rb=e.target.closest('[data-rgn]');
    if(rb){ openRegionOwner(parseInt(rb.getAttribute('data-rgn'),10), rb.getAttribute('data-rgnlabel'), rb.getAttribute('data-rgnowner')); return; }
    var rp=e.target.closest('[data-rgnpick]');
    if(rp){ setRegionOwner(parseInt(rp.getAttribute('data-rgnpick'),10), rp.getAttribute('data-rgnname')); return; }
    var ed=e.target.closest('[data-editlead]');
    if(ed){ e.preventDefault(); e.stopPropagation();
      editLeadById(parseInt(ed.getAttribute('data-editlead'),10)); return; }
    var cb=e.target.closest('[data-call]');
    if(cb){ e.preventDefault(); e.stopPropagation();
      dialLead(parseInt(cb.getAttribute('data-call'),10), cb.getAttribute('data-callname'), cb); return; }
    var la=e.target.closest('tr[data-liveagent]');
    if(la){ openAgentCalls(parseInt(la.getAttribute('data-liveagent'),10)); return; }
    var th=e.target.closest('th.sortable'); if(th){ pipeSort(th.getAttribute('data-sort')); return; }
    var kpi=e.target.closest('.kpi[data-kpi]'); if(kpi){ var b=kpiBucket(kpi.getAttribute('data-kpi'));
      drill('Command Center',kpi.querySelector('.label').textContent,'KPI drill',b[0],b[1]); return; }
    var fc=e.target.closest('.fcap[data-drop]'); if(fc){ var dk=fc.getAttribute('data-drop');
      drill('Lifecycle funnel',fc.getAttribute('data-droplabel'),'At the previous step, never reached this one',
            dk.indexOf(',')>=0?'STAGE_IN':'STAGE',dk); return; }
    var fs=e.target.closest('.fstep[data-stage]'); if(fs){ var st=fs.getAttribute('data-stage');
      drill('Lifecycle funnel',fs.getAttribute('data-label'),'Reached this stage',st==='ALL'?'ALL':'STAGE_REACHED',st==='ALL'?'':st); return; }
    var att=e.target.closest('.att[data-att]'); if(att){ drill('Needs attention',att.getAttribute('data-attt'),'Attention queue','ATTENTION',att.getAttribute('data-att')); return; }
    var reg=e.target.closest('tr[data-region]'); if(reg){ drill('State funnel',reg.getAttribute('data-rn'),'Region '+reg.getAttribute('data-region'),'REGION',reg.getAttribute('data-region')); return; }
    var rep=e.target.closest('tr[data-rep]'); if(rep){ openReport(rep.getAttribute('data-rep')); return; }
    var lead=e.target.closest('[data-leadid]'); if(lead){ var lid=lead.getAttribute('data-leadid');
      closeDrawer(); LOADED.record=true; byId('recLookup').value=lid; injectRecord(lid);
      go('record',document.querySelector('.tab[data-screen="record"]')); return; }
  });

  // ---- filters
  function refresh(){ STATE.regionId=byId('fRegion').value||''; STATE.agentId=byId('fAgent').value||''; STATE.from=byId('fFrom').value||''; STATE.to=byId('fTo').value||'';
    getJSON('/lms/dashboard/summary?_=1'+qs(),renderSummary); loadPipeline();
    getJSON('/lms/dashboard/state-funnel?_=1'+qs(),renderState);
    getJSON('/lms/dashboard/sla-heatmap?_=1'+qs(),renderHeat);
    getJSON('/lms/dashboard/ageing',renderAgeing);
    setDashPeriod(); }
  ['fAgent','fRegion','fFrom','fTo'].forEach(function(id){ byId(id).addEventListener('change',refresh); });

  // ====================== LEAD RECORD (native sts-mockup layout, real data) ======================
  var STEPS=[['NEW','New'],['ASSIGNED','Assigned'],['CONTACTED','Contacted'],['QUALIFIED','Qualified'],
    ['BEAT_PLANNED','Beat-plan'],['VISITED','Visited'],['ONBOARDED','Onboarded'],['ACTIVE','Active']];
  function fmtDT(s){ if(!s) return '—'; var d=new Date(s); if(isNaN(d)) return esc(s);
    var mo=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    function p(n){ return (n<10?'0':'')+n; }
    return p(d.getDate())+' '+mo[d.getMonth()]+' '+d.getFullYear()+' · '+p(d.getHours())+':'+p(d.getMinutes()); }
  function kvRow(k,v){ return '<div class="k">'+k+'</div><div class="v">'+(v==null||v===''?'—':v)+'</div>'; }
  function trailType(t){ if(t==='TELEPHONIC'||t==='CALL') return 'call'; if(!t) return 'sys'; return ''; }

  function injectRecord(id){ byId('recordHost').innerHTML='<div class="ph">Loading lead #'+esc(id)+'…</div>';
    getJSON('/lms/dashboard/record?leadId='+encodeURIComponent(id),function(d){ if(!d||!d.id){ byId('recordHost').innerHTML='<div class="ph">Lead #'+esc(id)+' not found.</div>'; return; } renderRecord(d); }); }
  function loadRecord(){ var v=(byId('recLookup').value||'').replace(/\D/g,''); if(!v){ toast('Enter a lead #'); return; } injectRecord(v); }
  function loadRecentRecord(){ getJSON('/lms/dashboard/leads?bucketType=ALL'+qs(),function(d){ var leads=(d&&d.leads)?d.leads:[];
    if(leads.length){ byId('recLookup').value=leads[0].id; injectRecord(leads[0].id); }
    else { byId('recordHost').innerHTML='<div class="ph">No leads to show. Create one from the Create Lead tab.</div>'; } }); }

  /** Trail type filter. '' is everything; the rest match LeadActivity.communicationType. */
  var TRAIL_TYPES=[['','All'],['TELEPHONIC','Telephonic'],['VISIT','Visit'],['UPDATE','Update']];
  var TRAIL={ filter:'' };

  /** An entry with no communication type is a stage move or a note — shown as Update. */
  function trailTypeKey(t){ return t && t.type ? t.type : 'UPDATE'; }

  function trailCounts(list){
    var c={};
    list.forEach(function(t){ var k=trailTypeKey(t); c[k]=(c[k]||0)+1; });
    return c;
  }

  function setTrailFilter(type){
    TRAIL.filter=type||'';
    document.querySelectorAll('#trailFilter .trailf').forEach(function(b){
      b.classList.toggle('sel', b.getAttribute('data-trailtype')===TRAIL.filter); });
    renderTrailList();
  }

  function renderTrailList(){
    var host=byId('trailHost'); if(!host || !REC) return;
    var all=REC.trail||[];
    var list=TRAIL.filter?all.filter(function(t){ return trailTypeKey(t)===TRAIL.filter; }):all;
    if(!list.length){
      host.innerHTML='<div class="ph">'+(all.length?'No entries of this type.':'No activity yet.')+'</div>';
      return;
    }
    var h='<div class="trail" id="trailScroll">';
    list.forEach(function(t){
      h+='<div class="tevt '+trailType(t.type)+'"><div class="tdot">&#9679;</div>'+
        '<div class="tt">'+(t.type?esc(t.type):'Update')+'</div>'+
        '<div class="tm">'+esc(t.actor||'System')+' · '+fmtDT(t.when)+(t.scheduled?(' · scheduled '+fmtDT(t.scheduled)):'')+'</div>'+
        (t.body?('<div class="td">'+esc(t.body)+'</div>'):'');
      // The recording of the call this entry came from, so the agent's account of the conversation
      // and the conversation itself sit together instead of in two separate lists.
      if(t.callId){
        h+='<div class="trec"><audio controls preload="none" src="'+CTX+'/lms/recording/'+t.callId+'"></audio>'+
          (t.durationSeconds?('<span class="note">'+t.durationSeconds+'s</span>'):'')+
          (t.archived?'':'<span class="note">archiving…</span>')+'</div>';
      }
      h+='</div>';
    });
    host.innerHTML=h+'</div>';
    capTrail();
  }

  /** Trail entries shown before the list starts scrolling. */
  var TRAIL_VISIBLE=5;

  /**
   * Cap the trail at TRAIL_VISIBLE entries and scroll the rest.
   *
   * Measured from the 6th entry's own offset rather than assumed from a row height — entries vary a
   * lot (a one-line note, a wrapped remark, one carrying an audio player), so any fixed px guess
   * would cut an entry in half on most leads.
   */
  function capTrail(){
    var box=byId('trailScroll'); if(!box) return;
    var items=box.children;
    if(items.length<=TRAIL_VISIBLE){ box.style.maxHeight=''; box.style.overflowY=''; box.classList.remove('scrolls'); return; }
    var cut=items[TRAIL_VISIBLE];
    box.style.maxHeight=Math.round(cut.offsetTop-box.firstElementChild.offsetTop)+'px';
    box.style.overflowY='auto';
    box.classList.add('scrolls');
  }

  function renderRecord(d){
    REC=d; CALL.id=null; TRAIL.filter='';
    // header
    var head='<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">'+
      '<div><div class="crumb">'+(d.lmsCode?('<span class="idpill">'+esc(d.lmsCode)+'</span>'):('Lead #'+d.id))+'</div>'+
      '<h1 class="page" style="margin-top:4px">'+esc(d.name||'—')+(d.outlet?' <span style="font-weight:500;color:#59668a;font-size:18px">· '+esc(d.outlet)+'</span>':'')+'</h1></div>'+
      '<div style="display:flex;gap:8px;align-items:center">'+stagePill(d.stage,d.stageLabel)+
      ' <span class="stage" style="background:#eef1f6;color:#69748c">SLA: '+esc(d.slaState||'NA')+'</span>'+
      (d.assignmentStatus==='HOLD'?' <span class="stage st-ni">HOLD</span>':'')+'</div></div>';
    // stepper
    var idx=(d.stageIndex==null?-1:d.stageIndex);
    // A terminal lead has no stepper to draw, and a whole card repeating what the header pill and
    // the Record card's Current stage already say is just a band of empty space. Omit it.
    var step='';
    if(!d.terminal){
      step='<div class="card" style="padding:16px 22px"><div class="rec-stepper">';
      STEPS.forEach(function(s,i){ var cls=i<idx?'done':(i===idx?'cur':''); var last=(i===STEPS.length-1);
        step+='<div class="rec-step '+cls+'"><div class="dot">'+(i<idx?'&#10003;':(i+1))+'</div><div class="sl">'+esc(s[1])+'</div>'+(last?'':'<div class="bar"></div>')+'</div>'; });
      step+='</div></div>';
    }
    // details
    var details='<div class="card"><h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px">Record'+
      '<button class="btn ghost sm" onclick="openEdit()">&#9998; Edit</button></h2>'+
      '<p class="desc">ID, dates &amp; auto-assignment are system-set and immutable. Everything else is correctable.</p>'+
      '<div class="grid g2" style="gap:20px"><div class="kv">'+
        kvRow('LMS ID', d.lmsCode?('<span class="mono">'+esc(d.lmsCode)+'</span>'):'—')+
        kvRow('Created', fmtDT(d.created)+(d.createdBy?(' · '+esc(d.createdBy)):''))+
        kvRow('Creation path', d.path?('<span class="tag '+(d.path==='B'?'b':'a')+'">'+(d.path==='B'?'B · Field':'A · BGC')+'</span>'):'—')+
        kvRow('Retailer', esc(d.name))+
        kvRow('Business', esc(d.outlet))+
        kvRow('Contact', d.contact?('<span class="mono">'+esc(d.contact)+'</span>'):'—')+
      '</div><div class="kv">'+
        kvRow('Location', esc(d.location))+
        kvRow('Region', esc(d.regionCode))+
        kvRow('Business value', inrShort(d.value))+
        kvRow('Source', esc(d.source))+
        kvRow('Last disposition', d.disposition?esc(d.disposition):'—')+
        kvRow('Owner BM/RSM', esc(d.ownerBm))+
      '</div></div><div class="divider"></div>'+
      '<div class="kv" style="grid-template-columns:130px 1fr 130px 1fr">'+
        kvRow('Working owner', esc(d.owner))+kvRow('Current stage', stagePill(d.stage,d.stageLabel))+
        kvRow('First contact', d.firstContactedAt?fmtDT(d.firstContactedAt):'<span style="color:#e8590c">not yet</span>')+
        kvRow('Unreachable tries', d.unreachableCount==null?'0':d.unreachableCount)+
      '</div></div>';
    // SLA card
    var slaClr=d.slaState==='MET'?'#2f9e44':(d.slaState==='BREACHED'?'#e03131':(d.slaState==='AT_RISK'?'#f08c00':'#69748c'));
    var sla='<div class="card"><h2>First-contact SLA</h2><p class="desc">5-hr commitment from creation (SOP §11).</p>'+
      '<div style="font-size:26px;font-weight:800;color:'+slaClr+'">'+esc(d.slaState||'NA')+'</div>'+
      '<div class="kv" style="margin-top:10px">'+kvRow('Due by', d.firstContactDue?fmtDT(d.firstContactDue):'—')+
      kvRow('First contact', d.firstContactedAt?fmtDT(d.firstContactedAt):'<span style="color:#e8590c">not yet</span>')+'</div></div>';
    // trail
    // Trail card. The list itself is rendered by renderTrailList() so the type filter can redraw it
    // without refetching the record — the whole trail is already in hand.
    var counts=trailCounts(d.trail||[]);
    var trail='<div class="card"><h2 style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">'+
      '<span>Trail <span style="color:#97a1b5;font-weight:500;font-size:12px">· append-only</span></span>'+
      (d.trail&&d.trail.length?('<span class="opts" id="trailFilter">'+
        TRAIL_TYPES.map(function(t){
          var n=counts[t[0]]||0;
          // Offer only the types this lead actually has — a filter that returns nothing is noise.
          if(t[0] && !n) return '';
          return '<button type="button" class="chkopt trailf'+(TRAIL.filter===t[0]?' sel':'')+'"'+
                 ' data-trailtype="'+t[0]+'">'+esc(t[1])+' <span class="note" style="display:inline">'+
                 (t[0]?n:(d.trail.length))+'</span></button>';
        }).join('')+'</span>'):'')+
      '</h2>'+
      '<div id="trailHost"></div>';
    trail+='</div>';

    // ---- Click-to-call (SOP §12). VBC places the call server-side: our own device rings first,
    // then the retailer. A blocked number never gets a button at all — the refusal belongs in
    // front of the agent, not in the response to a dial they already started.
    var call='<div class="card"><h2>Click-to-call</h2>';
    if(d.dnd){ call+='<p class="desc" style="color:#e03131"><b>Do-not-call.</b> '+esc(d.dndReason||'This retailer asked not to be contacted.')+'</p>'; }
    else if(!d.contact){ call+='<p class="desc">No contact number on this lead.</p>'; }
    else { call+='<p class="desc">Bridged call &middot; disposition required on disconnect.</p>'+
      '<button class="btn coral" id="callBtn" onclick="startCall()">&#9742; Call retailer (C2C)</button>'; }
    call+='<div class="note" style="margin-top:10px">A call is only worth what its disposition says — log one on every disconnect.</div></div>';

    // ---- Beat plan. Read-only on purpose: adding a stop belongs to the beat planner, and the
    // gate that matters (an approved geo-pin) is what this card exists to report.
    // The card used to state the geo gate and leave the agent to go and find the Leads screen.
    // The action that clears the gate now lives on it.
    var mapLink=(d.geoLat!=null&&d.geoLng!=null)
      ? ' <a class="btn ghost sm" target="_blank" rel="noopener" href="https://www.google.com/maps?q='+d.geoLat+','+d.geoLng+'">View on map</a>' : '';
    var photoLink=(d.geoPhotoId>0)
      ? ' <a class="btn ghost sm" target="_blank" rel="noopener" href="'+CTX+'/open-attachment?documentId='+d.geoPhotoId+'">Store photo</a>' : '';
    var beat='<div class="card"><h2>Beat plan</h2>'+
      (d.geoApproved
        ? '<p class="desc"><span class="stage st-visited">Geo verified</span> &mdash; this lead can be added to a beat.</p>'
        : '<p class="desc" style="color:#a9720a">Geo-pin not yet approved'+
          (d.geoStatus?(' ('+esc(d.geoStatus.toLowerCase())+')'):'')+
          '. Verify the location before adding this lead to a beat.</p>')+
      '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px">'+
        '<button class="btn ghost sm" onclick="openGeo()">'+(d.geoApproved?'Re-verify location':'Verify manually')+'</button>'+
        mapLink+photoLink+'</div>'+
      '<div class="note">Check-in at the retailer moves the stage to Visited.</div></div>';

    // ---- Advance stage. Forward-only and comment-mandatory, same rules the endpoint enforces.
    var adv='';
    if(!d.terminal){
      var opts='<option value="" selected disabled>Move to&hellip;</option>';
      STEPS.forEach(function(st,i){ if(i>idx) opts+='<option value="'+st[0]+'">'+esc(st[1])+'</option>'; });
      ['NOT_INTERESTED','DROPPED'].forEach(function(t){ opts+='<option value="'+t+'">'+t.replace('_',' ')+'</option>'; });
      adv='<div class="card"><h2>Advance stage</h2><p class="desc">Forward-only. The comment becomes the trail entry.</p>'+
        '<select id="advStage" class="inp" style="width:100%;margin-bottom:8px">'+opts+'</select>'+
        '<input id="advComment" class="inp" style="width:100%;margin-bottom:10px" placeholder="Comment (required)">'+
        '<button class="btn" style="background:#1f2a5e;color:#fff" onclick="advance()">Advance</button></div>';
    } else {
      adv='<div class="card"><h2>Advance stage</h2><p class="desc">'+esc(d.stageLabel)+' is terminal — this lead cannot be moved on.</p></div>';
    }

    byId('recordHost').innerHTML=head+step+
      '<div class="grid g3"><div>'+details+trail+'</div><div>'+sla+call+beat+adv+'</div></div>';
    renderTrailList();
  }

  // ====================== LIVE CALL BOARD ===================================================
  // Polls /lms/dashboard/live-calls. First paint builds the table; subsequent ticks PATCH the
  // volatile cells rather than re-rendering — re-drawing the whole table every 10s fights anyone
  // mid-read and throws away their scroll position. Same approach the RBM board takes.

  var LIVE = { timer:null, built:false, rows:[], failures:0, lastAt:null };
  var LIVE_MS = 10000;

  var LSTAT={'On Call':'oncall','Wrap Up':'wrap','Idle':'idle','Available':'avail','—':'off'};
  function lstat(s){ return '<span class="lstat '+(LSTAT[s]||'off')+'">'+esc(s)+'</span>'; }
  /** hh:mm:ss, like the RBM board's time-in-status. */
  function hms(sec){
    if(sec==null) return '—';
    sec=Math.max(0,Math.floor(sec));
    var h=Math.floor(sec/3600), m=Math.floor((sec%3600)/60), s2=sec%60;
    return (h?('0'+h).slice(-2)+':':'')+('0'+m).slice(-2)+':'+('0'+s2).slice(-2);
  }

  /** Successful refresh: stamp the time, pulse the dot. Time only — the board is always today. */
  function liveBeat(asOf){
    LIVE.failures=0;
    LIVE.lastAt=asOf?new Date(asOf):new Date();
    var dot=byId('liveDot'); if(dot){ dot.classList.remove('stalled','beat');
      void dot.offsetWidth;                  // restart the animation on a repeat refresh
      dot.classList.add('beat'); }
    byId('liveAsOf').textContent='updated '+clockOf(LIVE.lastAt);
  }
  function liveStalled(){
    var dot=byId('liveDot'); if(dot){ dot.classList.remove('beat'); dot.classList.add('stalled'); }
    byId('liveAsOf').textContent=LIVE.lastAt
      ? 'not updating · last '+clockOf(LIVE.lastAt) : 'not updating';
  }
  function clockOf(d){
    if(!d || isNaN(d)) return '—';
    return ('0'+d.getHours()).slice(-2)+':'+('0'+d.getMinutes()).slice(-2)+':'+('0'+d.getSeconds()).slice(-2);
  }

  function startLive(){
    LIVE.failures=0;
    // Default the log window to today; the board above is always "now" so this matches it.
    if(!byId('clFrom').value){
      var t=new Date().toISOString().slice(0,10);
      byId('clFrom').value=t; byId('clTo').value=t;
    }
    loadCallLog(1);
    loadLive();
    stopLive();
    LIVE.timer=setInterval(loadLive, LIVE_MS);
  }
  // Must be cleared on tab change, or every visit leaves another interval polling forever.
  function stopLive(){ if(LIVE.timer){ clearInterval(LIVE.timer); LIVE.timer=null; } }

  function loadLive(){
    getJSON('/lms/dashboard/live-calls', function(d){
      d=d||{}; LIVE.rows=d.rows||[];
      liveBeat(d.asOf);
      byId('liveKpis').innerHTML=
        kpiTile('On call now', fmtInt(d.onCallNow))+
        kpiTile('Calls today', fmtInt(d.calls))+
        kpiTile('Connect rate', (d.connectPct||0)+'%')+
        kpiTile('Talk time', (d.talkMinutes||0)+' min')+
        kpiTile('Agents', fmtInt(d.agents));
      if(!LIVE.built){ buildLiveTable(); LIVE.built=true; } else { patchLiveTable(); }
    }, function(){
      // A dropped poll keeps the last good picture, but must not keep claiming to be live.
      LIVE.failures++;
      if(LIVE.failures>=2) liveStalled();
    });
  }

  function buildLiveTable(){
    if(!LIVE.rows.length){
      byId('liveBody').innerHTML='<tr><td colspan="11"><div class="ph">No agents mapped to the dialer yet.</div></td></tr>';
      return;
    }
    byId('liveBody').innerHTML=LIVE.rows.map(function(r){
      return '<tr class="clickrow" data-liveagent="'+r.authId+'">'+
        '<td class="nowrap"><b>'+esc(r.agent)+'</b>'+(r.extension?'<br><span style="color:#97a1b5;font-size:11px">ext '+esc(r.extension)+'</span>':'')+'</td>'+
        '<td class="nowrap" data-live="status" data-authid="'+r.authId+'">'+liveStatusCell(r)+'</td>'+
        '<td class="nowrap mono" data-live="since" data-authid="'+r.authId+'">'+hms(r.sinceSeconds)+'</td>'+
        '<td class="num" data-live="calls" data-authid="'+r.authId+'">'+fmtInt(r.calls)+'</td>'+
        '<td class="num" data-live="connected" data-authid="'+r.authId+'">'+fmtInt(r.connected)+'</td>'+
        '<td class="num" data-live="connectPct" data-authid="'+r.authId+'">'+pctCell(r.connectPct)+'</td>'+
        '<td class="num" data-live="talk" data-authid="'+r.authId+'">'+secs(r.talkSeconds)+'</td>'+
        '<td class="num" data-live="longest" data-authid="'+r.authId+'">'+secs(r.longestSeconds)+'</td>'+
        '<td class="num">'+fmtInt(r.assigned)+'</td>'+
        '<td class="num" data-live="touched" data-authid="'+r.authId+'">'+fmtInt(r.touched)+'</td>'+
        '<td class="num" data-live="sla" data-authid="'+r.authId+'">'+slaBreachCell(r.slaBreached)+'</td></tr>';
    }).join('');
  }

  function liveStatusCell(r){
    // A stale row means the agent closed the tab mid-call; say so rather than silently showing Idle.
    return lstat(r.status)+(r.staleCall?'<span class="lstale" title="A call was never closed — the agent likely closed the tab mid-call">unclosed call</span>':'');
  }
  function slaBreachCell(n){
    n=Number(n)||0;
    return n>0?'<span style="font-weight:700;color:#e03131">'+fmtInt(n)+'</span>':'0';
  }

  function patchLiveTable(){
    // A new agent provisioned mid-session changes the row set — rebuild rather than patch.
    if(LIVE.rows.length!==document.querySelectorAll('#liveBody tr[data-liveagent]').length){
      buildLiveTable(); return;
    }
    LIVE.rows.forEach(function(r){
      set(r.authId,'status',liveStatusCell(r));
      set(r.authId,'since',hms(r.sinceSeconds));
      set(r.authId,'calls',fmtInt(r.calls));
      set(r.authId,'connected',fmtInt(r.connected));
      set(r.authId,'connectPct',pctCell(r.connectPct));
      set(r.authId,'talk',secs(r.talkSeconds));
      set(r.authId,'longest',secs(r.longestSeconds));
      set(r.authId,'touched',fmtInt(r.touched));
      set(r.authId,'sla',slaBreachCell(r.slaBreached));
    });
    function set(authId,key,html){
      var el=document.querySelector('#liveBody td[data-live="'+key+'"][data-authid="'+authId+'"]');
      if(el && el.innerHTML!==html) el.innerHTML=html;
    }
  }

  function exportLive(){
    if(!LIVE.rows.length){ toast('Nothing to export'); return; }
    var cols=[['agent','Agent'],['extension','Extension'],['status','Status'],['sinceSeconds','Seconds in status'],
              ['calls','Calls'],['connected','Connected'],['connectPct','Connect %'],['talkSeconds','Talk seconds'],
              ['longestSeconds','Longest call seconds'],['assigned','Leads assigned'],['touched','Touched today'],
              ['dispositioned','Dispositioned today'],['slaBreached','SLA breached']];
    var csv=[cols.map(function(c){ return '"'+c[1]+'"'; }).join(',')];
    LIVE.rows.forEach(function(r){
      csv.push(cols.map(function(c){ var v=r[c[0]]; if(v==null) v='';
        return '"'+String(v).replace(/"/g,'""')+'"'; }).join(','));
    });
    var blob=new Blob([""+csv.join('\r\n')],{type:'text/csv;charset=utf-8;'});
    var a=document.createElement('a');
    a.href=URL.createObjectURL(blob);
    a.download='lms-live-calls-'+new Date().toISOString().slice(0,10)+'.csv';
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    URL.revokeObjectURL(a.href);
    toast('Exported '+LIVE.rows.length+' agent(s)',1);
  }

  // ---- Call log -----------------------------------------------------------------------------
  var CL = { page:1, pageSize:50, pages:1, total:0, rows:[] };

  var CLSTAT={COMPLETED:'oncall',ANSWERED:'oncall',RINGING:'avail',INITIATED:'avail',
              UNANSWERED:'idle',BUSY:'idle',REJECTED:'off',FAILED:'off',CANCELLED:'off'};
  function clStatus(s){ return '<span class="lstat '+(CLSTAT[s]||'off')+'">'+esc((s||'').replace(/_/g,' '))+'</span>'; }

  function clDates(){
    var f=byId('clFrom').value, t=byId('clTo').value, q='?page='+CL.page+'&pageSize='+CL.pageSize;
    if(f) q+='&from='+encodeURIComponent(f);
    if(t) q+='&to='+encodeURIComponent(t);
    return q;
  }

  function loadCallLog(page){
    if(page) CL.page=page;
    byId('clBody').innerHTML='<tr><td colspan="9"><div class="ph">Loading&hellip;</div></td></tr>';
    getJSON('/lms/dashboard/call-log'+clDates(), function(d){
      d=d||{}; CL.rows=d.rows||[]; CL.total=d.total||0; CL.pages=d.pages||1; CL.page=d.page||1;
      if(!CL.rows.length){
        byId('clBody').innerHTML='<tr><td colspan="9"><div class="ph">No calls in this window.</div></td></tr>';
      } else {
        byId('clBody').innerHTML=CL.rows.map(function(r){
          return '<tr class="clickrow"'+(r.leadId?' data-leadid="'+r.leadId+'"':'')+'>'+
            '<td class="nowrap">'+fmtDT(r.startedAt)+'</td>'+
            '<td class="nowrap" title="'+esc(r.agent||'')+'">'+esc(r.agent||'—')+
              (r.extension?'<br><span style="color:#97a1b5;font-size:11px">ext '+esc(r.extension)+'</span>':'')+'</td>'+
            '<td><b>'+esc(r.retailer||('#'+(r.leadId||'')))+'</b>'+
              (r.lmsCode?'<br><span class="mono" style="color:#97a1b5;font-size:11px">'+esc(r.lmsCode)+'</span>':'')+'</td>'+
            '<td class="nowrap mono">'+esc(r.toNumber||'—')+'</td>'+
            '<td class="nowrap">'+clStatus(r.status)+'</td>'+
            // A dash, not 0s: never answered is not the same as answered instantly.
            '<td class="num nowrap">'+(r.ringSeconds==null?'—':secs(r.ringSeconds))+'</td>'+
            '<td class="num nowrap">'+(r.talkSeconds?secs(r.talkSeconds):'—')+'</td>'+
            '<td class="nowrap">'+clRec(r)+'</td>'+
            '<td>'+esc(r.disposition||'—')+'</td></tr>';
        }).join('');
      }
      var first=(CL.page-1)*CL.pageSize+(CL.rows.length?1:0), last=(CL.page-1)*CL.pageSize+CL.rows.length;
      byId('clCount').textContent=CL.total?('Showing '+first+'–'+last+' of '+fmtInt(CL.total)+' calls'):'';
      byId('clPageLbl').textContent='Page '+CL.page+' / '+Math.max(CL.pages,1);
      byId('clPrev').disabled=(CL.page<=1);
      byId('clNext').disabled=(CL.page>=CL.pages);
    });
  }

  function clRec(r){
    if(r.recording==='none') return '<span style="color:#97a1b5">—</span>';
    // Playback goes through the gated endpoint, never a vendor URL: it enforces the access matrix
    // and logs the open (SOP §15).
    return '<audio controls preload="none" style="height:28px;max-width:150px" src="'+CTX+'/lms/recording/'+r.callId+'"></audio>'+
      (r.recording==='vendor'?'<span class="note" style="display:inline;margin-left:4px">archiving…</span>':'');
  }

  function clPage(step){
    var n=CL.page+step;
    if(n<1||n>CL.pages) return;
    loadCallLog(n);
  }

  function exportCallLog(){
    if(!CL.rows.length){ toast('Nothing to export'); return; }
    var cols=[['startedAt','Started'],['answeredAt','Answered'],['endedAt','Ended'],['agent','Agent'],
              ['extension','Extension'],['lmsCode','LMS ID'],['retailer','Retailer'],['outlet','Business'],
              ['toNumber','Number'],['direction','Direction'],['status','Status'],
              ['ringSeconds','Ring seconds'],['talkSeconds','Talk seconds'],['recording','Recording'],
              ['disposition','Disposition']];
    var csv=[cols.map(function(c){ return '"'+c[1]+'"'; }).join(',')];
    CL.rows.forEach(function(r){
      csv.push(cols.map(function(c){ var v=r[c[0]]; if(v==null) v='';
        return '"'+String(v).replace(/"/g,'""')+'"'; }).join(','));
    });
    var blob=new Blob([""+csv.join('\r\n')],{type:'text/csv;charset=utf-8;'});
    var a=document.createElement('a');
    a.href=URL.createObjectURL(blob);
    a.download='lms-call-log-'+(byId('clFrom').value||'all')+'.csv';
    document.body.appendChild(a); a.click(); document.body.removeChild(a);
    URL.revokeObjectURL(a.href);
    toast('Exported '+CL.rows.length+' call(s)',1);
  }

  // ====================== STANDARD REPORT SUITE (SOP §18.2) =================================
  // Each catalogue row opens the real report in the drawer rather than a sentence describing it.
  // The four that were already "Live" reuse data this page has loaded; BGC Daily and Audit Hygiene
  // call their own endpoints. RBM Servicing stays honest about needing order data it cannot reach.

  function secs(n){ n=Number(n)||0; var m=Math.floor(n/60); return m? (m+'m '+(n%60)+'s') : (n+'s'); }
  function pctCell(v){ var c=v>=80?'#2f9e44':(v>=50?'#f08c00':'#e03131');
    return '<span style="font-weight:700;color:'+c+'">'+v+'%</span>'; }
  function tbl(head, rows){
    if(!rows.length) return '<div class="ph">Nothing in the selected period.</div>';
    return '<table><thead><tr>'+head.map(function(h){
        return '<th'+(h.n?' class="num"':'')+'>'+esc(h.t)+'</th>'; }).join('')+'</tr></thead><tbody>'+
      rows.join('')+'</tbody></table>';
  }

  function openReport(name){
    openDrawer('Report suite', name, 'SOP §18.2', '<div class="ph">Loading…</div>');
    if(name==='BGC Daily')          return reportBgcDaily();
    if(name==='Audit Hygiene')      return reportAuditHygiene();
    if(name==='State Funnel')       return reportStateFunnel();
    if(name==='SLA Compliance')     return reportSla();
    if(name==='Ageing')             return reportAgeing();
    if(name==='Management Roll-up') return reportRollup();
    // RBM Servicing: repeat-order rate, complaint rate and resolution TAT all live in order and
    // ticket data the lead record does not reach. Say so rather than showing an empty table.
    openDrawer('Report suite', name, 'SOP §18.2',
      '<div class="card"><div class="dnote">Repeat-order rate, complaint rate and resolution TAT need order '+
      'and ticket data, which the LMS does not hold. Post-sales (SOP §14) is not built yet — the lead '+
      'record stops at ONBOARDED.</div></div>');
  }

  function reportBgcDaily(){
    getJSON('/lms/dashboard/bgc-daily'+qsDates(),function(d){
      d=d||{};
      var head=[{t:'Day'},{t:'Agent'},{t:'Calls',n:1},{t:'Connected',n:1},{t:'Connect%',n:1},{t:'Avg talk',n:1},{t:'Longest',n:1}];
      var rows=(d.rows||[]).map(function(r){
        return '<tr><td class="nowrap">'+esc(r.day||'—')+'</td><td>'+esc(r.agent)+'</td>'+
          '<td class="num">'+fmtInt(r.calls)+'</td><td class="num">'+fmtInt(r.connected)+'</td>'+
          '<td class="num">'+pctCell(r.connectPct)+'</td><td class="num">'+secs(r.avgTalkSeconds)+'</td>'+
          '<td class="num">'+secs(r.longestSeconds)+'</td></tr>'; });
      var kpi='<div class="kpis" style="margin-bottom:12px">'+
        kpiTile('Calls placed', fmtInt(d.calls))+kpiTile('Connected', fmtInt(d.connected))+
        kpiTile('Connect rate', (d.connectPct||0)+'%')+kpiTile('Talk time', (d.talkMinutes||0)+' min')+'</div>';
      openDrawer('Report suite','BGC Daily','Real telephony from the call log',
        kpi+'<div class="card">'+tbl(head,rows)+
        '<div class="note">Connect rate = answered ÷ placed. Average talk time counts connected calls only — '+
        'averaging over every dial would make a day of unanswered ringing look like short conversations.</div></div>');
    });
  }

  function reportAuditHygiene(){
    getJSON('/lms/dashboard/audit-hygiene'+qsDates(),function(d){
      d=d||{};
      var kpi='<div class="kpis" style="margin-bottom:12px">'+
        kpiTile('Missing dispositions', fmtInt(d.missingDisposition))+
        kpiTile('SLA breached', fmtInt(d.slaBreached))+
        kpiTile('HOLD (no owner)', fmtInt(d.hold))+
        kpiTile('DND register', fmtInt(d.dndRegister))+'</div>';
      var head=[{t:'When'},{t:'Lead'},{t:'Number'},{t:'Call'}];
      var rows=(d.dndBreaches||[]).map(function(b){
        return '<tr class="clickrow" data-leadid="'+b.leadId+'"><td class="nowrap">'+fmtDT(b.when)+'</td>'+
          '<td>#'+b.leadId+'</td><td class="mono">'+esc(b.mobile||'—')+'</td><td>#'+b.callId+'</td></tr>'; });
      openDrawer('Report suite','Audit Hygiene','SOP §17',
        kpi+
        '<div class="card"><h2>DND breaches</h2><p class="desc">Calls placed to a number already on the '+
        'do-not-call register. The pre-check blocks these, so a row here is a bypass worth asking about.</p>'+
        tbl(head,rows)+'</div>'+
        '<div class="card"><h2>Recording access</h2><div class="kv">'+
        kvRow('Opens granted', fmtInt(d.recordingOpens))+
        kvRow('Opens denied', fmtInt(d.recordingDenied))+'</div>'+
        '<div class="note">Every open and every refusal is logged against the viewer (SOP §15). '+
        'Repeated denials are what a scope probe looks like.</div></div>');
    });
  }

  function reportStateFunnel(){
    var d=DATA.state||SEED.state||{}; var rows=(d.rows||[]).map(function(r){
      return '<tr><td><b>'+esc(r.regionName||r.regionCode||'—')+'</b></td><td class="num">'+fmtInt(r.newCount)+'</td>'+
        '<td class="num">'+fmtInt(r.contacted)+'</td><td class="num">'+fmtInt(r.qualified)+'</td>'+
        '<td class="num">'+fmtInt(r.beatPlanned)+'</td><td class="num">'+fmtInt(r.visited)+'</td><td class="num">'+fmtInt(r.onboarded)+'</td>'+
        '<td class="num">'+pctCell(r.convPct||0)+'</td><td class="num">'+pctCell(r.slaPct||0)+'</td></tr>'; });
    openDrawer('Report suite','State Funnel','NEW → ONBOARDED by region','<div class="card">'+
      tbl([{t:'Region'},{t:'Leads',n:1},{t:'Contacted',n:1},{t:'Qualified',n:1},{t:'Beat',n:1},{t:'Visited',n:1},{t:'Onboarded',n:1},{t:'Conv%',n:1},{t:'SLA%',n:1}],rows)+'</div>');
  }

  function reportSla(){
    var d=DATA.heat||SEED.heat||{}; var rows=(d.bms||[]).map(function(r){
      var cells=(r.cells||[]).map(function(c){ return '<td class="num">'+(c.pct==null?'—':pctCell(c.pct))+'</td>'; }).join('');
      return '<tr><td><b>'+esc(r.bmName||'—')+'</b></td>'+cells+'</tr>'; });
    var head=[{t:'Owner'}].concat((d.weeks||[]).map(function(c){ return {t:c,n:1}; }));
    openDrawer('Report suite','SLA Compliance','% first contact within 5 hrs','<div class="card">'+
      tbl(head,rows)+'<div class="note">Blank cells mean no leads in that week — not 0% compliance.</div></div>');
  }

  function reportAgeing(){
    var d=DATA.ageing||SEED.ageing||{}; var rows=(d.rows||[]).map(function(r){
      return '<tr><td><b>'+esc(r.label||r.stage||'—')+'</b></td>'+
        '<td class="num">'+fmtInt(r.count)+'</td><td class="num">'+fmtInt(r.days)+'</td></tr>'; });
    openDrawer('Report suite','Ageing','Open leads with no action for '+(d.days||7)+'+ days','<div class="card">'+
      tbl([{t:'Stage'},{t:'Leads',n:1},{t:'Days idle',n:1}],rows)+
      '<div class="note">Total stuck: '+fmtInt(d.total||0)+'</div></div>');
  }

  function reportRollup(){
    var s=DATA.summary||SEED.summary||{};
    var kpi='<div class="kpis" style="margin-bottom:12px">'+
      kpiTile('Leads in period', fmtInt(s.total))+
      kpiTile('Onboarded', fmtInt(onboardedCount()))+
      kpiTile('Conversion', (s.conversionPct||0)+'%')+
      kpiTile('Onboarded value', inrShort(s.onboardedValue))+'</div>';
    var rows=(s.funnel||[]).map(function(f){
      return '<tr><td><b>'+esc(f.label||f.stage)+'</b></td><td class="num">'+fmtInt(f.count)+'</td>'+
        '<td class="num">'+(f.pct==null?'—':pctCell(f.pct))+'</td></tr>'; });
    openDrawer('Report suite','Management Roll-up','Cross-region',
      kpi+'<div class="card">'+tbl([{t:'Stage'},{t:'Leads',n:1},{t:'% of top',n:1}],rows)+'</div>');
  }

  function openAgentCalls(authId){
    var r=null; LIVE.rows.forEach(function(x){ if(x.authId===authId) r=x; });
    if(!r) return;
    openDrawer('Live floor', r.agent, r.status+(r.extension?(' · ext '+r.extension):''),
      '<div class="card"><div class="kv">'+
        kvRow('Status', lstat(r.status))+
        kvRow('In status', hms(r.sinceSeconds))+
        kvRow('Calls today', fmtInt(r.calls)+' · '+fmtInt(r.connected)+' connected ('+(r.connectPct||0)+'%)')+
        kvRow('Talk time', secs(r.talkSeconds)+' · longest '+secs(r.longestSeconds))+
        kvRow('Last call', r.lastCallAt?fmtDT(r.lastCallAt):'—')+
        kvRow('Leads assigned', fmtInt(r.assigned))+
        kvRow('Touched today', fmtInt(r.touched)+' · '+fmtInt(r.dispositioned)+' dispositioned')+
        kvRow('SLA breached', slaBreachCell(r.slaBreached))+
      '</div>'+
      (r.liveLeadId?('<div class="note">On a call now &mdash; <a href="#" data-leadid="'+r.liveLeadId+'">open lead #'+r.liveLeadId+'</a></div>'):'')+
      (r.staleCall?'<div class="note" style="color:#e03131">An earlier call was never closed. Only the browser poll ends a VBC call, so a tab closed mid-call leaves the row open.</div>':'')+
      '</div>');
  }

  function kpiTile(label,val){
    return '<div class="kpi"><div class="top"><div class="label">'+esc(label)+'</div></div>'+
           '<div class="val">'+val+'</div></div>';
  }
  function qsDates(){ var q='?'; if(STATE.from)q+='from='+encodeURIComponent(STATE.from)+'&';
    if(STATE.to)q+='to='+encodeURIComponent(STATE.to); return q; }

  // ---- Export (SOP §18.1) -------------------------------------------------------------------
  // Exports what is on screen — the current filters, search and sort — rather than everything,
  // because an export that ignores the filters is a different report than the one being looked at.
  function exportPipeline(){
    var p='/lms/dashboard/pipeline?page=1&pageSize=500&sort='+encodeURIComponent(PIPE.sort)+
          '&dir='+encodeURIComponent(PIPE.dir);
    if(PIPE.q){ p+='&q='+encodeURIComponent(PIPE.q)+scopeQs(); }
    else { p+=qs(); }
    toast('Preparing export…');
    getJSON(p,function(d){
      var rows=(d&&d.rows)?d.rows:[];
      if(!rows.length){ toast('Nothing to export'); return; }
      var cols=[['lmsCode','LMS ID'],['name','Retailer'],['outlet','Business'],['path','Path'],
                ['stageLabel','Stage'],['owner','Owner'],['city','City'],['createdBy','Created by'],
                ['slaState','SLA'],['value','Business value (lakh)']];
      var csv=[cols.map(function(c){ return '"'+c[1]+'"'; }).join(',')];
      rows.forEach(function(r){
        csv.push(cols.map(function(c){
          var v=r[c[0]]; if(v==null) v='';
          // Quote everything and double embedded quotes: names here contain commas routinely.
          return '"'+String(v).replace(/"/g,'""')+'"'; }).join(','));
      });
      var blob=new Blob([""+csv.join('\r\n')],{type:'text/csv;charset=utf-8;'});
      var a=document.createElement('a');
      a.href=URL.createObjectURL(blob);
      a.download='lms-pipeline-'+(STATE.from||'all')+'-to-'+(STATE.to||'now')+'.csv';
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      URL.revokeObjectURL(a.href);
      toast('Exported '+rows.length+' lead(s)',1);
    });
  }

  // ====================== RECORD ACTIONS (edit · call · disposition · stage) =================
  // Every control here drives the SAME endpoints the in-app record uses, so the two screens cannot
  // drift into disagreeing about what a disposition or a stage move means.

  var REC = null;                 // the record currently rendered, for the action panels
  var CALL = { id:null, leadId:null, btn:null, poll:null, tick:null, startedAt:0, checklistShown:false };

  /** POST form-encoded (advanceStage / dialer take @RequestParam, not a JSON body). */
  function postForm(path, params, cb, onErr){
    var body = Object.keys(params).map(function(k){
      return encodeURIComponent(k)+'='+encodeURIComponent(params[k]==null?'':params[k]); }).join('&');
    fetch(CTX+path,{method:'POST',credentials:'same-origin',
      headers:{'Content-Type':'application/x-www-form-urlencoded','X-Requested-With':'XMLHttpRequest'},body:body})
      .then(function(r){ return r.text(); })
      .then(function(t){ var d=null; try{ d=JSON.parse(t); }catch(e){}
        var res=(d&&d.response!==undefined)?d.response:d; cb(res); })
      .catch(function(e){ console.error('LMS post failed',path,e);
        if(typeof onErr==='function') onErr(e); else toast('Request failed'); });
  }

  /** POST JSON (disposition / updateLead take @RequestBody). */
  function postJSON(path, payload, cb, onErr){
    fetch(CTX+path,{method:'POST',credentials:'same-origin',
      headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},body:JSON.stringify(payload)})
      .then(function(r){ return r.text(); })
      .then(function(t){ var d=null; try{ d=JSON.parse(t); }catch(e){}
        var res=(d&&d.response!==undefined)?d.response:d; cb(res); })
      .catch(function(e){ console.error('LMS post failed',path,e);
        if(typeof onErr==='function') onErr(e); else toast('Request failed'); });
  }

  /** A refusal comes back as a bare string under `response`; success is an object. */
  function refusal(res){ return (typeof res==='string' && res) ? res : null; }

  function reloadRecord(){ if(REC) injectRecord(REC.id); }

  // ---- stage --------------------------------------------------------------------------------
  function advance(){
    var to=byId('advStage').value, c=(byId('advComment').value||'').trim();
    if(!to){ toast('Choose a stage'); return; }
    if(!c){ toast('A comment is required'); return; }
    postForm('/lms/advanceStage',{leadId:REC.id,toStage:to,comment:c},function(res){
      var why=refusal(res); if(why){ toast(why); return; }
      toast('Stage advanced to '+to.replace('_',' '),1); reloadRecord(); refresh();
    });
  }

  // ---- edit ---------------------------------------------------------------------------------
  // EDIT.lead is the record being edited. It is NOT always REC: the pipeline can edit any row while
  // a different lead (or none) is open on the record tab, and binding the save to REC would have
  // written one lead's form over another lead's row.
  var EDIT = { lead:null };

  /** Edit straight from a list row — fetch that lead, then open the same form. */
  function editLeadById(leadId){
    if(!leadId) return;
    getJSON('/lms/dashboard/record?leadId='+leadId, function(d){
      if(!d || !d.id){ toast('Could not load lead #'+leadId); return; }
      openEditFor(d);
    }, function(){ toast('Could not load lead #'+leadId); });
  }

  function openEdit(){ if(REC) openEditFor(REC); }

  function openEditFor(rec){
    if(!rec) return;
    EDIT.lead=rec;
    var REC=rec;                       // shadow, so the markup below reads the target record
    var regionOpts='<option value="">&mdash; Not set &mdash;</option>';
    // Same region list the Create tab renders, so the two forms cannot offer different regions.
    byId('cRegion').querySelectorAll('option').forEach(function(o){
      if(!o.value) return;
      regionOpts+='<option value="'+esc(o.value)+'"'+(String(REC.regionId)===String(o.value)?' selected':'')+'>'+esc(o.textContent)+'</option>';
    });
    byId('editBody').innerHTML=
      '<div class="kv" style="margin-bottom:14px">'+
        kvRow('LMS ID','<span class="mono">'+esc(REC.lmsCode||('#'+REC.id))+'</span> <span class="note" style="display:inline">locked</span>')+
        kvRow('Created', fmtDT(REC.created)+' <span class="note" style="display:inline">locked</span>')+
      '</div>'+
      '<div class="grid g2" style="gap:12px">'+
        fld('eName','Retailer name (required)',REC.name)+
        fld('eBusiness','Business name',REC.outlet)+
        fld('eContact','Contact number (required)',REC.contact)+
        fld('eValue','Business value (&#8377; lakh / month)',(REC.value>0?Math.round(toLakh(REC.value)*10)/10:''))+
      '</div>'+
      fld('eAddress','Address',REC.address)+
      '<div class="grid g2" style="gap:12px">'+fld('eCity','City',REC.city)+fld('eState','State',REC.state)+'</div>'+
      '<label class="lbl">Region</label><select id="eRegion" class="inp" style="width:100%">'+regionOpts+'</select>'+
      '<div class="note">Changing the region re-runs auto-assignment. A lead already mapped to a named owner keeps that owner.</div>';
    byId('editModal').classList.remove('hide');
  }
  function fld(id,label,val){
    return '<div><label class="lbl">'+label+'</label><input id="'+id+'" class="inp" style="width:100%" value="'+esc(val==null?'':val)+'"></div>';
  }
  function closeEdit(){ byId('editModal').classList.add('hide'); }
  function saveEdit(){
    var target=EDIT.lead;
    if(!target){ toast('Nothing to edit'); return; }
    var name=(byId('eName').value||'').trim();
    if(!name){ toast('Retailer name is required'); return; }
    var mob=(byId('eContact').value||'').replace(/\D/g,'');
    if(mob.length<10){ toast('A valid 10-digit contact number is required'); return; }
    var v=parseFloat(byId('eValue').value), r=byId('eRegion').value;
    postJSON('/lms/updateLead',{leadId:target.id,retailerName:name,businessName:byId('eBusiness').value,
      mobile:mob,address:byId('eAddress').value,city:byId('eCity').value,state:byId('eState').value,
      regionId:r?parseInt(r,10):null,potential:isNaN(v)?null:v},function(res){
        var why=refusal(res); if(why){ toast(why); return; }
        closeEdit();
        toast('Record updated · '+(res&&res.changes||0)+' change(s) logged',1);
        // Refresh whichever views are showing this lead.
        if(REC && REC.id===target.id) reloadRecord();
        if(!byId('cmd').classList.contains('hide')) loadPipeline();
      });
  }

  // ---- call ---------------------------------------------------------------------------------
  // One flow for every entry point: the lead record's Call button and the phone icon on a pipeline
  // row both come through dialLead(). The bar is global so a call started from the pipeline still
  // has somewhere to report progress, and switching tabs mid-call does not hide the hang-up button.
  function callErr(msg){ var e=byId('gCallErr'); if(!e) return; e.textContent=msg; e.classList.remove('hide'); }
  function callState(t){ var e=byId('gCallState'); if(e) e.textContent=t; }
  function showBar(who){
    byId('gCallWho').textContent=who||'Calling…';
    byId('gCallErr').classList.add('hide');
    byId('gCallTimer').textContent='00:00';
    byId('gCallBar').classList.remove('hide');
  }
  function hideBar(){ byId('gCallBar').classList.add('hide'); }

  function startCall(){ if(REC) dialLead(REC.id, REC.name, byId('callBtn')); }

  function dialLead(leadId, label, btn){
    if(!leadId) return;
    // One call at a time: the dialer rings the agent's own device, so a second dial would collide.
    if(CALL.id){ toast('Already on a call — hang up first'); return; }
    if(btn) btn.disabled=true;
    // Pre-check server-side: DND and the 09:00-21:00 calling window. A check that only lives in
    // the browser is not a check, which is why this endpoint exists at all.
    postForm('/lms/dialer/precheck',{leadId:leadId},function(res){
      var why=refusal(res);
      if(why || !res || res.ok!==true){ if(btn) btn.disabled=false; toast(why||(res&&res.reason)||'Cannot place the call'); return; }
      showBar(label||('Lead #'+leadId)); callState('Ringing your device…');
      postForm('/lms/dialer/dial',{leadId:leadId},function(r2){
        var w2=refusal(r2);
        if(w2 || !r2 || r2.ok!==true){ if(btn) btn.disabled=false; hideBar();
          toast(w2||'Could not place the call'); return; }
        CALL.id=r2.leadCallId;
        CALL.checklistShown=false;
        // The disposition belongs to the lead that was DIALLED, which is not necessarily the record
        // currently open — the pipeline can start a call while another lead is on screen.
        CALL.leadId=leadId;
        CALL.btn=btn||null;
        CALL.startedAt=Date.now();
        CALL.tick=setInterval(function(){ var s=Math.floor((Date.now()-CALL.startedAt)/1000);
          byId('gCallTimer').textContent=('0'+Math.floor(s/60)).slice(-2)+':'+('0'+(s%60)).slice(-2); },1000);
        // click2dial has no event webhook, so the browser has to ask.
        CALL.poll=setInterval(pollCall,3000);
      });
    });
  }
  function pollCall(){
    if(!CALL.id) return;
    getJSON('/lms/dialer/state?leadCallId='+CALL.id,function(st){
      if(!st) return;
      if(st.status) callState(String(st.status).replace(/_/g,' ').toLowerCase());
      // Connected, not merely placed. The poll repeats every 3s while answered, so the latch stops
      // the checklist reopening over the agent every tick.
      if(st.answered && !CALL.checklistShown){
        CALL.checklistShown=true;
        maybeOpenChecklist(CALL.leadId, CALL.id);
      }
      if(st.terminal){ stopCall(); callState('Call ended'); openDisp(); }
    },function(){ /* a dropped poll is not a dropped call — keep waiting */ });
  }
  function stopCall(){ if(CALL.poll) clearInterval(CALL.poll); if(CALL.tick) clearInterval(CALL.tick);
    CALL.poll=CALL.tick=null;
    if(CALL.btn) CALL.btn.disabled=false;
    var b=byId('callBtn'); if(b) b.disabled=false; }
  function endCall(){
    if(!CALL.id){ stopCall(); return; }
    postForm('/lms/dialer/hangup',{leadCallId:CALL.id},function(){ stopCall(); callState('Call ended'); openDisp(); });
  }

  // ---- assign a lead to a sales person --------------------------------------------------------
  var ASG = { leadId:null, people:[], tiers:[], tier:'', regionId:null };

  function openAssign(leadId, name, currentOwner, regionId){
    ASG.leadId=leadId; ASG.tier=''; ASG.regionId=regionId||null;
    byId('asgWho').innerHTML='<b>'+esc(name||('Lead #'+leadId))+'</b>'+
      (currentOwner?(' &middot; currently '+esc(currentOwner)):' &middot; unassigned');
    byId('asgSearch').value='';
    byId('asgList').innerHTML='<div class="ph">Loading…</div>';
    byId('asgModal').classList.remove('hide');
    getJSON('/lms/salespeople'+(regionId?('?regionId='+encodeURIComponent(regionId)):''), function(d){
      d=d||{}; ASG.people=d.people||[]; ASG.tiers=d.tiers||[];
      byId('asgTiers').innerHTML=['<button type="button" class="chkopt sel" data-tier="">All</button>']
        .concat(ASG.tiers.map(function(t){
          return '<button type="button" class="chkopt" data-tier="'+t+'">'+t+'</button>'; })).join('');
      renderAssignList();
    }, function(){ byId('asgList').innerHTML='<div class="ph">Could not load the sales list.</div>'; });
  }
  function closeAssign(){ byId('asgModal').classList.add('hide'); }

  function renderAssignList(){
    var q=(byId('asgSearch').value||'').trim().toLowerCase();
    var list=ASG.people.filter(function(p){
      if(ASG.tier && p.tier!==ASG.tier) return false;
      if(!q) return true;
      return (p.name||'').toLowerCase().indexOf(q)>=0 || (p.tier||'').toLowerCase().indexOf(q)>=0
          || (p.regions||[]).join(' ').toLowerCase().indexOf(q)>=0;
    });
    // Whoever covers this lead's region first — the likely right answer without forcing it.
    list.sort(function(a,b){
      if(a.coversRegion!==b.coversRegion) return a.coversRegion?-1:1;
      if(a.tier!==b.tier) return a.tier<b.tier?-1:1;
      return (a.name||'').localeCompare(b.name||'');
    });
    if(!list.length){ byId('asgList').innerHTML='<div class="ph">Nobody matches.</div>'; return; }
    byId('asgList').innerHTML=list.map(function(p){
      return '<div class="asgrow'+(p.coversRegion?' covers':'')+'" data-assignto="'+p.authId+'">'+
        '<span class="tierpill">'+esc(p.tier)+'</span>'+
        '<span class="nm">'+esc(p.name)+'</span>'+
        '<span class="rg">'+(p.coversRegion?'covers this region · ':'')+esc((p.regions||[]).join(', ')||'no region')+'</span>'+
      '</div>'; }).join('');
  }

  function assignTo(authId){
    if(!ASG.leadId) return;
    postForm('/lms/assignLead',{leadId:ASG.leadId, authId:authId}, function(res){
      var why=refusal(res); if(why){ toast(why); return; }
      closeAssign();
      toast('Assigned to '+(res&&res.owner||'owner')+' ('+(res&&res.tier||'')+')',1);
      if(!byId('cmd').classList.contains('hide')) loadPipeline();
      if(REC && REC.id===ASG.leadId) reloadRecord();
      refresh();
    });
  }

  // ---- region owner (Auto-Assignment tab): add or change the BM/RSM behind a region -----------
  var RGN={ regionId:null, label:'', current:'', people:[] };
  function openRegionOwner(regionId,label,current){
    RGN.regionId=regionId; RGN.label=label; RGN.current=current||'';
    byId('rgnWho').innerHTML='<b>'+esc(label)+'</b> &middot; '+(current?('currently '+esc(current)):'vacant (HOLD)');
    byId('rgnSearch').value=''; byId('rgnList').innerHTML='<div class="ph">Loading…</div>';
    byId('rgnModal').classList.remove('hide');
    getJSON('/lms/salespeople?regionId='+encodeURIComponent(regionId), function(d){
      RGN.people=(d&&d.people)||[]; renderRegionOwnerList();
    }, function(){ byId('rgnList').innerHTML='<div class="ph">Could not load the sales list.</div>'; });
  }
  function closeRegionOwner(){ byId('rgnModal').classList.add('hide'); }
  function renderRegionOwnerList(){
    var q=(byId('rgnSearch').value||'').trim().toLowerCase();
    // One row per person: the tier they hold elsewhere is context, not a choice — the region
    // always gets an L4 row so the engine's first lookup finds them.
    var seen={}, list=[];
    RGN.people.forEach(function(p){ if(seen[p.authId]) { if(p.coversRegion) seen[p.authId].coversRegion=true; return; }
      var c={authId:p.authId,name:p.name,tier:p.tier,regions:(p.regions||[]).slice(),coversRegion:!!p.coversRegion}; seen[p.authId]=c; list.push(c); });
    list=list.filter(function(p){ if(!q) return true;
      return (p.name||'').toLowerCase().indexOf(q)>=0 || (p.tier||'').toLowerCase().indexOf(q)>=0 || (p.regions||[]).join(' ').toLowerCase().indexOf(q)>=0; });
    list.sort(function(a,b){ if(a.coversRegion!==b.coversRegion) return a.coversRegion?-1:1; return (a.name||'').localeCompare(b.name||''); });
    if(!list.length){ byId('rgnList').innerHTML='<div class="ph">Nobody matches. A person must already hold a sales position (L1–L5) to be offered here.</div>'; return; }
    byId('rgnList').innerHTML=list.map(function(p){
      return '<div class="asgrow'+(p.coversRegion?' covers':'')+'" data-rgnpick="'+p.authId+'" data-rgnname="'+esc(p.name)+'">'+
        '<span class="tierpill">'+esc(p.tier)+'</span><span class="nm">'+esc(p.name)+'</span>'+
        '<span class="rg">'+(p.coversRegion?'already covers this region · ':'')+esc((p.regions||[]).join(', ')||'no region')+'</span></div>'; }).join('');
  }
  function setRegionOwner(authId,name){
    if(!RGN.regionId) return;
    if(!confirm((RGN.current?('Change '+RGN.label+' from '+RGN.current+' to '+name+'?'):('Assign '+RGN.label+' to '+name+'?'))+'\n\nNew leads in this region will be routed to them.')) return;
    postForm('/lms/region-owner',{regionId:RGN.regionId, authId:authId}, function(res){
      var why=refusal(res); if(why){ toast(why); return; }
      closeRegionOwner();
      toast((res&&res.bmName?res.bmName:name)+' now owns '+RGN.label+(res&&res.previous?(' (was '+res.previous+')'):''),1);
      buildAssign();
    });
  }

  // ---- checklist question management (CRUD) --------------------------------------------------
  var QADM = { questions:[], stages:[], editing:null };

  function loadQuestions(){
    byId('qBody').innerHTML='<tr><td colspan="8"><div class="ph">Loading…</div></td></tr>';
    getJSON('/lms/checklist/questions', function(d){
      d=d||{}; QADM.questions=d.questions||[]; QADM.stages=d.stages||[];
      if(!QADM.questions.length){
        byId('qBody').innerHTML='<tr><td colspan="8"><div class="ph">No questions yet — add the first one.</div></td></tr>';
        return;
      }
      byId('qBody').innerHTML=QADM.questions.map(function(q){
        return '<tr'+(q.active?'':' style="opacity:.55"')+'>'+
          '<td class="num mono">'+q.sortOrder+'</td>'+
          '<td><b>'+esc(q.prompt)+'</b>'+
            (q.choices?'<br><span style="color:#97a1b5;font-size:11px">'+esc(q.choices.replace(/\|/g,' · '))+'</span>':'')+'</td>'+
          '<td class="nowrap">'+esc(q.answerType)+'</td>'+
          '<td class="num">'+(q.points||0)+'</td>'+
          '<td>'+(q.required?'<span class="lstat idle">Required</span>':'<span style="color:#97a1b5">—</span>')+'</td>'+
          '<td>'+stageChips(q.stages)+'</td>'+
          '<td>'+(q.active?'<span class="lstat oncall">Active</span>':'<span class="lstat off">Off</span>')+'</td>'+
          '<td class="nowrap"><button class="btn ghost sm" data-editq="'+q.id+'">Edit</button>'+
            (q.answerCount>0?'<span class="note" style="display:block;margin-top:3px">'+q.answerCount+' answered</span>':'')+
          '</td></tr>';
      }).join('');
    });
  }

  function stageChips(stages){
    if(!stages || !stages.trim()) return '<span style="color:#97a1b5">every stage</span>';
    return stages.split('|').map(function(x){
      return '<span class="lstat avail" style="margin:1px 2px">'+esc(prettyStage(x))+'</span>'; }).join('');
  }
  function prettyStage(x){ return (x||'').replace(/_/g,' ').toLowerCase().replace(/\b\w/g,function(c){return c.toUpperCase();}); }

  function editQuestion(id){
    var q=null;
    QADM.questions.forEach(function(x){ if(x.id===id) q=x; });
    QADM.editing=q;
    byId('qTitle').textContent=q?'Edit question':'New question';
    byId('qPrompt').value=q?q.prompt:'';
    byId('qType').value=q?q.answerType:'TEXT';
    byId('qPoints').value=q?(q.points||0):0;
    byId('qChoices').value=q&&q.choices?q.choices:'';
    byId('qOrder').value=q?q.sortOrder:nextOrder();
    byId('qRequired').checked=q?!!q.required:false;
    byId('qActive').checked=q?!!q.active:true;
    byId('qErr').classList.add('hide');
    // Delete is only offered when it is actually allowed; the server refuses it otherwise anyway.
    byId('qDelBtn').style.display=(q && !q.answerCount)?'':'none';
    var sel=(q&&q.stages)?q.stages.split('|'):[];
    byId('qStages').innerHTML=QADM.stages.map(function(st){
      return '<button type="button" class="chkopt qstage'+(sel.indexOf(st)>=0?' sel':'')+'" data-stage="'+st+'">'+
        esc(prettyStage(st))+'</button>'; }).join('');
    qTypeChanged();
    byId('qModal').classList.remove('hide');
  }
  function nextOrder(){
    var mx=0; QADM.questions.forEach(function(q){ if(q.sortOrder>mx) mx=q.sortOrder; });
    return mx+10;
  }
  function closeQ(){ byId('qModal').classList.add('hide'); }
  function qTypeChanged(){
    byId('qChoicesWrap').classList.toggle('hide', byId('qType').value!=='CHOICE');
  }
  function qErr(m){ var e=byId('qErr'); e.textContent=m; e.classList.remove('hide'); }

  function saveQuestion(){
    var prompt=(byId('qPrompt').value||'').trim();
    if(!prompt){ qErr('The question text is required'); return; }
    var type=byId('qType').value;
    var choices=(byId('qChoices').value||'').trim();
    if(type==='CHOICE' && !choices){ qErr('A choice question needs at least one option'); return; }
    var stages=[];
    document.querySelectorAll('#qStages .qstage.sel').forEach(function(b){ stages.push(b.getAttribute('data-stage')); });
    var body={ id:QADM.editing?QADM.editing.id:0, prompt:prompt, answerType:type,
      choices:choices, required:byId('qRequired').checked, active:byId('qActive').checked,
      points:parseInt(byId('qPoints').value,10)||0, stages:stages.join('|'),
      sortOrder:parseInt(byId('qOrder').value,10)||0 };
    var b=byId('qSaveBtn'); b.disabled=true; b.textContent='Saving…';
    postJSON('/lms/checklist/questions/save', body, function(res){
      b.disabled=false; b.textContent='Save';
      var why=refusal(res); if(why){ qErr(why); return; }
      closeQ(); toast(res&&res.created?'Question added':'Question updated',1); loadQuestions();
    }, function(){ b.disabled=false; b.textContent='Save'; qErr('Could not save the question'); });
  }

  function deleteQuestion(){
    if(!QADM.editing) return;
    if(!confirm('Delete this question? Switching it off keeps it out of calls without losing anything.')) return;
    postForm('/lms/checklist/questions/delete', {id:QADM.editing.id}, function(res){
      var why=refusal(res); if(why){ qErr(why); return; }
      closeQ(); toast('Question deleted',1); loadQuestions();
    });
  }

  // ---- first-call checklist -----------------------------------------------------------------
  // Opened automatically on the first ANSWERED call to a lead. Deliberately not on dial: a question
  // set that appears while the phone is still ringing is a question set that gets dismissed.
  var CHK = { leadId:null, callId:null, questions:[] };

  function maybeOpenChecklist(leadId, callId){
    if(!leadId) return;
    getJSON('/lms/checklist?leadId='+leadId+(callId?('&leadCallId='+callId):''), function(d){
      if(!d || !d.firstCall) return;              // not their first connected call — stay out of the way
      if(!d.questions || !d.questions.length) return;
      openChk(d, leadId, callId);
    }, function(){ /* the checklist must never take the call down with it */ });
  }

  function openChk(d, leadId, callId){
    CHK.leadId=leadId; CHK.callId=callId; CHK.questions=d.questions;
    byId('chkWho').textContent=d.retailer||('Lead #'+leadId);
    byId('chkNote').textContent=d.answered?'Already answered once — saving will update.':'';
    byId('chkBody').innerHTML=d.questions.map(function(q,i){
      var body;
      if(q.answerType==='CHOICE' && q.choices && q.choices.length){
        body='<div class="opts" data-qid="'+q.id+'">'+q.choices.map(function(c){
          return '<button type="button" class="chkopt'+(q.answer===c?' sel':'')+'" data-choice="'+esc(c)+'">'+esc(c)+'</button>';
        }).join('')+'</div>';
      } else if(q.answerType==='YESNO'){
        body='<div class="opts" data-qid="'+q.id+'">'+['Yes','No'].map(function(c){
          return '<button type="button" class="chkopt'+(q.answer===c?' sel':'')+'" data-choice="'+c+'">'+c+'</button>';
        }).join('')+'</div>';
      } else {
        body='<input id="chkq'+q.id+'" class="inp" style="width:100%"'+
             (q.answerType==='NUMBER'?' type="number" step="0.1" min="0"':'')+
             ' value="'+esc(q.answer==null?'':q.answer)+'">';
      }
      return '<div class="chkq"><div class="qp">'+(i+1)+'. '+esc(q.prompt)+
        (q.required?'<span class="req">*</span>':'')+
        (q.points?'<span class="note" style="display:inline;margin-left:6px">'+q.points+' pts</span>':'')+
        '</div>'+body+'</div>';
    }).join('');
    byId('chkModal').classList.remove('hide');
  }
  function closeChk(){ byId('chkModal').classList.add('hide'); }

  /** Read the current answer for a question, whichever control rendered it. */
  function chkValue(q){
    if(q.answerType==='CHOICE' || q.answerType==='YESNO'){
      var sel=document.querySelector('#chkBody .opts[data-qid="'+q.id+'"] .chkopt.sel');
      return sel?sel.getAttribute('data-choice'):'';
    }
    var el=byId('chkq'+q.id);
    return el?(el.value||'').trim():'';
  }

  function saveChk(){
    var answers=[], missing=[];
    CHK.questions.forEach(function(q){
      var v=chkValue(q);
      if(q.required && !v) missing.push(q.prompt);
      if(v) answers.push({questionId:q.id, answer:v});
    });
    if(missing.length){ toast('Still needed: '+missing[0]); return; }
    if(!answers.length){ toast('Nothing answered yet'); return; }
    var b=byId('chkSaveBtn'); b.disabled=true; b.textContent='Saving…';
    postJSON('/lms/checklist',{leadId:CHK.leadId, leadCallId:CHK.callId, answers:answers}, function(res){
      b.disabled=false; b.textContent='Save answers';
      var why=refusal(res); if(why){ toast(why); return; }
      closeChk();
      toast('Checklist saved ('+(res&&res.saved||0)+' answers)',1);
      if(REC && REC.id===CHK.leadId) reloadRecord();
    }, function(){ b.disabled=false; b.textContent='Save answers'; toast('Could not save the checklist'); });
  }

  // ---- disposition --------------------------------------------------------------------------
  var DISPS=[['INTERESTED','Interested'],['CALLBACK','Callback'],['NOT_REACHABLE','Not reachable'],
             ['WRONG_NUMBER','Wrong number'],['FOLLOW_UP','Follow-up'],['NOT_INTERESTED','Not interested'],
             ['DO_NOT_CALL','Do not call']];
  var DISP=null;
  /** The lead this disposition is about: the one dialled, else the record on screen. */
  function dispLeadId(){ return CALL.leadId || (REC ? REC.id : null); }

  function openDisp(){
    if(!dispLeadId()) return;
    DISP=null;
    byId('dispGrid').innerHTML=DISPS.map(function(d){
      return '<button class="btn ghost sm dispopt" data-d="'+d[0]+'" onclick="pickDisp(\''+d[0]+'\')">'+d[1]+'</button>'; }).join('');
    byId('dispExtra').innerHTML=''; byId('dispNote').value='';
    byId('dispModal').classList.remove('hide');
  }
  function closeDisp(){ byId('dispModal').classList.add('hide'); }
  function pickDisp(d){
    DISP=d;
    document.querySelectorAll('.dispopt').forEach(function(b){
      b.className='btn '+(b.getAttribute('data-d')===d?'coral':'ghost')+' sm dispopt'; });
    // Contextual sub-fields, mirroring SOP §12.2 and the in-app modal.
    var x='';
    if(d==='INTERESTED')        x=fld('dxValue','Business value (&#8377; lakh / month) — required','');
    else if(d==='CALLBACK')     x='<label class="lbl">Callback date &amp; time — required</label><input id="dxCallback" type="datetime-local" class="inp" style="width:100%">';
    else if(d==='NOT_REACHABLE')x=fld('dxRetry','Retry schedule (optional)','');
    else if(d==='WRONG_NUMBER') x=fld('dxCorrected','Corrected number (blank closes the lead)','');
    else if(d==='FOLLOW_UP')    x='<label class="lbl">Follow-up type</label><select id="dxFuType" class="inp" style="width:100%"><option value="CALL">Call</option><option value="MEETING">Meeting / visit</option></select>'+
                                  '<label class="lbl">Follow-up date &amp; time — required</label><input id="dxFollowUp" type="datetime-local" class="inp" style="width:100%">';
    else if(d==='NOT_INTERESTED')x='<label class="lbl">Sub-reason</label><select id="dxSub" class="inp" style="width:100%">'+
                                  ['Price','Terms','Already partnered','Category mismatch','Other'].map(function(o){return '<option>'+o+'</option>';}).join('')+'</select>';
    else if(d==='DO_NOT_CALL')  x='<div class="note" style="color:#e03131">Blocks this number permanently across every lead, not just this one.</div>';
    byId('dispExtra').innerHTML=x;
  }
  function saveDisp(){
    if(!DISP){ toast('Pick a disposition'); return; }
    var lid=dispLeadId();
    if(!lid){ toast('No lead to disposition'); return; }
    var p={leadId:lid,disposition:DISP,note:byId('dispNote').value,leadCallId:CALL.id||null};
    if(DISP==='INTERESTED'){ var v=parseFloat(byId('dxValue').value);
      if(!v||v<=0){ toast('Business value is required'); return; } p.value=v; }
    else if(DISP==='CALLBACK'){ if(!byId('dxCallback').value){ toast('Callback date/time is required'); return; }
      p.callbackAt=byId('dxCallback').value; }
    else if(DISP==='NOT_REACHABLE') p.retrySchedule=byId('dxRetry').value;
    else if(DISP==='WRONG_NUMBER')  p.correctedNumber=byId('dxCorrected').value;
    else if(DISP==='FOLLOW_UP'){ if(!byId('dxFollowUp').value){ toast('Follow-up date/time is required'); return; }
      p.followUpType=byId('dxFuType').value; p.followUpAt=byId('dxFollowUp').value; }
    else if(DISP==='NOT_INTERESTED') p.subReason=byId('dxSub').value;
    postJSON('/lms/disposition',p,function(res){
      var why=refusal(res); if(why){ toast(why); return; }
      closeDisp();
      var wasDialled=CALL.leadId;
      CALL.id=null; CALL.leadId=null; CALL.btn=null;
      hideBar();
      toast('Disposition saved: '+DISP.replace(/_/g,' '),1);
      // Refresh whichever view the user is actually looking at.
      if(REC && (!wasDialled || REC.id===wasDialled)) reloadRecord();
      if(!byId('cmd').classList.contains('hide')) loadPipeline();
      refresh();
    });
  }

  // ---- manual geo verification ---------------------------------------------------------------
  function geoErr(msg){ var e=byId('geoErr'); e.textContent=msg; e.classList.remove('hide'); }
  function geoClearErr(){ byId('geoErr').classList.add('hide'); }

  function openGeo(){
    if(!REC) return;
    geoClearErr();
    // Seed from what the record already knows, so a nudge is an edit rather than a re-entry.
    byId('geoAddress').value=[REC.address,REC.city,REC.state].filter(function(x){return x;}).join(', ');
    byId('geoLatLng').value=(REC.geoLat!=null&&REC.geoLng!=null)?(REC.geoLat+','+REC.geoLng):'';
    byId('geoRemark').value='';
    byId('geoPhoto').value='';
    byId('geoPhotoImg').classList.add('hide');
    byId('geoMapWrap').classList.add('hide');
    byId('geoModal').classList.remove('hide');
    if(REC.geoLat!=null&&REC.geoLng!=null) geoShowMap(REC.geoLat,REC.geoLng);
  }
  function closeGeo(){ byId('geoModal').classList.add('hide'); }

  /** Accepts "lat,lng" or a Maps URL: /@lat,lng, ?q=lat,lng, ?ll=, ?destination=. */
  function parseLatLng(raw){
    if(!raw) return null;
    var m=String(raw).match(/(-?\d{1,3}\.\d+)\s*,\s*(-?\d{1,3}\.\d+)/);
    return m?{lat:parseFloat(m[1]),lng:parseFloat(m[2])}:null;
  }
  function geoShowMap(lat,lng){
    byId('geoMapFrame').src='https://www.google.com/maps?q='+lat+','+lng+'&z=17&output=embed';
    byId('geoOpenMap').href='https://www.google.com/maps?q='+lat+','+lng;
    byId('geoMapWrap').classList.remove('hide');
  }
  function geoPreview(){
    var p=parseLatLng(byId('geoLatLng').value);
    if(!p){ geoErr('Enter latitude,longitude first — like 28.6139,77.2090.'); return; }
    geoClearErr(); geoShowMap(p.lat,p.lng);
  }
  function geoGeocode(){
    var a=(byId('geoAddress').value||'').trim();
    if(!a){ geoErr('Enter an address first.'); return; }
    geoClearErr();
    var b=byId('geoFindBtn'); b.disabled=true; b.textContent='Finding…';
    postForm('/lead-geo/geocode-address',{address:a},function(r){
      b.disabled=false; b.textContent='Find on map';
      if(!r||!r.success){ geoErr((r&&r.message)||'Could not geocode that address.'); return; }
      byId('geoLatLng').value=r.latitude+','+r.longitude;
      geoShowMap(r.latitude,r.longitude);
    },function(){ b.disabled=false; b.textContent='Find on map'; geoErr('Geocode request failed.'); });
  }
  function geoPickPhoto(){
    var f=byId('geoPhoto').files&&byId('geoPhoto').files[0];
    if(!f){ byId('geoPhotoImg').classList.add('hide'); return; }
    var fr=new FileReader();
    fr.onload=function(ev){ byId('geoPhotoImg').src=ev.target.result; byId('geoPhotoImg').classList.remove('hide'); };
    fr.readAsDataURL(f);
  }
  function geoSave(){
    var p=parseLatLng(byId('geoLatLng').value);
    if(!p){ geoErr('Could not read latitude/longitude. Paste like 28.6139,77.2090.'); return; }
    if(p.lat<-90||p.lat>90||p.lng<-180||p.lng>180||(p.lat===0&&p.lng===0)){ geoErr('Latitude/longitude out of range.'); return; }
    var f=byId('geoPhoto').files&&byId('geoPhoto').files[0];
    if(!f){ geoErr('Attach a store-board photo — the server requires one.'); return; }
    geoClearErr();
    var b=byId('geoSaveBtn'); b.disabled=true; b.textContent='Uploading photo…';

    // Upload first: manual-verify needs the document id, and uploading only on save means a
    // cancelled dialog never orphans a document.
    var fd=new FormData(); fd.append('file',f,f.name||'store-photo.jpg');
    fetch(CTX+'/lead-geo/upload-image',{method:'POST',credentials:'same-origin',
        headers:{'X-Requested-With':'XMLHttpRequest'},body:fd})
      .then(function(r){ return r.text(); })
      .then(function(t){
        var d=null; try{ d=JSON.parse(t); }catch(e){}
        var r=(d&&d.response!==undefined)?d.response:d;
        var docId=r&&(r.document_id||r.documentId||r.id);
        if(!docId){ b.disabled=false; b.textContent='Save & verify'; geoErr('Photo upload failed. Try again.'); return; }
        b.textContent='Verifying…';
        postForm('/lead-geo/manual-verify',
          {leadId:REC.id,latitude:p.lat,longitude:p.lng,remark:byId('geoRemark').value,imageDocumentId:docId},
          function(res){
            b.disabled=false; b.textContent='Save & verify';
            var why=refusal(res);
            if(why){ geoErr(why); return; }
            closeGeo(); toast('Location verified — this lead can now go on a beat',1); reloadRecord();
          },
          function(){ b.disabled=false; b.textContent='Save & verify'; geoErr('Could not save the verification.'); });
      })
      .catch(function(){ b.disabled=false; b.textContent='Save & verify'; geoErr('Photo upload failed. Try again.'); });
  }

  // ====================== CREATE LEAD (real /lms/resolve-region + /createLead) ======================
  var CREATE_PATH='A';
  function setPath(p,btn){ CREATE_PATH=p;
    byId('pathA').className='btn '+(p==='A'?'coral':'ghost')+' sm'; byId('pathB').className='btn '+(p==='B'?'coral':'ghost')+' sm';
    byId('createDesc').textContent=(p==='A')?'Path A — captured by a BGC agent during an outbound call, after consent. Owner is the region BM.':'Path B — field encounter. Owner is you, the creator.';
  }
  function initials(n){ n=(n||'').trim(); if(!n) return '—'; var p=n.split(/\s+/); return ((p[0]||'')[0]||'').toUpperCase()+((p[1]||'')[0]||'').toUpperCase(); }
  function resolveBM(regionId){ if(!regionId){ byId('rName').textContent='Pick a region…'; byId('rRegion').textContent='—'; byId('raAv').textContent='—';
      byId('rEsc').textContent='The owning BM/RSM is resolved from the region (cs.position).'; return; }
    getJSON('/lms/resolve-region?regionId='+encodeURIComponent(regionId),function(d){ d=d||{};
      byId('rRegion').textContent=d.regionCode||''; var nm=d.bmName||'';
      if(d.assignmentStatus==='HOLD' || !nm){ byId('rName').textContent='No active BM/RSM'; byId('raAv').textContent='!';
        byId('raAv').style.background='#e03131'; byId('rEsc').innerHTML='Region has no active owner &rarr; <b style="color:#e03131">HOLD queue</b>, Sales Head notified.'; }
      else { byId('rName').textContent=nm; byId('raAv').textContent=initials(nm); byId('raAv').style.background='#1f2a5e';
        byId('rEsc').textContent='Auto-resolved from region · escalation contact copied on the assignment email.'; } }); }
  // ---- brand-wise business value ------------------------------------------------------------
  // Agents write "1L", "50k", "1.5 lakh" as readily as digits, and rejecting those would just push
  // them back to typing a single lump sum. Parsed here so the stored value is always plain rupees.
  function parseMoney(raw){
    if(raw===null||raw===undefined) return 0;
    var t=(''+raw).trim().toLowerCase().replace(/[₹,\s]/g,'');
    if(!t) return 0;
    var m=t.match(/^([0-9]*\.?[0-9]+)(k|l|lac|lacs|lakh|lakhs|cr|crore|crores)?$/);
    if(!m) return 0;
    var n=parseFloat(m[1]); if(isNaN(n)) return 0;
    switch(m[2]){
      case 'k': return Math.round(n*1000);
      case 'l': case 'lac': case 'lacs': case 'lakh': case 'lakhs': return Math.round(n*100000);
      case 'cr': case 'crore': case 'crores': return Math.round(n*10000000);
      default: return Math.round(n);
    }
  }
  function collectBrands(){
    var out=[];
    document.querySelectorAll('#cBrandGrid .bval').forEach(function(el){
      var v=parseMoney(el.value);
      if(v>0) out.push({brand:el.getAttribute('data-brand'), value:v});
    });
    return out;
  }
  function brandTotal(){
    var t=0; collectBrands().forEach(function(b){ t+=b.value; });
    var el=byId('cValueTotal');
    if(el) el.textContent='total '+(t>0?fmtMoney(t):'₹0');
    syncCounter(t);
    return t;
  }
  // Counter size is the legacy name for the shop's monthly business in rupees (the Leads screen
  // stored 10,00,000-style values there), so it follows the brand total until the agent overrides
  // it by typing. Clearing the field hands it back to the sum.
  var COUNTER_MANUAL=false;
  function syncCounter(total){
    var c=byId('cCounter'); if(!c) return;
    if(COUNTER_MANUAL) return;
    c.value = total>0 ? String(total) : '';
    var h=byId('cCounterHint'); if(h) h.textContent='= brand total, editable';
  }
  function counterEdited(){
    var c=byId('cCounter'); if(!c) return;
    var v=(c.value||'').trim();
    COUNTER_MANUAL = v.length>0;
    var h=byId('cCounterHint');
    if(h) h.textContent = COUNTER_MANUAL ? 'manual — clear to use brand total' : '= brand total, editable';
    if(!COUNTER_MANUAL) syncCounter(brandTotal());
  }
  function fmtMoney(n){
    if(n>=10000000) return '₹'+(n/10000000).toFixed(n%10000000?2:0)+'Cr';
    if(n>=100000)   return '₹'+(n/100000).toFixed(n%100000?2:0)+'L';
    if(n>=1000)     return '₹'+(n/1000).toFixed(n%1000?1:0)+'K';
    return '₹'+n;
  }

  function val(id){ var e=byId(id); return e?e.value:''; }
  // Store photos go through the same /document-upload the Leads screen uses (multipart "file" ->
  // response.document_id) and the ids ride along in the create payload as lead_detail columns.
  function uploadPhoto(input){
    var f=input&&input.files&&input.files[0]; if(!f) return Promise.resolve(0);
    var fd=new FormData(); fd.append('file',f);
    return fetch(CTX+'/document-upload',{method:'POST',credentials:'same-origin',body:fd,headers:{'X-Requested-With':'XMLHttpRequest'}})
      .then(function(r){ return r.json(); })
      .then(function(d){ var id=d&&d.response&&d.response.document_id; if(!id) throw new Error('upload'); return parseInt(id,10); });
  }
  function uploadPhotos(){
    var inputs=Array.prototype.slice.call(document.querySelectorAll('#cPhotoGrid .cphoto'));
    var ids={};
    return inputs.reduce(function(chain,inp){ return chain.then(function(){
      return uploadPhoto(inp).then(function(id){ if(id) ids[inp.getAttribute('data-photo')]=id; }); }); }, Promise.resolve())
      .then(function(){ return ids; });
  }
  var CREATE_BUSY=false;
  function submitLead(){ if(CREATE_BUSY) return;
    var fn=val('cRetailer').trim(), biz=val('cBusiness').trim();
    var phone=(val('cContact')||'').replace(/\D/g,'').slice(-10);
    var brands=collectBrands(); var value=brandTotal();
    var region=val('cRegion'); var path=CREATE_PATH;
    if(!fn){ toast('Retailer name is required'); return; }
    if(phone.length!==10){ toast('A valid 10-digit contact is required'); return; }
    if(!region){ toast('Pick a region'); return; }
    var address=val('cAddress').trim(), city=val('cCity').trim(), state=val('cState');
    if(address.length>128){ toast('Address is too long (128 max)'); return; }
    if(city.length>30){ toast('City is too long (30 max)'); return; }
    var counter=parseMoney(val('cCounter'));
    if(counter>2147483647){ toast('Counter size is too large — enter rupees per month'); return; }
    // No address check on either path: the capture link is what establishes location, and it is
    // generated for every lead regardless of path. Address / city / state are kept when typed.
    var payload={ firstName:fn, mobile:phone, outletName:biz||'', source:val('cSource')||'LMS Dashboard',
      regionId:parseInt(region,10), creationPath:path,
      address:address, city:city, state:state||'',
      conversionHigh:(val('cConversion')==='true'), remark:val('cRemark').trim() };
    if(!isNaN(counter)&&counter>0) payload.counterSize=counter;
    // potential is the sum, so the funnel's value column keeps working, while the per-brand split
    // is what actually tells a BM what the counter is worth.
    if(value && value>0) payload.potential=value;
    if(brands.length) payload.leadBrands=brands;
    CREATE_BUSY=true;
    var anyPhoto=Array.prototype.some.call(document.querySelectorAll('#cPhotoGrid .cphoto'),function(i){ return i.files&&i.files.length; });
    if(anyPhoto) toast('Uploading photos…');
    uploadPhotos().then(function(ids){
      for(var k in ids){ if(ids.hasOwnProperty(k)) payload[k]=ids[k]; }
      // /lms/createLead, NOT the shared /createLead: this one honours regionId and creationPath, so
      // the lead actually gets a stage, an LMS code, an owner and an SLA clock.
      return fetch(CTX+'/lms/createLead',{method:'POST',credentials:'same-origin',
        headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest'},
        body:JSON.stringify(payload)}).then(function(r){ return r.text(); }); })
      .then(function(t){ CREATE_BUSY=false;
        var d=null; try{ d=JSON.parse(t); }catch(e){ d=null; }
        var res=(d&&d.response)?d.response:d;
        if(!res || res.ok!==true){
          // A refusal carries the reason as a bare string under `response` (badRequest("...")),
          // whereas success is an object. Surface the reason, not a generic failure.
          toast((typeof res==='string' && res) || (res&&res.message) || 'Create failed');
          return;
        }
        var held=(res.assignmentStatus==='HOLD');
        toast(held ? ('Lead '+res.lmsCode+' created · no BM for that region, parked in HOLD')
                   : ('Lead '+res.lmsCode+' created · assigned to '+(res.ownerName||'the region BM')+' · SLA started'), 1);
        ['cRetailer','cBusiness','cContact','cAddress','cCity','cCounter','cRemark'].forEach(function(x){ var e=byId(x); if(e) e.value=''; });
        ['cState'].forEach(function(x){ var e=byId(x); if(e) e.value=''; });
        var cs=byId('cSource'); if(cs) cs.value='LMS Dashboard'; var cc=byId('cConversion'); if(cc) cc.value='false';
        document.querySelectorAll('#cBrandGrid .bval').forEach(function(el){ el.value=''; });
        document.querySelectorAll('#cPhotoGrid .cphoto').forEach(function(el){ el.value=''; });
        COUNTER_MANUAL=false; brandTotal();

        // Hand the capture link over immediately — the whole point of generating it on create is
        // that the agent is still on the call with the retailer.
        if(res.geoLink){
          if(navigator.clipboard && navigator.clipboard.writeText){
            navigator.clipboard.writeText(res.geoLink).then(function(){
              alert('Capture link copied to your clipboard — send it to the retailer now:\n\n'+res.geoLink);
            }, function(){ prompt('Send this capture link to the retailer:', res.geoLink); });
          } else {
            prompt('Send this capture link to the retailer:', res.geoLink);
          }
        }

        byId('recLookup').value=res.leadId; injectRecord(res.leadId);
        go('record',document.querySelector('.tab[data-screen="record"]')); refresh(); })
      .catch(function(e){ CREATE_BUSY=false; toast(e&&e.message==='upload'?'A photo failed to upload — the lead was not created':'Create failed'); }); }

  // ====================== AUTO-ASSIGNMENT (real resolve per region) ======================
  function buildAssign(){ var opts=byId('cRegion').querySelectorAll('option'); var holdCount=0, assignedCount=0, pending=0;
    var body=byId('assignMap'); body.innerHTML='';
    // Rows are created up-front in region order, then filled in as each resolve lands — otherwise
    // the table would be ordered by whichever request happened to answer first.
    opts.forEach(function(o){ if(!o.value) return; pending++;
      var label=o.textContent;
      var tr=document.createElement('tr');
      tr.innerHTML='<td><b>'+esc(label)+'</b></td><td colspan="3"><span class="ph">Resolving…</span></td>';
      body.appendChild(tr);
      function done(){ if(--pending===0){ renderAssignKpis(assignedCount,holdCount); } }
      getJSON('/lms/resolve-region?regionId='+encodeURIComponent(o.value),function(d){ d=d||{};
        var hold=(d.assignmentStatus==='HOLD' || !d.bmName);
        if(hold) holdCount++; else assignedCount++;
        tr.innerHTML='<td><b>'+esc(label)+'</b></td>'+
          '<td>'+(hold?'<span class="warnflag">— vacant —</span>':esc(d.bmName))+'</td>'+
          '<td>'+(hold?'<span class="stage st-ni">HOLD</span>':'<span class="stage st-active">Active</span>')+'</td>'+
          '<td class="num"><button type="button" class="btn ghost sm" data-rgn="'+esc(o.value)+'" data-rgnlabel="'+esc(label)+'" data-rgnowner="'+esc(hold?'':(d.bmName||''))+'">'+(hold?'Assign':'Change')+'</button></td>';
        done();
      },function(){ tr.innerHTML='<td><b>'+esc(label)+'</b></td><td colspan="3"><span class="warnflag">could not resolve</span></td>';
        done(); }); });
    // HOLD queue leads
    getJSON('/lms/dashboard/leads?bucketType=ATTENTION&bucketKey=HOLD',function(d){ var leads=(d&&d.leads)?d.leads:[];
      if(!leads.length){ byId('holdQueue').innerHTML='<div class="ph">No leads in HOLD. 🎉</div>'; return; }
      var h=''; leads.slice(0,8).forEach(function(l){ h+='<div style="display:flex;align-items:center;gap:10px;font-size:12.5px;padding:5px 0" class="clickrow" data-leadid="'+l.id+'">'+
        '<span class="idpill">'+esc(l.lmsCode)+'</span> <span>'+esc(l.name||l.outlet||'—')+'</span></div>'; });
      byId('holdQueue').innerHTML=h; }); }
  function renderAssignKpis(assigned,hold){ var k=[
      {i:'&#128231;',bg:'#eef1fb',fg:'#3b5bdb',l:'Regions mapped',v:assigned,f:'active BM/RSM'},
      {i:'&#9208;',bg:'#fff0f0',fg:'#e03131',l:'Regions on HOLD',v:hold,f:'no active BM',vc:'#e03131'},
      {i:'&#128100;',bg:'#fff4e6',fg:'#e8590c',l:'HOLD leads',v:(DATA.summary&&attn('HOLD'))||0,f:'awaiting a BM',vc:'#e8590c'},
      {i:'&#9889;',bg:'#ebfbee',fg:'#2f9e44',l:'Resolve tiers',v:'L4→L5→L3',f:'cs.position'} ];
    var h=''; k.forEach(function(x){ h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+x.bg+';color:'+x.fg+'">'+x.i+'</div>'+
      '<div class="label">'+esc(x.l)+'</div></div><div class="val"'+(x.vc?' style="color:'+x.vc+'"':'')+'>'+(typeof x.v==='number'?fmtInt(x.v):x.v)+'</div><div class="foot">'+esc(x.f)+'</div></div>'; });
    byId('assignKpis').innerHTML=h; }

  function attn(key){ var s=DATA.summary; if(!s||!s.attention) return 0; var f=0; s.attention.forEach(function(a){ if(a.key===key)f=a.count; }); return f; }

  // ====================== RECORDINGS & AUDIT (live hygiene from attention) ======================
  function buildAudit(){
    // KPIs — missing dispositions is live; recording metrics are pending source.
    var miss=attn('MISSING_DISP'), br=attn('BREACHED_NO_CONTACT'), hold=attn('HOLD');
    var kp=[ {i:'&#127925;',bg:'#fff0ef',fg:'#f0483e',l:'Recordings (24 mo)',v:'—',f:'pending source'},
      {i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',l:'Missing dispositions',v:miss,f:'live',vc:'#e8590c'},
      {i:'&#128683;',bg:'#fff0f0',fg:'#e03131',l:'DND breaches',v:'—',f:'needs call log'},
      {i:'&#128065;',bg:'#eef1fb',fg:'#3b5bdb',l:'Recording opens',v:'—',f:'pending source'},
      {i:'&#129529;',bg:'#e6fcf5',fg:'#0ca678',l:'Onboarded (deep audit)',v:fmtInt(onboardedCount()),f:'5% sampled'} ];
    var h=''; kp.forEach(function(x){ h+='<div class="kpi"><div class="top"><div class="ic" style="background:'+x.bg+';color:'+x.fg+'">'+x.i+'</div>'+
      '<div class="label">'+esc(x.l)+'</div></div><div class="val"'+(x.vc?' style="color:'+x.vc+'"':'')+'>'+(typeof x.v==='number'?fmtInt(x.v):x.v)+'</div><div class="foot">'+esc(x.f)+'</div></div>'; });
    byId('auditKpis').innerHTML=h;
    // hygiene flags (clickable via data-att)
    var flags=[ {k:'MISSING_DISP',i:'&#128172;',bg:'#fff4e6',fg:'#e8590c',t:'LMS with missing dispositions',d:'Next action stays locked until dispositioned',c:'warnflag',v:miss},
      {k:'BREACHED_NO_CONTACT',i:'&#9888;',bg:'#fff0f0',fg:'#e03131',t:'SLA breaches — first contact',d:'Escalated to BM/RSM per matrix',c:'badflag',v:br},
      {k:'HOLD',i:'&#128100;',bg:'#fff0f0',fg:'#e03131',t:'Unassigned records (HOLD)',d:'Region awaiting a BM',c:'badflag',v:hold} ];
    var fh=''; flags.forEach(function(a){ fh+='<div class="att" data-att="'+a.k+'" data-attt="'+esc(a.t)+'"><div class="ic" style="background:'+a.bg+';color:'+a.fg+'">'+a.i+'</div>'+
      '<div class="ab"><div class="atitle">'+esc(a.t)+'</div><div class="adet">'+esc(a.d)+'</div></div><div class="acount '+a.c+'">'+fmtInt(a.v)+'</div></div>'; });
    byId('auditHygiene').innerHTML=fh; }
  function onboardedCount(){ var s=DATA.summary; if(!s||!s.funnel) return 0; var c=0; s.funnel.forEach(function(f){ if(f.stage==='ONBOARDED')c=f.count; }); return c; }

  // ---- generic table search + sort ---------------------------------------------------------
  // Every list table in the console gets a sortable header, and one with enough rows to be worth
  // filtering also gets a search box. Attached by scanning the DOM rather than by editing each of
  // the fifteen render functions: tables here are built as HTML strings in a dozen places, and a
  // per-call-site flag would have been missed by the next one written.
  //
  // Client-side, so it sorts and filters WHAT IS ON SCREEN. That is the whole population for the
  // report tables, and the loaded slice for the ones the server pages (the drawer stops at 100,
  // the call log at its page size) — the count reads "12 of 100 shown" so it never implies more.
  // The Lead pipeline is excluded: it sorts and searches server-side across every page, and that
  // is strictly better wherever it exists.

  var TS_SEARCH_MIN_ROWS = 8;   // below this a search box is clutter; the sort still attaches
  var tsBusy = false;           // our own DOM writes must not re-trigger the observer

  /** Tables that own their behaviour, or are not lists at all, opt out here. */
  function tsEligible(t){
    if(t.hasAttribute('data-ts') || t.hasAttribute('data-nots')) return false;
    if(t.classList.contains('matrix') || t.classList.contains('heat')) return false;
    if(t.querySelector('th.sortable')) return false;          // the pipeline: server-side sort
    var head=t.tHead;
    if(!head || head.rows.length!==1) return false;           // no header, or grouped headers:
    if(!t.tBodies.length) return false;                       // column index is not 1:1 with th
    return true;
  }

  /** Cell text for comparison; a cell may override it with data-sv (e.g. a raw timestamp). */
  function tsText(td){
    if(!td) return '';
    var v = td.getAttribute && td.getAttribute('data-sv');
    return ((v!==null&&v!==undefined) ? v : td.textContent).replace(/\s+/g,' ').trim();
  }

  /**
   * Comparable number for a rendered cell, or null when it is not a number.
   * Sorting on the printed text would put ₹8L above ₹10L and 2m 40s above 10m, which is the kind
   * of wrong that is hard to notice — so the formats this console actually prints are parsed.
   */
  function tsValue(txt){
    if(!txt || txt==='—' || txt==='-') return null;
    // duration: "2m 40s", "1h 05m", "45s"
    if(/\d/.test(txt) && /^(\d+h\s*)?(\d+m\s*)?(\d+s)?$/.test(txt)){
      var h=/(\d+)h/.exec(txt), mn=/(\d+)m/.exec(txt), sc=/(\d+)s/.exec(txt);
      return (h?+h[1]*3600:0)+(mn?+mn[1]*60:0)+(sc?+sc[1]:0);
    }
    // number, with optional currency prefix, thousands separators and a K / L / Cr / % suffix
    var m=/^[₹$]?\s*(-?[\d,]+(?:\.\d+)?)\s*(K|L|Cr|%)?$/i.exec(txt);
    if(m){
      var n=parseFloat(m[1].replace(/,/g,''));
      if(isNaN(n)) return null;
      var suf=(m[2]||'').toLowerCase();
      if(suf==='k') n*=1e3; else if(suf==='l') n*=1e5; else if(suf==='cr') n*=1e7;
      return n;
    }
    // "21 Sep 2026", with or without a time after it
    if(/^\d{1,2} [A-Za-z]{3} \d{4}/.test(txt)){ var d=Date.parse(txt); if(!isNaN(d)) return d; }
    return null;
  }

  /** Data rows only — a colspan placeholder ("Loading…", "No rows") is not one. */
  function tsRows(t){
    var out=[], b=t.tBodies[0], cols=t.tHead.rows[0].cells.length;
    if(!b) return out;
    for(var i=0;i<b.rows.length;i++){
      var r=b.rows[i];
      if(r.cells.length>=cols && !r.hasAttribute('data-tsempty')) out.push(r);
    }
    return out;
  }

  function tsSort(t, idx){
    var ths=t.tHead.rows[0].cells;
    var cur=t.getAttribute('data-tscol'), dir=t.getAttribute('data-tsdir')||'desc';
    // Same column flips; a new column starts descending — what people expect of values and dates,
    // and harmless on text.
    dir = (String(idx)===cur) ? (dir==='asc'?'desc':'asc') : 'desc';
    t.setAttribute('data-tscol', String(idx));
    t.setAttribute('data-tsdir', dir);

    var rows=tsRows(t), numeric=false, sawValue=false, allNumeric=true;
    rows.forEach(function(r){
      var txt=tsText(r.cells[idx]);
      if(txt==='' || txt==='—') return;
      sawValue=true;
      if(tsValue(txt)===null) allNumeric=false;
    });
    numeric = sawValue && allNumeric;

    rows.sort(function(a,b){
      var ta=tsText(a.cells[idx]), tb=tsText(b.cells[idx]);
      var va = numeric ? tsValue(ta) : (ta===''||ta==='—' ? null : ta.toLowerCase());
      var vb = numeric ? tsValue(tb) : (tb===''||tb==='—' ? null : tb.toLowerCase());
      if(va===null && vb===null) return 0;
      if(va===null) return 1;              // blanks sit last in BOTH directions, never at the top
      if(vb===null) return -1;
      var c = numeric ? (va-vb) : (va<vb ? -1 : (va>vb ? 1 : 0));
      return dir==='asc' ? c : -c;
    });

    tsBusy=true;
    var body=t.tBodies[0];
    rows.forEach(function(r){ body.appendChild(r); });
    for(var i=0;i<ths.length;i++){
      var on=(i===idx), label=ths[i].getAttribute('data-tslabel');
      ths[i].classList.toggle('on',on);
      ths[i].innerHTML = esc(label||'') + (on ? '<span class="arrow '+(dir==='asc'?'up':'down')+'"></span>' : '');
    }
    tsBusy=false;
  }

  function tsFilter(t){
    var bar=t.__tsBar, q=(bar && bar.__input ? bar.__input.value : '').trim().toLowerCase();
    var rows=tsRows(t), shown=0;
    tsBusy=true;
    rows.forEach(function(r){
      var hit = !q || r.textContent.toLowerCase().indexOf(q)>=0;
      r.style.display = hit ? '' : 'none';
      if(hit) shown++;
    });
    // One "no matches" row, reused, so a filter that hides everything does not look like a crash.
    var body=t.tBodies[0], empty=body.querySelector('tr[data-tsempty]');
    if(q && !shown){
      if(!empty){
        empty=document.createElement('tr');
        empty.setAttribute('data-tsempty','1');
        empty.innerHTML='<td colspan="'+t.tHead.rows[0].cells.length+'"><div class="tsempty">No rows match “'+esc(q)+'”.</div></td>';
        body.appendChild(empty);
      } else {
        empty.style.display='';
        empty.firstChild.firstChild.textContent='No rows match “'+q+'”.';
      }
    } else if(empty){ empty.style.display='none'; }
    if(bar && bar.__count){
      var txt = q ? (shown+' of '+rows.length+' shown') : (rows.length+(rows.length===1?' row':' rows'));
      if(bar.__count.textContent!==txt) bar.__count.textContent=txt;
      bar.style.display = (rows.length>=TS_SEARCH_MIN_ROWS || q) ? '' : 'none';
    }
    tsBusy=false;
  }

  function tsEnhance(t){
    t.setAttribute('data-ts','1');
    var ths=t.tHead.rows[0].cells;
    for(var i=0;i<ths.length;i++){
      (function(th,idx){
        th.setAttribute('data-tslabel', th.textContent.trim());
        th.classList.add('tsort');
        th.addEventListener('click', function(){ tsSort(t, idx); });
      })(ths[i], i);
    }
    // The toolbar goes OUTSIDE .pipewrap — inside it, it would scroll sideways with the table.
    var host = (t.parentNode && t.parentNode.classList && t.parentNode.classList.contains('pipewrap'))
             ? t.parentNode : t;
    if(!host.parentNode) return;
    // A drawer table's filter belongs in the drawer header, beside the title that says what the
    // list is — not floating above the first row, where it pushes the table down and reads as
    // part of the data. Only the first table claims the slot; a report drawer showing two keeps the
    // second one's filter inline, where it stays obvious which table it filters.
    var slot = t.closest('#drawer') ? byId('dTools') : null;
    if(slot && slot.childElementCount) slot=null;
    var bar=document.createElement('div');
    bar.className='tstools';
    var input=document.createElement('input');
    input.type='text'; input.className='inp'; input.placeholder='Filter these rows…';
    var count=document.createElement('span'); count.className='tscount';
    bar.appendChild(input); bar.appendChild(count);
    bar.__input=input; bar.__count=count; t.__tsBar=bar;
    input.addEventListener('input', function(){ tsFilter(t); });
    tsBusy=true;
    if(slot) slot.appendChild(bar); else host.parentNode.insertBefore(bar, host);
    tsBusy=false;
    tsFilter(t);
  }

  /** Enhance any new table, and re-count / re-filter ones whose rows were replaced under us. */
  function tsScan(){
    var tables=document.querySelectorAll('table');
    for(var i=0;i<tables.length;i++){
      var t=tables[i];
      if(tsEligible(t)) tsEnhance(t);
      else if(t.hasAttribute('data-ts') && t.__tsBar) tsFilter(t);
    }
  }

  (function(){
    var obs=null, queued=false;
    function run(){
      queued=false;
      tsScan();
      // A MutationObserver delivers asynchronously, so tsBusy alone cannot stop a scan from seeing
      // its own writes and scanning again. Dropping the records we just produced ends it here.
      if(obs) obs.takeRecords();
    }
    tsScan();
    if(typeof MutationObserver!=='function') return;
    obs=new MutationObserver(function(){
      if(queued) return;                      // at most one scan per frame
      queued=true;
      requestAnimationFrame(run);
    });
    obs.observe(document.body, {childList:true, subtree:true});
  })();

  // ---- initial paint from seeds, pipeline loads live
  renderSummary(SEED.summary); renderState(SEED.state); renderHeat(SEED.heat); renderAgeing(SEED.ageing);
  loadCallCenterUsers();
  setDashPeriod();
  loadPipeline();

  // ---- deep-link: a URL hash such as dash or record opens that tab
  // Tabs are looked up by data-screen, not position: a tab the viewer is not allowed to see (Create
  // Lead below L2) is simply absent, and a hash for it is ignored rather than opening the screen.
  (function(){ function tabFor(k){ return document.querySelector('.tab[data-screen="'+k+'"]'); }
    function open(k){ var b=tabFor(k); if(k && b){ go(k, b); } }
    open((location.hash||'').replace('#','').trim());
    window.addEventListener('hashchange',function(){ open((location.hash||'').replace('#','').trim()); }); })();
</script>
</body>
</html>