<!— cole tudo no Editor de Layout —>
<div class="sheet" id="sheet" data-status="{{status}}" data-tema="light">
  <header class="print-header">
    <div class="left">
      <img src="{{logo_url}}" alt="logo" onerror="this.style.display='none'" />
      <span class="empresa">{{empresa}}</span>
      <span class="form-name">{{form_name}}</span>
    </div>
    <div class="right">
      <div><strong>Protocolo:</strong> <span id="proto">{{protocolo}}{{submission_id}}</span></div>
      <div><strong>Data:</strong> {{data}}</div>
    </div>
  </header>
  <footer class="print-footer">
    Gerado por <strong>{{usuario}}</strong> em <strong>{{impresso_em}}</strong>
    <span class="spacer"></span>
    <span class="page-counter">Página <span class="pageNumber"></span> / <span class="totalPages"></span></span>
  </footer>
  <div class="wm" id="wm">NÃO CONFORME</div>
  <div class="stamp" id="stamp">{{status}}</div>
  <div class="actions no-print">
    <button class="btn" onclick="toggleTheme()">Alternar tema</button>
    <button class="btn" onclick="window.print()">Imprimir</button>
  </div>
  <section class="grid2 card">
    <div><label>Responsável</label><div class="val">{{responsavel}}</div></div>
    <div><label>Setor atual</label><div class="val">{{owner_role}}</div></div>
    <div><label>Status</label><div class="val">{{status}}</div></div>
    <div><label>Turno</label><div class="val">{{turno}}</div></div>
  </section>
  <section class="card">
    <h3>Descrição</h3>
    <div class="pre">{{descricao}}</div>
  </section>
  <section class="card">
    <h3>Itens</h3>
    <table class="tbl" id="tbl-itens">
      <thead><tr><th>Item</th><th class="num">Qtde</th><th>Unid</th></tr></thead>
      <tbody>
        {{#each itens}}
          <tr><td>{{descricao}}</td><td class="num">{{qtde}}</td><td>{{un}}</td></tr>
        {{/each}}
      </tbody>
      <tfoot><tr><th>Total</th><th class="num">{{sum itens.qtde}}</th><th></th></tr></tfoot>
    </table>
  </section>
  <section class="card">
    <h3>Fotos</h3>
    <div class="fotos" id="fotos"></div>
    <small class="muted">Use o campo <em>fotos_urls</em> com URLs separadas por vírgula.</small>
  </section>
  <section class="card assinaturas">
    <div class="sig">
      <div class="line"><img src="{{assinatura_recebimento}}" alt="" onerror="this.style.display='none'"></div>
      <div class="legend">Recebimento — {{nome_recebimento}} — {{data_recebimento}}</div>
    </div>
    <div class="sig">
      <div class="line"><img src="{{assinatura_qualidade}}" alt="" onerror="this.style.display='none'"></div>
      <div class="legend">Qualidade — {{nome_qualidade}} — {{data_qualidade}}</div>
    </div>
    <div class="sig">
      <div class="line"><img src="{{assinatura_supervisor}}" alt="" onerror="this.style.display='none'"></div>
      <div class="legend">Supervisor — {{nome_supervisor}} — {{data_supervisor}}</div>
    </div>
    <div class="sig">
      <div class="line"><img src="{{assinatura}}" alt="" onerror="this.style.display='none'"></div>
      <div class="legend">Assinatura</div>
    </div>
  </section>
  <section class="card">
    <div class="carimbo">
      <div class="carimbo-inner">
        <strong>{{empresa}}</strong><br>
        CNPJ: {{cnpj}}<br>
        {{endereco}}
      </div>
    </div>
  </section>
  <section class="card grid2">
    <div>
      <h4>Verificação</h4>
      <canvas id="qrcode" width="110" height="110"></canvas>
      <div class="muted">Abra com a câmera para validar</div>
    </div>
    <div>
      <h4>Protocolo</h4>
      <svg id="barcode"></svg>
    </div>
  </section>
</div>
<style>
:root{
  --bg:#ffffff; --fg:#1f2937; --muted:#6b7280; --border:#e5e7eb; --card:#fff; --surface:#f7f8fa;
  --ok:#2e7d32; --warn:#f9a825; --err:#c62828; --brand:#1976d2;
}
[data-theme="dark"], [data-tema="dark"]{
  --bg:#0b1220; --fg:#e5e7eb; --muted:#9ca3af; --border:#344054; --card:#0f172a; --surface:#0d1425;
}
*{box-sizing:border-box}
body{background:var(--surface)}
.sheet{color:var(--fg); background:var(--bg); max-width:900px; margin:0 auto; padding:16px 18px 24px; position:relative}
.print-header,.print-footer{position:sticky; z-index:5; background:var(--bg); color:var(--fg)}
.print-header{top:0; display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid var(--border); padding-bottom:8px; margin-bottom:12px}
.print-header img{height:28px; margin-right:8px}
.print-header .empresa{margin-left:6px; font-weight:600}
.print-header .form-name{margin-left:10px; color:var(--muted)}
.print-footer{bottom:0; display:flex; align-items:center; gap:8px; border-top:1px solid var(--border); padding-top:6px; margin-top:16px; font-size:12px}
.spacer{flex:1}
.no-print{margin:8px 0 12px; display:flex; gap:8px}
.btn{padding:6px 10px; border:1px solid var(--border); background:var(--card); color:var(--fg); border-radius:8px; cursor:pointer}
.btn:hover{background:#eef2f7}
.card{border:1px solid var(--border); background:var(--card); border-radius:12px; padding:12px; margin:10px 0}
.grid2{display:grid; grid-template-columns:1fr 1fr; gap:12px}
@media (max-width:760px){ .grid2{grid-template-columns:1fr} }
label{display:block; font-size:12px; color:var(--muted); margin-bottom:2px}
.val{font-weight:600}
.pre{white-space:pre-wrap}
.tbl{width:100%; border-collapse:collapse}
.tbl th,.tbl td{border:1px solid var(--border); padding:6px}
.tbl .num{text-align:right}
.fotos{display:grid; grid-template-columns:repeat(3,1fr); gap:10px}
.fotos img{width:100%; height:160px; object-fit:cover; border:1px solid var(--border); border-radius:6px}
@media (max-width:900px){ .fotos{grid-template-columns:repeat(2,1fr)} }
@media (max-width:600px){ .fotos{grid-template-columns:1fr} }
.assinaturas{display:grid; grid-template-columns:repeat(2,1fr); gap:14px}
@media (max-width:760px){ .assinaturas{grid-template-columns:1fr} }
.sig .line{height:50px; border-bottom:1px solid var(--fg); display:flex; align-items:center}
.sig img{height:46px; max-width:100%; object-fit:contain}
.sig .legend{font-size:12px; color:var(--muted); margin-top:4px}
.carimbo{display:flex; justify-content:flex-start}
.carimbo-inner{border:2px solid var(--fg); padding:8px 12px; border-radius:8px; display:inline-block}
.stamp{position:absolute; top:90px; right:24px; font-weight:800; padding:6px 10px; border:2px solid currentColor; border-radius:8px; transform:rotate(-8deg)}
.wm{position:fixed; inset:0; display:none; align-items:center; justify-content:center; font:800 90px/1 Inter,system-ui; color:#0002; transform:rotate(-25deg); pointer-events:none; z-index:0}
@media print{
  .no-print{display:none !important}
  .print-header{position:fixed; top:0; left:0; right:0}
  .print-footer{position:fixed; bottom:0; left:0; right:0}
  .sheet{padding-top:70px; padding-bottom:55px}
}
</style>
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>
<script>
(function(){
  const sheet = document.getElementById('sheet');
  const saved = localStorage.getItem('layout_theme');
  if(saved) sheet.setAttribute('data-tema', saved);
  window.toggleTheme = function(){
    const cur = sheet.getAttribute('data-tema') === 'dark' ? 'light' : 'dark';
    sheet.setAttribute('data-tema', cur);
    localStorage.setItem('layout_theme', cur);
  };
  const statusRaw = (sheet.getAttribute('data-status') || '').toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu,'');
  const stamp = document.getElementById('stamp');
  if (stamp){
    stamp.className = 'stamp';
    if (statusRaw.includes('conforme') && !statusRaw.includes('nao')) stamp.style.color = '#2e7d32';
    else if (statusRaw.includes('parcial')) stamp.style.color = '#f9a825';
    else if (statusRaw.includes('nao') || statusRaw.includes('reprov')) stamp.style.color = '#c62828';
  }
  const wm = document.getElementById('wm');
  if (wm){
    wm.style.display = (statusRaw.includes('nao') || statusRaw.includes('reprov')) ? 'flex' : 'none';
  }
  try{
    const base = "{{base_url}}".trim() || (location.origin + location.pathname.replace(/\/[^\/]*$/,''));
    const sid  = "{{submission_id}}".trim() || document.getElementById('proto').textContent.trim();
    const veri = "{{veri_hash}}".trim();
    const url  = veri ? `${base}/submission_view.php?id=${encodeURIComponent(sid)}&h=${encodeURIComponent(veri)}`
                      : `${base}/submission_view.php?id=${encodeURIComponent(sid)}`;
    const canvas = document.getElementById('qrcode');
    if (canvas && typeof QRCode !== 'undefined') { QRCode.toCanvas(canvas, url, { width: 110, margin: 1 }); }
  }catch(e){}
  try{
    const proto = document.getElementById('proto')?.textContent?.trim() || '';
    if (proto && typeof JsBarcode !== 'undefined') { JsBarcode("#barcode", proto, { format:"CODE128", height:32, displayValue:true }); }
  }catch(e){}
  (function(){
    const el = document.getElementById('fotos');
    if (!el) return;
    const listRaw = `{{fotos_urls}}`;
    if (!listRaw || listRaw.includes('{{')) { el.innerHTML = '<span class="muted">Sem fotos</span>'; return; }
    const urls = listRaw.split(',').map(s=>s.trim()).filter(Boolean);
    if (!urls.length){ el.innerHTML = '<span class="muted">Sem fotos</span>'; return; }
    el.innerHTML = urls.map(u => `<img src="${u}" alt="foto" onerror="this.style.display='none'">`).join('');
  })();
})();
</script>
