:root{
  --bg:      #2e1e0e;
  --bg2:     #3b2613;
  --bg3:     #7a5c3a;
  --bg4:     #8e6e48;
  --panel:   #7a5c3a;
  --panel2:  #8a6a46;
  --border:  #b08860;
  --border2: #caa878;
  --accent:  #e0a060;
  --accent2: #f0b878;
  --accent3: #ffd898;
  --gold:    #e8c060;
  --gold2:   #ffd878;
  --text:    #fff8ec;
  --text2:   #eedbb8;
  --text3:   #d4a878;
  --green:   #6abf78;
  --green2:  #88d890;
  --yellow:  #e8c040;
  --yellow2: #ffd858;
  --red:     #d05848;
  --red2:    #f07060;
  --blue:    #5090cc;
  --blue2:   #70b0e8;
  --radius:  7px;
  --shadow:  0 4px 20px rgba(0,0,0,.5);
}
/* ─ TEMA CLARO ─ */
body.theme-light{
  --bg:#f5f0e8;--bg2:#ede6d8;--bg3:#ddd5c0;--bg4:#cdc4a8;
  --panel:#fff8f0;--panel2:#f5edd8;
  --border:#c8a878;--border2:#b09060;
  --accent:#b06020;--accent2:#904010;--accent3:#7a3008;
  --gold:#9a7010;--gold2:#7a5800;
  --text:#2a1800;--text2:#4a3010;--text3:#7a5c2a;
  --green:#2a7a38;--green2:#1a6028;
  --yellow:#8a6a00;--yellow2:#6a5000;
  --red:#c03828;--red2:#a02818;
  --blue:#2860a8;--blue2:#1a4888;
  --shadow:0 4px 20px rgba(0,0,0,.15);
}
/* ─ TEMA ESCURO ─ */
body.theme-dark{
  --bg:#111418;--bg2:#181c22;--bg3:#232830;--bg4:#2e3440;
  --panel:#1e2330;--panel2:#252b3a;
  --border:#3a4458;--border2:#4a5470;
  --accent:#5a8ecc;--accent2:#7aaeee;--accent3:#9aceff;
  --gold:#d4a840;--gold2:#f0c858;
  --text:#dde8f8;--text2:#b8c8e0;--text3:#7890b0;
  --green:#48b860;--green2:#68d880;
  --yellow:#d4b830;--yellow2:#f0d850;
  --red:#d05848;--red2:#f07060;
  --blue:#5090cc;--blue2:#70b0e8;
  --shadow:0 4px 20px rgba(0,0,0,.7);
}
*{box-sizing:border-box;margin:0;padding:0;}
body{font-family:'Quattrocento Sans',sans-serif;background:var(--bg);color:var(--text);min-height:100vh;overflow-x:hidden;}
::-webkit-scrollbar{width:6px;height:6px;}
::-webkit-scrollbar-track{background:var(--bg2);}
::-webkit-scrollbar-thumb{background:var(--border2);border-radius:3px;}

/* ─ SIDEBAR ─ */
#sb{position:fixed;top:0;left:0;width:228px;height:100vh;background:var(--bg2);border-right:1px solid var(--border);display:flex;flex-direction:column;z-index:200;transition:width .28s;overflow:hidden;}
#sb.col{width:56px;}
.sb-logo{padding:12px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;}
.logo{display:flex;align-items:center;gap:.7rem;}
.logo img{height:44px;width:auto;object-fit:contain;filter:drop-shadow(0 2px 6px rgba(0,0,0,.5));}
.logo-text{font-family:'Quattrocento',serif;font-size:1.1rem;font-weight:700;white-space:nowrap;transition:opacity .18s,width .18s;}
#sb.col .logo-text{opacity:0;width:0;overflow:hidden;}
.nav-i{display:flex;align-items:center;gap:11px;padding:10px 15px;cursor:pointer;color:var(--text2);font-size:13px;transition:all .18s;white-space:nowrap;overflow:hidden;border-left:3px solid transparent;}
.nav-i:hover{background:var(--bg3);color:var(--accent2);}
.nav-i.act{background:var(--bg3);color:var(--accent3);border-left-color:var(--accent);}
.nav-ic{font-size:16px;flex-shrink:0;}
#sb.col .nav-lbl{display:none;}
.sb-tog{margin-top:auto;padding:13px;cursor:pointer;color:var(--text3);font-size:17px;text-align:center;border-top:1px solid var(--border);transition:color .2s;}
.sb-tog:hover{color:var(--accent);}

/* ─ MAIN ─ */
#main{margin-left:228px;min-height:100vh;transition:margin-left .28s;}
#sb.col~#main{margin-left:56px;}

/* ─ TOPBAR ─ */
.topbar{background:var(--bg2);border-bottom:1px solid var(--border);padding:12px 26px;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:100;}
.pg-title{font-family:'Quattrocento',serif;font-size:18px;color:var(--accent3);}
.tb-acts{display:flex;gap:9px;align-items:center;}

/* ─ BUTTONS ─ */
.btn{padding:7px 16px;border-radius:var(--radius);border:none;cursor:pointer;font-family:'Quattrocento Sans',sans-serif;font-size:12px;font-weight:700;transition:all .18s;}
.btn-p{background:var(--accent);color:#1a0800;}
.btn-p:hover{background:var(--accent2);}
.btn-s{background:var(--bg4);color:var(--text);border:1px solid var(--border2);}
.btn-s:hover{background:var(--bg3);border-color:var(--accent);}
.btn-d{background:var(--red);color:#fff;}
.btn-d:hover{background:var(--red2);}
.btn-sm{padding:4px 10px;font-size:11px;}
.btn-xs{padding:2px 7px;font-size:10px;}
.btn-exp{background:var(--bg4);color:var(--accent2);border:1px solid var(--border2);padding:6px 13px;font-size:11px;}
.btn-exp:hover{background:var(--bg3);border-color:var(--gold);}

/* ─ PAGES ─ */
.page{display:none;padding:20px 24px;}
.page.act{display:block;}

/* ─ CARD ─ */
.card{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:16px;box-shadow:var(--shadow);}
.card-t{font-family:'Quattrocento',serif;font-size:13px;color:var(--accent2);margin-bottom:11px;padding-bottom:8px;border-bottom:1px solid var(--border);}

/* ─ STATS ─ */
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:20px;}
.stat{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:14px 16px;position:relative;overflow:hidden;}
.stat::before{content:'';position:absolute;top:0;right:0;width:4px;height:100%;}
.st-g::before{background:var(--green);}
.st-y::before{background:var(--yellow);}
.st-r::before{background:var(--red2);}
.st-b::before{background:var(--blue2);}
.st-o::before{background:var(--gold);}
.stat-lbl{font-size:10px;color:var(--text3);text-transform:uppercase;letter-spacing:1px;margin-bottom:4px;}
.stat-val{font-family:'Quattrocento',serif;font-size:24px;color:var(--accent3);}
.stat-sub{font-size:10px;color:var(--text2);margin-top:2px;}

/* ─ TABLE ─ */
.tw{overflow-x:auto;border-radius:var(--radius);}
table{width:100%;border-collapse:collapse;font-size:12px;}
th{background:var(--bg3);color:var(--text2);padding:9px 10px;text-align:left;font-weight:700;letter-spacing:.3px;text-transform:uppercase;font-size:10px;border-bottom:2px solid var(--border2);white-space:nowrap;}
td{padding:7px 10px;border-bottom:1px solid var(--border);color:var(--text);vertical-align:middle;}
tr:hover td{background:rgba(110,78,50,.25);}

/* ─ INLINE EDITABLE ─ */
.ied{background:transparent;border:none;color:var(--text);font-family:'Quattrocento Sans',sans-serif;font-size:12px;cursor:pointer;padding:2px 4px;border-radius:4px;width:100%;}
.ied:hover,.ied:focus{background:var(--bg3);outline:1px solid var(--border2);}
.ied[type=date]{width:120px;color-scheme:dark;}

/* ─ STATUS BUTTONS ─ */
.sb-grp{display:flex;gap:3px;flex-wrap:nowrap;}
.sb-btn{border:none;cursor:pointer;padding:3px 8px;border-radius:4px;font-size:10px;font-weight:700;opacity:.45;transition:all .15s;white-space:nowrap;font-family:'Quattrocento Sans',sans-serif;}
.sb-btn.on{opacity:1;box-shadow:0 0 0 1px rgba(255,255,255,.2);}
.sb-btn:hover{opacity:.8;}
.sb-parado{background:rgba(160,110,80,.4);color:var(--text2);}
.sb-parado.on{background:var(--bg4);color:var(--accent2);}
.sb-andamento{background:rgba(80,144,204,.3);color:var(--blue2);}
.sb-andamento.on{background:rgba(80,144,204,.5);color:#a8d8ff;}
.sb-feito{background:rgba(106,191,120,.3);color:var(--green2);}
.sb-feito.on{background:rgba(106,191,120,.55);color:#b0f0c0;}
.sb-enviado{background:rgba(232,192,64,.3);color:var(--yellow2);}
.sb-enviado.on{background:rgba(232,192,64,.55);color:#fff0a0;}
.sb-aprovado{background:rgba(106,191,120,.3);color:var(--green2);}
.sb-aprovado.on{background:rgba(106,191,120,.55);color:#b0f0c0;}

/* ─ TIMER INLINE ─ */
.timer-cell{display:flex;align-items:center;gap:4px;min-width:120px;}
.timer-dsp{font-family:'Quattrocento',serif;font-size:12px;color:var(--accent2);letter-spacing:1px;min-width:62px;}
.timer-dsp.running{color:var(--green2);animation:blink 1s infinite;}
.timer-dsp.done{color:var(--gold);}
@keyframes blink{0%,100%{opacity:1}50%{opacity:.6}}
.tc-btn{width:22px;height:22px;border-radius:50%;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:10px;transition:all .15s;flex-shrink:0;}
.tc-play{background:var(--green);color:#fff;}
.tc-play:hover{background:var(--green2);}
.tc-pause{background:var(--yellow);color:#1a0800;}
.tc-pause:hover{background:var(--yellow2);}
.tc-done{background:var(--gold);color:#1a0800;}
.tc-done:hover{background:var(--gold2);}
.tc-reset{background:var(--bg4);color:var(--text2);border:1px solid var(--border);}
.tc-reset:hover{background:var(--bg3);}

/* ─ BADGES ─ */
.badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:12px;font-size:10px;font-weight:700;white-space:nowrap;}
.b-g{background:rgba(106,191,120,.22);color:var(--green2);border:1px solid rgba(106,191,120,.35);}
.b-b{background:rgba(80,144,204,.22);color:var(--blue2);border:1px solid rgba(80,144,204,.35);}
.b-y{background:rgba(232,192,64,.22);color:var(--yellow2);border:1px solid rgba(232,192,64,.35);}
.b-r{background:rgba(208,88,72,.22);color:var(--red2);border:1px solid rgba(208,88,72,.35);}
.b-d{background:rgba(100,70,40,.3);color:var(--text2);border:1px solid var(--border);}

/* ─ FILTERS ─ */
.filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;align-items:center;}
.fsel,.finp{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:var(--radius);padding:6px 10px;font-size:12px;font-family:'Quattrocento Sans',sans-serif;cursor:pointer;}
.fsel:focus,.finp:focus{outline:none;border-color:var(--accent);}
.finp{min-width:190px;}
.finp::placeholder{color:var(--text3);}

/* ─ MODAL ─ */
.mo{position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:1000;display:none;align-items:center;justify-content:center;}
.mo.open{display:flex;}
.md{background:var(--panel);border:1px solid var(--border2);border-radius:var(--radius);padding:24px;width:min(720px,96vw);max-height:92vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.7);}
.md-t{font-family:'Quattrocento',serif;font-size:16px;color:var(--accent3);margin-bottom:16px;padding-bottom:10px;border-bottom:1px solid var(--border);}
.fg{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
.ff{grid-column:1/-1;}
.fgr{display:flex;flex-direction:column;gap:4px;}
.fgr label{font-size:10px;color:var(--text2);text-transform:uppercase;letter-spacing:.5px;font-weight:700;}
.fgr input,.fgr select,.fgr textarea{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:var(--radius);padding:7px 10px;font-family:'Quattrocento Sans',sans-serif;font-size:13px;}
.fgr input:focus,.fgr select:focus,.fgr textarea:focus{outline:none;border-color:var(--accent);}
.fgr textarea{resize:vertical;min-height:55px;}
.md-acts{display:flex;gap:9px;justify-content:flex-end;margin-top:16px;padding-top:13px;border-top:1px solid var(--border);}

/* ─ STATUS SELECTOR in modal ─ */
.status-sel{display:flex;gap:6px;flex-wrap:wrap;}
.ss-opt{border:1px solid var(--border);border-radius:5px;padding:6px 12px;cursor:pointer;font-size:12px;font-weight:700;font-family:'Quattrocento Sans',sans-serif;background:var(--bg3);color:var(--text2);transition:all .15s;}
.ss-opt:hover{border-color:var(--accent);}
.ss-opt.sel-parado{background:var(--bg4);color:var(--accent2);border-color:var(--accent);}
.ss-opt.sel-andamento{background:rgba(80,144,204,.4);color:var(--blue2);border-color:var(--blue2);}
.ss-opt.sel-feito{background:rgba(106,191,120,.4);color:var(--green2);border-color:var(--green2);}
.ss-opt.sel-enviado{background:rgba(232,192,64,.4);color:var(--yellow2);border-color:var(--yellow2);}
.ss-opt.sel-aprovado{background:rgba(106,191,120,.4);color:var(--green2);border-color:var(--green2);}
.ss-opt.sel-revisao{background:rgba(80,144,204,.4);color:var(--blue2);border-color:var(--blue2);}
.ss-opt.sel-fazendo{background:rgba(90,180,255,.35);color:#a8d8ff;border-color:#7ab8e8;}

/* ─ GANTT MELHORADO ─ */
.m-nav{display:flex;align-items:center;gap:9px;margin-bottom:12px;}
.m-nav button{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:var(--radius);padding:4px 11px;cursor:pointer;font-size:13px;}
.m-nav button:hover{border-color:var(--accent);}
.m-lbl{font-family:'Quattrocento',serif;font-size:14px;color:var(--accent2);min-width:155px;text-align:center;}

/* Gantt table layout */
.gantt-wrap{overflow-x:auto;overflow-y:auto;border-radius:var(--radius);border:1px solid var(--border);max-height:72vh;}
.gantt-table{border-collapse:collapse;min-width:100%;font-size:11px;position:relative;}
.gantt-table th{background:var(--bg3);color:var(--text2);padding:0;border-right:1px solid var(--border);border-bottom:2px solid var(--border2);white-space:nowrap;position:sticky;top:0;z-index:10;}
.gantt-table td{border-right:1px solid var(--border);border-bottom:1px solid var(--border);padding:0;vertical-align:middle;}
/* Person header row */
.gantt-person-row td{background:var(--bg2);padding:7px 10px;font-weight:700;font-size:12px;color:var(--accent2);border-top:2px solid var(--border2);letter-spacing:.3px;}
/* OS label cell */
.gantt-lbl-cell{width:220px;min-width:220px;max-width:220px;padding:6px 10px 6px 22px;position:sticky;left:0;background:var(--panel);z-index:5;border-right:2px solid var(--border2)!important;}
.gantt-cod{font-weight:700;color:var(--accent2);font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.gantt-sub{font-size:9px;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:1px;}
/* Week header */
.gantt-wk-hdr{text-align:center;padding:5px 8px;font-size:9px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;color:var(--text3);min-width:96px;}
.gantt-wk-hdr.cur{color:var(--accent2);background:rgba(232,149,42,.08);}
/* Day cells */
.gantt-day-cell{width:22px;min-width:22px;max-width:22px;height:36px;position:relative;}
.gantt-day-cell.wk{background:rgba(0,0,0,.07);}
.gantt-day-cell.today-col{outline:2px solid var(--accent);outline-offset:-1px;z-index:2;}
/* Gantt bar */
.gantt-bar{position:absolute;top:50%;transform:translateY(-50%);height:14px;border-radius:3px;left:0;right:0;opacity:.88;z-index:1;}
.gantt-bar.status-feito{background:var(--green);}
.gantt-bar.status-andamento{background:var(--blue2);}
.gantt-bar.status-parado{background:var(--text3);}
/* Today vertical marker */
.gantt-today-marker{position:absolute;top:0;bottom:0;width:2px;background:var(--accent);z-index:6;pointer-events:none;}
/* Legend dots */
.g-legend{display:flex;gap:14px;font-size:11px;align-items:center;flex-wrap:wrap;}
.g-dot{width:11px;height:11px;border-radius:2px;display:inline-block;margin-right:4px;vertical-align:middle;}
/* Header sticky label cell */
.gantt-hdr-lbl{width:220px;min-width:220px;padding:8px 12px;position:sticky;left:0;background:var(--bg3);z-index:11;border-right:2px solid var(--border2)!important;font-size:10px;color:var(--text2);font-weight:700;text-transform:uppercase;letter-spacing:.5px;}
/* Month sub-header */
.gantt-month-cell{text-align:center;padding:4px 6px;font-size:9px;font-weight:700;color:var(--gold);letter-spacing:.5px;text-transform:uppercase;border-bottom:1px solid var(--border);}
/* Baseline mode toggle */
.gantt-mode-btn{padding:4px 11px;border-radius:var(--radius);border:1px solid var(--border);background:var(--bg3);color:var(--text2);font-size:11px;font-weight:700;cursor:pointer;transition:all .15s;}
.gantt-mode-btn.on{background:rgba(232,192,64,.2);border-color:var(--gold);color:var(--gold);}
/* Weeks view nav label */
.wk-range-lbl{font-size:11px;color:var(--text3);margin-left:6px;}

/* ─ CHARTS ─ */
.cg{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:18px;}
.cc{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:16px;}
.cc-t{font-family:'Quattrocento',serif;font-size:13px;color:var(--accent2);margin-bottom:10px;}

/* ─ EMPLOYEES ─ */
.eg{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:13px;align-items:start;}
.eg-setor-hdr{grid-column:1/-1;}
.ec{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:16px;text-align:center;}
.ea{width:72px;height:72px;border-radius:50%;background:var(--bg3);border:2px solid var(--accent);display:flex;align-items:center;justify-content:center;font-family:'Quattrocento',serif;font-size:22px;color:var(--accent2);margin:0 auto 9px;overflow:hidden;cursor:pointer;transition:border-color .2s;}
.ea:hover{border-color:var(--gold);}
.ea img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
.fa-mini{width:26px;height:26px;border-radius:50%;background:var(--bg4);border:1px solid var(--border2);display:inline-flex;align-items:center;justify-content:center;font-size:10px;color:var(--accent2);overflow:hidden;vertical-align:middle;margin-right:4px;flex-shrink:0;}
.fa-mini img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
.en{font-family:'Quattrocento',serif;font-size:13px;}
.er{font-size:10px;color:var(--text3);margin-top:2px;}
.es{display:flex;justify-content:space-around;margin-top:11px;padding-top:11px;border-top:1px solid var(--border);}
.esv{font-family:'Quattrocento',serif;font-size:16px;color:var(--accent2);}
.esl{font-size:10px;color:var(--text3);}

/* ─ CLIENTE accordion ─ */
/* ─ CLIENTE accordion ─ */
.cli-row{cursor:default;}
.cli-row td{background:var(--bg3);font-weight:700;}
.cli-row:hover td{background:var(--bg3);}
.tog-cell{cursor:pointer;text-align:center;color:var(--accent2);width:36px;padding:8px 6px !important;}
.tog-cell:hover{background:var(--bg4) !important;}
.tog-ic{transition:transform .2s;display:inline-block;font-size:13px;}
.cli-row.open .tog-ic{transform:rotate(90deg);}
.sub-row{display:none;}
.sub-row.open{display:table-row;}
.sub-row td{background:var(--panel);padding-left:30px;}
.sub-row:hover td{background:var(--panel2);}
.sub-row td:first-child{border-left:3px solid var(--accent);}

/* ─ PROGRESS ─ */
.pb{height:5px;background:var(--bg3);border-radius:3px;overflow:hidden;}
.pf{height:100%;border-radius:3px;transition:width .4s;}

/* ─ OS agrupada por cliente ─ */
.os-cli-hdr{cursor:pointer;}
.os-cli-hdr td{background:var(--bg2) !important;border-top:2px solid var(--border);border-bottom:2px solid var(--border2);padding:9px 14px !important;}
.os-cli-hdr:hover td{background:var(--bg3) !important;}
.os-cli-hdr .tog-ic{transition:transform .2s;display:inline-block;font-size:11px;}
.os-cli-hdr.open .tog-ic{transform:rotate(90deg);}
.os-row{display:none;}
.os-row.open{display:table-row;}

/* ─ SEC HDR ─ */
.shdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:13px;}
.stitle{font-family:'Quattrocento',serif;font-size:14px;color:var(--accent2);}

/* ─ ACT BTN ─ */
.ab{background:none;border:none;cursor:pointer;padding:3px 5px;border-radius:4px;font-size:12px;transition:background .15s;}
.ab:hover{background:var(--bg3);}

/* ─ EXPORT TOOLBAR ─ */
.exp-bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:14px;}
.exp-bar span{font-size:11px;color:var(--text3);}

/* ─ SE TAG ─ */
.se-tag{display:inline-flex;align-items:center;gap:3px;background:var(--bg4);border:1px solid var(--border2);border-radius:4px;padding:1px 7px;font-size:10px;color:var(--accent2);margin:1px;}

/* ─ INLINE STATUS SELECT ─ */
.isel{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:3px 6px;font-size:11px;font-weight:700;cursor:pointer;font-family:'Quattrocento Sans',sans-serif;max-width:130px;}
.isel:focus{outline:none;border-color:var(--accent);}
.isel.s-parado{background:rgba(100,68,48,.55);color:var(--text2);}
.isel.s-andamento{background:rgba(80,144,204,.35);color:var(--blue2);}
.isel.s-feito{background:rgba(106,191,120,.35);color:var(--green2);}
.isel.s-enviado{background:rgba(232,192,64,.35);color:var(--yellow2);}
.isel.s-aprovado{background:rgba(106,191,120,.35);color:var(--green2);}

/* ─ TIMER EDIT ROW ─ */
.trow{display:flex;align-items:center;gap:7px;padding:7px 0;border-bottom:1px solid var(--border);}
.trow-lbl{font-size:10px;color:var(--text3);text-transform:uppercase;letter-spacing:.5px;width:80px;flex-shrink:0;}
.trow-disp{font-family:'Quattrocento',serif;font-size:13px;color:var(--accent2);letter-spacing:1px;min-width:68px;}
.trow-disp.running{color:var(--green2);animation:blink 1s infinite;}
.trow-disp.done{color:var(--gold);}

/* ─ REPORT PAGE ─ */
.rpt-filter{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px;align-items:center;background:var(--panel);padding:14px;border-radius:var(--radius);border:1px solid var(--border);}
.rpt-card{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:18px;margin-bottom:16px;}
.rpt-card-t{font-family:'Quattrocento',serif;font-size:14px;color:var(--accent2);margin-bottom:14px;padding-bottom:9px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
.func-row{display:grid;grid-template-columns:200px 1fr 1fr 1fr 80px;gap:0;border-bottom:1px solid var(--border);align-items:center;}
.func-row:last-child{border-bottom:none;}
.func-row>div{padding:8px 10px;font-size:12px;}
.func-row.hdr>div{font-size:10px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:.5px;background:var(--bg3);}
.hbar-wrap{height:10px;background:var(--bg3);border-radius:5px;overflow:hidden;}
.hbar{height:100%;border-radius:5px;transition:width .5s;background:var(--accent);}
.func-detail-row{background:var(--bg3);font-size:11px;color:var(--text2);}
.func-detail-row>div{padding:5px 10px 5px 30px;}

/* ─ TOAST ─ */
#toast{position:fixed;bottom:20px;right:20px;background:var(--panel2);border:1px solid var(--border2);padding:10px 16px;border-radius:var(--radius);color:var(--text);font-size:13px;transform:translateY(60px);opacity:0;transition:all .28s;z-index:9999;}
#toast.show{transform:translateY(0);opacity:1;}

/* ─ MOBILE OVERLAY ─ */
#sb-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:199;}
#sb-overlay.open{display:block;}
.mob-menu-btn{display:none;background:none;border:none;cursor:pointer;color:var(--text2);font-size:20px;padding:4px 8px;border-radius:5px;line-height:1;transition:color .18s;}
.mob-menu-btn:hover{color:var(--accent);}

@media(max-width:1023px){
  #sb{width:228px;transform:translateX(-100%);transition:transform .28s;box-shadow:4px 0 24px rgba(0,0,0,.5);}
  #sb.sb-open{transform:translateX(0);}
  #sb.mob-open{transform:translateX(0);}
  #sb.col{width:228px;}
  #sb.col .nav-lbl{display:inline;}
  #sb.col .logo-text{opacity:1;width:auto;overflow:visible;}
  #main{margin-left:0!important;}
  #sb.col~#main{margin-left:0!important;}
  .mob-menu-btn{display:flex;align-items:center;}
  .cg{grid-template-columns:1fr;}
  .fg{grid-template-columns:1fr;}
  .topbar{padding:10px 14px;}
  .page{padding:14px 14px;}
  .filters{flex-direction:column;align-items:stretch;}
  .finp{min-width:0;}
}

/* ── Visibilidade de valores financeiros ──
   .adm-only  → oculto por padrão; visível apenas via classes escopadas por módulo
   .hide-values → força ocultamento residual (edge cases de banco legado) */
.adm-only { display: none !important; }
.is-admin .adm-only { display: flex !important; }
.is-admin .stat.adm-only { display: flex !important; }
.is-admin td.adm-only, .is-admin th.adm-only { display: table-cell !important; }
.is-admin button.adm-only, .is-admin a.adm-only { display: inline-flex !important; }
/* Não-admin com eng:semvalor ou eng:view — força ocultamento */
.hide-values .adm-only { display: none !important; }
.hide-values .val-only { display: none !important; }
/* Página com adm-only ativa via nav() */
.is-admin .page.adm-only.act { display: block !important; }
/* Cards de total do acomp — escopados por módulo (Bug 6 fix) */
.is-admin .acomp-total-card.adm-only { display: flex !important; flex-direction: column; }
/* Permissões escopadas por módulo (não-admin) */
/* eng:tudo → valores visíveis APENAS dentro da página de Engenharia */
.eng-values-on #page-engenharia .adm-only { display: flex !important; }
.eng-values-on #page-engenharia .stat.adm-only { display: flex !important; }
.eng-values-on #page-engenharia td.adm-only,
.eng-values-on #page-engenharia th.adm-only { display: table-cell !important; }
.eng-values-on #page-engenharia button.adm-only,
.eng-values-on #page-engenharia a.adm-only { display: inline-flex !important; }
/* acomp:tudo → valores visíveis APENAS dentro da página de Acomp. Produção */
.acomp-values-on #page-acomp .adm-only { display: flex !important; }
.acomp-values-on #page-acomp .stat.adm-only { display: flex !important; }
.acomp-values-on #page-acomp td.adm-only,
.acomp-values-on #page-acomp th.adm-only { display: table-cell !important; }
.acomp-values-on #page-acomp .acomp-total-card.adm-only { display: flex !important; flex-direction: column; }
.acomp-values-on #page-acomp .adm-only[style*="text-align:right"] { display: block !important; }
/* Dashboard Financeiro — visível apenas para admin ou quem tem permissão dashfin */
#page-dashfin { display: none !important; }
.is-admin #page-dashfin.act { display: block !important; }
.dashfin-allowed #page-dashfin.act { display: block !important; }

/* ─ THEME TOGGLE ─ */
.theme-btn{background:var(--bg3);border:1px solid var(--border);border-radius:var(--radius);padding:5px 10px;cursor:pointer;font-size:12px;color:var(--text2);display:flex;align-items:center;gap:5px;transition:all .18s;}
.theme-btn:hover{border-color:var(--accent);color:var(--accent2);}
.theme-picker{position:absolute;right:0;top:40px;background:var(--bg2);border:1px solid var(--border2);border-radius:var(--radius);box-shadow:var(--shadow);z-index:9000;display:none;min-width:150px;overflow:hidden;}
.theme-picker.open{display:block;}
.theme-opt{padding:9px 14px;cursor:pointer;font-size:12px;color:var(--text2);display:flex;align-items:center;gap:8px;transition:background .15s;}
.theme-opt:hover{background:var(--bg3);color:var(--accent2);}
.theme-opt.active{background:var(--bg3);color:var(--accent3);}

/* ─ COMPRAS ─ */
.comp-status-pend{background:rgba(232,192,64,.25);color:var(--yellow2);border:1px solid rgba(232,192,64,.5);}
.comp-status-aprov{background:rgba(106,191,120,.25);color:var(--green2);border:1px solid rgba(106,191,120,.5);}
.comp-status-receb{background:rgba(80,144,204,.25);color:var(--blue2);border:1px solid rgba(80,144,204,.5);}
.comp-status-cancel{background:rgba(208,88,72,.25);color:var(--red2);border:1px solid rgba(208,88,72,.5);}
.comp-attach{display:inline-flex;align-items:center;gap:4px;background:var(--bg3);border:1px solid var(--border2);border-radius:4px;padding:2px 8px;font-size:10px;cursor:pointer;color:var(--accent2);text-decoration:none;transition:background .15s;margin:1px;}
.comp-attach:hover{background:var(--bg4);}

/* ─ ACOMPANHAMENTO PRODUÇÃO ─ */
.acomp-parado{background:rgba(110,78,50,.4);color:var(--text2);}
.acomp-andamento{background:rgba(80,144,204,.4);color:#a8d8ff;}
.acomp-feito{background:rgba(106,191,120,.4);color:var(--green2);}
.acomp-sel{padding:3px 6px;border-radius:5px;font-size:10px;font-weight:700;cursor:pointer;border:1px solid var(--border);font-family:'Quattrocento Sans',sans-serif;max-width:110px;}
.acomp-sel:focus{outline:none;border-color:var(--accent);}
/* etapa badge card */
.etapa-card{display:inline-flex;flex-direction:column;align-items:center;border-radius:6px;padding:5px 4px;width:78px;min-height:58px;border:1px solid transparent;transition:all .15s;cursor:pointer;position:relative;justify-content:center;}
.etapa-card:hover{opacity:.85;border-color:var(--accent);}
.etapa-card.ep-parado{background:rgba(110,78,50,.3);border-color:rgba(110,78,50,.5);}
.etapa-card.ep-andamento{background:rgba(80,144,204,.25);border-color:rgba(80,144,204,.5);}
.etapa-card.ep-feito{background:rgba(106,191,120,.25);border-color:rgba(106,191,120,.5);}
.etapa-card .ep-lbl{font-size:9px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;color:var(--text3);}
.etapa-card.ep-andamento .ep-lbl{color:#7ab8e8;}
.etapa-card.ep-feito .ep-lbl{color:var(--green2);}
.etapa-card .ep-status{font-size:10px;font-weight:700;margin-top:1px;}
.etapa-card .ep-data{font-size:8px;color:var(--text3);margin-top:2px;letter-spacing:.2px;}
.etapa-card.ep-feito .ep-data{color:var(--green2);}
.acomp-row-card{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:10px;overflow:hidden;}
.acomp-row-card:hover{border-color:var(--accent);}
.acomp-row-top{display:flex;align-items:center;gap:12px;padding:10px 14px;border-bottom:1px solid var(--border);flex-wrap:wrap;}
.acomp-row-etapas{display:flex;gap:6px;padding:10px 14px;flex-wrap:wrap;align-items:stretch;}
.acomp-row-extra{display:flex;gap:14px;padding:8px 14px;background:var(--bg2);border-top:1px solid var(--border);flex-wrap:wrap;align-items:center;}
.acomp-cod{font-family:'Quattrocento',serif;font-size:15px;color:var(--accent2);font-weight:700;min-width:70px;}
.acomp-cli{font-size:11px;color:var(--text2);max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.acomp-sub{font-size:11px;color:var(--text3);max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
/* stats totais */
.acomp-totals{display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap;}
.acomp-total-card{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);padding:12px 18px;min-width:150px;flex:1;}
.acomp-total-lbl{font-size:9px;color:var(--text3);text-transform:uppercase;letter-spacing:.8px;margin-bottom:4px;}
.acomp-total-val{font-family:'Quattrocento',serif;font-size:20px;color:var(--accent2);}
.acomp-total-sub{font-size:10px;color:var(--text3);margin-top:2px;}

/* ─ ORÇAMENTOS KANBAN ─ */
.orc-col{background:var(--bg2);border:1px solid var(--border);border-radius:var(--radius);padding:12px;min-height:180px;display:flex;flex-direction:column;gap:10px;}
.orc-col-hdr{font-family:'Quattrocento',serif;font-size:13px;font-weight:700;padding:8px 12px;border-radius:5px;margin-bottom:4px;display:flex;align-items:center;justify-content:space-between;}
.orc-col-afazer .orc-col-hdr{background:rgba(142,110,72,.35);color:var(--accent3);}
.orc-col-andamento .orc-col-hdr{background:rgba(80,144,204,.3);color:var(--blue2);}
.orc-col-concluido .orc-col-hdr{background:rgba(106,191,120,.3);color:var(--green2);}
.orc-card{background:var(--panel);border:1px solid var(--border2);border-radius:6px;padding:11px 13px;cursor:pointer;transition:box-shadow .15s,border-color .15s;}
.orc-card:hover{border-color:var(--accent);box-shadow:0 2px 12px rgba(0,0,0,.3);}
.orc-card-title{font-size:12px;font-weight:700;color:var(--text);margin-bottom:6px;line-height:1.4;}
.orc-card-meta{font-size:10px;color:var(--text3);display:flex;flex-wrap:wrap;gap:5px;align-items:center;}
.orc-badge-parado{background:rgba(142,110,72,.35);color:var(--accent2);padding:1px 7px;border-radius:10px;font-size:10px;font-weight:700;}
.orc-badge-revisao{background:rgba(80,144,204,.3);color:var(--blue2);padding:1px 7px;border-radius:10px;font-size:10px;font-weight:700;}
.orc-badge-fazendo{background:rgba(80,144,204,.4);color:#a8d8ff;padding:1px 7px;border-radius:10px;font-size:10px;font-weight:700;}
.orc-badge-enviado{background:rgba(106,191,120,.4);color:var(--green2);padding:1px 7px;border-radius:10px;font-size:10px;font-weight:700;}

/* ─ NOTIFICATION BELL PER USER ─ */
.notif-dot{position:absolute;top:-4px;right:-4px;background:var(--red);color:#fff;border-radius:50%;width:17px;height:17px;font-size:9px;font-weight:700;display:flex;align-items:center;justify-content:center;}

/* ── Logo sem fundo branco ── */

/* ─ ENGENHARIA SUB-TABS ─ */
.eng-tabs{display:flex;gap:0;border-bottom:2px solid var(--border);margin-bottom:18px;overflow-x:auto;flex-wrap:nowrap;}
.eng-tab{padding:9px 18px;cursor:pointer;font-size:12px;font-weight:700;color:var(--text2);border-bottom:3px solid transparent;margin-bottom:-2px;white-space:nowrap;transition:all .18s;letter-spacing:.3px;}
.eng-tab:hover{color:var(--accent2);background:var(--bg3);}
.eng-tab.act{color:var(--accent3);border-bottom-color:var(--accent);background:var(--bg3);}
.eng-panel{display:none;}
.eng-panel.act{display:block;}

/* ─ MOB APROV STATUS ─ */
.mob-aprov-sel{background:var(--bg3);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:3px 7px;font-size:11px;font-weight:700;cursor:pointer;font-family:'Quattrocento Sans',sans-serif;transition:all .15s;}
.mob-aprov-sel:focus{outline:none;border-color:var(--accent);}
.mob-aprov-parado{background:rgba(100,68,48,.55);color:var(--text2);border-color:rgba(160,110,80,.4);}
.mob-aprov-andamento{background:rgba(80,144,204,.35);color:var(--blue2);border-color:rgba(80,144,204,.5);}
.mob-aprov-feito{background:rgba(106,191,120,.35);color:var(--green2);border-color:rgba(106,191,120,.5);}

/* ─ MOB CHECKLIST ─ */
.mob-etapas-row{display:none;background:var(--bg2);}
.mob-etapas-row.open{display:table-row;}
.mob-etapas-row td{border-bottom:2px solid var(--border2);padding:10px 14px 10px 38px !important;}
.mob-etapas-wrap{display:flex;flex-wrap:wrap;gap:6px;align-items:center;}
.mob-etapa-chip{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid;transition:all .15s;user-select:none;}
.mob-etapa-chip.off{background:rgba(100,68,48,.3);border-color:rgba(160,110,80,.4);color:var(--text3);}
.mob-etapa-chip.on{background:rgba(106,191,120,.25);border-color:rgba(106,191,120,.55);color:var(--green2);}
.mob-etapa-chip:hover{opacity:.8;transform:scale(1.03);}
.mob-etapa-chip .chk-ic{font-size:10px;}
.mob-etapas-prog{display:flex;align-items:center;gap:8px;margin-left:8px;}
.mob-etapas-lbl{font-size:10px;color:var(--text3);white-space:nowrap;}
/* ─ SUB-ELEMENTOS DO MOBILIÁRIO ─ */
.mob-sub-block{border:1px solid var(--border);border-radius:6px;background:var(--bg3);padding:8px 12px;margin-bottom:8px;}
.mob-sub-header{display:flex;align-items:center;gap:8px;margin-bottom:6px;}
.mob-sub-nome{font-size:12px;font-weight:700;color:var(--accent2);flex:1;}
.mob-sub-del{background:none;border:1px solid var(--border);border-radius:4px;cursor:pointer;padding:1px 6px;font-size:10px;color:var(--red2);transition:all .15s;}
.mob-sub-del:hover{border-color:var(--red2);background:rgba(208,88,72,.15);}
.mob-sub-add-row{display:flex;align-items:center;gap:6px;margin-top:8px;}
.mob-sub-inp{flex:1;background:var(--bg2);border:1px solid var(--border2);border-radius:4px;color:var(--text);font-family:'Quattrocento Sans',sans-serif;font-size:11px;padding:4px 8px;}
.mob-sub-inp:focus{outline:1px solid var(--accent);border-color:var(--accent);}
.mob-sub-inp::placeholder{color:var(--text3);}
.mob-sub-add-btn{background:var(--accent);color:#1a0800;border:none;border-radius:4px;cursor:pointer;padding:4px 10px;font-size:11px;font-weight:700;font-family:'Quattrocento Sans',sans-serif;transition:all .15s;white-space:nowrap;}
.mob-sub-add-btn:hover{background:var(--accent2);}

/* ─ MOB TOGGLE ETAPAS BTN ─ */
.mob-tog-etapas{background:none;border:1px solid var(--border);border-radius:4px;cursor:pointer;padding:2px 7px;font-size:10px;font-weight:700;color:var(--text3);transition:all .15s;white-space:nowrap;}
.mob-tog-etapas:hover{border-color:var(--accent);color:var(--accent2);}
.mob-tog-etapas.open{background:var(--bg3);color:var(--accent2);border-color:var(--accent);}

/* ─ MOB APROVADOS TAB ─ */
.mob-aprov-badge{display:inline-flex;align-items:center;gap:4px;background:rgba(106,191,120,.2);border:1px solid rgba(106,191,120,.4);color:var(--green2);border-radius:10px;padding:1px 8px;font-size:10px;font-weight:700;margin-left:6px;}

/* ─ TOPBAR OBRA PROGRESS DROPDOWN ─ */
#obraProgressWrap{display:none;position:relative;}
#obraProgressWrap.visible{display:inline-block;}
.obr-drop-btn{background:var(--bg4);color:var(--accent2);border:1px solid var(--border2);border-radius:var(--radius);padding:6px 13px;font-size:11px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:6px;font-family:'Quattrocento Sans',sans-serif;transition:all .18s;white-space:nowrap;}
.obr-drop-btn:hover{background:var(--bg3);border-color:var(--accent);}
.obr-drop-btn .obr-arrow{font-size:8px;transition:transform .2s;display:inline-block;}
.obr-drop-btn.open .obr-arrow{transform:rotate(180deg);}
.obr-drop-panel{position:absolute;right:0;top:calc(100% + 7px);background:var(--bg2);border:1px solid var(--border2);border-radius:var(--radius);padding:14px 16px;min-width:230px;box-shadow:0 8px 32px rgba(0,0,0,.65);z-index:9100;display:none;}
.obr-drop-panel.open{display:block;}
.obr-dp-group{margin-bottom:11px;}
.obr-dp-group:last-child{margin-bottom:0;}
.obr-dp-lbl{font-size:9px;color:var(--text3);text-transform:uppercase;letter-spacing:.8px;font-weight:700;margin-bottom:5px;}
.obr-dp-badges{display:flex;gap:4px;flex-wrap:wrap;}
.obr-b{border-radius:4px;padding:2px 7px;font-size:10px;font-weight:700;white-space:nowrap;border:1px solid transparent;}
.obr-b-parado{background:rgba(142,110,72,.4);color:var(--text2);border-color:rgba(190,150,100,.4);}
.obr-b-and{background:rgba(80,144,204,.35);color:var(--blue2);border-color:rgba(80,144,204,.5);}
.obr-b-feito{background:rgba(106,191,120,.35);color:var(--green2);border-color:rgba(106,191,120,.5);}
.obr-b-env{background:rgba(232,192,64,.35);color:var(--yellow2);border-color:rgba(232,192,64,.5);}
.obr-b-aprov{background:rgba(106,191,120,.55);color:#b0f0c0;border-color:rgba(106,191,120,.7);}
.mob-aprov-retornar{background:none;border:1px solid rgba(232,192,64,.5);border-radius:4px;cursor:pointer;padding:2px 9px;font-size:10px;font-weight:700;color:var(--yellow2);transition:all .15s;}
.mob-aprov-retornar:hover{background:rgba(232,192,64,.2);border-color:var(--yellow);}

/* ─ SORT HEADERS ─ */
th.sortable{cursor:pointer;user-select:none;white-space:nowrap;}
th.sortable:hover{background:var(--bg4);color:var(--accent2);}
th.sortable .sort-ic{display:inline-block;margin-left:4px;font-size:9px;opacity:.4;vertical-align:middle;transition:opacity .15s;}
th.sortable.sort-asc .sort-ic{opacity:1;color:var(--accent);}
th.sortable.sort-asc .sort-ic::after{content:'▲';}
th.sortable.sort-desc .sort-ic{opacity:1;color:var(--accent);}
th.sortable.sort-desc .sort-ic::after{content:'▼';}
th.sortable:not(.sort-asc):not(.sort-desc) .sort-ic::after{content:'⇅';}

/* ─ DRE PERMISSION ─ */
#acompTabDRE { display: none; }
.dre-allowed #acompTabDRE,
.is-admin #acompTabDRE { display: inline-block; }
#acompPanelDRE { display: none; }
.dre-panel-visible { display: block !important; }

/* ─ NF CHECKBOX ─ */
.nf-wrap { display:flex; align-items:center; gap:6px; }
.nf-chk  { width:16px; height:16px; cursor:pointer; accent-color:var(--accent); flex-shrink:0; }
.nf-date { background:var(--bg3); color:var(--text); border:1px solid var(--border);
           border-radius:5px; padding:3px 7px; font-size:10px; font-family:'Quattrocento Sans',sans-serif;
           cursor:pointer; transition:border-color .15s; width:115px; }
.nf-date:focus  { outline:none; border-color:var(--accent); }
.nf-badge { font-size:9px; background:rgba(106,191,120,.3); color:var(--green2);
            border:1px solid rgba(106,191,120,.5); border-radius:10px;
            padding:1px 7px; white-space:nowrap; font-weight:700; }
.nf-date.nf-hidden { display:none; }

/* ─ DRE CHART PANEL ─ */
#acompPanelDRE .dre-totals { display:flex; gap:12px; margin-bottom:18px; flex-wrap:wrap; }
#acompPanelDRE .dre-card   { background:var(--panel); border:1px solid var(--border);
  border-radius:var(--radius); padding:14px 18px; min-width:150px; flex:1; }

/* ─ CHAT PAGE ─ */
#chat-wrap{display:flex;gap:0;height:calc(100vh - 70px);overflow:hidden;}
    #chat-sidebar{width:260px;flex-shrink:0;background:var(--bg2);border-right:1px solid var(--border);display:flex;flex-direction:column;}
    #chat-tabs{display:flex;border-bottom:1px solid var(--border);}
    .chat-tab{flex:1;padding:11px 6px;text-align:center;font-size:.82rem;cursor:pointer;color:var(--text3);border:none;background:none;border-bottom:2px solid transparent;transition:all .2s;font-family:inherit;}
    .chat-tab.ativo{color:var(--accent2);border-bottom-color:var(--accent);}
    #chat-sidebar-lista{flex:1;overflow-y:auto;}
    .chat-func-item{padding:10px 14px;cursor:pointer;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;transition:background .15s;}
    .chat-func-item:hover{background:var(--bg3);}
    .chat-func-item.ativo{background:var(--bg3);}
    .chat-func-avatar{width:34px;height:34px;border-radius:50%;background:var(--accent);display:flex;align-items:center;justify-content:center;font-size:.85rem;font-weight:700;color:#fff;flex-shrink:0;overflow:hidden;}
    .chat-func-avatar img{width:100%;height:100%;object-fit:cover;border-radius:50%;}
    .chat-func-nome{font-size:.88rem;color:var(--text);}
    .chat-func-cargo{font-size:.72rem;color:var(--text3);}
    .chat-badge-item{margin-left:auto;background:var(--red);color:#fff;border-radius:999px;font-size:.7rem;min-width:18px;height:18px;display:flex;align-items:center;justify-content:center;padding:0 5px;}
    #chat-main{flex:1;display:flex;flex-direction:column;overflow:hidden;}
    #chat-header{padding:14px 18px;border-bottom:1px solid var(--border);background:var(--bg2);flex-shrink:0;display:flex;align-items:center;gap:12px;}
    #chat-msgs{flex:1;overflow-y:auto;padding:16px 18px;display:flex;flex-direction:column;gap:10px;scroll-behavior:smooth;}
    .chat-msg{display:flex;flex-direction:column;}
    .chat-msg.eu{align-items:flex-end;}
    .chat-msg.deles{align-items:flex-start;}
    .chat-msg-meta{font-size:.7rem;color:var(--text3);margin-bottom:3px;}
    .chat-bubble{max-width:78%;padding:9px 14px;font-size:.9rem;line-height:1.45;word-break:break-word;}
    .chat-msg.eu .chat-bubble{background:var(--accent);color:#fff;border-radius:14px 14px 4px 14px;}
    .chat-msg.deles .chat-bubble{background:var(--bg3);color:var(--text);border-radius:14px 14px 14px 4px;}
    #chat-input-area{padding:12px 16px;border-top:1px solid var(--border);background:var(--bg2);flex-shrink:0;display:flex;gap:8px;align-items:flex-end;}
    #chat-input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:var(--radius);color:var(--text);padding:9px 13px;font-size:.9rem;outline:none;resize:none;max-height:100px;font-family:inherit;line-height:1.4;}
    #chat-input:focus{border-color:var(--accent);}
    #chat-send-btn{background:var(--accent);color:#fff;border:none;border-radius:var(--radius);padding:9px 18px;font-size:.9rem;font-weight:700;cursor:pointer;transition:background .2s;flex-shrink:0;font-family:inherit;}
    #chat-send-btn:hover{background:var(--accent2);}
    #chat-counter-bar{text-align:right;padding:2px 16px 6px;font-size:.7rem;color:var(--text3);}
    @media(max-width:600px){#chat-sidebar{width:200px;}#chat-wrap{height:calc(100vh - 60px);}}

    /* ── Delete button + ticks ── */
    .chat-bubble-wrap{display:flex;align-items:flex-end;gap:5px;max-width:100%;}
    .chat-msg.eu  .chat-bubble-wrap{flex-direction:row-reverse;}
    .chat-msg.eu  .chat-bubble-wrap .chat-del-btn{order:1;}
    .chat-del-btn{
      opacity:0;background:none;border:none;cursor:pointer;font-size:.85rem;
      color:var(--text3);padding:2px 4px;border-radius:4px;transition:opacity .15s,color .15s;
      flex-shrink:0;line-height:1;
    }
    .chat-msg:hover .chat-del-btn{opacity:1;}
    .chat-del-btn:hover{color:var(--red2);}
    .chat-tick-wrap{display:inline-block;margin-left:5px;}
    .chat-tick{font-size:.72rem;color:var(--text3);letter-spacing:-2px;}
    .chat-tick.lido{color:var(--blue2);}
/**
 * designers.js — Módulo Cadastro Designers
 * Gestão de Projetos — integra com acomp.js e mobiliarios.js
 *
 * localStorage keys utilizadas:
 *   designers_list        → cadastro de designers
 *   designers_produtos    → cadastro de produtos + estoque
 *   designers_mov_estoque → histórico de movimentações de estoque
 *   designers_pedidos     → todos os pedidos (OS)
 *   designers_ped_estoque → pedidos enviados ao estoque
 *   designers_ped_producao→ pedidos enviados à produção
 *
 * Integração:
 *   "Pedido Estoque" → envia para acomp_items    (usado por acomp.js)
 *   "Pedido Produção" → envia para mob_pedidos   (usado por mobiliarios.js)
 *   ⚠️ Ajuste os nomes das chaves abaixo conforme seu sistema existente
 */

// ═══════════════════════════════════════════
// CHAVES DE INTEGRAÇÃO — ajuste se necessário
// ═══════════════════════════════════════════
const D_ACOMP_KEY    = 'acomp_items';    // chave usada por acomp.js
const D_MOB_KEY      = 'mob_pedidos';    // chave usada por mobiliarios.js

// ═══════════════════════════════════════════
// ESTADO TEMPORÁRIO DO MODAL DE PEDIDO
// ═══════════════════════════════════════════
let dPedidoTemp = {
  designers: [],  // [{id, nome}]
  itens: []       // [{produtoId, nomeProduto, qtd, valorVenda, valorMargem}]
};

let dPedidoDecisaoId  = null;  // id do pedido aguardando decisão
let dEnvioEstoqueId   = null;  // id aguardando confirmação de datas estoque
let dEnvioProducaoId  = null;  // id aguardando confirmação de datas produção

// ═══════════════════════════════════════════
// UTILITÁRIOS
// ═══════════════════════════════════════════
const dGet  = key       => JSON.parse(localStorage.getItem(key) || '[]');
const dSet  = (key, val) => localStorage.setItem(key, JSON.stringify(val));
const dUID  = ()        => Date.now().toString(36) + Math.random().toString(36).slice(2,6);
const dFmt  = v         => 'R$ ' + parseFloat(v||0).toFixed(2).replace('.',',').replace(/\B(?=(\d{3})+(?!\d))/g,'.');
const dFmtDate = d      => d ? d.split('-').reverse().join('/') : '—';

function dShowToast(msg, tipo='ok') {
  const t = document.createElement('div');
  t.textContent = msg;
  t.style.cssText = `position:fixed;bottom:28px;right:28px;z-index:9999;padding:12px 20px;
    border-radius:8px;font-size:13px;font-family:inherit;box-shadow:0 4px 16px #0003;
    background:${tipo==='ok'?'#1a7f4e':tipo==='warn'?'#c07a10':'#b33'};color:#fff;
    animation:fadeInUp .3s ease;`;
  document.body.appendChild(t);
  setTimeout(()=>t.remove(), 3200);
}

// ═══════════════════════════════════════════
// NAVEGAÇÃO DE TABS
// ═══════════════════════════════════════════
function dTab(tabId) {
  document.querySelectorAll('.dtab-content').forEach(el => el.style.display = 'none');
  document.getElementById('dtab-' + tabId).style.display = 'block';
  document.querySelectorAll('#designersTabs .eng-tab').forEach(b => b.classList.remove('active'));
  const idx = ['cadastro','produtos','estoque','pedido','ped-estoque','ped-producao'].indexOf(tabId);
  const tabs = document.querySelectorAll('#designersTabs .eng-tab');
  if (tabs[idx]) tabs[idx].classList.add('active');
  // Re-renderiza a aba ativa
  if (tabId === 'cadastro')     dRenderDesigners();
  if (tabId === 'produtos')     dRenderProdutos();
  if (tabId === 'estoque')      dRenderEstoque();
  if (tabId === 'pedido')       dRenderPedidos();
  if (tabId === 'ped-estoque')  dRenderPedEstoque();
  if (tabId === 'ped-producao') dRenderPedProducao();
}

// ═══════════════════════════════════════════
// MODAIS
// ═══════════════════════════════════════════
function dOpenModal(tipo) {
  if (tipo === 'designer') {
    document.getElementById('dDesignerId').value  = '';
    document.getElementById('dDesignerNome').value = '';
    document.getElementById('dDesignerEmail').value = '';
    document.getElementById('dDesignerTel').value  = '';
    document.getElementById('dDesignerEspec').value = '';
    document.getElementById('dModalDesignerTitle').textContent = 'Novo Designer';
    document.getElementById('dModalDesigner').style.display = 'flex';
  }
  if (tipo === 'produto') {
    document.getElementById('dProdutoId').value    = '';
    document.getElementById('dProdutoNome').value  = '';
    document.getElementById('dProdutoDesc').value  = '';
    document.getElementById('dProdutoCusto').value = '';
    document.getElementById('dProdutoVenda').value = '';
    document.getElementById('dProdutoMargem').value = '';
    document.getElementById('dProdutoEstoqueInicial').value = '0';
    document.getElementById('dModalProdutoTitle').textContent = 'Novo Produto';
    document.getElementById('dModalProduto').style.display = 'flex';
  }
  if (tipo === 'entrada-estoque') {
    const sel = document.getElementById('dEstoqueProduto');
    sel.innerHTML = '<option value="">Selecionar produto...</option>';
    dGet('designers_produtos').forEach(p => {
      sel.innerHTML += `<option value="${p.id}">${p.nome}</option>`;
    });
    document.getElementById('dEstoqueQtd').value  = '';
    document.getElementById('dEstoqueResp').value = '';
    document.getElementById('dEstoqueObs').value  = '';
    document.getElementById('dModalEntradaEstoque').style.display = 'flex';
  }
  if (tipo === 'pedido') {
    dPedidoTemp = { designers: [], itens: [] };
    document.getElementById('dPedidoId').value = '';
    document.getElementById('dPedidoOS').value = '';
    document.getElementById('dPedidoDataInicio').value = '';
    document.getElementById('dPedidoDataFim').value = '';
    document.getElementById('dAlertaEstoque').style.display = 'none';
    dPopulateDesignerSelect();
    dPopulateProdutoSelect();
    dRenderTagsDesignerPedido();
    dRenderItensPedido();
    dAtualizarTotais();
    document.getElementById('dModalPedido').style.display = 'flex';
  }
}

function dCloseModal(tipo) {
  const map = {
    'designer':       'dModalDesigner',
    'produto':        'dModalProduto',
    'entrada-estoque':'dModalEntradaEstoque',
    'pedido':         'dModalPedido',
    'decisao':        'dModalDecisao',
    'datas-estoque':  'dModalDatasEstoque',
    'datas-producao': 'dModalDatasProducao'
  };
  if (map[tipo]) document.getElementById(map[tipo]).style.display = 'none';
}

// ═══════════════════════════════════════════
// CRUD DESIGNERS
// ═══════════════════════════════════════════
function dSaveDesigner() {
  const nome = document.getElementById('dDesignerNome').value.trim();
  if (!nome) { dShowToast('Informe o nome do designer', 'err'); return; }
  const list = dGet('designers_list');
  const id   = document.getElementById('dDesignerId').value;
  const obj  = {
    id:    id || dUID(),
    nome,
    email: document.getElementById('dDesignerEmail').value.trim(),
    tel:   document.getElementById('dDesignerTel').value.trim(),
    espec: document.getElementById('dDesignerEspec').value.trim()
  };
  if (id) {
    const i = list.findIndex(d => d.id === id);
    if (i >= 0) list[i] = obj; else list.push(obj);
  } else {
    list.push(obj);
  }
  dSet('designers_list', list);
  dCloseModal('designer');
  dRenderDesigners();
  dShowToast('Designer salvo com sucesso!');
}

function dEditDesigner(id) {
  const d = dGet('designers_list').find(x => x.id === id);
  if (!d) return;
  document.getElementById('dDesignerId').value   = d.id;
  document.getElementById('dDesignerNome').value  = d.nome;
  document.getElementById('dDesignerEmail').value = d.email || '';
  document.getElementById('dDesignerTel').value   = d.tel   || '';
  document.getElementById('dDesignerEspec').value = d.espec || '';
  document.getElementById('dModalDesignerTitle').textContent = 'Editar Designer';
  document.getElementById('dModalDesigner').style.display = 'flex';
}

function dDeleteDesigner(id) {
  if (!confirm('Excluir este designer?')) return;
  dSet('designers_list', dGet('designers_list').filter(d => d.id !== id));
  dRenderDesigners();
  dShowToast('Designer removido', 'warn');
}

function dRenderDesigners() {
  const q    = (document.getElementById('dSearchDesigner')?.value || '').toLowerCase();
  const list = dGet('designers_list').filter(d => d.nome.toLowerCase().includes(q));
  const tbody = document.getElementById('bodyDesigners');
  if (!tbody) return;
  if (!list.length) {
    tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#999;padding:20px">Nenhum designer cadastrado</td></tr>';
    return;
  }
  tbody.innerHTML = list.map((d, i) => `
    <tr>
      <td>${i+1}</td>
      <td><strong>${d.nome}</strong></td>
      <td>${d.email||'—'}</td>
      <td>${d.tel||'—'}</td>
      <td>${d.espec||'—'}</td>
      <td>
        <button class="d-btn-xs" onclick="dEditDesigner('${d.id}')">✏️ Editar</button>
        <button class="d-btn-xs d-btn-xs-danger" onclick="dDeleteDesigner('${d.id}')">🗑️</button>
      </td>
    </tr>`).join('');
}

// ═══════════════════════════════════════════
// CRUD PRODUTOS
// ═══════════════════════════════════════════
function dSaveProduto() {
  const nome = document.getElementById('dProdutoNome').value.trim();
  if (!nome) { dShowToast('Informe o nome do produto', 'err'); return; }
  const list = dGet('designers_produtos');
  const id   = document.getElementById('dProdutoId').value;
  const estoqueInicial = parseInt(document.getElementById('dProdutoEstoqueInicial').value) || 0;
  const obj = {
    id:         id || dUID(),
    nome,
    desc:       document.getElementById('dProdutoDesc').value.trim(),
    custo:      parseFloat(document.getElementById('dProdutoCusto').value) || 0,
    valorVenda: parseFloat(document.getElementById('dProdutoVenda').value) || 0,
    margem:     parseFloat(document.getElementById('dProdutoMargem').value) || 0,
    estoque:    id ? (list.find(p=>p.id===id)?.estoque||0) : estoqueInicial
  };
  if (!id && estoqueInicial > 0) {
    // Registra movimentação de entrada inicial
    const movs = dGet('designers_mov_estoque');
    movs.push({ id:dUID(), data: new Date().toISOString().slice(0,10),
      produtoId: obj.id, nomeProduto: obj.nome,
      tipo: 'Entrada Inicial', qtd: estoqueInicial, resp: 'Sistema', os: '—' });
    dSet('designers_mov_estoque', movs);
  }
  if (id) {
    const i = list.findIndex(p => p.id === id);
    if (i >= 0) list[i] = obj; else list.push(obj);
  } else {
    list.push(obj);
  }
  dSet('designers_produtos', list);
  dCloseModal('produto');
  dRenderProdutos();
  dShowToast('Produto salvo com sucesso!');
}

function dEditProduto(id) {
  const p = dGet('designers_produtos').find(x => x.id === id);
  if (!p) return;
  document.getElementById('dProdutoId').value    = p.id;
  document.getElementById('dProdutoNome').value  = p.nome;
  document.getElementById('dProdutoDesc').value  = p.desc  || '';
  document.getElementById('dProdutoCusto').value = p.custo || '';
  document.getElementById('dProdutoVenda').value = p.valorVenda || '';
  document.getElementById('dProdutoMargem').value= p.margem || '';
  document.getElementById('dProdutoEstoqueInicial').value = p.estoque || 0;
  document.getElementById('dModalProdutoTitle').textContent = 'Editar Produto';
  document.getElementById('dModalProduto').style.display = 'flex';
}

function dDeleteProduto(id) {
  if (!confirm('Excluir este produto?')) return;
  dSet('designers_produtos', dGet('designers_produtos').filter(p => p.id !== id));
  dRenderProdutos();
  dShowToast('Produto removido', 'warn');
}

function dRenderProdutos() {
  const q    = (document.getElementById('dSearchProduto')?.value || '').toLowerCase();
  const list = dGet('designers_produtos').filter(p => p.nome.toLowerCase().includes(q));
  const tbody = document.getElementById('bodyProdutos');
  if (!tbody) return;
  if (!list.length) {
    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:#999;padding:20px">Nenhum produto cadastrado</td></tr>';
    return;
  }
  tbody.innerHTML = list.map((p, i) => `
    <tr>
      <td>${i+1}</td>
      <td><strong>${p.nome}</strong></td>
      <td style="max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${p.desc||'—'}</td>
      <td>${dFmt(p.custo)}</td>
      <td>${dFmt(p.valorVenda)}</td>
      <td>${dFmt(p.margem)}</td>
      <td><span class="d-badge ${p.estoque > 0 ? 'd-badge-ok' : 'd-badge-err'}">${p.estoque||0}</span></td>
      <td>
        <button class="d-btn-xs" onclick="dEditProduto('${p.id}')">✏️ Editar</button>
        <button class="d-btn-xs d-btn-xs-danger" onclick="dDeleteProduto('${p.id}')">🗑️</button>
      </td>
    </tr>`).join('');
}

// ═══════════════════════════════════════════
// ESTOQUE
// ═══════════════════════════════════════════
function dSaveEntradaEstoque() {
  const prodId = document.getElementById('dEstoqueProduto').value;
  const qtd    = parseInt(document.getElementById('dEstoqueQtd').value) || 0;
  if (!prodId) { dShowToast('Selecione o produto', 'err'); return; }
  if (qtd <= 0) { dShowToast('Informe uma quantidade válida', 'err'); return; }

  const prods = dGet('designers_produtos');
  const idx   = prods.findIndex(p => p.id === prodId);
  if (idx < 0) return;
  prods[idx].estoque = (prods[idx].estoque || 0) + qtd;
  dSet('designers_produtos', prods);

  const movs = dGet('designers_mov_estoque');
  movs.push({
    id: dUID(),
    data: new Date().toISOString().slice(0,10),
    produtoId: prodId,
    nomeProduto: prods[idx].nome,
    tipo: 'Entrada Manual',
    qtd,
    resp: document.getElementById('dEstoqueResp').value.trim() || '—',
    os:   document.getElementById('dEstoqueObs').value.trim()  || '—'
  });
  dSet('designers_mov_estoque', movs);
  dCloseModal('entrada-estoque');
  dRenderEstoque();
  dShowToast(`+${qtd} unidades adicionadas ao estoque`);
}

function dAjustarEstoque(prodId) {
  const prods = dGet('designers_produtos');
  const p = prods.find(x => x.id === prodId);
  if (!p) return;
  const novoValor = prompt(`Ajustar estoque de "${p.nome}"\nEstoque atual: ${p.estoque||0}\n\nInforme o novo valor total:`, p.estoque||0);
  if (novoValor === null) return;
  const novoInt = parseInt(novoValor);
  if (isNaN(novoInt) || novoInt < 0) { dShowToast('Valor inválido', 'err'); return; }
  const diff = novoInt - (p.estoque||0);
  p.estoque = novoInt;
  dSet('designers_produtos', prods);
  const movs = dGet('designers_mov_estoque');
  movs.push({ id:dUID(), data:new Date().toISOString().slice(0,10),
    produtoId: p.id, nomeProduto: p.nome,
    tipo: diff >= 0 ? 'Ajuste (+)' : 'Ajuste (-)', qtd: diff, resp:'Manual', os:'Ajuste' });
  dSet('designers_mov_estoque', movs);
  dRenderEstoque();
  dShowToast('Estoque ajustado');
}

function dRenderEstoque() {
  const prods = dGet('designers_produtos');
  const tbody = document.getElementById('bodyEstoque');
  if (!tbody) return;
  if (!prods.length) {
    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:#999;padding:20px">Nenhum produto cadastrado</td></tr>';
  } else {
    const movs = dGet('designers_mov_estoque');
    tbody.innerHTML = prods.map(p => {
      const ultMov = [...movs].filter(m => m.produtoId === p.id).pop();
      return `<tr>
        <td><strong>${p.nome}</strong></td>
        <td><span class="d-badge ${p.estoque > 0 ? 'd-badge-ok' : 'd-badge-err'}">${p.estoque||0} un.</span></td>
        <td>${ultMov ? dFmtDate(ultMov.data) : '—'}</td>
        <td>${ultMov ? ultMov.qtd : '—'}</td>
        <td><button class="d-btn-xs" onclick="dAjustarEstoque('${p.id}')">⚙️ Ajustar</button></td>
      </tr>`;
    }).join('');
  }
  // Histórico de movimentações
  const movs = dGet('designers_mov_estoque').slice().reverse();
  const tbodyMov = document.getElementById('bodyMovEstoque');
  if (!tbodyMov) return;
  if (!movs.length) {
    tbodyMov.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#999;padding:14px">Sem movimentações</td></tr>';
    return;
  }
  tbodyMov.innerHTML = movs.map(m => `
    <tr>
      <td>${dFmtDate(m.data)}</td>
      <td>${m.nomeProduto||'—'}</td>
      <td><span class="d-badge ${m.tipo.includes('Saída')||m.tipo.includes('(-)')?'d-badge-err':'d-badge-ok'}">${m.tipo}</span></td>
      <td>${m.qtd > 0 ? '+'+m.qtd : m.qtd}</td>
      <td>${m.resp||'—'}</td>
      <td>${m.os||'—'}</td>
    </tr>`).join('');
}

// ═══════════════════════════════════════════
// PEDIDO — selects e tags
// ═══════════════════════════════════════════
function dPopulateDesignerSelect() {
  const sel = document.getElementById('dPedidoDesignerSelect');
  if (!sel) return;
  sel.innerHTML = '<option value="">+ Adicionar designer...</option>';
  dGet('designers_list').forEach(d => {
    sel.innerHTML += `<option value="${d.id}">${d.nome}</option>`;
  });
}

function dPopulateProdutoSelect() {
  const sel = document.getElementById('dPedidoItemProduto');
  if (!sel) return;
  sel.innerHTML = '<option value="">Selecionar produto...</option>';
  dGet('designers_produtos').forEach(p => {
    sel.innerHTML += `<option value="${p.id}">${p.nome} (estoque: ${p.estoque||0})</option>`;
  });
}

function dAddDesignerToPedido() {
  const sel = document.getElementById('dPedidoDesignerSelect');
  const id  = sel.value;
  if (!id) return;
  if (dPedidoTemp.designers.find(d => d.id === id)) {
    dShowToast('Designer já adicionado', 'warn'); sel.value=''; return;
  }
  const d = dGet('designers_list').find(x => x.id === id);
  if (d) { dPedidoTemp.designers.push({ id: d.id, nome: d.nome }); }
  sel.value = '';
  dRenderTagsDesignerPedido();
}

function dRenderTagsDesignerPedido() {
  const area = document.getElementById('dPedidoDesignersTags');
  if (!area) return;
  area.innerHTML = dPedidoTemp.designers.map(d =>
    `<span class="d-tag">${d.nome} <span onclick="dRemoveDesignerPedido('${d.id}')" style="cursor:pointer;margin-left:4px;opacity:.7">✕</span></span>`
  ).join('');
}

function dRemoveDesignerPedido(id) {
  dPedidoTemp.designers = dPedidoTemp.designers.filter(d => d.id !== id);
  dRenderTagsDesignerPedido();
}

function dAddItemPedido() {
  const prodId = document.getElementById('dPedidoItemProduto').value;
  const qtd    = parseInt(document.getElementById('dPedidoItemQtd').value) || 0;
  const venda  = parseFloat(document.getElementById('dPedidoItemVenda').value) || 0;
  const margem = parseFloat(document.getElementById('dPedidoItemMargem').value) || 0;
  if (!prodId) { dShowToast('Selecione um produto', 'err'); return; }
  if (qtd <= 0) { dShowToast('Informe uma quantidade válida', 'err'); return; }
  if (dPedidoTemp.itens.find(i => i.produtoId === prodId)) {
    dShowToast('Produto já adicionado. Edite a quantidade na tabela.', 'warn'); return;
  }
  const p = dGet('designers_produtos').find(x => x.id === prodId);
  dPedidoTemp.itens.push({
    produtoId: prodId, nomeProduto: p.nome,
    qtd, valorVenda: venda, margem, estoqueAtual: p.estoque||0
  });
  document.getElementById('dPedidoItemProduto').value = '';
  document.getElementById('dPedidoItemQtd').value = '';
  document.getElementById('dPedidoItemVenda').value = '';
  document.getElementById('dPedidoItemMargem').value = '';
  dRenderItensPedido();
  dAtualizarTotais();
}

function dRemoveItemPedido(produtoId) {
  dPedidoTemp.itens = dPedidoTemp.itens.filter(i => i.produtoId !== produtoId);
  dRenderItensPedido();
  dAtualizarTotais();
}

function dRenderItensPedido() {
  const tbody = document.getElementById('bodyItensPedido');
  if (!tbody) return;
  if (!dPedidoTemp.itens.length) {
    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#999;padding:12px">Nenhum item adicionado</td></tr>';
    return;
  }
  tbody.innerHTML = dPedidoTemp.itens.map(item => {
    const ok = item.estoqueAtual >= item.qtd;
    const status = ok
      ? '<span class="d-badge d-badge-ok">✓ Em estoque</span>'
      : `<span class="d-badge d-badge-warn">⚠️ Insuf. (${item.estoqueAtual} disp.)</span>`;
    return `<tr>
      <td>${item.nomeProduto}</td>
      <td>${item.qtd}</td>
      <td>${item.estoqueAtual}</td>
      <td>${status}</td>
      <td>${dFmt(item.valorVenda)}</td>
      <td>${dFmt(item.margem)}</td>
      <td><button class="d-btn-xs d-btn-xs-danger" onclick="dRemoveItemPedido('${item.produtoId}')">✕</button></td>
    </tr>`;
  }).join('');
}

function dAtualizarTotais() {
  const totalQtd   = dPedidoTemp.itens.reduce((s, i) => s + i.qtd, 0);
  const totalVenda = dPedidoTemp.itens.reduce((s, i) => s + (i.valorVenda * i.qtd), 0);
  const totalMarg  = dPedidoTemp.itens.reduce((s, i) => s + (i.margem * i.qtd), 0);
  const el = id => document.getElementById(id);
  if (el('dTotalItens'))  el('dTotalItens').textContent  = totalQtd;
  if (el('dTotalVenda'))  el('dTotalVenda').textContent  = dFmt(totalVenda);
  if (el('dTotalMargem')) el('dTotalMargem').textContent = dFmt(totalMarg);
}

// ═══════════════════════════════════════════
// CRIAR PEDIDO — verificar estoque e confirmar
// ═══════════════════════════════════════════
function dVerificarEConfirmarPedido() {
  const os     = document.getElementById('dPedidoOS').value.trim();
  const dtIni  = document.getElementById('dPedidoDataInicio').value;
  const dtFim  = document.getElementById('dPedidoDataFim').value;

  if (!os)                         { dShowToast('Informe o número da OS', 'err'); return; }
  if (!dtIni)                      { dShowToast('Informe a data de início', 'err'); return; }
  if (!dPedidoTemp.designers.length){ dShowToast('Adicione ao menos um designer', 'err'); return; }
  if (!dPedidoTemp.itens.length)   { dShowToast('Adicione ao menos um produto', 'err'); return; }

  // Verifica duplicidade de OS
  const pedidos = dGet('designers_pedidos');
  const idEdit  = document.getElementById('dPedidoId').value;
  if (!idEdit && pedidos.find(p => p.os === os)) {
    dShowToast(`OS "${os}" já existe!`, 'err'); return;
  }

  // Checa estoque atual (refresca)
  const prods = dGet('designers_produtos');
  const itensComEstoque = dPedidoTemp.itens.map(item => {
    const p = prods.find(x => x.id === item.produtoId);
    return { ...item, estoqueAtual: p ? (p.estoque||0) : 0 };
  });
  dPedidoTemp.itens = itensComEstoque;

  const insuficientes = itensComEstoque.filter(i => i.estoqueAtual < i.qtd);

  const pedido = {
    id:        idEdit || dUID(),
    os,
    designers: dPedidoTemp.designers,
    itens:     dPedidoTemp.itens,
    dataInicio: dtIni,
    dataFim:    dtFim,
    status:    'pendente',
    criadoEm:  new Date().toISOString()
  };

  if (idEdit) {
    const idx = pedidos.findIndex(p => p.id === idEdit);
    if (idx >= 0) pedidos[idx] = pedido; else pedidos.push(pedido);
  } else {
    pedidos.push(pedido);
  }
  dSet('designers_pedidos', pedidos);
  dCloseModal('pedido');
  dRenderPedidos();

  if (insuficientes.length) {
    // Mostra modal de decisão
    dPedidoDecisaoId = pedido.id;
    let info = '<p style="font-size:13px;margin-bottom:8px;">Produtos com estoque insuficiente:</p><ul style="font-size:13px;padding-left:16px;">';
    insuficientes.forEach(i => {
      info += `<li><strong>${i.nomeProduto}</strong>: pedido ${i.qtd}, disponível ${i.estoqueAtual}</li>`;
    });
    info += '</ul>';
    document.getElementById('dDecisaoInfo').innerHTML = info;
    document.getElementById('dModalDecisao').style.display = 'flex';
  } else {
    // Tudo em estoque → vai para Pedido Estoque
    dEncaminharParaEstoque(pedido.id);
    dShowToast('✅ Pedido criado e enviado para Pedido Estoque!');
  }
}

// ═══════════════════════════════════════════
// DECISÃO DE ESTOQUE
// ═══════════════════════════════════════════
function dDecidirPedido(opcao) {
  dCloseModal('decisao');
  const id = dPedidoDecisaoId;
  if (!id) return;

  if (opcao === 'estoque') {
    // Baixa o que tiver e vai para Pedido Estoque
    dBaixarEstoque(id, 'disponivel');
    dEncaminharParaEstoque(id);
    dShowToast('📦 Pedido encaminhado para Pedido Estoque (estoque baixado)');
  } else if (opcao === 'producao') {
    // Não baixa estoque, vai para Pedido Produção
    dEncaminharParaProducao(id);
    dShowToast('🔧 Pedido encaminhado para Pedido Produção');
  } else if (opcao === 'parcial') {
    // Baixa do estoque os disponíveis + envia o restante para produção
    dBaixarEstoque(id, 'disponivel');
    dEncaminharParaEstoque(id, true);  // true = parcial
    dEncaminharParaProducao(id, true); // true = parcial (só itens insuficientes)
    dShowToast('⚡ Pedido dividido: Pedido Estoque + Pedido Produção');
  }
  dPedidoDecisaoId = null;
  dRenderPedidos();
}

function dBaixarEstoque(pedidoId, modo) {
  const pedido = dGet('designers_pedidos').find(p => p.id === pedidoId);
  if (!pedido) return;
  const prods = dGet('designers_produtos');
  const movs  = dGet('designers_mov_estoque');
  pedido.itens.forEach(item => {
    const idx = prods.findIndex(p => p.id === item.produtoId);
    if (idx < 0) return;
    const disponivel = prods[idx].estoque || 0;
    const baixar = modo === 'disponivel' ? Math.min(disponivel, item.qtd) : item.qtd;
    if (baixar > 0) {
      prods[idx].estoque = disponivel - baixar;
      movs.push({ id:dUID(), data:new Date().toISOString().slice(0,10),
        produtoId: item.produtoId, nomeProduto: item.nomeProduto,
        tipo:'Saída (Pedido)', qtd: -baixar, resp:'Sistema', os: pedido.os });
    }
  });
  dSet('designers_produtos', prods);
  dSet('designers_mov_estoque', movs);
}

// ═══════════════════════════════════════════
// ENCAMINHAR PARA PEDIDO ESTOQUE
// ═══════════════════════════════════════════
function dEncaminharParaEstoque(pedidoId, parcial=false) {
  const pedido  = dGet('designers_pedidos').find(p => p.id === pedidoId);
  if (!pedido) return;
  const pedEst  = dGet('designers_ped_estoque');
  const itens   = parcial
    ? pedido.itens.filter(i => (i.estoqueAtual||0) >= i.qtd)
    : pedido.itens;
  if (!itens.length && parcial) return;
  pedEst.push({
    id:         dUID(),
    pedidoId:   pedido.id,
    os:         pedido.os,
    designers:  pedido.designers,
    itens,
    dataInicio: pedido.dataInicio,
    dataFim:    pedido.dataFim,
    status:     'aguardando_envio',
    criadoEm:   new Date().toISOString()
  });
  dSet('designers_ped_estoque', pedEst);
  // Atualiza status do pedido
  const pedidos = dGet('designers_pedidos');
  const idx = pedidos.findIndex(p => p.id === pedidoId);
  if (idx >= 0) {
    pedidos[idx].status = parcial ? 'parcial' : 'estoque';
    dSet('designers_pedidos', pedidos);
  }
  dRenderPedEstoque();
}

// ═══════════════════════════════════════════
// ENCAMINHAR PARA PEDIDO PRODUÇÃO
// ═══════════════════════════════════════════
function dEncaminharParaProducao(pedidoId, parcial=false) {
  const pedido  = dGet('designers_pedidos').find(p => p.id === pedidoId);
  if (!pedido) return;
  const pedProd = dGet('designers_ped_producao');
  const itens   = parcial
    ? pedido.itens.filter(i => (i.estoqueAtual||0) < i.qtd)
    : pedido.itens;
  if (!itens.length && parcial) return;
  pedProd.push({
    id:         dUID(),
    pedidoId:   pedido.id,
    os:         pedido.os,
    designers:  pedido.designers,
    itens,
    dataInicio: pedido.dataInicio,
    dataFim:    pedido.dataFim,
    status:     'aguardando_envio',
    criadoEm:   new Date().toISOString()
  });
  dSet('designers_ped_producao', pedProd);
  const pedidos = dGet('designers_pedidos');
  const idx = pedidos.findIndex(p => p.id === pedidoId);
  if (idx >= 0) {
    const s = pedidos[idx].status;
    pedidos[idx].status = (s === 'estoque' || s === 'parcial') ? 'parcial' : 'producao';
    dSet('designers_pedidos', pedidos);
  }
  dRenderPedProducao();
}

// ═══════════════════════════════════════════
// RENDER: LISTA DE PEDIDOS
// ═══════════════════════════════════════════
function dRenderPedidos() {
  const q      = (document.getElementById('dSearchPedido')?.value || '').toLowerCase();
  const fStat  = document.getElementById('dFilterStatusPedido')?.value || '';
  const pedidos = dGet('designers_pedidos').filter(p =>
    p.os.toLowerCase().includes(q) && (!fStat || p.status === fStat)
  ).reverse();
  const tbody = document.getElementById('bodyPedidos');
  if (!tbody) return;
  if (!pedidos.length) {
    tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;color:#999;padding:20px">Nenhum pedido encontrado</td></tr>';
    return;
  }
  const statusLabel = {
    pendente: '<span class="d-badge d-badge-warn">Pendente</span>',
    estoque:  '<span class="d-badge d-badge-ok">📦 Estoque</span>',
    producao: '<span class="d-badge d-badge-info">🔧 Produção</span>',
    parcial:  '<span class="d-badge d-badge-parcial">⚡ Parcial</span>',
  };
  tbody.innerHTML = pedidos.map(p => {
    const totalVenda = p.itens.reduce((s, i) => s + (i.valorVenda * i.qtd), 0);
    const totalMarg  = p.itens.reduce((s, i) => s + (i.margem * i.qtd), 0);
    const totalQtd   = p.itens.reduce((s, i) => s + i.qtd, 0);
    return `<tr>
      <td><strong>${p.os}</strong></td>
      <td style="max-width:140px">${p.designers.map(d=>d.nome).join(', ')}</td>
      <td style="max-width:160px">${p.itens.map(i=>i.nomeProduto).join(', ')}</td>
      <td>${totalQtd}</td>
      <td>${dFmt(totalVenda)}</td>
      <td>${dFmt(totalMarg)}</td>
      <td>${statusLabel[p.status]||p.status}</td>
      <td>
        ${p.status === 'pendente'
          ? `<button class="d-btn-xs" onclick="dVerificarEstoqueExistente('${p.id}')">🔄 Processar</button>`
          : ''}
        <button class="d-btn-xs d-btn-xs-danger" onclick="dExcluirPedido('${p.id}')">🗑️</button>
      </td>
    </tr>`;
  }).join('');
}

function dVerificarEstoqueExistente(pedidoId) {
  const pedido = dGet('designers_pedidos').find(p => p.id === pedidoId);
  if (!pedido) return;
  const prods = dGet('designers_produtos');
  const itensAtual = pedido.itens.map(item => {
    const p = prods.find(x => x.id === item.produtoId);
    return { ...item, estoqueAtual: p ? (p.estoque||0) : 0 };
  });
  const pedidos = dGet('designers_pedidos');
  const idx = pedidos.findIndex(p => p.id === pedidoId);
  if (idx >= 0) { pedidos[idx].itens = itensAtual; dSet('designers_pedidos', pedidos); }

  const insuf = itensAtual.filter(i => i.estoqueAtual < i.qtd);
  if (insuf.length) {
    dPedidoDecisaoId = pedidoId;
    let info = '<p style="font-size:13px;margin-bottom:8px;">Produtos com estoque insuficiente:</p><ul style="font-size:13px;padding-left:16px;">';
    insuf.forEach(i => { info += `<li><strong>${i.nomeProduto}</strong>: pedido ${i.qtd}, disponível ${i.estoqueAtual}</li>`; });
    info += '</ul>';
    document.getElementById('dDecisaoInfo').innerHTML = info;
    document.getElementById('dModalDecisao').style.display = 'flex';
  } else {
    dBaixarEstoque(pedidoId, 'disponivel');
    dEncaminharParaEstoque(pedidoId);
    dShowToast('✅ Pedido enviado para Pedido Estoque!');
    dRenderPedidos();
  }
}

function dExcluirPedido(id) {
  if (!confirm('Excluir este pedido?')) return;
  dSet('designers_pedidos', dGet('designers_pedidos').filter(p => p.id !== id));
  dRenderPedidos();
  dShowToast('Pedido removido', 'warn');
}

// ═══════════════════════════════════════════
// RENDER: PEDIDO ESTOQUE
// ═══════════════════════════════════════════
function dRenderPedEstoque() {
  const list  = dGet('designers_ped_estoque').slice().reverse();
  const tbody = document.getElementById('bodyPedEstoque');
  if (!tbody) return;
  if (!list.length) {
    tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;color:#999;padding:20px">Nenhum pedido de estoque</td></tr>';
    return;
  }
  tbody.innerHTML = list.map(p => {
    const totalVenda = p.itens.reduce((s, i) => s + (i.valorVenda * i.qtd), 0);
    const totalMarg  = p.itens.reduce((s, i) => s + (i.margem * i.qtd), 0);
    const statusOk   = p.status === 'enviado_acomp';
    return `<tr>
      <td><strong>${p.os}</strong></td>
      <td style="max-width:120px">${p.designers.map(d=>d.nome).join(', ')}</td>
      <td style="max-width:180px">${p.itens.map(i=>`${i.nomeProduto} (${i.qtd})`).join('<br>')}</td>
      <td>${dFmt(totalVenda)}</td>
      <td>${dFmt(totalMarg)}</td>
      <td>${dFmtDate(p.dataInicio)}</td>
      <td>${dFmtDate(p.dataFim)}</td>
      <td>${statusOk
        ? '<span class="d-badge d-badge-ok">✓ Enviado Acomp.</span>'
        : '<span class="d-badge d-badge-warn">Aguardando</span>'}</td>
      <td>
        ${!statusOk
          ? `<button class="d-btn-xs d-btn-primary-xs" onclick="dAbrirDatasEstoque('${p.id}')">📤 Enviar Acomp.</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');
}

function dAbrirDatasEstoque(id) {
  const p = dGet('designers_ped_estoque').find(x => x.id === id);
  if (!p) return;
  dEnvioEstoqueId = id;
  document.getElementById('dDatasEstoqueInfo').textContent = `OS ${p.os} — Definir datas para Acomp. Produção`;
  document.getElementById('dPedEstoqueInicio').value = p.dataInicio || '';
  document.getElementById('dPedEstoqueFim').value    = p.dataFim    || '';
  document.getElementById('dModalDatasEstoque').style.display = 'flex';
}

function dConfirmarEnvioAcomp() {
  const inicio = document.getElementById('dPedEstoqueInicio').value;
  const fim    = document.getElementById('dPedEstoqueFim').value;
  if (!inicio || !fim) { dShowToast('Preencha as datas', 'err'); return; }
  const id = dEnvioEstoqueId;
  const list = dGet('designers_ped_estoque');
  const idx  = list.findIndex(p => p.id === id);
  if (idx < 0) return;
  list[idx].dataInicio = inicio;
  list[idx].dataFim    = fim;
  list[idx].status     = 'enviado_acomp';
  dSet('designers_ped_estoque', list);

  // ═══ INTEGRAÇÃO COM ACOMP. PRODUÇÃO ═══
  // Ajuste a estrutura abaixo conforme o formato esperado por acomp.js
  const acompItems = dGet(D_ACOMP_KEY);
  acompItems.push({
    id:         list[idx].id,
    os:         list[idx].os,
    origem:     'Designers',
    designers:  list[idx].designers,
    itens:      list[idx].itens,
    dataInicio: inicio,
    dataFim:    fim,
    status:     'Em Andamento',
    criadoEm:   new Date().toISOString()
  });
  dSet(D_ACOMP_KEY, acompItems);

  dCloseModal('datas-estoque');
  dRenderPedEstoque();
  dShowToast('✅ Pedido enviado para Acomp. Produção!');
  dEnvioEstoqueId = null;

  // Atualiza acomp se estiver na tela
  if (typeof renderAcomp === 'function') renderAcomp();
}

// ═══════════════════════════════════════════
// RENDER: PEDIDO PRODUÇÃO
// ═══════════════════════════════════════════
function dRenderPedProducao() {
  const list  = dGet('designers_ped_producao').slice().reverse();
  const tbody = document.getElementById('bodyPedProducao');
  if (!tbody) return;
  if (!list.length) {
    tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;color:#999;padding:20px">Nenhum pedido de produção</td></tr>';
    return;
  }
  tbody.innerHTML = list.map(p => {
    const totalVenda = p.itens.reduce((s, i) => s + (i.valorVenda * i.qtd), 0);
    const totalMarg  = p.itens.reduce((s, i) => s + (i.margem * i.qtd), 0);
    const statusOk   = p.status === 'enviado_eng';
    return `<tr>
      <td><strong>${p.os}</strong></td>
      <td style="max-width:120px">${p.designers.map(d=>d.nome).join(', ')}</td>
      <td style="max-width:180px">${p.itens.map(i=>`${i.nomeProduto} (${i.qtd})`).join('<br>')}</td>
      <td>${dFmt(totalVenda)}</td>
      <td>${dFmt(totalMarg)}</td>
      <td>${dFmtDate(p.dataInicio)}</td>
      <td>${dFmtDate(p.dataFim)}</td>
      <td>${statusOk
        ? '<span class="d-badge d-badge-ok">✓ Enviado Eng.</span>'
        : '<span class="d-badge d-badge-warn">Aguardando</span>'}</td>
      <td>
        ${!statusOk
          ? `<button class="d-btn-xs d-btn-primary-xs" onclick="dAbrirDatasProducao('${p.id}')">🔧 Enviar Engenharia</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');
}

function dAbrirDatasProducao(id) {
  const p = dGet('designers_ped_producao').find(x => x.id === id);
  if (!p) return;
  dEnvioProducaoId = id;
  document.getElementById('dDatasProducaoInfo').textContent = `OS ${p.os} — Definir datas para Engenharia Mobiliários`;
  document.getElementById('dPedProducaoInicio').value = p.dataInicio || '';
  document.getElementById('dPedProducaoFim').value    = p.dataFim    || '';
  document.getElementById('dModalDatasProducao').style.display = 'flex';
}

function dConfirmarEnvioEngenharia() {
  const inicio = document.getElementById('dPedProducaoInicio').value;
  const fim    = document.getElementById('dPedProducaoFim').value;
  if (!inicio || !fim) { dShowToast('Preencha as datas', 'err'); return; }
  const id  = dEnvioProducaoId;
  const list = dGet('designers_ped_producao');
  const idx  = list.findIndex(p => p.id === id);
  if (idx < 0) return;
  list[idx].dataInicio = inicio;
  list[idx].dataFim    = fim;
  list[idx].status     = 'enviado_eng';
  dSet('designers_ped_producao', list);

  // ═══ INTEGRAÇÃO COM ENGENHARIA - MOBILIÁRIOS ═══
  // Ajuste a estrutura abaixo conforme o formato esperado por mobiliarios.js
  const mobPedidos = dGet(D_MOB_KEY);
  mobPedidos.push({
    id:         list[idx].id,
    os:         list[idx].os,
    origem:     'Designers',
    designers:  list[idx].designers,
    itens:      list[idx].itens,
    dataInicio: inicio,
    dataFim:    fim,
    status:     'Novo',
    criadoEm:   new Date().toISOString()
  });
  dSet(D_MOB_KEY, mobPedidos);

  dCloseModal('datas-producao');
  dRenderPedProducao();
  dShowToast('✅ Pedido enviado para Engenharia - Mobiliários!');
  dEnvioProducaoId = null;

  // Atualiza mobiliarios se estiver na tela
  if (typeof renderMobiliarios === 'function') renderMobiliarios();
}

// ═══════════════════════════════════════════
// INICIALIZAÇÃO
// ═══════════════════════════════════════════
document.addEventListener('DOMContentLoaded', () => {
  // Renderiza tab inicial ao abrir a seção
  const page = document.getElementById('page-designers');
  if (page) {
    const observer = new MutationObserver(() => {
      if (page.style.display !== 'none') {
        dRenderDesigners();
      }
    });
    observer.observe(page, { attributes: true, attributeFilter: ['style'] });
  }
});
