Subversion Repositories SmartDukaan

Rev

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Beat Journey</title>
<style>
  :root{
    --bg:#eef1f7; --card:#ffffff; --ink:#1d2433; --muted:#69748c; --soft:#97a1b5;
    --line:#e6e9f1; --line2:#eef1f6;
    --brand:#3b5bdb; --brand2:#5c7cfa; --teal:#0ca678; --cyan:#1098ad;
    --amber:#f59f00; --orange:#e8590c; --red:#e03131; --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:1320px;margin:0 auto;padding:20px 24px 90px}
  a{color:var(--brand)}
  header.top{display:flex;align-items:center;justify-content:space-between;gap:18px;flex-wrap:wrap;margin-bottom:16px}
  .brand .crumb{font-size:12px;color:var(--soft);font-weight:600}
  .brand h1{margin:3px 0 0;font-size:23px;font-weight:740;letter-spacing:-.01em}
  .brand h1 .live{font-size:11px;font-weight:700;color:var(--teal);background:#e6fcf5;border:1px solid #c3fae8;border-radius:999px;padding:3px 9px;vertical-align:middle;margin-left:10px}
  .brand h1 .live i{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--teal);margin-right:5px;animation:pulse 1.6s infinite}
  @keyframes pulse{0%,100%{opacity:1}50%{opacity:.25}}
  .hd-right{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
  .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,input.ctl{appearance:none;cursor:pointer;height:36px}
  input.ctl{cursor:auto}
  .btn-r{background:var(--brand);border:0;color:#fff;font-weight:650;padding:9px 15px;border-radius:9px;cursor:pointer;font-size:13px;height:36px}
  .lenses{display:flex;gap:4px;border-bottom:1px solid var(--line);margin-bottom:20px}
  .lens{padding:11px 4px;margin-right:22px;font-size:14px;font-weight:650;color:var(--muted);cursor:pointer;border:0;background:transparent;border-bottom:2.5px solid transparent;margin-bottom:-1px}
  .lens.active{color:var(--brand);border-bottom-color:var(--brand)}
  .lens .b{display:inline-block;background:#eef1fb;color:var(--brand);font-size:11px;font-weight:700;border-radius:999px;padding:1px 7px;margin-left:6px}
  .kpis{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:20px}
  .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);display:flex;flex-direction:column}
  .kpi.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}
  .kpi.clickable:hover{border-color:#c7d0e8;box-shadow:0 3px 10px rgba(20,30,60,.09);transform:translateY(-1px)}
  .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:auto;padding-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}
  .kpi .brow{display:flex;align-items:flex-start;text-align:center}
  .kpi .brow.blabs{margin-top:11px}
  .kpi .brow.bvals{margin-top:auto;padding-top:4px}
  .kpi .blab{flex:1;font-size:11px;color:var(--soft);font-weight:600;line-height:1.25}
  .kpi .bval{flex:1;font-size:24px;font-weight:760;letter-spacing:-.02em;line-height:1}
  .kpi .bval small{font-size:12px;color:var(--soft);font-weight:600}
  .kpi .bsep{color:var(--line);font-weight:600;align-self:center}
  .grid{display:grid;gap:16px}
  .g2{grid-template-columns:1fr 1fr}
  .g3{grid-template-columns:1.55fr 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}
  .sectionlabel{font-size:11.5px;letter-spacing:.12em;text-transform:uppercase;color:var(--soft);font-weight:700;margin:24px 2px 12px}
  .funnel{display:flex;gap:9px;align-items:stretch}
  .fstep{flex:1;border:1px solid var(--line);border-radius:11px;padding:13px 12px;position:relative;text-align:center;background:#fbfcfe}
  .fstep.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}
  .fstep.clickable:hover{border-color:#c7d0e8;box-shadow:0 3px 10px rgba(20,30,60,.09);transform:translateY(-1px)}
  .fstep.active{border-color:var(--brand);background:#eef1fb;box-shadow:0 0 0 1px var(--brand) inset}
  .boardfilter{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);margin:0 0 10px;padding:7px 11px;background:#eef1fb;border:1px solid #d7deef;border-radius:8px}
  .boardfilter b{color:#28304a}
  .boardfilter .clearf{margin-left:auto;border:1px solid #c7d0e8;background:#fff;color:#3b5bdb;border-radius:7px;padding:3px 10px;font-size:12px;font-weight:600;cursor:pointer}
  .boardfilter .clearf:hover{background:#f1f4ff}
  .fstep .fn{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--muted);font-weight:600}
  .fstep .fv{font-size:26px;font-weight:770;margin-top:6px}
  .fstep .fbar{height:5px;border-radius:3px;margin-top:10px;background:linear-gradient(90deg,var(--brand),var(--brand2))}
  .fstep .drop{font-size:11px;color:var(--red);margin-top:7px;font-weight:600}
  .fstep .keep{font-size:11px;color:var(--good);margin-top:7px;font-weight:600}
  .fstep .arrow{position:absolute;right:-12px;top:50%;transform:translateY(-50%);z-index:2;color:#c5cce0;font-size:15px}
  .fstep .ssplit{display:flex;align-items:flex-start;margin-top:11px}
  .fstep .scol{flex:1}
  .fstep .scol .sl{font-size:11px;color:var(--soft);font-weight:600;line-height:1.25}
  .fstep .scol .sv{font-size:23px;font-weight:760;letter-spacing:-.02em;line-height:1;margin-top:7px;color:#1b2436}
  .fstep .scol .sv .u{font-size:11px;color:var(--soft);font-weight:600;margin-left:2px}
  .fstep .scol .sv.good{color:#2f9e44}
  .fstep .scol .sv.bad{color:#e8590c}
  .leak{display:flex;gap:10px;margin-top:12px}
  .leakbox{flex:1;border:1px solid var(--line2);border-radius:10px;padding:10px 12px;background:#f8f9fc}
  .leakbox .lt{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--soft);font-weight:600}
  .leakbox .lv{font-size:20px;font-weight:760;margin-top:4px}
  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;cursor:pointer}
  th.num,td.num{text-align:right}
  tbody tr:hover{background:#f7f9fd}
  tr.clickable{cursor:pointer}
  .lvl{display:inline-block;font-size:10.5px;font-weight:700;padding:2px 6px;border-radius:5px;background:#eef1fb;color:var(--brand)}
  .pill-state{display:inline-flex;align-items:center;gap:6px;font-weight:600;font-size:12.5px;padding:3px 9px;border-radius:999px}
  .ps-store{background:#e7f5ff;color:#1971c2}
  .ps-travel{background:#e6fcf5;color:#0ca678}
  .ps-done{background:#ebfbee;color:#2f9e44}
  .ps-idle{background:#fff4e6;color:#e8590c}
  .ps-no{background:#fff0f0;color:#e03131}
  .meter{display:inline-block;width:54px;height:7px;border-radius:4px;background:#eef1f6;vertical-align:middle;margin-left:7px;overflow:hidden}
  .meter > i{display:block;height:100%;border-radius:4px}
  .warnflag{color:var(--orange);font-weight:700}
  .badflag{color:var(--red);font-weight:700}
  .leavebtn{border:1px solid #ffd8a8;background:#fff4e6;color:#e8590c;font-weight:650;font-size:11px;padding:2px 9px;border-radius:6px;cursor:pointer;white-space:nowrap}
  .leavebtn:hover{background:#ffe8cc}
  .leavebtn:disabled{opacity:.6;cursor:default}
  .rowwarn{background:#fff9f0}
  .rowbad{background:#fff5f5}
  .bstat{display:inline-block;font-size:10.5px;font-weight:700;padding:3px 9px;border-radius:999px;white-space:nowrap}
  .bstat.ok{background:#ebfbee;color:#2f9e44}
  .bstat.warn{background:#fff4e6;color:#e8590c}
  .bstat.no{background:#fff0f0;color:#e03131}
  .bdot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:6px;vertical-align:middle}
  .ptime{display:inline-block;background:#ebfbee;color:#2f9e44;font-weight:700;font-size:11px;padding:2px 7px;border-radius:6px;font-variant-numeric:tabular-nums}
  .potime{display:inline-block;background:#ebfbee;color: #D60303A8;font-weight:700;font-size:11px;padding:2px 7px;border-radius:6px;font-variant-numeric:tabular-nums}
  td.cnt{font-weight:700;font-variant-numeric:tabular-nums}
  .cgreen{color:#2f9e44}.camber{color:#f08c00}.cred{color:#e03131}.cmuted{color:#69748c}
  tr.boardtot td{background:#f4f6fb;border-bottom:2px solid #cdd3df;font-weight:700}
  .actbtn{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:7px;border:0;cursor:pointer;color:#fff;font-size:12px;margin-left:3px}
  .actbtn.map{background:#12b886}.actbtn.view{background:#3b5bdb}
  .actbtn.edit{background:#f08c00}.actbtn.add{background:#2f9e44;font-size:15px}
  .actbtn:active{transform:translateY(1px)}
  .att{display:flex;align-items:center;gap:12px;padding:11px 12px;border:1px solid var(--line);border-radius:11px;margin-bottom:9px}
  .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}
  .att.clickable{cursor:pointer;transition:border-color .12s,box-shadow .12s}
  .att.clickable:hover{border-color:#c7d0e8;box-shadow:0 2px 8px rgba(20,30,60,.08)}
  .att .chev{color:#c2cadb;font-size:13px;margin-left:8px}
  .attrow{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}
  .attrow .att{margin-bottom:0}
  @media (max-width:1000px){.attrow{grid-template-columns:repeat(2,1fr)}}
  .barrow{display:grid;grid-template-columns:60px 1fr 90px;align-items:center;gap:11px;margin:8px 0}
  .barrow .name{font-size:13px;font-weight:600}
  .track{background:#f1f3f9;border-radius:7px;height:20px;position:relative;overflow:hidden}
  .fill{height:100%;border-radius:7px;display:flex;align-items:center;justify-content:flex-end;padding-right:6px;font-size:10.5px;color:#fff;font-weight:650;min-width:2px}
  .barrow .meta{font-size:11.5px;color:var(--muted);text-align:right}
  .donutwrap{display:flex;align-items:center;gap:20px}
  .donut{width:138px;height:138px;border-radius:50%;flex:none;position:relative;
    -webkit-mask:radial-gradient(circle 42px at center,transparent 98%,#000 100%);mask:radial-gradient(circle 42px at center,transparent 98%,#000 100%)}
  .donut .center{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;-webkit-mask:none;mask:none}
  .legend{display:flex;flex-direction:column;gap:9px;font-size:12.5px}
  .legend .it{display:flex;align-items:flex-start;gap:9px}
  .legend .it.clickable{cursor:pointer;border-radius:8px;padding:4px 6px;margin:-4px -6px;transition:background .12s}
  .legend .it.clickable:hover{background:#f1f3f9}
  .barrow.clickable{cursor:pointer}
  .barrow.clickable:hover .track{outline:2px solid #c7d0e8;outline-offset:1px;border-radius:7px}
  .donut.clickable{cursor:pointer}
  .dot{width:11px;height:11px;border-radius:3px;flex:none;margin-top:3px}
  .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}
  .util{display:flex;height:30px;border-radius:8px;overflow:hidden}
  .util div{display:flex;align-items:center;justify-content:center;font-size:11.5px;font-weight:650;color:#fff}
  .utlegend{display:flex;gap:18px;margin-top:12px;font-size:12px;color:var(--muted);flex-wrap:wrap}
  .utlegend span{display:inline-flex;align-items:center;gap:7px}
  .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}
  .callout .desc{color:var(--muted);font-size:12.5px;margin-bottom:14px}
  .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}
  .hide{display:none}
  .loading{padding:70px;text-align:center;color:var(--muted)}
  .spinner{width:30px;height:30px;border:3px solid #e3e8f5;border-top-color:var(--brand);border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 12px}
  @keyframes spin{to{transform:rotate(360deg)}}
  .modal-back{position:fixed;inset:0;background:rgba(15,22,40,.45);display:none;align-items:flex-start;justify-content:center;z-index:50;padding:40px 16px;overflow:auto}
  /* image lightbox — stacks above the journey modal */
  .img-back{position:fixed;inset:0;background:rgba(8,12,24,.82);display:none;align-items:center;justify-content:center;z-index:60;padding:30px}
  .img-back.show{display:flex}
  .img-back img{max-width:95%;max-height:92vh;border-radius:10px;box-shadow:0 16px 60px rgba(0,0,0,.5);background:#fff}
  .img-x{position:absolute;top:18px;right:22px;width:40px;height:40px;border-radius:50%;border:0;background:rgba(255,255,255,.18);color:#fff;font-size:26px;line-height:1;cursor:pointer}
  .img-x:hover{background:rgba(255,255,255,.3)}
  .modal-back.show{display:flex}
  .modal{background:#fff;border-radius:14px;max-width:780px;width:100%;padding:20px 22px;box-shadow:0 20px 60px rgba(10,20,50,.3);position:relative}
  .modal h3{margin:0 0 2px;font-size:17px;text-align:center}
  .modal > .desc{text-align:center}
  .modal .x,.rh-panel .x,.od-panel .x{position:absolute;top:14px;right:16px;cursor:pointer;color:var(--soft);font-size:22px;line-height:1;border:0;background:none}
  /* journey totals bar */
  .jstats{display:flex;gap:9px;margin:12px 0 2px;flex-wrap:wrap}
  .js{flex:1;min-width:104px;background:#f8f9fc;border:1px solid var(--line2);border-radius:10px;padding:9px 10px;text-align:center}
  .js .jv{font-size:15.5px;font-weight:760;color:var(--ink);font-variant-numeric:tabular-nums}
  .js .jl{font-size:10px;color:var(--soft);text-transform:uppercase;letter-spacing:.04em;margin-top:3px;font-weight:600}
  .btn-ok{background:var(--good);border:0;color:#fff;font-weight:650;padding:6px 12px;border-radius:7px;cursor:pointer;font-size:12px}
  /* journey timeline (exec drilldown) */
  .tl{position:relative;margin:14px 2px 4px;padding:4px 0}
  .tl::before{content:"";position:absolute;left:50%;top:6px;bottom:6px;width:2px;background:#e9edf5;transform:translateX(-50%)}
  .tlgap{position:relative;display:flex;justify-content:center;margin:-3px 0}
  .tlgap .gappill{background:#fff;border:1px solid var(--line);border-radius:999px;padding:3px 11px;font-size:11px;font-weight:600;color:var(--muted);z-index:2;box-shadow:0 1px 2px rgba(20,30,60,.05);font-variant-numeric:tabular-nums}
  .tlgap .gappill.overrun{border-color:var(--red);color:var(--red)}
  .tlrow{position:relative;display:flex;justify-content:space-between;align-items:flex-start;margin:14px 0}
  .tlrow .node{position:absolute;left:50%;top:8px;transform:translateX(-50%);width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:13px;z-index:2;box-shadow:0 0 0 4px #fff}
  .tlcard{width:calc(50% - 26px);background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 2px 10px rgba(20,30,60,.07);display:flex;overflow:hidden}
  .tlrow.left .tlcard{flex-direction:row-reverse;text-align:right}
  .tlrow.right .tlcard{flex-direction:row;text-align:left}
  /* remark on the opposite half, hugging the centre line */
  .tlremark{width:calc(50% - 26px);display:flex;align-items:flex-start;padding-top:6px}
  .tlrow.right .tlremark{justify-content:flex-end}
  .tlrow.left .tlremark{justify-content:flex-start}
  .tlremark .rk{max-width:100%;background:#fbfcfe;border:1px solid var(--line2);border-left:3px solid #c7d0e8;border-radius:8px;padding:7px 10px;font-size:11.5px;color:#4a5468;line-height:1.45;word-break:break-word}
  .tlrow.right .tlremark .rk{text-align:right}
  .tlrow.left .tlremark .rk{text-align:left}
  .tlremark .rkl{font-size:9px;text-transform:uppercase;letter-spacing:.05em;color:var(--soft);font-weight:700;margin-bottom:3px}
  .tlremark .rkhist{display:inline-block;margin-top:6px;background:none;border:0;padding:0;color:var(--brand);font-size:10.5px;font-weight:700;cursor:pointer}
  .tlremark .rkhist:hover{text-decoration:underline}
  /* past-discussions drawer */
  .rh-back{position:fixed;inset:0;background:rgba(15,22,40,.42);z-index:1200;display:none}
  .rh-back.show{display:block}
  .rh-panel{position:absolute;top:0;right:0;height:100%;width:min(400px,92vw);background:#fff;box-shadow:-8px 0 30px rgba(20,30,60,.18);display:flex;flex-direction:column;padding:18px 18px 14px;transform:translateX(100%);transition:transform .22s ease}
  .rh-back.show .rh-panel{transform:translateX(0)}
  .rh-panel h3{margin:0 0 2px;font-size:15px;color:var(--ink)}
  .rh-panel .desc{margin:0;font-size:12px;color:var(--soft)}
  .rh-list{flex:1;overflow-y:auto;margin-top:12px;display:flex;flex-direction:column;gap:9px}
  .rhitem{background:#fbfcfe;border:1px solid var(--line2);border-left:3px solid #c7d0e8;border-radius:9px;padding:9px 11px}
  .rhtop{display:flex;justify-content:space-between;align-items:center;gap:8px}
  .rhdate{font-size:11px;font-weight:700;color:var(--muted);font-variant-numeric:tabular-nums}
  .rhb{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;padding:1px 6px;border-radius:5px;white-space:nowrap}
  .rhb.ok{background:#e7f7ec;color:#1a7a3c}
  .rhb.def{background:#fff4e6;color:#e8590c}
  .rhexec{font-size:10px;color:var(--soft);font-weight:600;margin:3px 0 4px}
  .rhtext{font-size:12px;color:#4a5468;line-height:1.45;word-break:break-word;white-space:pre-wrap}
  .rhloading,.rhempty{color:var(--soft);font-size:12px;text-align:center;padding:24px 8px}
  .rh-more{margin-top:10px;background:var(--brand);color:#fff;border:0;border-radius:8px;padding:9px;font-weight:650;font-size:12.5px;cursor:pointer;display:none}
  .rh-more:disabled{opacity:.6;cursor:default}
  /* orders drawer (stacks above the remark drawer) */
  .od-back{position:fixed;inset:0;background:rgba(15,22,40,.42);z-index:1300;display:none}
  .od-back.show{display:block}
  .od-panel{position:absolute;top:0;right:0;height:100%;width:min(440px,94vw);background:#fff;box-shadow:-8px 0 30px rgba(20,30,60,.18);display:flex;flex-direction:column;padding:18px 18px 14px;transform:translateX(100%);transition:transform .22s ease}
  .od-back.show .od-panel{transform:translateX(0)}
  .od-panel h3{margin:0 0 2px;font-size:15px;color:var(--ink)}
  .od-panel .desc{margin:0;font-size:12px;color:var(--soft)}
  .od-body{flex:1;overflow-y:auto;margin-top:12px}
  .odorder{border:1px solid var(--line);border-radius:11px;padding:11px;margin-bottom:12px;box-shadow:0 1px 2px rgba(20,30,60,.04)}
  .odorder .odsum{margin-bottom:8px}
  .odsum{display:flex;flex-wrap:wrap;gap:8px 18px;padding:10px 12px;background:#fbfcfe;border:1px solid var(--line2);border-radius:9px;margin-bottom:12px}
  .odsum .k{font-size:9px;text-transform:uppercase;letter-spacing:.05em;color:var(--soft);font-weight:700}
  .odsum .v{font-size:13px;font-weight:700;color:var(--ink);font-variant-numeric:tabular-nums}
  .odtable{width:100%;border-collapse:collapse;font-size:11.5px}
  .odtable th{text-align:left;color:var(--soft);font-weight:700;font-size:9px;text-transform:uppercase;letter-spacing:.03em;padding:5px 6px;border-bottom:1px solid var(--line2)}
  .odtable td{padding:6px;border-bottom:1px solid #eef1f7;color:#4a5468;vertical-align:top}
  .odtable td.num{text-align:right;font-variant-numeric:tabular-nums}
  .odloading,.odempty{color:var(--soft);font-size:12px;text-align:center;padding:24px 8px}
  .tlcard .tm{flex:none;width:62px;display:flex;flex-direction:column;align-items:center;justify-content:center;color:#fff;font-weight:750;font-size:13px;padding:6px 4px;line-height:1.05}
  .tlcard .tm small{font-weight:600;font-size:8.5px;opacity:.9;text-transform:uppercase;letter-spacing:.04em;margin-top:3px}
  .tlcard .bd{padding:8px 11px;flex:1;min-width:0}
  .tlcard .bd .ti{font-size:12.5px;font-weight:700;color:var(--ink);line-height:1.25;word-break:break-word}
  .tlcard .bd .stt{display:inline-block;font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;padding:1px 6px;border-radius:5px;margin-top:5px;color:#fff}
  .tlcard .bd .stt.unplanned{background:#fff4e6;color:#e8590c;border:1px solid #ffd8a8;margin-left:5px}
  .tlcard .bd .mt{font-size:11px;color:var(--muted);margin-top:6px}
  .tlcard .bd .tlags{margin-top:6px}
  .tlag{display:inline-block;font-size:9.5px;font-weight:700;color:#5646c9;background:#eeeafc;border:1px solid #ddd5f7;border-radius:5px;padding:1px 6px;margin:2px 4px 0 0}
  .tlrow.left .tlcard .bd .tlag{margin:2px 0 0 4px}
  .tlextra{display:flex;align-items:center;gap:7px;margin-top:8px;flex-wrap:wrap}
  .tlrow.left .tlextra{justify-content:flex-end}
  .tlrow.right .tlextra{justify-content:flex-start}
  .tlthumb{width:46px;height:46px;border-radius:8px;object-fit:cover;border:1px solid var(--line);cursor:pointer;background:#f1f3f9}
  .tlph{width:46px;height:46px;border-radius:8px;border:1px dashed #cfd6e6;background:#f4f6fb;display:flex;align-items:center;justify-content:center;color:#b3bcce;font-size:18px}
  .tlchip{font-size:10.5px;font-weight:600;color:var(--muted);background:#f1f3f9;border-radius:6px;padding:2px 7px;white-space:nowrap}
  .tlbadge{font-size:10.5px;font-weight:700;border:0;border-radius:6px;padding:2px 8px;white-space:nowrap;cursor:pointer;line-height:1.5}
  .tlbadge.ord{background:#e7f0ff;color:#1c56c9}
  .tlbadge.ord:hover{background:#d4e4ff}
  .tlbadge.sch{background:#fff4e6;color:#c25709;cursor:default}
  .exectabs{display:flex;gap:6px;justify-content:center;margin:12px 0 4px}
  .exectab{padding:6px 14px;border-radius:8px;font-size:12.5px;font-weight:650;color:var(--muted);cursor:pointer;border:1px solid var(--line);background:#fff}
  .exectab.active{background:var(--brand);color:#fff;border-color:var(--brand)}
  #bjMap{width:100%;height:460px;border-radius:12px;border:1px solid var(--line);margin-top:10px;background:#eef1f7;overflow:hidden}
  .bjlegend{display:flex;gap:16px;align-items:center;flex-wrap:wrap;margin-top:12px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;background:#f8f9fc;font-size:12.5px;min-height:20px}
  .bjlegend .lg{font-weight:700}
  .bjlegend .sw{display:inline-block;width:24px;vertical-align:middle;margin-right:7px}
  .bjlegend .ln{border-top:4px solid #e03131}
  .bjlegend .dt{border-top:4px dotted #2f9e44}
  .valwrap{display:flex;justify-content:center;margin:14px 0 6px}
  .valimg{max-width:100%;max-height:440px;border-radius:12px;border:1px solid var(--line);cursor:zoom-in}
  .valph{width:100%;padding:48px;text-align:center;color:var(--soft);border:1px dashed #cfd6e6;border-radius:12px;background:#f4f6fb;font-size:14px}
  .valactions{display:flex;justify-content:center;gap:10px;margin-top:8px}
  @media (max-width:1000px){.kpis{grid-template-columns:repeat(3,1fr)}.g2,.g3{grid-template-columns:1fr}.funnel{flex-wrap:wrap}.fstep{min-width:46%}.fstep .arrow{display:none}}
  @media (max-width:560px){.tl::before{left:20px}.tlrow.left,.tlrow.right{justify-content:flex-end}.tlrow .node{left:20px}.tlcard{width:calc(100% - 44px)}.tlrow.left .tlcard{flex-direction:row;text-align:left}.tlremark{display:none}}
</style>
</head>
<body>
<div class="wrap">
  <header class="top">
    <div class="brand">
      <div class="crumb"><a href="${rc.contextPath}/dashboard">&larr; Dashboard</a> &middot; Field Sales &middot; Beat / Monthly PJP</div>
      <h1>Beat Journey <span class="live"><i></i>Live</span></h1>
    </div>
    <div class="hd-right">
      <select class="ctl" id="bj-level">
        <option value="">All levels below me</option>
        #foreach($lvl in $escalationTypes)
          <option value="$lvl">$lvl</option>
        #end
      </select>
      #if($topLevel)
      <select class="ctl hide" id="bj-user">
        <option value="">All users at level</option>
      </select>
      #end
      <input class="ctl" type="date" id="bj-date" value="$today">
      <span id="bj-period-range" class="hide">
        <input class="ctl" type="date" id="bj-start" value="$monthStart">
        <input class="ctl" type="date" id="bj-end" value="$today">
      </span>
      <button class="btn-r" id="bj-apply">Apply</button>
      <button class="btn-r" id="bj-export" style="background:#2f9e44" title="Download an Excel report for the selected date / range">&#11015; Export Excel</button>
    </div>
  </header>

  <div class="lenses">
    <button class="lens active" data-lens="today" id="lens-today">Today (Live)</button>
    <button class="lens" data-lens="period" id="lens-period">Period (Analytics)</button>
  </div>

  <div id="bj-content"><div class="loading"><div class="spinner"></div>Loading&hellip;</div></div>
</div>

<div class="modal-back" id="bj-modal-back">
  <div class="modal" id="bj-modal"></div>
</div>

<div class="img-back" id="bj-img-back">
  <button class="img-x" id="bj-img-x" title="Close">&times;</button>
  <img id="bj-img" alt="Attachment">
</div>

<!-- past-discussions drawer — slides in from the right, above the journey modal -->
<div class="rh-back" id="bj-rh-back" onclick="if(event.target===this)closeRemarkHistory()">
  <div class="rh-panel" id="bj-rh-panel">
    <button class="x" onclick="closeRemarkHistory()">&times;</button>
    <h3 id="bj-rh-title"></h3>
    <p class="desc" id="bj-rh-sub"></p>
    <div class="rh-list" id="bj-rh-list"></div>
    <button class="rh-more" id="bj-rh-more" onclick="bjLoadRemarkHistory()">Load more</button>
  </div>
</div>

<!-- orders drawer — slides in from the right, above the remark drawer -->
<div class="od-back" id="bj-od-back" onclick="if(event.target===this)closeOrderDetail()">
  <div class="od-panel" id="bj-od-panel">
    <button class="x" onclick="closeOrderDetail()">&times;</button>
    <h3 id="bj-od-title"></h3>
    <p class="desc" id="bj-od-sub"></p>
    <div class="od-body" id="bj-od-body"></div>
  </div>
</div>

<script>
var CTX = '${rc.contextPath}';
var BASE = CTX + '/beat-journey';
var LENS = 'today';
var TODAY = '$today';
var CAN_EDIT_BEAT = $canEditBeat;

function el(id){ return document.getElementById(id); }
// The first lens reads "Today (Live)" for today's date, otherwise it shows the
// selected date (the tab is still the live/single-day view, just for that day).
function fmtDateLabel(d){
  var p=(d||'').split('-'); if(p.length!==3) return d;
  var mo=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  return parseInt(p[2],10)+' '+(mo[parseInt(p[1],10)-1]||p[1])+' '+p[0];
}
function updateTodayLabel(){
  var b=el('bj-date'), lbl=el('lens-today'); if(!lbl) return;
  var d=b?b.value:'';
  lbl.innerHTML = (!d || d===TODAY) ? 'Today (Live)' : esc(fmtDateLabel(d));
}
function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
function num(n){ return (n==null?0:n).toLocaleString(); }
function adhColor(p){ if(p>=80)return '#2f9e44'; if(p>=60)return '#f08c00'; if(p>=40)return '#e8590c'; return '#e03131'; }
function pct(a,b){ return b? Math.round(100*a/b):0; }
function qs(){
  var lvl = el('bj-level').value;
  var s = '';
  if(lvl) s += '&escalationType=' + encodeURIComponent(lvl);
  var usr = el('bj-user');           // only present for L5/Final
  if(usr && usr.value) s += '&teamOfAuthUserId=' + encodeURIComponent(usr.value);
  return s;
}
// L5/Final: when a level is picked, list its users so a specific manager's team
// can be selected. Selecting a user scopes the whole view to that user's team.
function onLevelChange(){
  var usr = el('bj-user');
  if(!usr){ load(); return; }       // not top-level: just reload on level change
  var lvl = el('bj-level').value;
  usr.innerHTML = '<option value="">All users at level</option>';
  if(!lvl){ usr.classList.add('hide'); load(); return; }
  fetch(BASE + '/users?escalationType=' + encodeURIComponent(lvl), {headers:{'Accept':'application/json'}})
    .then(function(r){ return r.json(); })
    .then(function(d){
      var us = d.users || [];
      var h = '<option value="">All ' + esc(lvl) + ' users</option>';
      us.forEach(function(u){ h += '<option value="' + u.id + '">' + esc(u.name) + '</option>'; });
      usr.innerHTML = h;
      usr.classList.toggle('hide', us.length === 0);
      load();
    })
    .catch(function(){ usr.classList.add('hide'); load(); });
}
function spinner(){ el('bj-content').innerHTML = '<div class="loading"><div class="spinner"></div>Loading&hellip;</div>'; }
function fail(e){ el('bj-content').innerHTML = '<div class="loading">Could not load data ('+esc(e&&e.message||e)+'). Are you signed in?</div>'; }

function setLens(name){
  LENS = name;
  var tabs = document.querySelectorAll('.lens');
  for(var i=0;i<tabs.length;i++){ tabs[i].classList.toggle('active', tabs[i].getAttribute('data-lens')===name); }
  el('bj-date').classList.toggle('hide', name!=='today');
  el('bj-period-range').classList.toggle('hide', name==='today');
  load();
}
function load(){
  if(LENS==='today') return loadToday();
  if(LENS==='period') return loadPeriod();
  return loadApproval();
}

/* ============================ TODAY ============================ */
function loadToday(){
  updateTodayLabel();
  spinner();
  fetch(BASE + '/today?date=' + encodeURIComponent(el('bj-date').value) + qs(), {headers:{'Accept':'application/json'}})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(renderToday).catch(fail);
}
function kpi(ic, bg, fg, label, val, foot, valColor, click){
  return '<div class="kpi'+(click?' clickable':'')+'"'+(click?' onclick="'+click+'" title="Click for details"':'')+'><div class="top"><div class="ic" style="background:'+bg+';color:'+fg+'">'+ic+'</div>'+
    '<div class="label">'+label+'</div></div>'+
    '<div class="foot">'+foot+'</div>'+
    '<div class="val"'+(valColor?' style="color:'+valColor+'"':'')+'>'+val+'</div></div>';
}
// Multi-column breakdown card: centered title, a row of sub-labels, the number under each.
// cols = [[label, value], ...]; unit (optional) is appended after each number, e.g. 'min'.
function kpiCols(ic, bg, fg, title, cols, fg2, click, unit){
  var lab='', val='', u=unit?' <small>'+unit+'</small>':'';
  for(var i=0;i<cols.length;i++){
    var sep=i?'<span class="bsep">&middot;</span>':'';
    lab+=sep+'<div class="blab">'+cols[i][0]+'</div>';
    val+=(i?'<span class="bsep">&nbsp;</span>':'')+'<div class="bval"'+(fg2?' style="color:'+fg2+'"':'')+'>'+num(cols[i][1])+u+'</div>';
  }
  return '<div class="kpi kpicols'+(click?' clickable':'')+'"'+(click?' onclick="'+click+'" title="Click for details"':'')+'>'+
    '<div class="top"><div class="ic" style="background:'+bg+';color:'+fg+'">'+ic+'</div><div class="label">'+title+'</div></div>'+
    '<div class="brow blabs">'+lab+'</div>'+
    '<div class="brow bvals">'+val+'</div></div>';
}
// Period journey summary as a row of cards (old funnel layout). Each card is a
// group (Total Visits / Avg Time Spent / Idle-Break / Deferred / Completed),
// planned and self-assigned merged into one value. col=[[label,value,colorClass],...].
function summaryCard(title, cols, last){
  var body='';
  for(var i=0;i<cols.length;i++){
    body+='<div class="scol"><div class="sl">'+cols[i][0]+'</div>'+
          '<div class="sv'+(cols[i][2]?' '+cols[i][2]:'')+'">'+cols[i][1]+'</div></div>';
  }
  return '<div class="fstep"><div class="fn">'+title+'</div><div class="ssplit">'+body+'</div>'+
    (last?'':'<span class="arrow">&#10148;</span>')+'</div>';
}
function summaryCards(s){
  if(!s) return '';
  var mn=function(v){return num(v)+'<span class="u">min</span>';};
  // planned + self-assigned merged into single totals
  var totalVisits=(s.plannedVisits||0)+(s.selfVisits||0);
  var completed=(s.completedPlanned||0)+(s.completedSelf||0);
  var deferred=(s.deferredPlanned||0)+(s.deferredSelf||0);
  return summaryCard('Total Visits',[['Visits',num(totalVisits),'']])+
    summaryCard('Average Time Spent',[['Per visit',mn(s.avgTimeAllMin),'']])+
    summaryCard('Idle / Break',[['Total Average',mn(s.idleAvgMin),'']])+
    summaryCard('Completed Visits',[['Completed',num(completed),'good']])+
    summaryCard('Deferred',[['Deferred',num(deferred),deferred>0?'bad':'']],true);
}
function fstep(name, val, w, sub, drop, last, key){
  return '<div class="fstep'+(key?' clickable" data-fkey="'+key+'" onclick="funnelClick(\''+key+'\')" title="Click to filter the board to these executives':'')+'"><div class="fn">'+name+'</div><div class="fv">'+num(val)+'</div>'+
    '<div class="fbar" style="width:'+Math.min(w,100)+'%"></div><div class="'+(drop?'drop':'keep')+'">'+sub+'</div>'+
    (last?'':'<span class="arrow">&#10148;</span>')+'</div>';
}
// Funnel drop sub-text: positive = fell out (red); negative = above planned
// (leads push visits past planned stops) shown green; zero = on plan.
function fdrop(p, badLabel){
  if(p>0) return '&minus;'+p+'% '+badLabel;
  if(p<0) return '+'+(-p)+'% above planned';
  return 'on plan';
}
function leakbox(t, v, color){ return '<div class="leakbox"><div class="lt">'+t+'</div><div class="lv"'+(color?' style="color:'+color+'"':'')+'>'+num(v)+'</div></div>'; }

function renderToday(d){
  var k=d.kpis, f=d.funnel, s=d.stops, a=d.attention;
  window._canApprove = !!d.canApprove;
  window._canMarkLeave = !!d.canMarkLeave;
  window._mediaUrl = d.mediaUrl || window._mediaUrl || '';
  window._board = d.board || [];          // funnel drill-down filters this
  window._boardDate = d.date || '';
  window._leadsList = d.leadsList || [];  // leads drill-down
  window._execList = d.execList || [];    // main-card drill-downs
  var h='';
  h+='<div class="kpis">';
  h+=kpi('&#128101;','#eef1fb','#3b5bdb','Total Executives',num(k.totalExecs),'in your team',null,"openCards('total')");
  h+=kpi('&#128197;','#ebfbee','#2f9e44','Scheduled PJP',num(k.scheduledPjp)+' <small>/'+k.totalExecs+'</small>',k.unscheduled+' unscheduled',null,"openCards('scheduled')");
  h+=kpi('&#9998;','#fff4e6','#e8590c','Agenda Filled',num(k.agendaFilled)+' <small>/'+k.scheduledPjp+'</small>',(k.scheduledPjp-k.agendaFilled)+' pending',null,"openCards('agenda')");
  h+=kpi('&#10060;','#fff0f6','#d6336c','Unscheduled',num(k.unscheduled),'no PJP today',null,"openCards('unscheduled')");
  h+='</div>';

  h+='<div class="card"><h2>Needs attention now</h2><p class="desc">Things a manager should clear today.</p>'+attentionList(a)+'</div>';

  h+='<div class="sectionlabel">Today\'s Journey Funnel</div><div class="card"><div class="funnel">';
  var sp=f.scheduledPjp||1, pin=f.punchedIn||1;
  h+=fstep('Punched In',f.punchedIn,pct(f.punchedIn,sp),f.punchedIn+' of '+f.scheduledPjp+' scheduled',false,false,'punchedIn');
  h+=fstep('Traveling',f.travelling,pct(f.travelling,pin),'on the road',false,false,'travelling');
  h+=fstep('In Store',f.inStore,pct(f.inStore,pin),'at a stop',false,false,'inStore');
  h+=fstep('Idle / Break',f.idle,pct(f.idle,pin),'&lt; 1 km in 15 min',true,false,'idle');
  h+=fstep('Punched Out',f.punchedOut,pct(f.punchedOut,pin),'journey ended',false,true,'punchedOut');
  h+='</div></div>';

  window._boardFilter = null;             // funnel-card filter (null = all rows)
  h+='<div class="card"><h2>Live executive board</h2><p class="desc">Each executive\'s journey right now. Click a row for the day\'s visit detail.</p><div id="bj-board">'+boardCard()+'</div></div>';
  el('bj-content').innerHTML=h;
}
function stateClass(st){ return st==='IN_STORE'?'ps-store':st==='TRAVELLING'?'ps-travel':st==='DONE'?'ps-done':st==='NOT_STARTED'?'ps-no':'ps-idle'; }
function js(s){ return String(s==null?'':s).replace(/\\/g,'\\\\').replace(/'/g,"\\'"); }
// Open the Beat Planner (map-first planner window) for this executive/beat/day,
// in a new tab. Edit pre-selects the beat; add opens it to assign/add a visit.
function openPlanner(authUserId, beatId, date, mode){
  var u = CTX + '/beatPlanWindow?autoUserId=' + encodeURIComponent(authUserId) + '&editDate=' + encodeURIComponent(date);
  if(beatId && beatId>0) u += '&editBeatId=' + encodeURIComponent(beatId);
  if(mode==='add') u += '&assign=1';
  window.open(u, '_blank');
}
// Funnel-card click: period cards (p_*) open their drill-down popup; today's
// funnel cards filter the Live executive board in place. Clicking the active
// card again clears the filter.
function funnelClick(key){
  if(key && key.indexOf('p_')===0) return openFunnel(key);
  setBoardFilter(window._boardFilter===key ? null : key);
}
// Apply / clear the funnel filter and re-render just the board card. Also marks
// the active funnel card so it's clear which cohort the board is showing.
function setBoardFilter(key){
  window._boardFilter = key || null;
  var c=el('bj-board'); if(c) c.innerHTML=boardCard();
  document.querySelectorAll('.fstep[data-fkey]').forEach(function(s){
    s.classList.toggle('active', !!key && s.getAttribute('data-fkey')===key);
  });
}
// Board card content: an optional "filtered by …" bar plus the table, showing
// only the rows that reached the selected funnel stage (Scheduled = all rows).
function boardCard(){
  var rows=window._board||[], date=window._boardDate||'', key=window._boardFilter;
  var view=rows, m=key?FUNNEL_META[key]:null;
  if(m) view=rows.filter(m.f);
  var bar='';
  if(m){
    bar='<div class="boardfilter">Showing <b>'+esc(m.title)+'</b> &middot; '+view.length+
        ' of '+rows.length+'<button class="clearf" onclick="setBoardFilter(null)">&times; Clear filter</button></div>';
  }
  return bar+boardTable(view, date);
}
// Merge planned partner visits and self-assigned leads into one set of tallies.
// Total reconciles with the parts: Total = Completed + Pending + Deferred, where
// Total is the plan (or activity total if it ran past the plan).
function boardCounts(r){
  var completed=r.completedVisits||0, deferred=r.deferred||0;
  var total=Math.max(r.planned||0, completed+deferred);
  return {total:total, completed:completed, deferred:deferred, pending:total-completed-deferred};
}
// seconds -> compact "1h 20m" / "45m" for the board's time columns.
function bhm(sec){ sec=Math.max(0,Math.round(sec||0)); var h=Math.floor(sec/3600), m=Math.round((sec%3600)/60); return h?(h+'h '+m+'m'):(m+'m'); }
function boardTable(rows, date){
  if(!rows||!rows.length) return '<p class="desc">No executives scheduled or active for this date.</p>';
  var h='<div style="overflow-x:auto"><table><thead><tr>'+
    '<th>Agenda</th><th>Executive</th><th>Punch In/Out</th>'+
    '<th class="num" title="Planned partner visits + self-assigned leads">Total</th>'+
    '<th class="num">Completed</th><th class="num">Pending</th><th class="num">Deferred</th>'+
    '<th class="num" title="Transit time between stops so far today">Transit</th>'+
    '<th class="num" title="Time spent inside stores so far today">In-store</th>'+
    '<th>State</th><th>Action</th>'+
    '</tr></thead><tbody>';
  // column totals, computed up front so the Total row can lead the table
  var t={total:0,completed:0,pending:0,deferred:0,transit:0,inStore:0};
  rows.forEach(function(r){
    var c=boardCounts(r);
    t.total+=c.total; t.completed+=c.completed; t.pending+=c.pending; t.deferred+=c.deferred;
    t.transit+=(r.transitSecs||0); t.inStore+=(r.inStoreSecs||0);
  });
  h+='<tr class="boardtot">'+
     '<td></td><td><b>Total</b><br><span style="color:#97a1b5;font-size:11px">'+rows.length+' executives</span></td><td></td>'+
     '<td class="num cnt cmuted">'+t.total+'</td>'+
     '<td class="num cnt cgreen">'+t.completed+'</td>'+
     '<td class="num cnt">'+t.pending+'</td>'+
     '<td class="num cnt camber">'+t.deferred+'</td>'+
     '<td class="num cnt cmuted">'+bhm(t.transit)+'</td>'+
     '<td class="num cnt cmuted">'+bhm(t.inStore)+'</td><td></td><td></td>'+
     '</tr>';
  rows.forEach(function(r){
    var rowcls = r.state==='NOT_STARTED' ? 'rowbad' : (r.idleAway?'rowwarn':'');
    var A = r.userId+",'"+js(r.name)+"','"+date+"'";   // openExec args
    var go = 'onclick="openExec('+A+')"';
    var c=boardCounts(r);
    h+='<tr class="clickable '+rowcls+'" '+go+'>'+
       '<td style="text-align:center">'+(r.agendaFilled?'<span style="color:#2f9e44;font-size:15px">&#10003;</span>':'<span class="badflag" style="font-size:15px">&#10007;</span>')+'</td>'+
       '<td><b>'+esc(r.name)+'</b><br>'+esc(r.beatName||'-')+'</td>'+
       '<td style="white-space:nowrap">'+(r.punchInTime?'<span class="ptime">'+esc(r.punchInTime)+'</span>':'<span class="badflag">-</span>')+
         ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOutTime?esc(r.punchOutTime):'--')+'</span></td>'+
       '<td class="num cnt cmuted">'+c.total+'</td>'+
       '<td class="num cnt cgreen">'+c.completed+'</td>'+
       '<td class="num cnt">'+c.pending+'</td>'+
       '<td class="num cnt camber">'+c.deferred+'</td>'+
       '<td class="num cnt cmuted">'+(r.transitSecs?bhm(r.transitSecs):'<span style="color:#c5cce0">&mdash;</span>')+'</td>'+
       '<td class="num cnt cmuted">'+(r.inStoreSecs?bhm(r.inStoreSecs):'<span style="color:#c5cce0">&mdash;</span>')+'</td>'+
       '<td><span class="pill-state '+stateClass(r.state)+'">'+esc(r.stateLabel)+'</span></td>'+
       '<td style="white-space:nowrap" onclick="event.stopPropagation()">'+
         '<button class="actbtn map" title="Live location" onclick="openExec('+A+',\'map\')">&#128205;</button>'+
         '<button class="actbtn view" title="Journey detail" onclick="openExec('+A+')">&#128065;</button>'+
         (CAN_EDIT_BEAT
           ? '<button class="actbtn edit" title="Edit beat in Beat Planner" onclick="openPlanner('+r.authUserId+','+(r.beatId||0)+',\''+date+'\',\'edit\')">&#9998;</button>'+
             '<button class="actbtn add" title="Assign / add visit in Beat Planner" onclick="openPlanner('+r.authUserId+','+(r.beatId||0)+',\''+date+'\',\'add\')">&#43;</button>'
           : '')+
       '</td></tr>';
  });
  return h+'</tbody></table></div>';
}
// Funnel drill-down: each stage shows the executives who reached it AND the
// drop-off cohort that fell out at this step (the "−N …" sub-line). Filters
// mirror the backend funnel conditions exactly (rows carry the per-stage flags).
var FUNNEL_META = {
  punchedIn:  {title:'Punched In',   desc:'Started the day (punch-in recorded)', f:function(r){ return r.punchedIn; }},
  travelling: {title:'Traveling',    desc:'On the road between stops',           f:function(r){ return r.state==='TRAVELLING'; }},
  inStore:    {title:'In Store',     desc:'Currently checked in at a stop',      f:function(r){ return r.state==='IN_STORE'; }},
  idle:       {title:'Idle / Break', desc:'Punched in but < 1 km covered in the last 15 min', f:function(r){ return r.state==='IDLE'; }},
  punchedOut: {title:'Punched Out',  desc:'Ended the day (punch-out recorded)',  f:function(r){ return r.punchedOut; }}
};
function funnelRows(list, date){
  if(!list.length) return '<p class="desc">None.</p>';
  var h='<table><thead><tr><th>Executive / Beat</th><th>Punch In/Out</th><th class="num">Completed</th><th class="num">Planned</th><th>State</th></tr></thead><tbody>';
  list.slice().sort(function(a,b){ return (''+a.name).localeCompare(b.name); }).forEach(function(r){
    var A=r.userId+",'"+js(r.name)+"','"+date+"'";
    h+='<tr class="clickable" onclick="openExec('+A+')">'+
       '<td><b>'+esc(r.name)+'</b><br><span style="color:#97a1b5;font-size:11px">'+esc(r.beatName||'-')+'</span></td>'+
       '<td style="white-space:nowrap">'+(r.punchInTime?'<span class="ptime">'+esc(r.punchInTime)+'</span>':'<span class="badflag">-</span>')+
         ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOutTime?esc(r.punchOutTime):'--')+'</span></td>'+
       '<td class="num cnt cgreen">'+r.completedVisits+'</td>'+
       '<td class="num">'+r.planned+'</td>'+
       '<td><span class="pill-state '+stateClass(r.state)+'">'+esc(r.stateLabel)+'</span></td></tr>';
  });
  return h+'</tbody></table>';
}
function openFunnel(key){
  if(key && key.indexOf('p_')===0) return openPFunnel(key);   // period funnel
  var m=FUNNEL_META[key]; if(!m) return;
  var board=window._board||[], date=window._boardDate||'';
  var reached=board.filter(m.f);
  var dropped=m.drop ? board.filter(m.drop) : [];
  var mb=el('bj-modal-back'), md=el('bj-modal');
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(m.title)+'</h3>'+
        '<p class="desc">'+reached.length+' '+(reached.length===1?'executive':'executives')+' &middot; '+esc(m.desc)+'</p>'+
        funnelRows(reached, date);
  if(m.drop){
    h+='<div class="sectionlabel" style="margin-top:18px;color:#e8590c">'+esc(m.dropLabel)+' &middot; '+dropped.length+'</div>'+
       funnelRows(dropped, date);
  }
  h+='<p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
  md.innerHTML=h; mb.classList.add('show');
}
// Main-card drill-downs: roster of executives behind each top KPI card.
// 'drop' (optional) adds a second, highlighted section for the complementary
// cohort — e.g. who's scheduled but hasn't filled the agenda.
var CARD_META = {
  total:       {title:'Total Executives', desc:'Everyone in your team',        f:function(r){ return true; }},
  scheduled:   {title:'Scheduled PJP',     desc:'Executives with a beat today', f:function(r){ return r.hasBeat; }},
  agenda:      {title:'Agenda Filled',     desc:'Beats with the agenda filled', f:function(r){ return r.agendaFilled; },
                dropLabel:'Agenda not filled (scheduled)', drop:function(r){ return r.hasBeat && !r.agendaFilled; }},
  unscheduled: {title:'Unscheduled',       desc:'No PJP scheduled today',       f:function(r){ return !r.hasBeat && !r.onLeave; }}
};
// Renders an executive roster table (used by the card drill-downs).
function execRows(list, date){
  if(!list.length) return '<p class="desc">None.</p>';
  var h='<table><thead><tr><th>Executive</th><th>Beat</th><th>Agenda</th><th>Status</th></tr></thead><tbody>';
  list.forEach(function(r){
    var A=r.userId+",'"+js(r.name)+"','"+date+"'";
    var go = r.userId ? ' class="clickable" onclick="openExec('+A+')"' : '';
    var agenda = !r.hasBeat ? '<span style="color:#97a1b5">&mdash;</span>'
      : (r.agendaFilled ? '<span style="color:#2f9e44">&#10003;</span>' : '<span class="badflag">&#10007;</span>');
    // Execs who aren't clearly working today can be marked on leave: agenda not
    // filled or not punched in (covers unscheduled). Manager / super-user only;
    // server-enforced. Already-on-leave rows show no button.
    var leaveBtn = (window._canMarkLeave && r.authUserId && !r.onLeave && (!r.agendaFilled || !r.punchedIn))
      ? ' <button class="leavebtn" onclick="event.stopPropagation();markLeave('+r.authUserId+",'"+js(r.name)+"',this)\">Mark leave</button>" : '';
    h+='<tr'+go+'>'+
       '<td><b>'+esc(r.name)+'</b></td>'+
       '<td>'+esc(r.beatName||'-')+'</td>'+
       '<td style="text-align:center">'+agenda+'</td>'+
       '<td>'+esc(r.statusLabel||'')+leaveBtn+'</td></tr>';
  });
  return h+'</tbody></table>';
}
function openCards(key){
  var m=CARD_META[key]; if(!m) return;
  window._openCardKey=key;   // remembered so markLeave can re-render the same view
  var all=(window._execList||[]), date=window._boardDate||'';
  var list=all.filter(m.f);
  var dropped=m.drop ? all.filter(m.drop) : [];
  var mb=el('bj-modal-back'), md=el('bj-modal');
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(m.title)+'</h3>'+
        '<p class="desc">'+list.length+' '+(list.length===1?'executive':'executives')+' &middot; '+esc(m.desc)+'</p>'+
        execRows(list, date);
  if(m.drop){
    h+='<div class="sectionlabel" style="margin-top:18px;color:#e8590c">'+esc(m.dropLabel)+' &middot; '+dropped.length+'</div>'+
       execRows(dropped, date);
  }
  h+='<p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
  md.innerHTML=h; mb.classList.add('show');
}
// Leads drill-down: lists every lead visit logged today (matches the KPI count).
function openLeads(){
  var list=window._leadsList||[], date=window._boardDate||'';
  var mb=el('bj-modal-back'), md=el('bj-modal');
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Leads on route</h3>'+
        '<p class="desc">'+list.length+' lead '+(list.length===1?'visit':'visits')+' logged'+(date?' on '+esc(date):'')+'</p>';
  if(!list.length){ h+='<p class="desc">No leads logged for this date.</p>'; }
  else {
    h+='<table><thead><tr><th>Executive</th><th>Lead</th><th>Check-in</th><th>Status</th></tr></thead><tbody>';
    list.slice().sort(function(a,b){ return (''+a.exec).localeCompare(b.exec); }).forEach(function(r){
      var A=r.userId+",'"+js(r.exec)+"','"+date+"'";
      var go = r.userId ? ' class="clickable" onclick="openExec('+A+')"' : '';
      h+='<tr'+go+'>'+
         '<td><b>'+esc(r.exec)+'</b></td>'+
         '<td>'+esc(r.lead||'-')+'</td>'+
         '<td style="white-space:nowrap">'+(r.checkInTime?'<span class="ptime">'+esc(hhmm(r.checkInTime))+'</span>':'<span class="badflag">-</span>')+'</td>'+
         '<td>'+esc(r.status||'')+'</td></tr>';
    });
    h+='</tbody></table><p class="desc" style="margin-top:10px">Click a row to open that executive\'s journey detail.</p>';
  }
  md.innerHTML=h; mb.classList.add('show');
}
/* ===================== PERIOD (ANALYTICS) DRILL-DOWNS ===================== */
function pModal(html){ el('bj-modal').innerHTML=html; el('bj-modal-back').classList.add('show'); }
function pRange(){ return (el('bj-start')?el('bj-start').value:'')+' to '+(el('bj-end')?el('bj-end').value:''); }

// Scorecard list popup (used by KPI cards + funnel stages). Rows drill to the
// executive's day-by-day. sortKey sorts descending.
function openPScore(sortKey, title, desc){
  var rows=(((window._period||{}).scorecard)||[]).slice();
  if(sortKey) rows.sort(function(a,b){ return (b[sortKey]||0)-(a[sortKey]||0); });
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(title)+'</h3>'+
    '<p class="desc">'+esc(desc)+' &middot; '+esc(pRange())+' &middot; click a row for the day-by-day</p>'+pScoreTable(rows));
}
function pScoreTable(rows){
  if(!rows.length) return '<p class="desc">No executives in scope.</p>';
  var h='<table><thead><tr><th>Executive</th><th class="num">Plan</th><th class="num">Done</th><th class="num">Adher.</th>'+
    '<th class="num" title="Avg lead visits per active (punched-in) day">Lead/day</th>'+
    '<th class="num" title="Avg franchisee visits per active (punched-in) day">Fr/day</th>'+
    '<th class="num">Disc.</th><th class="num">Hrs</th><th class="num">Leads</th></tr></thead><tbody>';
  rows.forEach(function(r){
    var c=adhColor(r.adherencePct);
    h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')">'+
       '<td><span class="lvl">'+esc(r.level)+'</span> <b>'+esc(r.name)+'</b></td>'+
       '<td class="num">'+r.planned+'</td><td class="num">'+r.done+'</td>'+
       '<td class="num"><b style="color:'+c+'">'+r.adherencePct+'%</b></td>'+
       '<td class="num">'+(r.avgLeadVisitsPerDay||'-')+'</td>'+
       '<td class="num">'+(r.avgFranchiseeVisitsPerDay||'-')+'</td>'+
       '<td class="num'+(r.discussionMin>0&&r.discussionMin<10?' warnflag':'')+'">'+(r.discussionMin||'-')+(r.discussionMin?'m':'')+'</td>'+
       '<td class="num">'+r.workingHrs+'</td><td class="num">'+r.leads+'</td></tr>';
  });
  return h+'</tbody></table>';
}
// Funnel stage → the executives behind it (the scorecard, focused).
function openPFunnel(key){
  var map={ p_planned:['planned','Planned stops','Planned partner + lead stops per executive'],
            p_punchedin:['done','Planned on punch-in days','Executives, planned vs done'],
            p_checkedin:['done','Checked in','Visits checked in per executive'],
            p_checkedout:['done','Checked out (done)','Visits completed per executive'] };
  var m=map[key]; if(m) openPScore(m[0],m[1],m[2]);
}
// Executive day-by-day (scorecard row drill). Fetches /exec-period; each day
// opens the journey detail / map modal.
function openExecPeriod(authUserId, name){
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(name)+'</h3>'+
    '<p class="desc">Day-by-day &middot; '+esc(pRange())+'</p><div class="loading"><div class="spinner"></div>Loading&hellip;</div>');
  fetch(BASE+'/exec-period?authUserId='+authUserId+'&startDate='+encodeURIComponent(el('bj-start').value)+'&endDate='+encodeURIComponent(el('bj-end').value),{headers:{'Accept':'application/json'}})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(function(d){
      var rows=d.rows||[], uid=d.userId, nm=d.name||name;
      var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(nm)+'</h3>'+
        '<p class="desc">'+rows.length+' day'+(rows.length===1?'':'s')+' &middot; '+esc(pRange())+(uid?' &middot; click a day for the journey detail':'')+'</p>';
      if(!rows.length){ h+='<p class="desc">No scheduled or active days in this range.</p>'; }
      else {
        h+='<table><thead><tr><th>Date</th><th>Punch In/Out</th><th class="num">Planned</th><th class="num">Completed</th><th class="num">Deferred</th><th class="num">Total</th></tr></thead><tbody>';
        rows.forEach(function(r){
          var go = uid ? ' class="clickable" onclick="openExec('+uid+',\''+js(nm)+'\',\''+r.date+'\')"' : '';
          h+='<tr'+go+'><td>'+esc(r.date)+'</td>'+
             '<td style="white-space:nowrap">'+(r.punchIn?'<span class="ptime">'+esc(hhmm(r.punchIn))+'</span>':'<span class="badflag">-</span>')+
               ' <span style="color:#97a1b5;font-size:11px">/ '+(r.punchOut?esc(hhmm(r.punchOut)):'--')+'</span></td>'+
             '<td class="num">'+r.planned+'</td><td class="num cnt cgreen">'+r.done+'</td>'+
             '<td class="num cnt cred">'+r.deferred+'</td><td class="num cnt cmuted">'+r.total+'</td></tr>';
        });
        h+='</tbody></table>';
      }
      el('bj-modal').innerHTML=h;
    })
    .catch(function(){ el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><p class="desc">Could not load day-by-day.</p>'; });
}
// PJP coverage drill — execs with / without a plan (optionally one level).
function openCoverage(level){
  var all=((window._period||{}).coverageDetail)||[];
  var list=level ? all.filter(function(r){ return r.level===level; }) : all;
  var without=list.filter(function(r){ return !r.hasPlan; }), withP=list.filter(function(r){ return r.hasPlan; });
  function tbl(rs){
    if(!rs.length) return '<p class="desc">None.</p>';
    var h='<table><tbody>';
    rs.forEach(function(r){ h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')"><td style="font-weight:600">'+esc(r.name)+'</td><td><span class="lvl">'+esc(r.level)+'</span></td></tr>'; });
    return h+'</tbody></table>';
  }
  pModal('<button class="x" onclick="closeModal()">&times;</button><h3>PJP coverage'+(level?' &middot; '+esc(level):'')+'</h3>'+
    '<p class="desc">'+withP.length+' of '+list.length+' have a monthly plan &middot; '+esc(pRange())+'</p>'+
    '<div class="sectionlabel" style="color:#e03131">No plan &middot; '+without.length+'</div>'+tbl(without)+
    '<div class="sectionlabel" style="color:#2f9e44;margin-top:16px">Has a plan &middot; '+withP.length+'</div>'+tbl(withP));
}
// Deferrals drill — all, or just system / genuine (from the donut segments).
function openDeferrals(filter){
  var all=((window._period||{}).deferralsList)||[];
  var list = filter==='system' ? all.filter(function(r){ return r.system; })
           : filter==='genuine' ? all.filter(function(r){ return !r.system; }) : all;
  var title = filter==='system' ? 'Deferrals — system-flagged' : filter==='genuine' ? 'Deferrals — genuine reason' : 'Deferrals';
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(title)+'</h3>'+
        '<p class="desc">'+list.length+' deferral'+(list.length===1?'':'s')+' &middot; '+esc(pRange())+'</p>';
  if(!list.length){ h+='<p class="desc">None in this range.</p>'; }
  else {
    h+='<table><thead><tr><th>Executive</th><th>Partner</th><th>Reason</th><th>Date</th><th>Status</th></tr></thead><tbody>';
    list.forEach(function(r){
      h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r.exec)+'</td>'+
         '<td>'+esc(r.partner||'-')+'</td>'+
         '<td style="color:'+(r.system?'#f08c00':'#2f9e44')+'">'+esc(r.reason||'-')+'</td>'+
         '<td style="white-space:nowrap">'+esc(r.date||'')+'</td>'+
         '<td>'+esc(r.status||'')+'</td></tr>';
    });
    h+='</tbody></table>';
  }
  pModal(h);
}
// Auto "missed" drill — the three execution-gap causes behind the card, plus
// the underlying deferral records (system-flagged "beat missed" / "no punch-in").
function openMissed(){
  var k=(window._period||{}).kpis||{};
  var rows=[
    ['Unscheduled', k.autoMissedUnscheduled||0, 'Executives (sales roles) with no PJP scheduled in this range'],
    ['Unfilled agenda', k.autoMissedUnfilledAgenda||0, 'Scheduled beat-days where the agenda was never filled'],
    ['Missed punch', k.autoMissedMissedPunchin||0, 'Scheduled beat-days the owner never punched in on']
  ];
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Auto &ldquo;missed&rdquo;</h3>'+
        '<p class="desc">Why planned execution broke down &middot; '+esc(pRange())+'</p>'+
        '<table><thead><tr><th>Cause</th><th class="num">Count</th><th>What it means</th></tr></thead><tbody>';
  rows.forEach(function(r){
    h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r[0])+'</td>'+
       '<td class="num cnt cred">'+num(r[1])+'</td>'+
       '<td style="color:#69748c">'+esc(r[2])+'</td></tr>';
  });
  h+='<tr class="boardtot"><td><b>Total</b></td><td class="num cnt"><b>'+num(k.autoMissed||0)+'</b></td><td></td></tr>';
  h+='</tbody></table>'+
     '<p class="desc" style="margin-top:12px">See also the <a href="javascript:void(0)" onclick="openDeferrals()" style="color:#3b5bdb">deferral records</a> for the partner-level &ldquo;beat missed&rdquo; / &ldquo;no punch-in&rdquo; entries.</p>';
  pModal(h);
}
// Leads drill (period) — every lead created in the range.
function openPLeads(){
  var list=((window._period||{}).leadsList)||[];
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>Leads on route</h3>'+
        '<p class="desc">'+list.length+' lead'+(list.length===1?'':'s')+' created &middot; '+esc(pRange())+'</p>';
  if(!list.length){ h+='<p class="desc">No leads created in this range.</p>'; }
  else {
    h+='<table><thead><tr><th>Executive</th><th>Lead</th><th>City</th><th>Date</th><th>Status</th></tr></thead><tbody>';
    list.forEach(function(r){
      h+='<tr><td style="font-weight:600;white-space:nowrap">'+esc(r.exec)+'</td>'+
         '<td>'+esc(r.lead||'-')+'</td><td>'+esc(r.city||'')+'</td>'+
         '<td style="white-space:nowrap">'+esc(r.date||'')+'</td><td>'+esc(r.status||'')+'</td></tr>';
    });
    h+='</tbody></table>';
  }
  pModal(h);
}
function names(list,n){ if(!list||!list.length) return 'None'; var s=list.slice(0,n).join(', '); if(list.length>n) s+=' +'+(list.length-n); return s; }
var ATT_META = {
  notPunchedIn:    {bg:'#fff0f0', fg:'#e03131', ic:'&#9888;',   title:'Not punched in',                  sub:'executives with a beat, not started', cls:'badflag'},
  idleStale:       {bg:'#fff4e6', fg:'#e8590c', ic:'&#9201;',   title:'Idle &mdash; off-store &gt; 59 min', sub:'stationary &gt;20 m from any store',  cls:'warnflag'},
  geofence:        {bg:'#fff0f0', fg:'#e03131', ic:'&#128205;', title:'Check-in outside store geofence',  sub:'&gt;50 m from partner\'s saved location', cls:'badflag'},
  locationOff:     {bg:'#fff4e6', fg:'#e8590c', ic:'&#128244;', title:'Location turned off mid-journey',  sub:'GPS toggled off',                     cls:'warnflag'},
  deferredAwaiting:{bg:'#eef1f6', fg:'#69748c', ic:'&#8635;',   title:'Deferred, awaiting re-action',     sub:'shops deferred today',                cls:''}
};
function attentionList(a){
  window._att = a;
  var order=['notPunchedIn','idleStale','geofence','locationOff','deferredAwaiting'];
  var h='<div class="attrow">';
  order.forEach(function(k){
    var m=ATT_META[k], list=a[k]||[], n=list.length;
    var detail = n ? names(list.map(function(x){return x.name;}),3) : m.sub;
    var cls = n ? ' att clickable' : ' att';
    var click = n ? ' onclick="openAttention(\''+k+'\')"' : '';
    h+='<div class="'+cls.trim()+'"'+click+'><div class="ic" style="background:'+m.bg+';color:'+m.fg+'">'+m.ic+'</div>'+
       '<div class="ab"><div class="atitle">'+m.title+'</div><div class="adet">'+detail+'</div></div>'+
       '<div class="acount '+(n?m.cls:'')+'">'+n+'</div>'+(n?'<span class="chev">&#9656;</span>':'')+'</div>';
  });
  return h+'</div>';
}
function openAttention(key){
  var a=window._att||{}, list=a[key]||[], m=ATT_META[key]||{title:'Detail'};
  var mb=el('bj-modal-back'), md=el('bj-modal');
  // Off-site check-ins can be approved here, but only by L5/Final (canApprove).
  var showApprove = (key==='geofence' && window._canApprove);
  var h='<button class="x" onclick="closeModal()">&times;</button><h3>'+m.title+'</h3>'+
        '<p class="desc">'+list.length+' '+(list.length===1?'item':'items')+
        (showApprove?' &middot; approving updates the partner\'s saved coordinates':'')+'</p>';
  if(!list.length){ h+='<p class="desc">Nothing here.</p>'; }
  else{
    var date=window._boardDate||'';
    h+='<p class="desc">Click a row to open that executive\'s journey detail.</p><table><tbody>';
    list.forEach(function(x){
      var act='';
      // approve button gets its own cell that swallows the click so it doesn't drill down
      if(showApprove) act='<td class="num" style="white-space:nowrap" onclick="event.stopPropagation()">'+(x.trackingId?'<button class="btn-ok" onclick="openValidate('+x.trackingId+')">Validate &amp; Approve</button>':'')+'</td>';
      var canOpen = x.userId>0;
      var go = canOpen ? ' class="clickable" onclick="openExec('+x.userId+",'"+js(x.name)+"','"+date+"')\"" : '';
      h+='<tr'+go+'><td style="font-weight:600;white-space:nowrap">'+esc(x.name)+'</td>'+
         '<td style="color:#69748c">'+esc(x.detail||'')+'</td>'+act+'</tr>';
    });
    h+='</tbody></table>';
  }
  md.innerHTML=h; mb.classList.add('show');
}
// Step 2: review the check-in photo/document before approving.
function openValidate(trackingId){
  var list=(window._att&&window._att.geofence)||[], item=null;
  for(var i=0;i<list.length;i++){ if(list[i].trackingId===trackingId){ item=list[i]; break; } }
  if(!item){ return; }
  var img = (item.attachment && window._mediaUrl)
    ? '<img class="valimg" src="'+esc(window._mediaUrl+item.attachment)+'" onclick="bjOpenImage(this.src)" onerror="this.outerHTML=\'<div class=&quot;valph&quot;>&#128247; Photo unavailable</div>\'">'
    : '<div class="valph">&#128247; No photo on this check-in</div>';
  el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><h3>Validate check-in</h3>'+
    '<p class="desc">'+esc(item.name)+' &middot; '+esc(item.detail||'')+'</p>'+
    '<div class="valwrap">'+img+'</div>'+
    '<div class="valactions">'+
      '<button class="exectab" onclick="openAttention(\'geofence\')">&larr; Back</button>'+
      '<button class="btn-ok" onclick="approveValidated('+trackingId+',this)">Approve</button>'+
    '</div>';
}
function approveValidated(trackingId, btn){
  btn.disabled=true; btn.textContent='Approving…';
  fetch(CTX+'/beat-journey/approve-checkin',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'trackingId='+trackingId})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(function(){
      if(window._att && window._att.geofence){ window._att.geofence = window._att.geofence.filter(function(x){ return x.trackingId!==trackingId; }); }
      if(window._att && window._att.geofence && window._att.geofence.length) openAttention('geofence');
      else closeModal();
    })
    .catch(function(){ btn.disabled=false; btn.textContent='Approve'; alert('Approve failed (not authorised, or server error).'); });
}

// Mark an executive on leave for the board date (unscheduled, or scheduled but not
// started / agenda unfilled). Manager / super-user only (server-enforced).
// Optimistically flips the row to "On leave" and re-renders the open drill-down.
function markLeave(authUserId, name, btn){
  if(!authUserId) return;
  var reason = prompt('Mark '+name+' on leave for '+(window._boardDate||'today')+'?\nOptional reason:', '');
  if(reason===null) return;   // cancelled
  btn.disabled=true; btn.textContent='Marking…';
  var body='authUserId='+authUserId+'&date='+encodeURIComponent(window._boardDate||'')+'&reason='+encodeURIComponent(reason||'');
  fetch(CTX+'/beat-journey/mark-leave',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:body})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(function(){
      (window._execList||[]).forEach(function(x){ if(x.authUserId===authUserId){ x.onLeave=true; x.statusLabel='On leave'; } });
      openCards(window._openCardKey||'unscheduled');   // re-render the open drill-down (row now shows "On leave", no button)
      loadToday();                // refresh KPI tiles / counts in the background
    })
    .catch(function(){ btn.disabled=false; btn.textContent='Mark leave'; alert('Could not mark leave (not authorised, or server error).'); });
}

/* ============================ PERIOD ============================ */
function loadPeriod(){
  spinner();
  var u = BASE + '/data?startDate=' + encodeURIComponent(el('bj-start').value) + '&endDate=' + encodeURIComponent(el('bj-end').value) + qs();
  fetch(u, {headers:{'Accept':'application/json'}})
    .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
    .then(renderPeriod).catch(fail);
}
function tile(t,v){ return '<div class="tile"><div class="t">'+t+'</div><div class="v">'+v+'</div></div>'; }
function renderPeriod(d){
  window._period = d;          // drill-downs read scorecard / lists from here
  var k=d.kpis, f=d.funnel, df=d.deferral, u=d.utilization, t=d.travel, o=d.outcomes;
  var neverTouched = Math.max((f.plannedStops||0)-(f.checkedIn||0)-(df.total||0),0);
  var h='';
  h+='<div class="kpis">';
  h+=kpi('&#9878;','#fff4e6','#f08c00','Adherence',k.adherencePct+'<small>%</small>',num(k.doneStops)+' of '+num(k.plannedStops)+' planned visits done',adhColor(k.adherencePct),"openPScore('adherencePct','Adherence','Planned visits done vs planned, per executive')");
  h+=kpi('&#128506;','#e7f5ff','#1098ad','PJP coverage L1',k.coverageL1Pct+'<small>%</small>',k.coverageL1With+'/'+k.coverageL1Total+' have a plan','#1098ad',"openCoverage('L1')");
  h+=kpiCols('&#128694;','#ebfbee','#2f9e44','Average Visit (per day)',
    [['Franchisee',k.avgPartnersPerActiveDay],['Lead',k.avgLeadsPerActiveDay]],
    null,"openPScore('done','Visits / active day','Visits completed per executive')");
  h+=kpiCols('&#128172;','#eef1fb','#3b5bdb','Average discussion (per executive)',
    [['Partner',k.avgDiscussionPartnerMin],['Lead',k.avgDiscussionLeadMin]],
    k.avgDiscussionMin>0&&k.avgDiscussionMin<30?'#e8590c':null,"openPScore('discussionMin','Average discussion minutes','Avg in-store discussion per executive')",'min');
  h+=kpiCols('&#8635;','#fff0f0','#e03131','Auto "missed"',
    [['Unscheduled',k.autoMissedUnscheduled],['Unfilled agenda',k.autoMissedUnfilledAgenda],['Missed punch',k.autoMissedMissedPunchin]],
    '#e03131',"openMissed()");
  h+=kpi('&#9733;','#fff0f6','#d6336c','Leads on route',num(k.leadsCreated),'this period',null,"openPLeads()");
  h+='</div>';

  h+='<div class="sectionlabel">Journey Summary</div><div class="card"><p class="desc">Planned (PJP) and self-assigned visits combined.</p><div class="funnel">'+summaryCards(d.summary)+'</div></div>';

  h+='<div class="sectionlabel">Adherence &amp; Coverage</div><div class="grid g3">';
  h+='<div class="card"><h2>Per-executive scorecard <span style="color:#97a1b5;font-weight:500;font-size:12px">&middot; '+d.scorecard.length+' executives</span></h2><p class="desc">The coaching list &mdash; click a header to sort. Reds are where to intervene.</p>'+scorecardTable(d.scorecard)+'</div>';
  h+='<div class="card"><h2>Coverage by sales level</h2><p class="desc">Filled = executives with a plan; light = total at that level.</p>'+coverageBars(d.coverageByLevel)+utilBlock(u)+'</div>';
  h+='</div>';

  h+='<div class="sectionlabel">Deferrals, Travel &amp; Outcomes</div><div class="grid g2">';
  h+='<div class="card"><h2>Deferral nature</h2><p class="desc">Deliberate, or just auto-flagged missed beats?</p>'+deferDonut(df)+'</div>';
  h+='<div class="card"><h2>Travel &amp; route quality</h2><p class="desc">Straight-line distance per leg between consecutive stops.</p>'+travelBlock(t)+'</div>';
  h+='</div>';

  h+='<div class="sectionlabel">Outcomes &amp; Visit Quality</div><div class="card"><p class="desc">Captured on the check-out form &mdash; the substance of each store conversation.</p>'+
     '<div class="tiles" style="grid-template-columns:repeat(4,1fr)">'+
     tile('Partner remark filled', o.remarkFilledPct+'<small>%</small>')+
     tile('Avg partner rating', (o.avgRating||0)+'<small>/5</small>')+
     tile('Audit checklist done', o.auditDonePct+'<small>%</small>')+
     tile('Next-visit follow-up set', o.nextVisitPct+'<small>%</small>')+
     '</div></div>';

  h+='<div class="sectionlabel">What to fix</div>'+findingsBlock(d.findings);
  h+=sourcesCard();
  el('bj-content').innerHTML=h;
  window._scorecard = d.scorecard;
}
var sortKey=null, sortAsc=false;
function sortCard(key){
  if(sortKey===key) sortAsc=!sortAsc; else { sortKey=key; sortAsc=false; }
  window._scorecard.sort(function(a,b){ var x=a[key],y=b[key];
    if(typeof x==='string') return sortAsc? (''+x).localeCompare(y):(''+y).localeCompare(x);
    return sortAsc? x-y : y-x; });
  document.getElementById('scTbl').outerHTML = scorecardTable(window._scorecard);
}
function scorecardTable(rows){
  if(!rows||!rows.length) return '<p class="desc">No beat owners in scope for this period.</p>';
  var h='<table id="scTbl"><thead><tr>'+
    '<th onclick="sortCard(\'name\')">Executive</th>'+
    '<th class="num" onclick="sortCard(\'planned\')">Plan</th>'+
    '<th class="num" onclick="sortCard(\'done\')">Done</th>'+
    '<th class="num" onclick="sortCard(\'adherencePct\')">Adher.</th>'+
    '<th class="num" onclick="sortCard(\'avgLeadVisitsPerDay\')" title="Avg lead visits per active (punched-in) day">Lead/day</th>'+
    '<th class="num" onclick="sortCard(\'avgFranchiseeVisitsPerDay\')" title="Avg franchisee visits per active (punched-in) day">Fr/day</th>'+
    '<th class="num" onclick="sortCard(\'discussionMin\')">Disc.</th>'+
    '<th class="num" onclick="sortCard(\'workingHrs\')">Hrs</th>'+
    '<th class="num" onclick="sortCard(\'leads\')">Leads</th></tr></thead><tbody>';
  rows.forEach(function(r){
    var c=adhColor(r.adherencePct);
    h+='<tr class="clickable" onclick="openExecPeriod('+r.authUserId+',\''+js(r.name)+'\')"><td><span class="lvl">'+esc(r.level)+'</span>'+esc(r.name)+'</td>'+
       '<td class="num">'+r.planned+'</td><td class="num">'+r.done+'</td>'+
       '<td class="num"><b style="color:'+c+'">'+r.adherencePct+'%</b><span class="meter"><i style="width:'+Math.min(100,r.adherencePct)+'%;background:'+c+'"></i></span></td>'+
       '<td class="num">'+(r.avgLeadVisitsPerDay||'-')+'</td>'+
       '<td class="num">'+(r.avgFranchiseeVisitsPerDay||'-')+'</td>'+
       '<td class="num'+(r.discussionMin>0&&r.discussionMin<10?' warnflag':'')+'">'+(r.discussionMin||'-')+(r.discussionMin?'m':'')+'</td>'+
       '<td class="num">'+r.workingHrs+'</td><td class="num">'+r.leads+'</td></tr>';
  });
  return h+'</tbody></table>';
}
function coverageBars(rows){
  if(!rows||!rows.length) return '<p class="desc">No coverage data.</p>';
  var max=0; rows.forEach(function(r){ if(r.totalUsers>max)max=r.totalUsers; }); if(!max)max=1;
  var h=''; rows.forEach(function(r){
    var w=pct(r.withPjp,max), wt=pct(r.totalUsers,max);
    h+='<div class="barrow clickable" onclick="openCoverage(\''+js(r.level)+'\')" title="Click to see these executives"><div class="name">'+esc(r.level)+'</div><div class="track">'+
       '<div style="position:absolute;inset:0;width:'+wt+'%;background:#e3e8f5;border-radius:7px"></div>'+
       '<div class="fill" style="width:'+w+'%;position:relative;background:linear-gradient(90deg,#1098ad,#22b8cf)">'+(r.withPjp||'')+'</div></div>'+
       '<div class="meta">'+r.withPjp+'/'+r.totalUsers+' &middot; '+r.coveragePct+'%</div></div>';
  });
  return h;
}
function utilBlock(u){
  return '<h2 style="margin-top:18px">Working-hour utilization</h2><p class="desc">Where the average working day goes.</p>'+
    '<div class="util">'+
    '<div style="width:'+u.inStorePct+'%;background:#2f9e44">In-store '+u.inStorePct+'%</div>'+
    '<div style="width:'+u.travelPct+'%;background:#3b5bdb">Travel '+u.travelPct+'%</div>'+
    '<div style="width:'+u.idlePct+'%;background:#e03131">Idle '+u.idlePct+'%</div></div>'+
    '<div class="utlegend"><span><span class="dot" style="background:#2f9e44;margin:0"></span>Selling '+u.inStoreHrs+' h</span>'+
    '<span><span class="dot" style="background:#3b5bdb;margin:0"></span>Travel '+u.travelHrs+' h</span>'+
    '<span><span class="dot" style="background:#e03131;margin:0"></span>Idle '+u.idleHrs+' h</span></div>';
}
function deferDonut(df){
  var sysPct=df.systemPct||0;
  var g='conic-gradient(#f59f00 0 '+sysPct+'%, #2f9e44 '+sysPct+'% 100%)';
  return '<div class="donutwrap"><div class="donut clickable" onclick="openDeferrals()" title="Click to see all deferrals" style="background:'+g+'"><div class="center">'+
    '<div style="font-size:24px;font-weight:780">'+num(df.total)+'</div><div style="font-size:11px;color:#97a1b5">deferrals</div></div></div>'+
    '<div class="legend">'+
    '<div class="it clickable" onclick="openDeferrals(\'system\')"><span class="dot" style="background:#f59f00"></span><div><b>'+df.systemGenerated+'</b> system auto-flagged ('+sysPct+'%)<br><span style="color:#97a1b5;font-size:11.5px">"beat missed", "no punch-in"</span></div></div>'+
    '<div class="it clickable" onclick="openDeferrals(\'genuine\')"><span class="dot" style="background:#2f9e44"></span><div><b>'+df.human+'</b> genuine reason ('+df.humanPct+'%)</div></div>'+
    '<div class="it"><span class="dot" style="background:#3b5bdb"></span><div><b>'+df.actioned+'</b> acted on by a head'+(df.avgDaysToAction?'<br><span style="color:#97a1b5;font-size:11.5px">avg '+df.avgDaysToAction+' days to action</span>':'')+'</div></div>'+
    '</div></div><p class="desc" style="margin-top:13px">Click the chart for all deferrals, or a legend row for system / genuine. "System" vs "genuine" is read from the deferral reason.</p>';
}
function travelBlock(t){
  var rows=t.legBuckets||[], max=0; rows.forEach(function(r){ if(r.count>max)max=r.count; }); if(!max)max=1;
  var colors={'0-2 km':'#2f9e44','2-5 km':'#2f9e44','5-15 km':'#82c91e','15-50 km':'#f59f00','50 km+':'#e03131'};
  var h=''; rows.forEach(function(r){
    h+='<div class="barrow"><div class="name">'+esc(r.bucket)+'</div><div class="track"><div class="fill" style="width:'+pct(r.count,max)+'%;background:'+(colors[r.bucket]||'#3b5bdb')+'">'+r.count+'</div></div><div class="meta"></div></div>';
  });
  h+='<div class="tiles" style="margin-top:14px">'+
     tile('Avg leg', t.avgLegKm+'<small> km</small>')+
     tile('Legs &gt; 15 km', t.pctOver15+'<small>%</small>')+
     tile('Actual / estimate', (t.actualVsEstimateRatio||0)+'<small>&times;</small>')+'</div>';
  return h;
}
function findingsBlock(items){
  if(!items||!items.length) return '<div class="callout"><h2>Nothing flagged</h2><p class="desc">No issues crossed the alert thresholds for this period.</p></div>';
  var sev={high:'#e03131',med:'#f59f00',low:'#2f9e44'};
  var h='<div class="callout"><h2>Recommended management actions</h2><p class="desc">Generated from this period\'s data.</p>';
  items.forEach(function(x){
    h+='<div class="fix"><div class="sev" style="background:'+(sev[x.severity]||'#3b5bdb')+'"></div><div class="fb">'+
       '<div class="ft">'+esc(x.title)+'</div><div class="fd">'+esc(x.detail)+'</div>'+
       '<div class="act">&rarr; '+esc(x.action)+'</div></div></div>';
  });
  return h+'</div>';
}
function sourcesCard(){
  return '<div class="sectionlabel">Where the numbers come from</div><div class="card">'+
    '<p class="desc">Nothing new needs to be captured &mdash; everything here is built from what the field app already records on each journey.</p>'+
    '<ul style="margin:0;padding-left:18px;line-height:1.95;font-size:13px;color:#3a4459">'+
    '<li>The <b>journey timeline</b> (punch-in, check-ins/outs, deferrals, punch-out) comes from what the executive taps in the app.</li>'+
    '<li><b>Adherence</b> compares the partners planned on each beat against the stores actually visited.</li>'+
    '<li><b>Time, travel and distance</b> use the in-store and travel durations logged per visit.</li>'+
    '<li><b>Geofence / fake-visit checks</b> compare the check-in GPS against the partner\'s saved shop location (flagged beyond ~50 m).</li>'+
    '<li><b>Visit outcomes</b> (remarks, rating, audit, next visit) come from the check-out form.</li>'+
    '<li><b>Coverage and the manager view</b> follow the existing L1&ndash;L5 sales hierarchy, so each manager sees only their team.</li>'+
    '</ul></div>';
}

/* ============================ EXEC DRILLDOWN ============================ */
function openExec(userId, name, date, tab){
  if(!userId){ return; }
  window._exec = {userId:userId, name:name, date:date, detail:null, tab:(tab||'timeline')};
  var mb=el('bj-modal-back'), m=el('bj-modal');
  m.innerHTML='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(name)+'</h3><p class="desc">Journey detail &middot; '+esc(date)+'</p><div class="loading"><div class="spinner"></div>Loading&hellip;</div>';
  mb.classList.add('show');
  fetch(CTX+'/beat-journey/journey-detail?userId='+userId+'&date='+encodeURIComponent(date),{headers:{'Accept':'application/json'}})
    .then(function(r){ return r.json(); }).then(function(d){
      window._mediaUrl = d.mediaUrl || '';
      window._exec.detail = d;
      renderExec(window._exec.tab);
    }).catch(function(){ el('bj-modal').innerHTML='<button class="x" onclick="closeModal()">&times;</button><p class="desc">Could not load detail.</p>'; });
}
function renderExec(tab){
  var ex=window._exec; if(!ex) return;
  var d=ex.detail||{};
  var head='<button class="x" onclick="closeModal()">&times;</button><h3>'+esc(ex.name)+'</h3>'+
    '<p class="desc">Journey detail &middot; '+esc(ex.date)+' &middot; battery '+(d.batteryLevel==null?'-':d.batteryLevel+'%')+' &middot; loc-off '+(d.locationToggleCount||0)+'</p>'+
    '<div class="exectabs">'+
      '<button class="exectab'+(tab==='timeline'?' active':'')+'" onclick="renderExec(\'timeline\')">&#128221; Timeline</button>'+
      '<button class="exectab'+(tab==='map'?' active':'')+'" onclick="renderExec(\'map\')">&#128205; Live Location</button>'+
    '</div>';
  if(tab==='map'){
    el('bj-modal').innerHTML=head+'<div id="bjRouteLegend" class="bjlegend"></div>'+
      '<div id="bjMap"><div class="loading"><div class="spinner"></div>Loading map&hellip;</div></div>';
    bjShowMap(ex.userId, ex.date);
  } else {
    el('bj-modal').innerHTML=head+buildTimelineHtml(d, ex.date);
  }
}
function buildTimelineHtml(d, date){
  var all=(d.visits||[]).slice();
  // Sequence like the field report: Punch in -> visited stops (by check-in time)
  // -> PENDING/not-visited -> Punch out. The attendance row carries both punch-in
  // & punch-out times; split it into the two bookends.
  var att=null, visited=[], pending=[];
  all.forEach(function(x){
    var tt=(x.taskType||'').toLowerCase(), mt=(x.markType||'').toUpperCase();
    if(tt==='attendance' || mt.indexOf('PUNCH')>=0){ if(!att) att=x; }
    else if(x.checkInTime){ visited.push(x); }
    else { pending.push(x); }
  });
  visited.sort(function(a,b){ return tlSecs(a.checkInTime)-tlSecs(b.checkInTime); });

  var distKm=0, inStoreSec=0, leadsN=0;
  all.forEach(function(x){
    var tt=(x.taskType||'').toLowerCase();
    if(tt==='attendance') return;
    if(x.totalDistance) distKm += (parseFloat(x.totalDistance)||0);
    inStoreSec += toSec(x.timeSpent);
    if(tt==='lead') leadsN++;
  });
  var workSec = (att && att.checkInTime && att.checkOutTime) ? (toSec(att.checkOutTime)-toSec(att.checkInTime)) : (att?toSec(att.timeSpent):0);
  if(workSec<0) workSec=0;
  // Travel = working − in-store, so In-store + Travel = Working hours exactly
  // (summing per-leg transit under-counts the idle/waiting between stops).
  var transitSec = Math.max(0, workSec - inStoreSec);

  var seq=[];
  if(att && att.checkInTime) seq.push(punchEntry('in', att.checkInTime));
  visited.forEach(function(x){ seq.push(x); });
  pending.forEach(function(x){ seq.push(x); });
  if(att && att.checkOutTime) seq.push(punchEntry('out', att.checkOutTime));

  var h='<div class="jstats">'+
    jstat(fmtSec(workSec),'Working hours')+
    jstat(fmtSec(inStoreSec),'In-store time')+
    jstat(fmtSec(transitSec),'Travel time')+
    jstat(distKm.toFixed(2)+' km','Distance Covered')+
    jstat(visited.length+(leadsN?' / '+leadsN+'L':''),'Visits / Leads')+
    '</div>';
  if(!seq.length){ return h+'<p class="desc">No tracking events for this day.</p>'; }
  h+='<div class="tl">';
  var ri=0;
  seq.forEach(function(x){
    if(!x._punch && x.checkInTime){
      var tr=(x.transitTime && x.transitTime!=='00:00:00') ? x.transitTime : null;
      var km=(x.totalDistance && parseFloat(x.totalDistance)>0) ? (parseFloat(x.totalDistance).toFixed(2)+' km') : null;
      var eta=(x.estimatedTime && x.estimatedTime!=='00:00:00') ? x.estimatedTime : null;
      if(tr || km || eta){
        var parts=[]; if(tr) parts.push('&#128663; '+esc(tr)); if(km) parts.push(esc(km)); if(eta) parts.push('ETA '+esc(eta));
        // flag the leg red when actual transit exceeds 1.5x the ETA (same rule as the export)
        var overrun = eta && toSec(tr) > 1.5*toSec(eta);
        h+='<div class="tlgap"><span class="gappill'+(overrun?' overrun':'')+'"'+(overrun?' title="Travel overran 1.5x the ETA"':'')+'>'+parts.join(' &middot; ')+'</span></div>';
      }
    }
    h+=tlRow(x, ri%2===0?'left':'right'); ri++;
  });
  h+='</div>';
  return h;
}

/* ---- live location map (reuses /beat-report/live-tracking pathPoints) ---- */
function bjLoadMaps(cb){
  if(window.google && window.google.maps){ cb(); return; }
  window._mapsCbs = window._mapsCbs || [];
  window._mapsCbs.push(cb);
  if(window._mapsLoading) return;
  window._mapsLoading=true;
  window.__bjMapsReady=function(){ (window._mapsCbs||[]).forEach(function(f){ try{f();}catch(e){} }); window._mapsCbs=[]; };
  var s=document.createElement('script');
  s.src='https://maps.googleapis.com/maps/api/js?key=AIzaSyAckO0y4Z6WhBOuMjNjioWLSYZDhGEvGBc&libraries=geometry&v=weekly&callback=__bjMapsReady';
  s.async=true; document.head.appendChild(s);
}
function bjShowMap(userId, date){
  bjLoadMaps(function(){
    fetch(CTX+'/beat-journey/track-map?userId='+userId+'&date='+encodeURIComponent(date),{headers:{'Accept':'application/json'}})
      .then(function(r){ return r.json(); }).then(function(data){ bjDrawMap(data); })
      .catch(function(){ var e=document.getElementById('bjMap'); if(e) e.innerHTML='<div class="loading">Could not load location.</div>'; });
  });
}
function bjMarkColor(mt){
  mt=(mt||'').toUpperCase();
  if(mt.indexOf('CHECKOUT')>=0) return '#2f9e44';
  if(mt==='CHECKIN') return '#f59f00';
  if(mt==='DEFERRED') return '#e8590c';
  if(mt==='PENDING') return '#97a1b5';
  return '#3b5bdb';
}
function bjMarkInfo(v,color){
  return '<div style="font-size:12px;max-width:240px"><b>'+esc(v.name||'')+'</b><br>'+
    '<span style="background:'+color+';color:#fff;border-radius:4px;padding:1px 6px;font-size:10px">'+esc(v.markType||'')+'</span>'+
    (v.checkInTime?'<br>In: <b>'+esc(v.checkInTime)+'</b>':'')+
    (v.checkOutTime?'<br>Out: <b>'+esc(v.checkOutTime)+'</b>':'')+
    (v.timeSpent?'<br>Time spent: <b>'+esc(v.timeSpent)+'</b>':'')+
    (v.address?'<br>'+esc(v.address):'')+'</div>';
}
// Teardrop pin (same shape as Beat Report) with a white disc + label.
function bjPin(color, label){
  var svg='<svg xmlns="http://www.w3.org/2000/svg" width="28" height="40" viewBox="0 0 28 40">'+
    '<path d="M14 0C6.268 0 0 6.268 0 14c0 10.5 14 26 14 26s14-15.5 14-26C28 6.268 21.732 0 14 0z" fill="'+color+'"/>'+
    '<circle cx="14" cy="14" r="7" fill="#ffffff"/>'+
    '<text x="14" y="18" text-anchor="middle" font-size="10" font-weight="bold" fill="'+color+'">'+label+'</text></svg>';
  return {url:'data:image/svg+xml;charset=UTF-8,'+encodeURIComponent(svg), scaledSize:new google.maps.Size(28,40), anchor:new google.maps.Point(14,40)};
}
// Larger pin sized to fit a duration label (idle stops).
function bjStopPin(label){
  var s=String(label), d=Math.max(40, 14+s.length*7), H=d+10, r=d/2;
  var svg='<svg xmlns="http://www.w3.org/2000/svg" width="'+d+'" height="'+H+'" viewBox="0 0 '+d+' '+H+'">'+
    '<polygon points="'+(r-7)+','+(d-7)+' '+(r+7)+','+(d-7)+' '+r+','+H+'" fill="#e8590c"/>'+
    '<circle cx="'+r+'" cy="'+r+'" r="'+(r-2)+'" fill="#e8590c" stroke="#ffffff" stroke-width="2"/>'+
    '<text x="'+r+'" y="'+(r+4)+'" text-anchor="middle" font-size="12" font-weight="bold" fill="#ffffff">'+s+'</text></svg>';
  return {url:'data:image/svg+xml;charset=UTF-8,'+encodeURIComponent(svg), scaledSize:new google.maps.Size(d,H), anchor:new google.maps.Point(r,H)};
}
function fmtDur2(sec){ sec=sec||0; var m=Math.floor(sec/60), s=sec%60; return m+'m'+(s>0?' '+s+'s':''); }
function bjDrawMap(data){
  var box=document.getElementById('bjMap'); if(!box) return;
  box.innerHTML='';
  var map=new google.maps.Map(box,{zoom:12,center:{lat:20.5937,lng:78.9629},mapTypeControl:true,streetViewControl:false});
  var bounds=new google.maps.LatLngBounds(), has=false;
  function pin(pos,icon,zi,title,info){
    has=true; bounds.extend(pos);
    var m=new google.maps.Marker({position:pos,map:map,zIndex:zi||100,icon:icon,title:title||''});
    if(info){ var iw=new google.maps.InfoWindow({content:info}); m.addListener('click',function(){ iw.open(map,m); }); }
    return m;
  }

  // 1) last-known location marker (the GPS trail itself is drawn as the "taken"
  // route in bjDrawRoutes, straight from location_tracking_path).
  var pts=(data.path||[]).map(function(p){ return {lat:p.lat,lng:p.lng}; });
  if(pts.length){
    pts.forEach(function(p){ bounds.extend(p); has=true; });
    var lastPt=pts[pts.length-1];
    var lk=new google.maps.Marker({position:lastPt,map:map,zIndex:999,title:'Last Known Location',
      icon:{url:CTX+'/resources/images/salesman.png',scaledSize:new google.maps.Size(40,40),anchor:new google.maps.Point(20,20)}});
    var lkIw=new google.maps.InfoWindow({content:'<div style="font-size:12px"><b>&#128205; Last known location</b></div>'});
    lk.addListener('click',function(){ lkIw.open(map,lk); });
  }

  // 2) idle stops (>=10 min within 50 m)
  (data.idleStops||[]).forEach(function(s){
    var lbl=fmtDur2(s.seconds);
    pin({lat:s.lat,lng:s.lng}, bjStopPin(lbl), 80, 'Idle '+lbl,
      '<div style="font-size:12px"><b>&#9201; Idle stop</b><br>Stayed ~'+esc(lbl)+' within 50 m</div>');
  });

  // 3) every visit — visited stops are numbered in array order; pending / deferred
  // stops (plotted at their planned store location) get a neutral dot and sit
  // below the visited pins.
  var idx=0;
  (data.visits||[]).forEach(function(v){
    var color=bjMarkColor(v.markType);
    var visited = !!v.checkInTime;
    pin({lat:v.lat,lng:v.lng}, bjPin(color, visited?String(++idx):'•'), visited?100:60,
      (v.name||'')+' ('+v.markType+')', bjMarkInfo(v,color));
  });

  // 4) punch in / punch out
  if(data.punchIn){
    pin({lat:data.punchIn.lat,lng:data.punchIn.lng}, bjPin('#2f9e44','P'), 300,
      'Punch in'+(data.punchIn.time?' · '+data.punchIn.time:''),
      '<div style="font-size:12px"><b>&#9873; Punch in</b>'+(data.punchIn.time?'<br>'+esc(data.punchIn.time):'')+'</div>');
  }
  if(data.punchOut){
    pin({lat:data.punchOut.lat,lng:data.punchOut.lng}, bjPin('#7048e8','X'), 300,
      'Punch out'+(data.punchOut.time?' · '+data.punchOut.time:''),
      '<div style="font-size:12px"><b>&#9873; Punch out</b>'+(data.punchOut.time?'<br>'+esc(data.punchOut.time):'')+'</div>');
  }

  // 5) routes — actual road taken vs Google-suggested optimal, for comparison.
  // Suggested-route checkpoints = the whole day's stops (planned + visited), not
  // just the ones already visited, so the suggestion shows from punch-in onward
  // (and even before the first check-in). optimizeWaypoints reorders them, so the
  // input order only needs to keep punch-in first / punch-out last; visited stops
  // are listed by check-in time and still-pending stops after them.
  var cps=[];
  if(data.punchIn) cps.push({lat:data.punchIn.lat,lng:data.punchIn.lng});
  (data.visits||[]).slice()
    .filter(function(v){ return v.lat && v.lng; })                   // every stop with coords
    .sort(function(a,b){ return tlSecs(a.checkInTime)-tlSecs(b.checkInTime); })
    .forEach(function(v){ cps.push({lat:v.lat,lng:v.lng}); });
  if(data.punchOut) cps.push({lat:data.punchOut.lat,lng:data.punchOut.lng});
  // Actual time window of the GPS trail (first → last breadcrumb timestamp),
  // shown on the taken-route click detail alongside the driving estimate.
  var takenTime='';
  var dp=data.path||[];
  if(dp.length>=2 && dp[0].ts && dp[dp.length-1].ts && dp[dp.length-1].ts>dp[0].ts){
    var t0=dp[0].ts, t1=dp[dp.length-1].ts;
    takenTime=bjClock(t0)+' &rarr; '+bjClock(t1)+' ('+bjElapsed(t1-t0)+')';
  }
  bjDrawRoutes(map, cps, pts, takenTime, dp);

  if(has){
    map.fitBounds(bounds);
    google.maps.event.addListenerOnce(map,'idle',function(){ if(map.getZoom()>16) map.setZoom(16); });
  } else {
    box.innerHTML='<div class="loading">No GPS / location recorded for this day.</div>';
  }
}
// TAKEN route = the recorded GPS trail (location_tracking_path) routed along the
// road network so it follows actual roads rather than straight hops between sparse
// pings. SUGGESTED route = the Google-optimal road route through the journey's
// checkpoints (green dotted). Both are drawn and compared by distance.
function bjDrawRoutes(map, cps, pathPts, takenTime, timedPts){
  var legend=bjRouteLegend();

  // De-jitter the breadcrumb first: stationary GPS drift (e.g. under a roof)
  // scatters points around a fixed spot, which makes the road-snapped route weave
  // back and forth and inflates the taken distance. Collapsing sub-JITTER_MIN_M
  // hops removes those clusters before we draw or measure the trail.
  var trail=bjCleanTrail(pathPts, 30);

  // taken — road route traced through the recorded breadcrumb (in order)
  if(trail && trail.length>=2){
    var ds1=new google.maps.DirectionsService();
    var sample=bjSample(trail, 25);                           // Directions cap: 25 incl. ends
    var o=sample[0], d=sample[sample.length-1];
    var vias=sample.slice(1,-1).map(function(p){ return {location:new google.maps.LatLng(p.lat,p.lng), stopover:false}; });
    bjRouteRequest(ds1, o, d, vias, false, function(res){
      bjRenderRoute(map, res, {color:'#e03131', dashed:false, z:55, label:'Route taken (actual GPS)', time:takenTime, timed:timedPts});
      legend.set('taken', bjRouteKm(res));
    }, function(status){
      console.warn('Directions (taken) failed:', status);
      // fallback: plot the cleaned breadcrumb (straight hops), with arrows, and measure along it
      var poly=new google.maps.Polyline({path:trail,geodesic:false,strokeColor:'#e03131',strokeOpacity:.9,strokeWeight:4,zIndex:55,map:map,
        icons:[{icon:{path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW,strokeColor:'#e03131',fillColor:'#e03131',fillOpacity:1,scale:3},offset:'3%',repeat:'120px'}]});
      var km=google.maps.geometry.spherical.computeLength(trail.map(function(p){ return new google.maps.LatLng(p.lat,p.lng); }))/1000;
      bjRouteClick(map, poly, '#e03131', 'Route taken (actual GPS)', km, '', takenTime, timedPts);
      legend.set('taken', km);
    });
  } else {
    legend.set('taken', false);
  }

  // suggested — Google-optimal route through punch-in → visits → punch-out
  if(cps.length>=2){
    var ds=new google.maps.DirectionsService();
    var origin=cps[0], dest=cps[cps.length-1], mids=cps.slice(1,-1), capped=false;
    if(mids.length>23){ mids=mids.slice(0,23); capped=true; }  // Directions allows 23 waypoints
    var wpts=mids.map(function(p){ return {location:new google.maps.LatLng(p.lat,p.lng), stopover:true}; });
    bjRouteRequest(ds, origin, dest, wpts, true, function(res){
      bjRenderRoute(map, res, {color:'#2f9e44', dashed:true, z:50, label:'Suggested route (optimal)'});
      legend.set('suggested', bjRouteKm(res));
    }, function(status){ console.warn('Directions (suggested) failed:', status); legend.set('suggested', false); });
    if(capped) legend.note('Suggested route limited to first 23 stops');
  } else {
    legend.set('suggested', false);
  }
}
// Collapse stationary GPS jitter: keep the first point, then only points that
// moved at least `minM` metres from the last kept one; the true final point is
// always kept so the trail ends at the last known location. This removes the
// dense drift clusters (weak signal indoors) that otherwise draw back-and-forth
// loops and inflate the taken distance, while preserving real movement.
function bjCleanTrail(pts, minM){
  if(!pts || pts.length<2) return pts ? pts.slice() : [];
  var out=[pts[0]], last=pts[0];
  for(var i=1;i<pts.length-1;i++){
    var p=pts[i];
    var d=google.maps.geometry.spherical.computeDistanceBetween(
      new google.maps.LatLng(last.lat,last.lng), new google.maps.LatLng(p.lat,p.lng));
    if(d>=minM){ out.push(p); last=p; }
  }
  out.push(pts[pts.length-1]);   // keep the final fix regardless
  return out;
}
// Evenly downsample a list to at most `max` items, always keeping first and last.
function bjSample(arr, max){
  if(arr.length<=max) return arr.slice();
  var out=[], step=(arr.length-1)/(max-1);
  for(var i=0;i<max;i++) out.push(arr[Math.round(i*step)]);
  return out;
}
function bjRouteRequest(ds, origin, dest, wpts, optimize, ok, err){
  ds.route({
    origin:new google.maps.LatLng(origin.lat,origin.lng),
    destination:new google.maps.LatLng(dest.lat,dest.lng),
    waypoints:wpts, optimizeWaypoints:optimize,
    travelMode:google.maps.TravelMode.DRIVING
  }, function(res, status){
    if(status===google.maps.DirectionsStatus.OK && res && res.routes && res.routes.length) ok(res);
    else err(status);
  });
}
// Draw a route as a custom polyline (so we can add direction arrows + a click
// info window). Forward arrows are repeated along the line; dashed routes also
// get the dash pattern. Clicking the line opens its distance / duration detail.
function bjRenderRoute(map, res, opt){
  var path=res.routes[0].overview_path;
  var arrow={icon:{path:google.maps.SymbolPath.FORWARD_CLOSED_ARROW, strokeColor:opt.color,
                   strokeOpacity:1, strokeWeight:1, fillColor:opt.color, fillOpacity:1, scale:opt.dashed?2.6:3.2},
             offset:'3%', repeat:opt.dashed?'95px':'120px'};
  var icons=[arrow];
  if(opt.dashed){
    icons.unshift({icon:{path:'M 0,-1 0,1', strokeColor:opt.color, strokeOpacity:1, strokeWeight:4, scale:3}, offset:'0', repeat:'14px'});
  }
  var poly=new google.maps.Polyline({path:path, map:map, zIndex:opt.z,
    strokeColor:opt.color, strokeOpacity:opt.dashed?0:0.85, strokeWeight:opt.dashed?0:5, icons:icons});
  bjRouteClick(map, poly, opt.color, opt.label||(opt.dashed?'Suggested route':'Route taken'),
    bjRouteKm(res), bjRouteDur(res), opt.time, opt.timed);
}
// Attach a click handler that opens an info window with the route's details at
// the clicked point. Reused by both the routed line and the breadcrumb fallback.
// `time` (optional) is the actual GPS time window, e.g. "09:28 → 16:03 (6h 35m)".
// `timed` (optional) are the raw breadcrumbs with timestamps; when present, the
// captured time at the nearest breadcrumb to the click is shown.
function bjRouteClick(map, poly, color, label, km, dur, time, timed){
  var iw=new google.maps.InfoWindow();
  poly.addListener('click', function(e){
    var here='';
    if(timed && timed.length){
      var np=bjNearestPt(timed, e.latLng);
      if(np && np.ts) here='&#128205; At this point: <b>'+bjClockS(np.ts)+'</b><br>';
    }
    iw.setContent('<div style="font-size:12px;line-height:1.5"><b style="color:'+color+'">&#10148; '+esc(label)+'</b><br>'+
      here+(time?'Time: <b>'+time+'</b><br>':'')+
      'Distance: <b>'+km.toFixed(1)+' km</b>'+(dur?'<br>Est. drive: <b>'+esc(dur)+'</b>':'')+'</div>');
    iw.setPosition(e.latLng); iw.open(map);
  });
}
// Nearest timestamped breadcrumb to a clicked LatLng (great-circle distance).
function bjNearestPt(timed, latLng){
  var best=null, bd=Infinity;
  for(var i=0;i<timed.length;i++){
    var d=google.maps.geometry.spherical.computeDistanceBetween(latLng, new google.maps.LatLng(timed[i].lat, timed[i].lng));
    if(d<bd){ bd=d; best=timed[i]; }
  }
  return best;
}
// Format an epoch-millis timestamp as a local HH:MM clock, and a millisecond
// span as a compact "Nh Nm" / "Nm" elapsed string (for the GPS time window).
function bjClock(ts){
  var d=new Date(ts), h=d.getHours(), m=d.getMinutes();
  return (h<10?'0':'')+h+':'+(m<10?'0':'')+m;
}
function bjClockS(ts){
  var d=new Date(ts), h=d.getHours(), m=d.getMinutes(), s=d.getSeconds();
  return (h<10?'0':'')+h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s;
}
function bjElapsed(ms){
  var s=Math.round(ms/1000), h=Math.floor(s/3600), m=Math.round((s%3600)/60);
  return h ? (h+'h '+m+'m') : (m+'m');
}
function bjRouteKm(res){
  var m=0; (res.routes[0].legs||[]).forEach(function(l){ m+=(l.distance?l.distance.value:0); }); return m/1000;
}
function bjRouteDur(res){
  var s=0; (res.routes[0].legs||[]).forEach(function(l){ s+=(l.duration?l.duration.value:0); });
  if(!s) return '';
  var h=Math.floor(s/3600), m=Math.round((s%3600)/60);
  return h ? (h+'h '+m+'m') : (m+'m');
}
// Route-comparison panel rendered into the modal (#bjRouteLegend), above the map.
// Each distance fills in as its route resolves. value: number = km, false =
// unavailable, undefined = still loading.
function bjRouteLegend(){
  var div=el('bjRouteLegend');
  if(!div) return { set:function(){}, note:function(){} };
  var taken, sugg, noteTxt='';
  function val(v){ return typeof v==='number' ? '<b>'+v.toFixed(1)+' km</b>' : (v===false ? 'n/a' : '…'); }
  function render(){
    var cmp='';
    if(typeof taken==='number' && typeof sugg==='number'){
      cmp = taken>sugg+0.05
        ? '<span style="color:#e03131">+'+(taken-sugg).toFixed(1)+' km longer than suggested</span>'
        : '<span style="color:#2f9e44">on / better than the suggested route</span>';
    }
    div.innerHTML=
      '<span class="lg">Route comparison</span>'+
      '<span><span class="sw ln"></span>Taken (GPS)</span>'+
      '<span><span class="sw dt"></span>Suggested</span>'+
      cmp+
      (noteTxt?'<span style="color:#e8590c">'+noteTxt+'</span>':'');
  }
  render();
  return { set:function(k,v){ if(k==='taken')taken=v; else sugg=v; render(); }, note:function(t){ noteTxt=t; render(); } };
}
function tlSecs(t){ if(!t) return 1e9; var p=t.split(':'); return (+p[0])*3600+(+(p[1]||0))*60+(+(p[2]||0)); }
function toSec(t){ if(!t||t==='00:00:00') return 0; var p=t.split(':'); return (+p[0])*3600+(+(p[1]||0))*60+(+(p[2]||0)); }
function fmtSec(s){ s=Math.max(0,Math.round(s)); var h=Math.floor(s/3600), m=Math.floor((s%3600)/60), ss=s%60; function z(n){return (n<10?'0':'')+n;} return z(h)+':'+z(m)+':'+z(ss); }
function jstat(v,l){ return '<div class="js"><div class="jv">'+v+'</div><div class="jl">'+l+'</div></div>'; }
function hhmm(t){ return t? t.slice(0,5):''; }
// Best-effort: pull a "when will they order" hint out of a free-text remark.
// English + Hinglish. Display-only; returns '' when nothing recognizable is found.
function bjScheduledFromRemark(remark){
  if(!remark) return '';
  var t = String(remark).toLowerCase();
  // day-after (before tomorrow/kal, since "parso" is distinct)
  if(/\b(day[\s-]?after(\s+tomorrow)?|parso)\b/.test(t)) return 'day after';
  if(/\b(tomorrow|kal|tmrw|tmr)\b/.test(t)) return 'tomorrow';
  if(/\b(today|aaj|abhi)\b/.test(t)) return 'today';
  // range "N-M days" / "N-M din" (check before single N)
  var range = t.match(/\b(\d{1,2})\s*[-–to]+\s*(\d{1,2})\s*(days?|din)\b/);
  if(range) return 'in '+range[1]+'–'+range[2]+' days';
  var nd = t.match(/\b(?:in\s+)?(\d{1,2})\s*(days?|din)\b/);
  if(nd) return 'in '+nd[1]+' day'+(nd[1]==='1'?'':'s');
  if(/\b(this\s*week|is\s*week|is\s*haft[ae])\b/.test(t)) return 'this week';
  if(/\b(next\s*week|agle\s*haft[ae]|agla\s*week)\b/.test(t)) return 'next week';
  // explicit "DD Mon" / "DD Month"
  var mon = t.match(/\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\b/);
  if(mon){
    var M={jan:'Jan',feb:'Feb',mar:'Mar',apr:'Apr',may:'May',jun:'Jun',jul:'Jul',aug:'Aug',sep:'Sep',oct:'Oct',nov:'Nov',dec:'Dec'};
    return parseInt(mon[1],10)+' '+M[mon[2]];
  }
  // "DD/MM" or "DD-MM" (reject year-like / out-of-range month)
  var dm = t.match(/\b(\d{1,2})[\/\-](\d{1,2})\b(?!\d)/);
  if(dm && parseInt(dm[2],10)>=1 && parseInt(dm[2],10)<=12){
    var mo=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return parseInt(dm[1],10)+' '+mo[parseInt(dm[2],10)-1];
  }
  // weekday names (English + common Hinglish)
  var wk = t.match(/\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday|somwar|mangalwar|budhwar|guruwar|shukrawar|shaniwar|raviwar|itwar)\b/);
  if(wk){
    var W={monday:'Mon',somwar:'Mon',tuesday:'Tue',mangalwar:'Tue',wednesday:'Wed',budhwar:'Wed',
           thursday:'Thu',guruwar:'Thu',friday:'Fri',shukrawar:'Fri',saturday:'Sat',shaniwar:'Sat',
           sunday:'Sun',raviwar:'Sun',itwar:'Sun'};
    return W[wk[1]];
  }
  return '';
}
function tlThumb(att){
  if(att && window._mediaUrl) return '<img class="tlthumb" src="'+esc(window._mediaUrl+att)+'" onclick="bjOpenImage(this.src)" onerror="tlImgErr(this)">';
  return '';   // no image -> render nothing (no placeholder box)
}
function tlImgErr(im){ var d=document.createElement('div'); d.className='tlph'; d.title='Photo unavailable'; d.innerHTML='&#128247;'; if(im.parentNode) im.parentNode.replaceChild(d, im); }
function punchEntry(kind, time){ return {_punch:kind, checkInTime:time, markType:(kind==='in'?'PUNCHIN':'PUNCHOUT'), taskType:'attendance'}; }
function tlStyle(x){
  var mt=(x.markType||'').toUpperCase(), tt=(x.taskType||'').toLowerCase();
  if(x._punch || tt==='attendance' || mt.indexOf('PUNCH')>=0) return {c:'#7048e8', l:(x._punch==='out'?'Punch out':'Punch in'), ic:'&#9873;'};
  if(mt.indexOf('CHECKOUT')>=0) return {c:'#2f9e44', l:'Visited', ic:'&#10003;'};
  if(mt==='CHECKIN') return {c:'#1098ad', l:'In', ic:'&#128205;'};
  if(mt==='DEFERRED') return {c:'#e8590c', l:'Deferred', ic:'&#9888;'};
  if(mt==='PENDING' || !x.checkInTime) return {c:'#97a1b5', l:'Pending', ic:'&#9675;'};
  return {c:'#3b5bdb', l:(mt||'-'), ic:'&#9679;'};
}
function tlTitle(x){
  if(x._punch) return x._punch==='in' ? 'Journey start (Punch in)' : 'Journey end (Punch out)';
  var n=x.taskName||'';
  var taskType=(x.taskType||'').toLowerCase();
  if(taskType==='franchisee-visit') {
    var pipe = n.lastIndexOf('|');
    if (pipe >= 0) n = n.slice(pipe + 1);      // drop leading agenda tags
    n = n.replace(/\s*VISIT\b.*$/i, '').replace(/\s*visit\s*$/i, '').replace(/\bnull\b/gi, '').replace(/\s{2,}/g, ' ').trim();
  }
  return n || '(stop)';
}
// Agenda chips: task_name is "agenda1, agenda2 | Outlet" — show the prefix (partner visits only).
function tlAgendas(x){
  if(x._punch || (x.taskType||'').toLowerCase()!=='franchisee-visit') return '';
  var n=x.taskName||'', pipe=n.lastIndexOf(' | ');
  var part = pipe>0 ? n.slice(0,pipe) : '';
  if(!part) return '';
  var out='';
  part.split(',').forEach(function(a){ var t=a.trim(); if(t) out += '<span class="tlag">'+esc(t)+'</span>'; });
  return out ? '<div class="tlags">'+out+'</div>' : '';
}
function tlRow(x, side){
  var s=tlStyle(x);
  var tt=(x.taskType||'').toLowerCase();
  var timeTop = x.checkInTime ? hhmm(x.checkInTime) : '-';
  var tlabel = x._punch ? (x._punch==='in'?'punch in':'punch out') : (x.checkInTime?'check-in':'pending');
  var meta;
  if(x._punch){
    meta = (x._punch==='in'?'Punch in':'Punch out') + ' &middot; ' + hhmm(x.checkInTime);
  } else {
    var io = (x.checkInTime?hhmm(x.checkInTime):'-') + ' &rarr; ' + (x.checkOutTime?hhmm(x.checkOutTime):'-');
    var dur = (x.timeSpent && x.timeSpent!=='00:00:00') ? ' &middot; '+esc(x.timeSpent) : '';
    var typeLabel = tt==='lead' ? 'Lead' : (tt==='office-visit'?'Office':'Partner');
    meta = x.checkInTime ? (typeLabel+' &middot; '+io+dur) : (typeLabel+' &middot; not visited');
  }
  // image (or placeholder) + battery + location-toggle on real stops
  var extra='';
  if(!x._punch){
    var chips='';
    if(x.battery!=null) chips += '<span class="tlchip">&#128267; '+x.battery+'%</span>';
    if(x.locOff!=null) chips += '<span class="tlchip">&#128244; '+x.locOff+'</span>';
    // orders placed that day (any agenda): one badge -> drawer lists them all.
    // No order + billing agenda -> a parsed "scheduled" chip instead.
    if(x.orders && x.orders.length){
      var n=x.orders.length;
      chips += '<button type="button" class="tlbadge ord" title="View orders placed this day"'
             + ' onclick="bjOpenOrderList('+x.taskId+')">&#129534; '+n+' order'+(n>1?'s':'')+'</button>';
    } else if(x.billingAgenda){
      var sch = bjScheduledFromRemark(x.remarks);
      if(sch) chips += '<span class="tlbadge sch" title="Scheduled (from remark)">&#128197; '+esc(sch)+'</span>';
    }
    var thumb=tlThumb(x.attachment);
    if(thumb || chips) extra = '<div class="tlextra">'+thumb+chips+'</div>';
  }
  var card='<div class="tlcard">'+
        '<div class="tm" style="background:'+s.c+'">'+timeTop+'<small>'+tlabel+'</small></div>'+
        '<div class="bd"><div class="ti">'+esc(tlTitle(x))+'</div>'+
          '<span class="stt" style="background:'+s.c+'">'+s.l+'</span>'+
          (tt==='lead' ? '<span class="stt unplanned">Unplanned</span>' : '')+
          tlAgendas(x)+
          '<div class="mt">'+meta+'</div>'+extra+'</div>'+
      '</div>';
  // remark sits on the opposite half of the timeline (empty spacer when none)
  var rk='';
  if(!x._punch && x.remarks){
    rk='<div class="rk"><div class="rkl">Remark</div>'+esc(x.remarks);
    if(x.taskId && x.taskId>0){
      // one big-string timeline -> global fn + primitive args (partner name escaped for the attribute)
      rk+='<button type="button" class="rkhist" onclick="bjOpenRemarkHistory('+x.taskId+',\''+js(x.taskType||'')+'\',\''+js(tlTitle(x))+'\')">&#128220; Past discussions</button>';
    }
    rk+='</div>';
  }
  var remark='<div class="tlremark">'+rk+'</div>';
  var halves = side==='left' ? (card+remark) : (remark+card);
  return '<div class="tlrow '+side+'">'+
      '<div class="node" style="background:'+s.c+'">'+s.ic+'</div>'+
      halves+'</div>';
}
function closeModal(){ el('bj-modal-back').classList.remove('show'); }
// Image lightbox — opens an attachment larger, stacked above the journey modal.
function bjOpenImage(src){ if(!src) return; el('bj-img').src=src; el('bj-img-back').classList.add('show'); }
function bjCloseImage(){ el('bj-img-back').classList.remove('show'); el('bj-img').removeAttribute('src'); }

/* ===================== REMARK HISTORY DRAWER ===================== */
// All prior discussions for one partner/lead (task_id + task_type), across every
// executive and date, newest first. Paged via /beat-journey/remark-history.
function bjOpenRemarkHistory(taskId, taskType, name){
  if(!taskId || taskId<=0) return;
  window._rh = { taskId:taskId, taskType:taskType, name:name, offset:0, limit:8, items:[], loading:false, total:0 };
  el('bj-rh-title').innerHTML='&#128220; '+esc(name);
  el('bj-rh-sub').textContent='Past discussions across all executives';
  el('bj-rh-list').innerHTML='<div class="rhloading"><div class="spinner"></div>Loading&hellip;</div>';
  el('bj-rh-more').style.display='none';
  el('bj-rh-back').classList.add('show');
  bjLoadRemarkHistory();
}
function closeRemarkHistory(){ el('bj-rh-back').classList.remove('show'); window._rh=null; }
function bjLoadRemarkHistory(){
  var s=window._rh; if(!s || s.loading) return;          // block re-entrant fetches
  s.loading=true;
  var more=el('bj-rh-more'); more.disabled=true; more.textContent='Loading…';
  var u=CTX+'/beat-journey/remark-history?taskId='+s.taskId
        +'&taskType='+encodeURIComponent(s.taskType||'')
        +'&offset='+s.offset+'&limit='+s.limit;
  fetch(u,{headers:{'Accept':'application/json'}})
    .then(function(r){ return r.json(); })
    .then(function(d){
      var st=window._rh; if(!st || st.taskId!==s.taskId) return;  // drawer changed mid-flight
      st.total=d.total||0;
      (d.items||[]).forEach(function(it){ st.items.push(it); });
      st.offset += (d.items||[]).length;
      st.loading=false;
      bjRenderRemarkHistory(!!d.hasMore);
    })
    .catch(function(){
      var st=window._rh; if(st) st.loading=false;
      el('bj-rh-list').innerHTML='<div class="rhempty">Could not load past discussions.</div>';
      el('bj-rh-more').style.display='none';
    });
}
function bjRenderRemarkHistory(hasMore){
  var s=window._rh; if(!s) return;
  if(!s.items.length){
    el('bj-rh-list').innerHTML='<div class="rhempty">No earlier discussions for this partner.</div>';
    el('bj-rh-more').style.display='none';
    return;
  }
  var h='';
  s.items.forEach(function(it){
    var mt=(it.markType||'').toUpperCase();
    var badge = mt.indexOf('CHECKOUT')>=0 ? '<span class="rhb ok">visited</span>'
              : (mt==='DEFERRED' ? '<span class="rhb def">deferred</span>' : '');
    var when = esc(it.date||'')+(it.time?' &middot; '+esc(hhmm(it.time)):'');
    h+='<div class="rhitem">'
      +'<div class="rhtop"><span class="rhdate">'+when+'</span>'+badge+'</div>'
      +'<div class="rhexec">'+esc(it.exec||'')+'</div>'
      +'<div class="rhtext">'+esc(it.remark||'')+'</div></div>';
  });
  el('bj-rh-list').innerHTML=h;
  var more=el('bj-rh-more');
  more.disabled=false; more.textContent='Load more';
  more.style.display = hasMore ? 'block' : 'none';
}

/* ===================== ORDERS DRAWER ===================== */
// All retail orders a partner placed on the visit day, each with its line items.
function bjOpenOrderList(fofoId){
  if(!fofoId) return;
  var date=(window._exec && window._exec.date) || '';
  window._od = { fofoId:fofoId, date:date };
  el('bj-od-title').innerHTML='&#129534; Orders';
  el('bj-od-sub').textContent='Orders placed on '+date;
  el('bj-od-body').innerHTML='<div class="odloading"><div class="spinner"></div>Loading&hellip;</div>';
  el('bj-od-back').classList.add('show');
  fetch(CTX+'/beat-journey/order-list?fofoId='+encodeURIComponent(fofoId)+'&date='+encodeURIComponent(date),
        {headers:{'Accept':'application/json'}})
    .then(function(r){ return r.json(); })
    .then(function(d){
      var st=window._od; if(!st || st.fofoId!==fofoId) return;   // drawer changed mid-flight
      bjRenderOrderList(d);
    })
    .catch(function(){ el('bj-od-body').innerHTML='<div class="odempty">Could not load orders.</div>'; });
}
function closeOrderDetail(){ el('bj-od-back').classList.remove('show'); window._od=null; }
function bjRenderOrderList(d){
  var orders=d.orders||[];
  if(!orders.length){ el('bj-od-body').innerHTML='<div class="odempty">No orders placed on this day.</div>'; return; }
  var money=function(n){ return '₹'+(Math.round(Number(n)||0)).toLocaleString(); };
  el('bj-od-sub').textContent=orders.length+' order'+(orders.length>1?'s':'')+' placed on '+(window._od?window._od.date:'');
  var h='';
  orders.forEach(function(o){
    h+='<div class="odorder"><div class="odsum">'
      +'<div><div class="k">Invoice</div><div class="v">'+esc(o.invoice||('#'+o.orderId))+'</div></div>'
      +'<div><div class="k">Amount</div><div class="v">'+money(o.amount)+'</div></div>'
      +'<div><div class="k">Time</div><div class="v">'+esc(o.time?hhmm(o.time):'—')+'</div></div>'
      +'</div>';
    var items=o.items||[];
    if(items.length){
      h+='<table class="odtable"><thead><tr><th>Item</th><th class="num">Qty</th><th class="num">MOP</th></tr></thead><tbody>';
      items.forEach(function(it){
        var name=[it.brand,it.model,it.color].filter(function(s){return s;}).map(esc).join(' &middot; ');
        h+='<tr><td>'+(name||'&mdash;')+'</td><td class="num">'+(it.qty||0)+'</td><td class="num">'+money(it.mop)+'</td></tr>';
      });
      h+='</tbody></table>';
    } else { h+='<div class="odempty">No line items.</div>'; }
    h+='</div>';
  });
  el('bj-od-body').innerHTML=h;
}

/* ============================ APPROVAL ============================ */
function loadApproval(){
  spinner();
  var from=el('bj-start').value, to=el('bj-end').value;
  var u=CTX+'/beat-report/approval/data?fromDate='+encodeURIComponent(from)+'&toDate='+encodeURIComponent(to)+qs();
  fetch(u,{headers:{'Accept':'application/json'}}).then(function(r){ return r.json(); }).then(function(d){
    var rows=d.rows||[];
    var h='<div class="card"><h2>Location Approval <span style="color:#97a1b5;font-weight:500;font-size:12px">&middot; '+rows.length+' off-site check-ins</span></h2>'+
      '<p class="desc">Check-ins recorded &gt;50 m from the partner\'s saved location, across your downline. Approving updates the partner\'s coordinates.</p>';
    if(!rows.length){ h+='<p class="desc">Nothing pending in this window.</p></div>'; el('bj-content').innerHTML=h; return; }
    h+='<table><thead><tr><th>Executive</th><th>Store</th><th>Date</th><th>Check-in</th><th class="num">Distance</th><th class="num">Action</th></tr></thead><tbody>';
    rows.forEach(function(r){
      h+='<tr id="appr-'+r.trackingId+'"><td>'+esc(r.username)+'</td><td>'+esc(r.taskName)+'</td><td>'+esc(r.taskDate)+'</td><td>'+esc(r.checkInTime)+'</td>'+
         '<td class="num '+(r.distanceM>200?'badflag':'warnflag')+'">'+r.distanceM+' m</td>'+
         '<td class="num"><button class="btn-ok" onclick="approve('+r.trackingId+')">Approve</button></td></tr>';
    });
    h+='</tbody></table></div>';
    el('bj-content').innerHTML=h;
  }).catch(fail);
}
function approve(trackingId){
  fetch(CTX+'/beat-report/approve-checkin',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'trackingId='+trackingId})
    .then(function(r){ return r.json(); }).then(function(){ var row=el('appr-'+trackingId); if(row) row.parentNode.removeChild(row); }).catch(function(){ alert('Approve failed'); });
}

/* ============================ EXPORT ============================ */
// Download the Employee Task Report (.xlsx). Today lens exports the single
// selected day; Period lens exports the whole start..end range. Both carry the
// current level / team scope (qs()). The download is served as an attachment, so
// navigating to the URL triggers the file save without leaving the page.
function exportReport(){
  var start, end, path;
  if(LENS==='period'){
    // Period lens: per-employee totals + a Raw Data sheet (separate endpoint).
    start=el('bj-start').value; end=el('bj-end').value; path='/export-period';
  } else {
    // Today lens: the day-grouped Employee Task Report (unchanged).
    start=el('bj-date').value; end=start; path='/export';
  }
  var u = BASE + path + '?startDate=' + encodeURIComponent(start) + '&endDate=' + encodeURIComponent(end) + qs();
  window.location.href = u;
}

/* ============================ INIT ============================ */
document.querySelectorAll('.lens').forEach(function(b){ b.addEventListener('click', function(){ setLens(b.getAttribute('data-lens')); }); });
el('bj-apply').addEventListener('click', load);
el('bj-export').addEventListener('click', exportReport);
el('bj-level').addEventListener('change', onLevelChange);
if(el('bj-user')) el('bj-user').addEventListener('change', load);
el('bj-date').addEventListener('change', updateTodayLabel);
el('bj-modal-back').addEventListener('click', function(e){ if(e.target===el('bj-modal-back')) closeModal(); });
el('bj-img-back').addEventListener('click', function(e){ if(e.target===el('bj-img-back')) bjCloseImage(); });
el('bj-img-x').addEventListener('click', bjCloseImage);
// Esc closes the lightbox first (if open), otherwise the journey modal.
document.addEventListener('keydown', function(e){
  if(e.key!=='Escape') return;
  if(el('bj-img-back').classList.contains('show')) bjCloseImage();
  else if(el('bj-modal-back').classList.contains('show')) closeModal();
});
updateTodayLabel();
load();
</script>
</body>
</html>