/* O Tal Picolé — Sistema de comprovantes (impressão / PDF)
   Suporta 3 formatos: A4, 80mm térmica, 58mm térmica.
   Abre uma nova janela com o conteúdo formatado e chama print(). */

function _money(v){ return "R$ " + (v||0).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2}); }
function _date(d){ const dt = d instanceof Date ? d : new Date(d); return dt.toLocaleDateString("pt-BR"); }
function _now(){ const d = new Date(); return d.toLocaleDateString("pt-BR") + " " + d.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}); }
function _docNum(prefix, id){
  const n = (id||"").replace(/[^a-z0-9]/gi,"").slice(-6).toUpperCase().padStart(6,"0");
  return (prefix||"DOC") + "-" + n;
}

/* Carrega logo customizada (data URL) salva pela fábrica, se houver. */
function _getLogoDataUrl(){
  try { return localStorage.getItem("otp.logo") || ""; } catch(e){ return ""; }
}

/* Cores da marca alinhadas ao design system */
const BRAND_COLORS = {
  red:      "#D4310B",
  redDark:  "#B3270A",
  redSoft:  "#FFF1EA",
  redSofter:"#FDE6DC",
  ink:      "#1A1A1A",
  inkSoft:  "#666666",
  cream:    "#FAFAFB",
};

/* Renderiza HTML do cabeçalho da empresa — minimalista e profissional. */
function _headerHtml(company, fmt){
  const logoUrl = _getLogoDataUrl();
  if (fmt === "a4") {
    const logoSize = 64;
    const logoBlock = logoUrl
      ? `<img src="${logoUrl}" style="width:${logoSize}px;height:${logoSize}px;object-fit:contain;display:block;" />`
      : `<div style="width:${logoSize}px;height:${logoSize}px;display:flex;align-items:center;justify-content:center;background:${BRAND_COLORS.red};color:white;border-radius:6px;font-weight:800;font-size:${logoSize*0.5}px;font-family:Helvetica,Arial,sans-serif;letter-spacing:-.04em;">P</div>`;
    return `
      <header style="display:flex;gap:18px;align-items:center;padding-bottom:14px;margin-bottom:20px;border-bottom:1.5px solid #222;">
        ${logoBlock}
        <div style="flex:1;min-width:0;">
          <div style="font-weight:800;font-size:15px;letter-spacing:.04em;text-transform:uppercase;color:#111;line-height:1.2;">${company.name||""}</div>
          <div style="font-size:9.5px;line-height:1.55;color:#555;margin-top:5px;">
            ${company.cnpj ? "CNPJ "+company.cnpj : ""}
            ${company.cnpj && company.ie ? "  ·  " : ""}
            ${company.ie ? "IE "+company.ie : ""}
            ${(company.cnpj || company.ie) ? "<br/>" : ""}
            ${company.address ? company.address+"<br/>" : ""}
            ${[company.phone, company.email].filter(Boolean).join("  ·  ")}
          </div>
        </div>
      </header>`;
  }
  const logoSize = fmt === "mm80" ? 48 : 38;
  const logoBlock = logoUrl
    ? `<img src="${logoUrl}" style="width:${logoSize}px;height:${logoSize}px;object-fit:contain;display:block;margin:0 auto 4px;" />`
    : `<div style="width:${logoSize}px;height:${logoSize}px;margin:0 auto 4px;display:flex;align-items:center;justify-content:center;background:${BRAND_COLORS.red};color:white;border-radius:4px;font-weight:800;font-size:${logoSize*0.45}px;font-family:Helvetica,Arial,sans-serif;">P</div>`;
  return `
    <div style="text-align:center;border-bottom:1px dashed #333;padding-bottom:6px;margin-bottom:8px;">
      ${logoBlock}
      <div style="font-weight:700;font-size:12px;text-transform:uppercase;letter-spacing:.04em;">${company.name||""}</div>
      <div style="font-size:9.5px;line-height:1.45;margin-top:2px;color:#000;">
        ${company.cnpj ? "CNPJ "+company.cnpj+"<br/>" : ""}
        ${company.address||""}<br/>
        ${[company.phone, company.email].filter(Boolean).join(" · ")}
      </div>
    </div>`;
}

/* Estilo base para janela de impressão por formato */
function _baseCss(fmt){
  if (fmt === "a4") {
    return `
      @page { size: A4; margin: 12mm 10mm; }
      * { box-sizing: border-box; }
      html, body { margin:0; padding:0; }
      body { font-family: Helvetica, Arial, sans-serif; color:#222; font-size:11px; line-height:1.5; }
      .doc { max-width: 760px; margin: 0 auto; padding: 0; }
      @media print {
        .doc { max-width: none; width: 100%; margin: 0; padding: 0; box-shadow: none !important; }
        body { background: white !important; }
      }
      table { table-layout: auto; word-wrap: break-word; }
      .brand-bar { height: 3px; background: ${BRAND_COLORS.red}; margin-bottom: 8px; }
      h1.doc-title { font-size:14px; text-transform:uppercase; letter-spacing:.1em; font-weight:700; color:#111; margin:0 0 4px; }
      h1 { font-size:14px; text-transform:uppercase; letter-spacing:.1em; font-weight:700; color:#111; margin:0 0 4px; }
      .doc-meta { font-size:10px; color:#666; font-family: 'Courier New', monospace; letter-spacing:.04em; margin-bottom:14px; padding-bottom:10px; border-bottom:1px solid #ddd; display:flex; justify-content:space-between; align-items:center; gap:14px; }
      .via-tag { display:inline-block; font-size:8.5px; font-weight:700; letter-spacing:.12em; color:${BRAND_COLORS.red}; text-transform:uppercase; border:1px solid ${BRAND_COLORS.red}; padding:2px 8px; }
      .section-title, .ttl { font-size:9.5px; font-weight:700; text-transform:uppercase; letter-spacing:.12em; color:#111; margin:18px 0 6px; padding-bottom:3px; border-bottom:1px solid #aaa; }
      .meta, .meta-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px 28px; margin:0 0 16px; padding:0; background:transparent; border:none; }
      .meta > div, .meta-grid .item { font-size:11px; color:#222; }
      .meta strong, .meta-grid .item strong.lbl { display:block; font-size:8.5px; font-weight:700; color:#888; text-transform:uppercase; letter-spacing:.1em; margin-bottom:3px; }
      table { width:100%; border-collapse: collapse; }
      th { text-align:left; padding:7px 6px; font-size:9px; font-weight:700; color:#555; text-transform:uppercase; letter-spacing:.08em; border-bottom:1.5px solid #333; background:transparent; }
      td { padding:6px; font-size:10.5px; border-bottom:1px solid #eee; color:#222; vertical-align:top; }
      tbody tr:nth-child(even) { background:transparent; }
      tbody tr:last-child td { border-bottom:none; }
      .num { text-align:right; font-variant-numeric: tabular-nums; }
      .totals { margin-left:auto; width:300px; margin-top:14px; background:transparent; border:none; padding:0; border-radius:0; }
      .totals .row { display:flex; justify-content:space-between; padding:5px 0; font-size:11px; border-bottom:1px solid #eee; }
      .totals .row:last-of-type { border-bottom:none; }
      .totals .row.big { border-top:1.5px solid #333; border-bottom:3px double #333; padding:10px 0; margin-top:6px; font-size:13px; font-weight:700; color:#111; text-transform:uppercase; letter-spacing:.04em; }
      .totals .row.profit { background:#FAFAFA; padding:8px 10px; margin-top:6px; font-size:12px; font-weight:700; color:${BRAND_COLORS.red}; border-bottom:none; }
      .sigs, .signatures { display:grid; grid-template-columns:1fr 1fr; gap:60px; margin-top:54px; }
      .sig, .signature { text-align:center; font-size:9.5px; color:#555; }
      .sig .line, .signature .line { border-top:1px solid #222; padding-top:4px; font-size:9.5px; color:#555; }
      .footer { margin-top:30px; padding-top:10px; border-top:1px solid #ddd; font-size:9px; color:#888; text-align:center; line-height:1.6; }
      .footer .doc-no { color:#222; font-weight:700; font-family:'Courier New', monospace; letter-spacing:.05em; }
      .badge-status { display:inline-block; font-size:9px; font-weight:700; padding:2px 7px; border:1px solid; letter-spacing:.05em; text-transform:uppercase; border-radius:0; }
      .badge-pago { color:#15803D; border-color:#15803D; background:transparent; }
      .badge-pendente { color:#B45309; border-color:#B45309; background:transparent; }
      .badge-parcial { color:#1E40AF; border-color:#1E40AF; background:transparent; }
      .terms-box, .terms { margin-top:18px; padding:10px 12px; border:1px solid #ddd; border-left:3px solid ${BRAND_COLORS.red}; border-radius:0; background:transparent; font-size:9.5px; line-height:1.55; color:#444; }
      .terms strong, .terms-box strong { color:#111; }
      .via-divider { border:none; border-top:1.5px dashed #aaa; margin:36px 0 26px; position:relative; height:1.5px; }
      .via-divider span { position:absolute; left:50%; top:-9px; transform:translateX(-50%); background:white; padding:0 14px; color:#666; font-size:9px; font-weight:700; letter-spacing:.12em; text-transform:uppercase; }
      .page-break { page-break-after: always; }
    `;
  }
  // térmica
  const w = fmt === "mm80" ? "76mm" : "54mm";
  const fz = fmt === "mm80" ? "11px" : "10px";
  const fzS = fmt === "mm80" ? "9.5px" : "9px";
  return `
    @page { size: ${w} auto; margin: 2mm; }
    body { font-family: 'Courier New', ui-monospace, monospace; color:#000; margin:0; padding:0; font-size:${fz}; line-height:1.35; }
    .doc { width: ${w}; padding: 2mm 1mm; }
    h1 { font-size:12px; margin:0; text-transform:uppercase; letter-spacing:.05em; }
    table { width:100%; border-collapse: collapse; }
    td { padding:1px 0; font-size:${fz}; vertical-align:top; }
    .num { text-align:right; font-variant-numeric: tabular-nums; }
    .sep { border-top:1px dashed #333; margin:5px 0; }
    .meta { font-size:${fzS}; margin:4px 0; }
    .row { display:flex; justify-content:space-between; font-size:${fz}; padding:1px 0; }
    .row.big { font-weight:700; font-size:12px; border-top:1px dashed #333; padding-top:3px; margin-top:3px; }
    .row.profit { font-weight:700; font-size:12px; border:1px solid #333; padding:3px 4px; margin-top:3px; }
    .center { text-align:center; }
    .small { font-size:${fzS}; }
    .ttl { font-weight:700; font-size:${fz}; text-transform:uppercase; margin:4px 0 2px; letter-spacing:.06em; }
    .via-divider { border:none; border-top:1px dashed #333; margin: 8px 0; text-align:center; font-size:${fzS}; padding-top:4px; }
  `;
}

/* Abre nova janela já com botões de imprimir/baixar/fechar */
function _openPrintWindow(title, css, bodyHtml, autoPrint){
  const win = window.open("", "_blank", "width=900,height=900");
  if (!win) {
    alert("O bloqueador de pop-ups impediu a impressão. Habilite pop-ups para este site.");
    return;
  }
  const html = `<!DOCTYPE html>
<html lang="pt-BR"><head>
<meta charset="UTF-8" />
<title>${title}</title>
<style>${css}
  .toolbar { position:sticky; top:0; background:#1A1A1A; color:white; padding:10px 14px; display:flex; gap:8px; align-items:center; z-index:50; }
  .toolbar h3 { margin:0; flex:1; font-size:13px; font-weight:600; font-family: ui-sans-serif, system-ui, sans-serif; }
  .toolbar button { background:white; color:#1A1A1A; border:none; padding:7px 12px; border-radius:6px; font-weight:600; font-size:12px; cursor:pointer; font-family: ui-sans-serif, system-ui, sans-serif; }
  .toolbar button.ghost { background:transparent; color:white; border:1px solid rgba(255,255,255,.4); }
  @media print { .toolbar { display:none !important; } body { background: white !important; padding: 0 !important; } .doc { box-shadow: none !important; margin: 0 !important; padding: 0 !important; max-width: none !important; width: auto !important; } }
  body { background:#f0f0f0; margin: 0; }
  .doc { background: white; box-shadow: 0 4px 24px rgba(0,0,0,.12); margin: 14px auto; padding: 22px 24px; max-width: 760px; }
</style>
</head><body>
<div class="toolbar">
  <h3>${title}</h3>
  <button onclick="window.print()">🖨 Imprimir</button>
  <button class="ghost" onclick="window.close()">Fechar</button>
</div>
<div class="doc">${bodyHtml}</div>
${autoPrint ? `<script>setTimeout(()=>window.print(),300);</script>` : ""}
</body></html>`;
  win.document.open();
  win.document.write(html);
  win.document.close();
}

/* ============================================================
   COMPROVANTE DE VENDA (Distribuidor)
   Suporta 2 vias: "empresa" (cópia interna) e "distribuidor" (cliente).
   vias: "both" | "empresa" | "distribuidor"
   ============================================================ */
function _saleBodyA4({ company, sale, items, products, viaLabel, viaDestinatario }) {
  const head = _headerHtml(company, "a4");
  const docNum = _docNum("VEN", sale.id || Date.now()+"");

  const rows = (items.length === 0
    ? [`<tr><td colspan="5" style="text-align:center;color:#666;padding:14px;">(Sem detalhamento de itens nesta reimpressão)</td></tr>`]
    : items.map(it => {
        const p = products.find(x => x.id === it.productId);
        const boxes = it.boxes || 0;
        const loose = it.loose || 0;
        const productBox = it.boxSize || p?.boxSize || sale.perBox || 60;
        const units = boxes * productBox + loose;
        const unitPrice = it.unitPrice != null ? it.unitPrice : (p?.price || 0) * 0.55;
        const subtotal = it.subtotal != null ? it.subtotal : units * unitPrice;
        const qtyDesc = [boxes > 0 ? `${boxes} cx <span style="color:#888">(${productBox}un)</span>` : "", loose > 0 ? `${loose} av.` : ""].filter(Boolean).join(" + ") || "—";
        return `<tr>
          <td><strong>${p?.flavor||"—"}</strong> <span style="color:#888;font-size:9.5px">· ${p?.line||""}</span></td>
          <td class="num">${qtyDesc}</td>
          <td class="num">${units}</td>
          <td class="num">${_money(unitPrice)}</td>
          <td class="num"><strong>${_money(subtotal)}</strong></td>
        </tr>`;
      })
  ).join("");

  const paid = sale.paid != null ? sale.paid : (sale.status === "a_receber" ? 0 : sale.total);
  const pending = Math.max(0, sale.total - paid);
  const statusHtml = pending === 0
    ? `<span class="badge-status badge-pago">Pago</span>`
    : paid > 0
      ? `<span class="badge-status badge-parcial">Parcial · falta ${_money(pending)}</span>`
      : `<span class="badge-status badge-pendente">Pendente · ${_money(pending)}</span>`;

  return `
    <div class="brand-bar"></div>
    ${head}
    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:14px;margin-bottom:10px;">
      <div>
        <span class="via-tag">${viaLabel}</span>
        <h1 class="doc-title" style="margin-top:8px;">Comprovante de Venda</h1>
      </div>
      <div style="text-align:right;">${statusHtml}</div>
    </div>
    <div class="doc-meta">
      <span>Nº ${docNum}</span>
      <span>Emitido em ${_now()}</span>
    </div>
    <div class="meta-grid">
      <div class="item"><strong class="lbl">${viaDestinatario === "empresa" ? "Cliente (Distribuidor)" : "Emitente"}</strong>${viaDestinatario === "empresa" ? (sale.client?.name || "—") : (company.name||"—")}<br/><span style="color:#666;font-size:10px;">${viaDestinatario === "empresa" ? (sale.client?.doc||"") : (company.cnpj||"")}</span></div>
      <div class="item"><strong class="lbl">${viaDestinatario === "empresa" ? "Cidade" : "Adquirente"}</strong>${viaDestinatario === "empresa" ? (sale.client?.city || "—") : (sale.client?.name||"—")}</div>
      <div class="item"><strong class="lbl">Forma de pagamento</strong>${sale.payment||"—"}</div>
      <div class="item"><strong class="lbl">Data da operação</strong>${_date(sale.date||new Date())}${sale.time ? " · "+sale.time : ""}</div>
    </div>
    <div class="section-title">Discriminação dos itens</div>
    <table>
      <thead><tr><th>Produto</th><th class="num">Quantidade</th><th class="num">Un.</th><th class="num">Vl. unitário</th><th class="num">Subtotal</th></tr></thead>
      <tbody>${rows}</tbody>
    </table>
    <div class="totals">
      <div class="row"><span>Subtotal</span><span class="num">${_money(sale.subtotal||sale.total)}</span></div>
      ${sale.discount>0 ? `<div class="row"><span>Desconto</span><span class="num">− ${_money(sale.discount)}</span></div>` : ""}
      <div class="row big"><span>Total</span><span class="num">${_money(sale.total)}</span></div>
      ${paid > 0 && paid < sale.total ? `<div class="row" style="color:#15803D;"><span>Valor pago</span><span class="num">${_money(paid)}</span></div><div class="row" style="color:#B45309;font-weight:700;"><span>Saldo pendente</span><span class="num">${_money(pending)}</span></div>` : ""}
    </div>
    ${pending > 0 ? `<div class="terms-box">
      <strong>Venda a prazo:</strong> O cliente compromete-se a quitar o saldo pendente de <strong>${_money(pending)}</strong> conforme condições negociadas. Pagamentos parciais serão registrados sequencialmente até a quitação integral.
    </div>` : ""}
    <div class="sigs">
      <div class="sig"><div class="line">${viaDestinatario === "empresa" ? "Cliente / Distribuidor" : "Adquirente — Recebi os produtos"}</div></div>
      <div class="sig"><div class="line">${viaDestinatario === "empresa" ? "Vendedor / Conferente" : "Emitente — "+(company.name||"")}</div></div>
    </div>
    <div class="footer">
      Documento de controle interno · sem valor fiscal<br/>
      <span class="doc-no">${docNum}</span> · ${company.name||""} · gerado em ${_now()}
    </div>`;
}

function _saleBodyThermal({ company, sale, items, products, fmt, viaLabel }) {
  const head = _headerHtml(company, fmt);
  const docNum = _docNum("VEN", sale.id || Date.now()+"");
  const rows = items.map(it => {
    const p = products.find(x => x.id === it.productId);
    const boxes = it.boxes || 0;
    const loose = it.loose || 0;
    const productBox = it.boxSize || p?.boxSize || sale.perBox || 60;
    const units = boxes * productBox + loose;
    const unitPrice = it.unitPrice != null ? it.unitPrice : (p?.price || 0) * 0.55;
    const subtotal = it.subtotal != null ? it.subtotal : units * unitPrice;
    const name = (p?.flavor||"—").slice(0, fmt==="mm80"?26:18);
    const qtyTxt = [boxes > 0 ? `${boxes}cx×${productBox}un` : "", loose > 0 ? `${loose} av.` : ""].filter(Boolean).join(" + ");
    return `<tr><td colspan="2" style="padding-top:3px;"><strong>${name}</strong></td></tr>
            <tr><td class="small">${qtyTxt} × ${_money(unitPrice)}</td><td class="num">${_money(subtotal)}</td></tr>`;
  }).join("");
  const paid = sale.paid != null ? sale.paid : (sale.status === "a_receber" ? 0 : sale.total);
  const pending = Math.max(0, sale.total - paid);
  return `<div>
    ${head}
    <div class="center"><strong>COMPROVANTE DE VENDA</strong></div>
    <div class="center small">${viaLabel}</div>
    <div class="center small">Nº ${docNum}</div>
    <div class="sep"></div>
    <div class="meta">
      Cliente: <strong>${sale.client?.name||"—"}</strong><br/>
      ${sale.client?.doc ? "CNPJ: "+sale.client.doc+"<br/>" : ""}
      Data: ${_date(sale.date||new Date())}${sale.time ? " · "+sale.time : ""}<br/>
      Pagto: <strong>${sale.payment||"—"}</strong>
    </div>
    <div class="sep"></div>
    <div class="ttl">Itens</div>
    <table>${rows}</table>
    <div class="sep"></div>
    <div class="row"><span>Subtotal</span><span>${_money(sale.subtotal||sale.total)}</span></div>
    ${sale.discount>0 ? `<div class="row"><span>Desconto</span><span>-${_money(sale.discount)}</span></div>` : ""}
    <div class="row big"><span>TOTAL</span><span>${_money(sale.total)}</span></div>
    ${pending > 0 ? `<div class="row" style="color:#B45309"><span>PENDENTE</span><span>${_money(pending)}</span></div>` : ""}
    <div class="sep"></div>
    <div class="center small">_________________________<br/>Assinatura</div>
    <div class="sep"></div>
    <div class="center small">Documento sem valor fiscal<br/>${_now()}<br/>${company.name||""}</div>
  </div>`;
}

function printSaleReceipt({ company, sale, items, products, fmt, autoPrint, vias }){
  const docNum = _docNum("VEN", sale.id || Date.now()+"");
  const css = _baseCss(fmt);
  const viaList = vias === "empresa"     ? [{ key:"empresa", label:"Via da Empresa" }]
                : vias === "distribuidor" ? [{ key:"distribuidor", label:"Via do Distribuidor" }]
                : [{ key:"empresa", label:"Via da Empresa" }, { key:"distribuidor", label:"Via do Distribuidor" }];

  let body = "";
  if (fmt === "a4") {
    body = viaList.map((v, idx) => {
      const block = _saleBodyA4({
        company, sale, items, products,
        viaLabel: v.label,
        viaDestinatario: v.key,
      });
      const wrapper = idx < viaList.length - 1
        ? `<div class="page-break">${block}</div>`
        : block;
      return wrapper;
    }).join("");
  } else {
    body = viaList.map((v) => _saleBodyThermal({
      company, sale, items, products, fmt,
      viaLabel: v.label,
    })).join('<div class="via-divider">--- corte ---</div>');
  }

  const title = "Comprovante de Venda — " + docNum + (vias && vias !== "both" ? " ("+(vias==="empresa"?"Empresa":"Distribuidor")+")" : "");
  _openPrintWindow(title, css, body, autoPrint);
}

/* ============================================================
   COMPROVANTE DE SAÍDA (Picolezeiro · consignação)
   ============================================================ */
function printSaidaReceipt({ company, trip, picolezeiro, beaches, products, fmt, autoPrint }){
  const head = _headerHtml(company, fmt);
  const docNum = _docNum("SAI", trip.id || Date.now()+"");
  const css = _baseCss(fmt);
  const beachNames = (trip.beachesPlanned||[]).map(bid => beaches.find(b=>b.id===bid)?.name).filter(Boolean);
  const totalUnits = trip.items.reduce((s,i)=>s+i.qty,0);
  const expectedValue = trip.items.reduce((s,i)=>{
    const p = products.find(x=>x.id===i.productId);
    return s + i.qty * (p?.price||0);
  },0);

  let body = "";
  if (fmt === "a4") {
    const rows = trip.items.map(it => {
      const p = products.find(x=>x.id===it.productId);
      return `<tr>
        <td>${p?.flavor||"—"} <span style="color:#888;font-size:10.5px">· ${p?.line||""}</span></td>
        <td class="num">${it.qty}</td>
        <td class="num">${_money(p?.price||0)}</td>
        <td class="num"><strong>${_money((p?.price||0) * it.qty)}</strong></td>
      </tr>`;
    }).join("");
    body = `
      <div class="brand-bar"></div>
      ${head}
      <h1 class="doc-title">Comprovante de Saída · Consignação</h1>
      <div class="doc-meta">
        <span>Nº ${docNum}</span>
        <span>Emitido em ${_now()}</span>
      </div>
      <div class="meta-grid">
        <div class="item"><strong class="lbl">Picolezeiro</strong>${picolezeiro?.name||"—"}<br/><span style="color:#666;font-size:10px;">${picolezeiro?.cpf||""} · ${picolezeiro?.phone||""}</span></div>
        <div class="item"><strong class="lbl">Data de saída</strong>${_date(trip.date||new Date())}</div>
        <div class="item"><strong class="lbl">Praias planejadas</strong>${beachNames.join(", ")||"—"}</div>
        <div class="item"><strong class="lbl">Comissão acordada</strong>${picolezeiro?.commission||0}% sobre valor vendido</div>
      </div>
      <div class="section-title">Produtos retirados (${totalUnits} un)</div>
      <table>
        <thead><tr><th>Produto</th><th class="num">Quantidade</th><th class="num">Vl. unitário</th><th class="num">Valor máx.</th></tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <div class="totals">
        <div class="row"><span>Total de unidades</span><span class="num">${totalUnits} un</span></div>
        <div class="row big"><span>Valor máximo previsto</span><span class="num">${_money(expectedValue)}</span></div>
      </div>
      <div class="terms-box">
        <strong>Termos da consignação:</strong> O picolezeiro recebe os produtos relacionados em consignação. No retorno deverá prestar contas dos valores efetivamente vendidos. Sobras retornam ao estoque da fábrica. A comissão é calculada sobre o faturamento líquido confirmado no retorno.
      </div>
      <div class="sigs">
        <div class="sig"><div class="line">Picolezeiro — Recebi os produtos</div></div>
        <div class="sig"><div class="line">Conferente / Fábrica</div></div>
      </div>
      <div class="footer">
        Documento de controle interno · sem valor fiscal<br/>
        <span class="doc-no">${docNum}</span> · ${company.name||""} · gerado em ${_now()}
      </div>`;
  } else {
    const rows = trip.items.map(it => {
      const p = products.find(x=>x.id===it.productId);
      const name = (p?.flavor||"—").slice(0, fmt==="mm80"?26:18);
      return `<tr><td colspan="2" style="padding-top:3px;"><strong>${name}</strong></td></tr>
              <tr><td class="small">${it.qty} un × ${_money(p?.price||0)}</td><td class="num">${_money((p?.price||0)*it.qty)}</td></tr>`;
    }).join("");
    body = `<div>
      ${head}
      <div class="center"><strong>COMPROVANTE DE SAÍDA</strong></div>
      <div class="center small">CONSIGNAÇÃO · Nº ${docNum}</div>
      <div class="sep"></div>
      <div class="meta">
        Picolezeiro: <strong>${picolezeiro?.name||"—"}</strong><br/>
        CPF: ${picolezeiro?.cpf||"—"}<br/>
        Data: ${_date(trip.date||new Date())}<br/>
        Praias: ${beachNames.join(", ")||"—"}<br/>
        Comissão: <strong>${picolezeiro?.commission||0}%</strong>
      </div>
      <div class="sep"></div>
      <div class="ttl">Itens retirados</div>
      <table>${rows}</table>
      <div class="sep"></div>
      <div class="row"><span>Unidades</span><span>${totalUnits}</span></div>
      <div class="row big"><span>VALOR MÁX</span><span>${_money(expectedValue)}</span></div>
      <div class="sep"></div>
      <div class="small">_____________________________<br/>Picolezeiro</div>
      <div class="small" style="margin-top:6px;">_____________________________<br/>Conferente</div>
      <div class="sep"></div>
      <div class="center small">${_now()}<br/>${company.name||""}</div>
    </div>`;
  }
  _openPrintWindow("Comprovante de Saída — " + docNum, css, body, autoPrint);
}

/* ============================================================
   COMPROVANTE DE RETORNO (Picolezeiro)
   ============================================================ */
function printRetornoReceipt({ company, trip, picolezeiro, beaches, products, fmt, autoPrint }){
  const head = _headerHtml(company, fmt);
  const docNum = _docNum("RET", trip.id || Date.now()+"");
  const css = _baseCss(fmt);
  const beachNames = (trip.beachesActual||trip.beachesPlanned||[]).map(bid => beaches.find(b=>b.id===bid)?.name).filter(Boolean);

  const totalSold = (trip.sold||[]).reduce((s,x)=>s+x.qty,0);
  const totalRet = (trip.returned||[]).reduce((s,x)=>s+x.qty,0);
  const faturado = trip.faturado || 0;
  const comissao = trip.comissao || 0;
  const recebido = trip.recebido || 0;
  const liquido = faturado - comissao;
  const diff = recebido - faturado;

  let body = "";
  if (fmt === "a4") {
    const rows = trip.items.map(it => {
      const p = products.find(x=>x.id===it.productId);
      const sold = (trip.sold||[]).find(x=>x.productId===it.productId)?.qty || 0;
      const ret = (trip.returned||[]).find(x=>x.productId===it.productId)?.qty ?? (it.qty - sold);
      return `<tr>
        <td>${p?.flavor||"—"} <span style="color:#888;font-size:10.5px">· ${p?.line||""}</span></td>
        <td class="num">${it.qty}</td>
        <td class="num"><strong>${sold}</strong></td>
        <td class="num" style="color:#B45309">${ret}</td>
        <td class="num">${_money((p?.price||0)*sold)}</td>
      </tr>`;
    }).join("");
    body = `
      <div class="brand-bar"></div>
      ${head}
      <h1 class="doc-title">Comprovante de Retorno · Consignação</h1>
      <div class="doc-meta">
        <span>Nº ${docNum}</span>
        <span>Emitido em ${_now()}</span>
      </div>
      <div class="meta-grid">
        <div class="item"><strong class="lbl">Picolezeiro</strong>${picolezeiro?.name||"—"}<br/><span style="color:#666;font-size:10px;">${picolezeiro?.cpf||""}</span></div>
        <div class="item"><strong class="lbl">Data do retorno</strong>${_date(trip.date||new Date())}</div>
        <div class="item"><strong class="lbl">Praias atendidas</strong>${beachNames.join(", ")||"—"}</div>
        <div class="item"><strong class="lbl">Comissão aplicada</strong>${picolezeiro?.commission||0}% sobre valor vendido</div>
      </div>
      <div class="section-title">Prestação de contas</div>
      <table>
        <thead><tr><th>Produto</th><th class="num">Retirado</th><th class="num">Vendido</th><th class="num">Sobra</th><th class="num">Faturado</th></tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <div class="totals">
        <div class="row"><span>Total vendido</span><span class="num">${totalSold} un</span></div>
        <div class="row"><span>Sobra (estoque)</span><span class="num">${totalRet} un</span></div>
        <div class="row"><span>Faturado</span><span class="num">${_money(faturado)}</span></div>
        <div class="row" style="color:#B91C1C"><span>Comissão picolezeiro</span><span class="num">− ${_money(comissao)}</span></div>
        <div class="row big"><span>Líquido p/ empresa</span><span class="num">${_money(liquido)}</span></div>
        <div class="row"><span>Valor recebido em dinheiro</span><span class="num">${_money(recebido)}</span></div>
        ${diff !== 0 ? `<div class="row" style="color:${diff>0?'#15803D':'#B91C1C'};font-weight:700;"><span>Divergência</span><span class="num">${diff>0?'+':'−'} ${_money(Math.abs(diff))}</span></div>` : ""}
      </div>
      <div class="sigs">
        <div class="sig"><div class="line">Picolezeiro — Prestou contas</div></div>
        <div class="sig"><div class="line">Conferente / Fábrica</div></div>
      </div>
      <div class="footer">
        Documento de controle interno · sem valor fiscal<br/>
        <span class="doc-no">${docNum}</span> · ${company.name||""} · gerado em ${_now()}
      </div>`;
  } else {
    const rows = trip.items.map(it => {
      const p = products.find(x=>x.id===it.productId);
      const sold = (trip.sold||[]).find(x=>x.productId===it.productId)?.qty || 0;
      const ret = (trip.returned||[]).find(x=>x.productId===it.productId)?.qty ?? (it.qty - sold);
      const name = (p?.flavor||"—").slice(0, fmt==="mm80"?22:14);
      return `<tr><td colspan="2" style="padding-top:3px;"><strong>${name}</strong></td></tr>
              <tr><td class="small">Ret:${it.qty} Vd:${sold} Sb:${ret}</td><td class="num">${_money((p?.price||0)*sold)}</td></tr>`;
    }).join("");
    body = `<div>
      ${head}
      <div class="center"><strong>COMPROVANTE DE RETORNO</strong></div>
      <div class="center small">Nº ${docNum}</div>
      <div class="sep"></div>
      <div class="meta">
        Picolezeiro: <strong>${picolezeiro?.name||"—"}</strong><br/>
        Data: ${_date(trip.date||new Date())}<br/>
        Praias: ${beachNames.join(", ")||"—"}<br/>
        Comissão: <strong>${picolezeiro?.commission||0}%</strong>
      </div>
      <div class="sep"></div>
      <div class="ttl">Itens</div>
      <table>${rows}</table>
      <div class="sep"></div>
      <div class="row"><span>Vendidos</span><span>${totalSold} un</span></div>
      <div class="row"><span>Sobra</span><span>${totalRet} un</span></div>
      <div class="row"><span>Faturado</span><span>${_money(faturado)}</span></div>
      <div class="row"><span>Comissão</span><span>-${_money(comissao)}</span></div>
      <div class="row big"><span>LÍQUIDO</span><span>${_money(liquido)}</span></div>
      <div class="row"><span>Recebido</span><span>${_money(recebido)}</span></div>
      ${diff !== 0 ? `<div class="row"><span>Diferença</span><span>${diff>0?'+':'-'}${_money(Math.abs(diff))}</span></div>` : ""}
      <div class="sep"></div>
      <div class="small">_____________________________<br/>Picolezeiro</div>
      <div class="small" style="margin-top:6px;">_____________________________<br/>Conferente</div>
      <div class="sep"></div>
      <div class="center small">${_now()}<br/>${company.name||""}</div>
    </div>`;
  }
  _openPrintWindow("Comprovante de Retorno — " + docNum, css, body, autoPrint);
}

/* ============================================================
   Modal de seleção de formato (UI compartilhada)
   ============================================================ */
function ReceiptFormatModal({ title, subtitle, onClose, onPrint }) {
  const [fmt, setFmt] = useState("a4");
  const options = [
    { value:"a4",   label:"Papel A4",       hint:"Comprovante completo (impressora comum)", icon:"📄" },
    { value:"mm80", label:"Térmica 80mm",   hint:"Cupom largo (impressora de cupom)",       icon:"🧾" },
    { value:"mm58", label:"Térmica 58mm",   hint:"Cupom estreito (mini-impressora)",         icon:"🎫" },
  ];
  return (
    <Modal title={title} subtitle={subtitle} onClose={onClose}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" icon={<Icons.Print size={14}/>} onClick={() => onPrint(fmt)}>Gerar comprovante</Button>
        </>
      }
    >
      <p className="muted" style={{ marginTop:0, fontSize:12.5 }}>Selecione o formato de impressão:</p>
      <div style={{ display:"flex", flexDirection:"column", gap:10 }}>
        {options.map(o => (
          <button key={o.value} onClick={() => setFmt(o.value)}
            style={{
              padding:"14px 16px", borderRadius:10, textAlign:"left", cursor:"pointer",
              display:"flex", alignItems:"center", gap:14,
              border:"1px solid " + (fmt===o.value ? "var(--brand-600)" : "var(--line)"),
              background: fmt===o.value ? "var(--brand-50)" : "white",
              boxShadow: fmt===o.value ? "0 0 0 3px var(--brand-100)" : "none",
              transition:"all .12s",
            }}>
            <div style={{ fontSize:28 }}>{o.icon}</div>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:700, color:"var(--ink-900)", fontSize:14 }}>{o.label}</div>
              <div className="subtle">{o.hint}</div>
            </div>
            {fmt===o.value && <Icons.Check size={18} color="var(--brand-600)" strokeWidth={2.4}/>}
          </button>
        ))}
      </div>
    </Modal>
  );
}

/* ============================================================
   COMPROVANTE DE COMISSÃO (Picolezeiro · LUCRO)
   Recibo formal de pagamento da comissão devida ao picolezeiro.
   Pode ser por 1 retorno OU por período (várias trips).

   props:
     - company
     - picolezeiro
     - trips: array de trips fechados (1 ou mais)
     - period: { label, start, end } opcional
     - paymentMethod: forma de pagamento da comissão
     - paymentDate: data do pagamento (default hoje)
     - fmt: "a4" | "mm80" | "mm58"
   ============================================================ */
function printCommissionReceipt({ company, picolezeiro, trips, beaches, period, paymentMethod, paymentDate, fmt, autoPrint }){
  const tripsArr = Array.isArray(trips) ? trips : [trips];
  const beachesArr = beaches || [];
  const docNum = _docNum("COM", (tripsArr[0]?.id || "") + (tripsArr.length > 1 ? "-" + tripsArr.length : "") + Date.now().toString(36));
  const css = _baseCss(fmt);

  const faturadoTotal = tripsArr.reduce((s, t) => s + (t.faturado || 0), 0);
  const comissaoTotal = tripsArr.reduce((s, t) => s + (t.comissao || 0), 0);
  const liquidoEmpresa = faturadoTotal - comissaoTotal;
  const totalSold = tripsArr.reduce((s, t) => s + ((t.sold||[]).reduce((a, x) => a + x.qty, 0)), 0);

  /* Valor da comissão por extenso (simples). */
  const valorPorExtenso = (v) => {
    const reais = Math.floor(v);
    const cent = Math.round((v - reais) * 100);
    return `${reais} reais${cent > 0 ? " e " + cent + " centavos" : ""}`;
  };

  const dataPgto = paymentDate || new Date().toISOString().slice(0,10);
  const periodLabel = period?.label || (tripsArr.length === 1
    ? "Retorno de " + _date(tripsArr[0].date)
    : tripsArr.length + " retornos");

  let body = "";

  if (fmt === "a4") {
    const tripRows = tripsArr.map(t => {
      const tripFat = t.faturado || 0;
      const tripCom = t.comissao || 0;
      const tripSold = (t.sold||[]).reduce((s,x)=>s+x.qty,0);
      const tripBeaches = (t.beachesActual || t.beachesPlanned || [])
        .map(bid => beachesArr.find(b => b.id === bid)?.name)
        .filter(Boolean)
        .join(", ") || "—";
      return `<tr>
        <td>${_date(t.date)}</td>
        <td style="font-size:10px;">${tripBeaches}</td>
        <td class="num">${tripSold}</td>
        <td class="num">${_money(tripFat)}</td>
        <td class="num"><strong>${_money(tripCom)}</strong></td>
      </tr>`;
    }).join("");

    body = `
      <div class="brand-bar"></div>
      ${_headerHtml(company, "a4")}
      <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:14px;margin-bottom:10px;">
        <div>
          <span class="via-tag">Recibo de Pagamento</span>
          <h1 class="doc-title" style="margin-top:8px;">Recibo de Comissão · Picolezeiro</h1>
        </div>
        <div style="text-align:right;">
          <span class="badge-status badge-pago">Pago</span>
        </div>
      </div>
      <div class="doc-meta">
        <span>Nº ${docNum}</span>
        <span>Emitido em ${_now()}</span>
      </div>

      <div style="border:1.5px solid #333;padding:14px 16px;margin-bottom:18px;">
        <div style="font-size:9.5px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:.12em;margin-bottom:6px;">Valor recebido</div>
        <div style="font-size:24px;font-weight:800;color:${BRAND_COLORS.red};letter-spacing:-.01em;margin-bottom:4px;">${_money(comissaoTotal)}</div>
        <div style="font-size:10px;color:#666;font-style:italic;">(${valorPorExtenso(comissaoTotal)})</div>
      </div>

      <p style="font-size:11px;line-height:1.7;color:#222;margin:0 0 18px;text-align:justify;">
        Eu, <strong>${picolezeiro?.name||"—"}</strong>${picolezeiro?.cpf ? ", portador(a) do CPF nº " + picolezeiro.cpf : ""}, declaro ter recebido da empresa <strong>${company.name||"—"}</strong>${company.cnpj ? ", inscrita no CNPJ sob nº " + company.cnpj : ""}, a importância de <strong>${_money(comissaoTotal)}</strong> (${valorPorExtenso(comissaoTotal)}), referente à comissão de <strong>${picolezeiro?.commission||0}%</strong> sobre o faturamento de <strong>${_money(faturadoTotal)}</strong> apurado em <strong>${periodLabel}</strong>, conforme detalhamento abaixo. Para clareza, firmo o presente recibo, dando plena e geral quitação da obrigação acima referida.
      </p>

      <div class="meta-grid">
        <div class="item"><strong class="lbl">Beneficiário</strong>${picolezeiro?.name||"—"}<br/><span style="color:#666;font-size:10px;">CPF ${picolezeiro?.cpf||"—"}${picolezeiro?.phone ? " · " + picolezeiro.phone : ""}</span></div>
        <div class="item"><strong class="lbl">Pagador</strong>${company.name||"—"}<br/><span style="color:#666;font-size:10px;">CNPJ ${company.cnpj||"—"}</span></div>
        <div class="item"><strong class="lbl">Período de apuração</strong>${periodLabel}</div>
        <div class="item"><strong class="lbl">Data do pagamento</strong>${_date(dataPgto)}</div>
        <div class="item"><strong class="lbl">Forma de pagamento</strong>${paymentMethod || "Dinheiro"}</div>
        <div class="item"><strong class="lbl">Comissão acordada</strong>${picolezeiro?.commission||0}% sobre valor vendido</div>
      </div>

      <div class="section-title">Detalhamento por retorno</div>
      <table>
        <thead>
          <tr>
            <th>Data</th>
            <th>Praias</th>
            <th class="num">Un. vendidas</th>
            <th class="num">Faturado</th>
            <th class="num">Comissão (${picolezeiro?.commission||0}%)</th>
          </tr>
        </thead>
        <tbody>${tripRows}</tbody>
        <tfoot>
          <tr style="border-top:1.5px solid #333;font-weight:700;">
            <td colspan="2" style="padding-top:8px;text-transform:uppercase;font-size:10px;letter-spacing:.06em;color:#111;">Totais</td>
            <td class="num" style="padding-top:8px;">${totalSold} un</td>
            <td class="num" style="padding-top:8px;">${_money(faturadoTotal)}</td>
            <td class="num" style="padding-top:8px;color:${BRAND_COLORS.red};font-weight:800;">${_money(comissaoTotal)}</td>
          </tr>
        </tfoot>
      </table>

      <div class="totals">
        <div class="row"><span>Faturamento total</span><span class="num">${_money(faturadoTotal)}</span></div>
        <div class="row"><span>Alíquota de comissão</span><span class="num">${picolezeiro?.commission||0}%</span></div>
        <div class="row"><span>Líquido retido pela empresa</span><span class="num">${_money(liquidoEmpresa)}</span></div>
        <div class="row profit"><span>LUCRO DO PICOLEZEIRO</span><span class="num">${_money(comissaoTotal)}</span></div>
      </div>

      <div class="terms-box">
        Dou plena, geral e irrevogável quitação à empresa pagadora quanto ao valor acima descrito, referente exclusivamente ao período/retornos discriminados. Nada mais tendo a reclamar a qualquer título.
      </div>

      <div class="sigs">
        <div class="sig">
          <div class="line">${picolezeiro?.name||""}<br/><span style="font-size:9px;">CPF ${picolezeiro?.cpf||"—"}</span></div>
        </div>
        <div class="sig">
          <div class="line">${company.name||""}<br/><span style="font-size:9px;">CNPJ ${company.cnpj||"—"}</span></div>
        </div>
      </div>

      <div class="footer">
        Recibo de pagamento de comissão · documento sem valor fiscal<br/>
        <span class="doc-no">${docNum}</span> · ${company.name||""} · ${_date(dataPgto)} · ${_now()}
      </div>`;
  } else {
    // Térmica
    const trRows = tripsArr.map(t => `
      <div class="row"><span>${_date(t.date)}</span><span>${_money(t.comissao||0)}</span></div>
      <div class="small" style="color:#444;padding-left:0;">Fat ${_money(t.faturado||0)}</div>
      <div class="sep" style="margin:3px 0;"></div>
    `).join("");

    body = `<div>
      ${_headerHtml(company, fmt)}
      <div class="center"><strong>RECIBO DE COMISSÃO</strong></div>
      <div class="center small">Picolezeiro · Nº ${docNum}</div>
      <div class="sep"></div>
      <div class="meta">
        <strong>${picolezeiro?.name||"—"}</strong><br/>
        CPF ${picolezeiro?.cpf||"—"}<br/>
        Data pgto: ${_date(dataPgto)}<br/>
        Período: ${periodLabel}<br/>
        Comissão: <strong>${picolezeiro?.commission||0}%</strong><br/>
        Pgto: <strong>${paymentMethod||"Dinheiro"}</strong>
      </div>
      <div class="sep"></div>
      <div class="ttl">Retornos no período</div>
      ${trRows}
      <div class="row"><span>Faturado total</span><span>${_money(faturadoTotal)}</span></div>
      <div class="row"><span>Un. vendidas</span><span>${totalSold}</span></div>
      <div class="sep"></div>
      <div class="row.profit row" style="font-weight:700;border:1px solid #333;padding:4px;margin:3px 0;text-align:center;display:flex;justify-content:space-between;">
        <span>LUCRO RECEBIDO</span><span>${_money(comissaoTotal)}</span>
      </div>
      <div class="sep"></div>
      <div class="small">Recebi da empresa ${company.name||""} a importância acima referente à comissão da consignação. Dou plena quitação.</div>
      <div class="sep"></div>
      <div class="small">_________________________<br/>${picolezeiro?.name||""}</div>
      <div class="small" style="margin-top:5px;">_________________________<br/>Pagador</div>
      <div class="sep"></div>
      <div class="center small">${_now()}<br/>${company.name||""}</div>
    </div>`;
  }
  _openPrintWindow("Recibo de Comissão — " + (picolezeiro?.name||"") + " — " + docNum, css, body, autoPrint);
}

Object.assign(window, {
  printSaleReceipt, printSaidaReceipt, printRetornoReceipt, printCommissionReceipt, ReceiptFormatModal,
});
