// screen-pdv.jsx — Frente de Caixa (PDV) — the "wow" screen

const { useState, useEffect, useRef, useMemo } = React;

function PDVScreen({ currentUser, onToast }) {
  const [search, setSearch] = useState("");
  const [activeCat, setActiveCat] = useState("all");
  const [cart, setCart] = useState([]);
  const [discount, setDiscount] = useState({ type: "R$", value: 0 });
  const [client, setClient] = useState(null);
  const [showClient, setShowClient] = useState(false);
  const [showPay, setShowPay] = useState(false);
  const [showCupom, setShowCupom] = useState(null);
  const [showCashOpen, setShowCashOpen] = useState(!CASH_SESSION.open);
  const [showCashOps, setShowCashOps] = useState(false);
  const [cashSession, setCashSession] = useState(CASH_SESSION);
  const searchRef = useRef(null);

  // Filter products
  const filtered = useMemo(() => {
    const s = search.trim().toLowerCase();
    return PRODUCTS.filter(p => {
      if (activeCat !== "all" && p.cat !== activeCat) return false;
      if (!s) return true;
      return (
        p.name.toLowerCase().includes(s) ||
        p.sku.toLowerCase().includes(s) ||
        p.barcode.includes(s)
      );
    }).slice(0, 60);
  }, [search, activeCat]);

  // Cart math
  const subtotal = cart.reduce((s, x) => s + x.price * x.qty, 0);
  const desc = discount.type === "%" ? subtotal * (discount.value / 100) : Number(discount.value || 0);
  const total = Math.max(0, subtotal - desc);
  const totalItems = cart.reduce((s, x) => s + x.qty, 0);

  // Actions
  function addToCart(p) {
    if (p.stock <= 0) { onToast({ msg: "Produto sem estoque", kind: "err" }); return; }
    setCart(prev => {
      const idx = prev.findIndex(x => x.id === p.id);
      if (idx >= 0) {
        const copy = [...prev];
        copy[idx] = { ...copy[idx], qty: copy[idx].qty + 1 };
        return copy;
      }
      return [...prev, { id: p.id, sku: p.sku, name: p.name, price: p.price, qty: 1 }];
    });
  }
  function setQty(id, qty) {
    if (qty <= 0) { setCart(prev => prev.filter(x => x.id !== id)); return; }
    setCart(prev => prev.map(x => x.id === id ? { ...x, qty } : x));
  }
  function clearCart() { setCart([]); setDiscount({ type: "R$", value: 0 }); setClient(null); }
  function onPaid(payment) {
    const saleId = "V" + (10500 + Math.floor(Math.random() * 999)).toString();
    const nfNumber = (28911 + Math.floor(Math.random() * 99)).toString();
    setShowPay(false);
    setShowCupom({
      id: saleId,
      data: new Date().toISOString(),
      items: cart,
      cliente: client ? client.nome : "Consumidor Final",
      cliente_cpf: client?.cpf,
      vendedor: currentUser.nome,
      pdv: "PDV01",
      subtotal, desc, total,
      payment,
      nf: "NFC-e " + nfNumber,
      operador: currentUser.nome,
    });
    setCashSession(prev => ({ ...prev, sales: prev.sales + total, current: prev.current + (payment.cash || 0) }));
    onToast({ msg: `Venda ${saleId} finalizada — ${brl(total)}`, kind: "ok" });
    clearCart();
  }
  function onBarcodeScan() {
    const random = PRODUCTS[Math.floor(Math.random() * 18)];
    addToCart(random);
    onToast({ msg: `📷 Leitura: ${random.sku}`, kind: "ok" });
    if (searchRef.current) searchRef.current.focus();
  }

  // Hotkey on Enter — if search matches exactly one item, add it
  function onSearchKey(e) {
    if (e.key === "Enter" && filtered.length > 0) {
      addToCart(filtered[0]);
      setSearch("");
    }
  }

  // Block PDV until cash open
  if (showCashOpen) {
    return <CashOpenModal onOpen={(initial) => { setCashSession({ ...CASH_SESSION, open: true, initial, current: initial, opened_by: currentUser.nome }); setShowCashOpen(false); onToast({ msg: "Caixa aberto.", kind: "ok" }); }} />;
  }

  return (
    <div className="pdv">
      {/* Left — product browser */}
      <div className="pdv-left">
        {/* Status bar */}
        <div className="pdv-status">
          <div className="seg">
            <span className="lbl">PDV</span>
            <b>{cashSession.pdv || "PDV01"}</b>
          </div>
          <div className="sep" />
          <div className="seg">
            <span className="lbl">Operador</span>
            <b>{currentUser.nome}</b>
          </div>
          <div className="sep" />
          <div className="seg">
            <span className="lbl">Caixa aberto</span>
            <b>{cashSession.opened_at} • {brl(cashSession.current)}</b>
          </div>
          <div className="sep" />
          <div className="seg">
            <span className="lbl">Conexão</span>
            <b style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span className="live-dot" /> Online · sync ML, Shopee, Magalu
            </b>
          </div>
          <div className="grow"></div>
          <button className="btn btn-sm" onClick={() => setShowCashOps(true)}>
            <I.Cash size={13} /> Sangria / Suprimento
          </button>
          <button className="btn btn-sm btn-danger" onClick={() => { setCashSession({ ...cashSession, open: false }); setShowCashOpen(true); onToast({ msg: "Caixa fechado.", kind: "ok" }); }}>
            Fechar caixa
          </button>
        </div>

        {/* Search */}
        <div className="pdv-search">
          <div style={{ position: "relative", flex: 1 }}>
            <I.Search size={18} style={{ position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }} />
            <input
              ref={searchRef}
              className="input"
              style={{ height: 56, fontSize: 16, paddingLeft: 46 }}
              placeholder="Buscar produto por nome, SKU ou ler código de barras…"
              value={search}
              onChange={e => setSearch(e.target.value)}
              onKeyDown={onSearchKey}
              autoFocus
            />
          </div>
          <button className="btn barcode-btn" onClick={onBarcodeScan} title="Simular leitura de código de barras">
            <I.Barcode size={22} />
          </button>
        </div>

        {/* Category tabs */}
        <div style={{ display: "flex", gap: 6, overflowX: "auto", paddingBottom: 4 }}>
          <button
            className={`btn btn-sm${activeCat === "all" ? " btn-green" : ""}`}
            onClick={() => setActiveCat("all")}
          >Todos</button>
          {CATS.map(c => (
            <button
              key={c.id}
              className={`btn btn-sm${activeCat === c.id ? " btn-green" : ""}`}
              onClick={() => setActiveCat(c.id)}
            >
              <span>{c.icon}</span> {c.name}
            </button>
          ))}
        </div>

        {/* Product grid */}
        <div className="pdv-grid">
          {filtered.map(p => (
            <div key={p.id} className="pdv-product" onClick={() => addToCart(p)}>
              <div className="thumb">[ foto produto ]</div>
              <div className="name">{p.name}</div>
              <div className="meta">
                <span style={{ fontFamily: "var(--font-mono)" }}>{p.sku}</span>
                <span className={`stock-pill${p.stock === 0 ? " out" : p.stock <= p.min ? " low" : ""}`}>
                  {p.stock}
                </span>
              </div>
              <div className="price">{brl(p.price)}</div>
            </div>
          ))}
          {filtered.length === 0 && (
            <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: 40, color: "var(--ink-3)" }}>
              Nenhum produto encontrado para "{search}"
            </div>
          )}
        </div>
      </div>

      {/* Right — cart */}
      <div className="pdv-right">
        <div className="pdv-cart-head">
          <div className="row between" style={{ marginBottom: 10 }}>
            <h3><I.Receipt size={16} /> Venda em andamento</h3>
            {cart.length > 0 && (
              <button className="btn btn-ghost btn-sm" onClick={clearCart}>
                <I.Trash size={13} /> Limpar
              </button>
            )}
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button
              className="btn btn-sm"
              style={{ flex: 1 }}
              onClick={() => setShowClient(true)}
            >
              <I.Users size={13} />
              {client ? client.nome.split(" ")[0] + " " + (client.nome.split(" ")[1] || "") : "Consumidor Final"}
            </button>
          </div>
        </div>

        {/* Items */}
        <div className="pdv-cart-items">
          {cart.length === 0 ? (
            <div className="pdv-cart-empty">
              <I.Receipt size={40} />
              <div>
                <div style={{ fontWeight: 700, fontSize: 14, color: "var(--ink-2)" }}>Carrinho vazio</div>
                <div style={{ fontSize: 12, marginTop: 4 }}>Busque um produto ou bipe o código de barras para começar.</div>
              </div>
            </div>
          ) : (
            cart.map(item => (
              <div key={item.id} className="pdv-cart-row">
                <div style={{ minWidth: 0 }}>
                  <div className="nm">{item.name}</div>
                  <div className="sku">{item.sku}</div>
                  <div className="row" style={{ gap: 10, marginTop: 6 }}>
                    <div className="qty-stepper">
                      <button onClick={() => setQty(item.id, item.qty - 1)}><I.Minus size={12} /></button>
                      <input value={item.qty} onChange={e => setQty(item.id, parseInt(e.target.value) || 0)} />
                      <button onClick={() => setQty(item.id, item.qty + 1)}><I.Plus size={12} /></button>
                    </div>
                    <span style={{ fontSize: 11, color: "var(--ink-3)" }}>
                      {brl(item.price)} × {item.qty}
                    </span>
                  </div>
                </div>
                <div className="pr">{brl(item.price * item.qty)}</div>
              </div>
            ))
          )}
        </div>

        {/* Discount input */}
        {cart.length > 0 && (
          <div style={{ padding: "10px 20px", borderTop: "1px solid var(--line)", display: "flex", gap: 8, alignItems: "center" }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-3)" }}>Desconto:</span>
            <select
              className="select"
              style={{ width: 56, height: 32, fontSize: 12, padding: "0 8px" }}
              value={discount.type}
              onChange={e => setDiscount(prev => ({ ...prev, type: e.target.value }))}
            >
              <option>R$</option>
              <option>%</option>
            </select>
            <input
              className="input"
              type="number"
              min="0"
              step="0.01"
              style={{ height: 32, fontSize: 12, flex: 1 }}
              value={discount.value}
              onChange={e => setDiscount(prev => ({ ...prev, value: parseFloat(e.target.value) || 0 }))}
            />
          </div>
        )}

        {/* Totals */}
        <div className="pdv-totals">
          <div className="tot-row">
            <span>Subtotal ({totalItems} {totalItems === 1 ? "item" : "itens"})</span>
            <span>{brl(subtotal)}</span>
          </div>
          {desc > 0 && (
            <div className="tot-row" style={{ color: "var(--err)" }}>
              <span>Desconto</span>
              <span>- {brl(desc)}</span>
            </div>
          )}
          <div className="tot-row big">
            <span>Total</span>
            <span>{brl(total)}</span>
          </div>
        </div>

        <button className="pdv-pay-btn" disabled={cart.length === 0} onClick={() => setShowPay(true)}>
          <I.Lightning size={20} /> Finalizar venda · {brl(total)}
        </button>
      </div>

      {/* Modals */}
      {showClient && (
        <ClientPickerModal
          onClose={() => setShowClient(false)}
          onPick={(c) => { setClient(c); setShowClient(false); onToast({ msg: "Cliente vinculado à venda.", kind: "ok" }); }}
        />
      )}
      {showPay && (
        <PaymentModal
          total={total}
          onClose={() => setShowPay(false)}
          onPaid={onPaid}
        />
      )}
      {showCupom && (
        <CupomModal
          sale={showCupom}
          onClose={() => setShowCupom(null)}
        />
      )}
      {showCashOps && (
        <CashOpsModal
          session={cashSession}
          onClose={() => setShowCashOps(false)}
          onOp={(op) => {
            setCashSession(prev => ({
              ...prev,
              cash_in: prev.cash_in + (op.kind === "suprimento" ? op.value : 0),
              cash_out: prev.cash_out + (op.kind === "sangria" ? op.value : 0),
              current: prev.current + (op.kind === "suprimento" ? op.value : -op.value),
            }));
            setShowCashOps(false);
            onToast({ msg: `${op.kind === "sangria" ? "Sangria" : "Suprimento"} de ${brl(op.value)} registrado.`, kind: "ok" });
          }}
        />
      )}
    </div>
  );
}

/* ──────── Sub-modals used only by PDV ──────── */

function CashOpenModal({ onOpen }) {
  const [val, setVal] = useState("200,00");
  return (
    <div className="modal-overlay">
      <div className="modal">
        <div className="modal-hd">
          <I.Cash size={20} />
          <h3>Abertura de caixa</h3>
        </div>
        <div className="modal-bd">
          <p className="muted" style={{ marginTop: 0, fontSize: 13 }}>
            Para começar a vender, informe o valor inicial do caixa (fundo de troco).
          </p>
          <div className="field">
            <label>Valor inicial (R$)</label>
            <input className="input input-lg" autoFocus value={val} onChange={e => setVal(e.target.value)} />
          </div>
        </div>
        <div className="modal-ft">
          <button className="btn btn-primary btn-lg" onClick={() => {
            const n = parseFloat(val.replace(/\./g, "").replace(",", "."));
            onOpen(isNaN(n) ? 0 : n);
          }}>
            <I.Check size={16} /> Abrir caixa
          </button>
        </div>
      </div>
    </div>
  );
}

function CashOpsModal({ session, onClose, onOp }) {
  const [kind, setKind] = useState("sangria");
  const [val, setVal] = useState("");
  const [reason, setReason] = useState("");
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-hd">
          <I.Cash size={20} />
          <h3>Sangria / Suprimento</h3>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><I.X size={14} /></button>
        </div>
        <div className="modal-bd">
          <div className="row" style={{ marginBottom: 14 }}>
            <button
              className={`btn ${kind === "sangria" ? "btn-danger" : ""}`}
              style={{ flex: 1 }}
              onClick={() => setKind("sangria")}
            >Sangria (saída)</button>
            <button
              className={`btn ${kind === "suprimento" ? "btn-green" : ""}`}
              style={{ flex: 1 }}
              onClick={() => setKind("suprimento")}
            >Suprimento (entrada)</button>
          </div>
          <div className="field" style={{ marginBottom: 12 }}>
            <label>Valor</label>
            <input className="input" placeholder="0,00" value={val} onChange={e => setVal(e.target.value)} autoFocus />
          </div>
          <div className="field">
            <label>Motivo</label>
            <input className="input" placeholder={kind === "sangria" ? "Ex: troco recolhido pelo gerente" : "Ex: reforço de troco"} value={reason} onChange={e => setReason(e.target.value)} />
          </div>
          <div className="muted" style={{ marginTop: 14, fontSize: 12 }}>
            Saldo atual em caixa: <b style={{ color: "var(--ink)" }}>{brl(session.current)}</b>
          </div>
        </div>
        <div className="modal-ft">
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button className="btn btn-primary" onClick={() => {
            const n = parseFloat(val.replace(/\./g, "").replace(",", "."));
            if (!n || n <= 0) return;
            onOp({ kind, value: n, reason });
          }}>Confirmar</button>
        </div>
      </div>
    </div>
  );
}

function ClientPickerModal({ onClose, onPick }) {
  const [q, setQ] = useState("");
  const [adding, setAdding] = useState(false);
  const [nf, setNf] = useState({ nome: "", cpf: "", fone: "" });
  const list = CLIENTS.filter(c =>
    c.nome.toLowerCase().includes(q.toLowerCase()) ||
    c.cpf.includes(q) ||
    c.fone.includes(q)
  );
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-hd">
          <I.Users size={20} />
          <h3>{adding ? "Cadastrar cliente" : "Vincular cliente"}</h3>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><I.X size={14} /></button>
        </div>
        <div className="modal-bd">
          {!adding ? (
            <>
              <div className="row" style={{ marginBottom: 12, gap: 8 }}>
                <input className="input" autoFocus placeholder="Buscar por nome, CPF ou telefone" value={q} onChange={e => setQ(e.target.value)} />
                <button className="btn btn-primary" onClick={() => setAdding(true)}><I.Plus size={14} /> Novo</button>
              </div>
              <div style={{ maxHeight: 320, overflowY: "auto" }}>
                <div className="user-pick" onClick={() => onPick({ nome: "Consumidor Final" })}>
                  <I.Users size={16} />
                  <div className="grow"><b>Consumidor Final</b><span>Venda sem CPF na nota</span></div>
                </div>
                {list.map(c => (
                  <div key={c.id} className="user-pick" onClick={() => onPick(c)}>
                    <div className="avatar" style={{ width: 32, height: 32, fontSize: 12 }}>
                      {c.nome.split(" ").map(p => p[0]).slice(0, 2).join("")}
                    </div>
                    <div className="grow">
                      <b>{c.nome}</b>
                      <span>{c.cpf} · {c.fone}</span>
                    </div>
                    <I.ChevR size={14} />
                  </div>
                ))}
              </div>
            </>
          ) : (
            <>
              <div className="field" style={{ marginBottom: 10 }}>
                <label>Nome completo</label>
                <input className="input" autoFocus value={nf.nome} onChange={e => setNf({ ...nf, nome: e.target.value })} />
              </div>
              <div className="grid-2">
                <div className="field">
                  <label>CPF / CNPJ</label>
                  <input className="input" value={nf.cpf} onChange={e => setNf({ ...nf, cpf: e.target.value })} />
                </div>
                <div className="field">
                  <label>Telefone</label>
                  <input className="input" value={nf.fone} onChange={e => setNf({ ...nf, fone: e.target.value })} />
                </div>
              </div>
            </>
          )}
        </div>
        <div className="modal-ft">
          {adding ? (
            <>
              <button className="btn" onClick={() => setAdding(false)}>Voltar</button>
              <button className="btn btn-primary" onClick={() => { if (nf.nome) onPick(nf); }}>Salvar e vincular</button>
            </>
          ) : (
            <button className="btn" onClick={onClose}>Fechar</button>
          )}
        </div>
      </div>
    </div>
  );
}

function PaymentModal({ total, onClose, onPaid }) {
  const [methods, setMethods] = useState([{ id: 1, type: "dinheiro", value: total }]);
  const sum = methods.reduce((s, m) => s + (Number(m.value) || 0), 0);
  const remaining = Math.max(0, total - sum);
  const change = Math.max(0, sum - total);
  const isPaid = sum >= total - 0.005;

  function addMethod(type) {
    setMethods(prev => [...prev, { id: Date.now(), type, value: remaining }]);
  }
  function update(id, patch) {
    setMethods(prev => prev.map(m => m.id === id ? { ...m, ...patch } : m));
  }
  function remove(id) {
    setMethods(prev => prev.filter(m => m.id !== id));
  }

  const TYPES = [
    { id: "dinheiro", label: "Dinheiro", icon: "💵" },
    { id: "pix",      label: "PIX",      icon: "⚡" },
    { id: "credito",  label: "Cartão Crédito", icon: "💳" },
    { id: "debito",   label: "Cartão Débito",  icon: "🏦" },
    { id: "voucher",  label: "Vale", icon: "🎟️" },
  ];

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
        <div className="modal-hd">
          <I.Cash size={20} />
          <h3>Pagamento</h3>
          <span className="grow" />
          <span className="muted" style={{ fontSize: 13 }}>Total a pagar:</span>
          <b style={{ fontFamily: "var(--font-display)", fontSize: 22, color: "var(--brand-orange-deep)" }}>{brl(total)}</b>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><I.X size={14} /></button>
        </div>
        <div className="modal-bd">
          <div className="row" style={{ gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
            {TYPES.map(t => (
              <button key={t.id} className="btn btn-sm" onClick={() => addMethod(t.id)}>
                <span style={{ fontSize: 14 }}>{t.icon}</span> + {t.label}
              </button>
            ))}
          </div>

          {methods.map((m, i) => {
            const meta = TYPES.find(t => t.id === m.type);
            return (
              <div key={m.id} className="row" style={{ background: "var(--bg-sunk)", padding: "10px 12px", borderRadius: 10, marginBottom: 8, gap: 10 }}>
                <span style={{ fontSize: 20 }}>{meta.icon}</span>
                <select className="select" style={{ width: 160 }} value={m.type} onChange={e => update(m.id, { type: e.target.value })}>
                  {TYPES.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
                </select>
                <input
                  className="input"
                  type="number"
                  step="0.01"
                  style={{ flex: 1, fontWeight: 700, fontSize: 15 }}
                  value={m.value}
                  onChange={e => update(m.id, { value: parseFloat(e.target.value) || 0 })}
                />
                {methods.length > 1 && (
                  <button className="btn btn-ghost btn-icon btn-sm" onClick={() => remove(m.id)}><I.X size={14} /></button>
                )}
              </div>
            );
          })}

          <div style={{ marginTop: 18, padding: "12px 16px", background: isPaid ? "var(--ok-bg)" : "var(--warn-bg)", color: isPaid ? "var(--ok)" : "var(--warn)", borderRadius: 10, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            {isPaid ? (
              change > 0 ? (
                <>
                  <span style={{ fontWeight: 700, fontSize: 13 }}><I.Check size={14} /> Troco para o cliente:</span>
                  <b style={{ fontSize: 22, fontFamily: "var(--font-display)" }}>{brl(change)}</b>
                </>
              ) : (
                <>
                  <span style={{ fontWeight: 700, fontSize: 13 }}><I.Check size={14} /> Pagamento conferido</span>
                  <b style={{ fontSize: 16 }}>{brl(sum)}</b>
                </>
              )
            ) : (
              <>
                <span style={{ fontWeight: 700, fontSize: 13 }}>Falta receber:</span>
                <b style={{ fontSize: 22, fontFamily: "var(--font-display)" }}>{brl(remaining)}</b>
              </>
            )}
          </div>
        </div>
        <div className="modal-ft">
          <button className="btn" onClick={onClose}>Cancelar</button>
          <button
            className="btn btn-primary btn-lg"
            disabled={!isPaid}
            onClick={() => onPaid({ methods, change, cash: methods.find(m => m.type === "dinheiro")?.value || 0 })}
          >
            <I.Printer size={16} /> Finalizar e imprimir cupom
          </button>
        </div>
      </div>
    </div>
  );
}

function CupomModal({ sale, onClose }) {
  const PAY_LABELS = { dinheiro: "Dinheiro", pix: "PIX", credito: "Cartão Crédito", debito: "Cartão Débito", voucher: "Vale" };
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 420 }}>
        <div className="modal-hd">
          <I.Check size={20} style={{ color: "var(--ok)" }} />
          <h3>Venda finalizada</h3>
          <button className="btn btn-ghost btn-icon btn-sm" onClick={onClose}><I.X size={14} /></button>
        </div>
        <div className="modal-bd" style={{ background: "#f3f1ea" }}>
          <div className="print-area">
            <div className="cupom">
              <div className="center b lg">{STORE_INFO.name.toUpperCase()}</div>
              <div className="center">{STORE_INFO.razao}</div>
              <div className="center">CNPJ {STORE_INFO.cnpj}</div>
              <div className="center">{STORE_INFO.endereco} — {STORE_INFO.cidade}</div>
              <hr />
              <div className="center b">CUPOM FISCAL ELETRÔNICO — NFC-e</div>
              <div className="row"><span>{sale.nf}</span><span>{dateBR(sale.data)}</span></div>
              <div className="row"><span>PDV: {sale.pdv}</span><span>Venda: {sale.id}</span></div>
              <div>Operador: {sale.operador}</div>
              <hr />
              <table>
                <tbody>
                  {sale.items.map((it, i) => (
                    <tr key={i}>
                      <td colSpan="2">
                        <div>{(i + 1).toString().padStart(3, "0")} {it.sku}</div>
                        <div>{it.name}</div>
                      </td>
                      <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                        {it.qty} x {it.price.toFixed(2).replace(".", ",")}<br />
                        <b>{(it.qty * it.price).toFixed(2).replace(".", ",")}</b>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <hr />
              <div className="row"><span>Subtotal</span><span>R$ {sale.subtotal.toFixed(2).replace(".", ",")}</span></div>
              {sale.desc > 0 && <div className="row"><span>Desconto</span><span>- R$ {sale.desc.toFixed(2).replace(".", ",")}</span></div>}
              <div className="row b lg"><span>TOTAL</span><span>R$ {sale.total.toFixed(2).replace(".", ",")}</span></div>
              <hr />
              <div className="b">PAGAMENTOS</div>
              {sale.payment.methods.map((m, i) => (
                <div key={i} className="row">
                  <span>{PAY_LABELS[m.type]}</span>
                  <span>R$ {Number(m.value).toFixed(2).replace(".", ",")}</span>
                </div>
              ))}
              {sale.payment.change > 0 && (
                <div className="row b"><span>Troco</span><span>R$ {sale.payment.change.toFixed(2).replace(".", ",")}</span></div>
              )}
              <hr />
              <div className="center">CONSUMIDOR: {sale.cliente}</div>
              {sale.cliente_cpf && <div className="center">CPF: {sale.cliente_cpf}</div>}
              <hr />
              <div className="center">QR Code de consulta da NFC-e:</div>
              <div className="center" style={{ margin: "6px 0" }}>
                <div style={{
                  width: 90, height: 90, display: "inline-block",
                  background: `repeating-linear-gradient(0deg, #000 0 2px, transparent 2px 4px),
                               repeating-linear-gradient(90deg, #000 0 2px, transparent 2px 4px)`,
                  border: "3px solid #000",
                  position: "relative",
                }}>
                  <div style={{ position: "absolute", top: 3, left: 3, width: 14, height: 14, background: "#fff", border: "3px solid #000" }} />
                  <div style={{ position: "absolute", top: 3, right: 3, width: 14, height: 14, background: "#fff", border: "3px solid #000" }} />
                  <div style={{ position: "absolute", bottom: 3, left: 3, width: 14, height: 14, background: "#fff", border: "3px solid #000" }} />
                </div>
              </div>
              <div className="center" style={{ fontSize: 9 }}>Chave: 4126 0548 2214 5600 0109 6500 1{sale.id.replace("V", "")} 8910 2376 11</div>
              <hr />
              <div className="center b">OBRIGADO E BOA PESCARIA! 🎣</div>
              <div className="center">capivarasfishing.com.br</div>
            </div>
          </div>
        </div>
        <div className="modal-ft">
          <button className="btn" onClick={onClose}>Concluir</button>
          <button className="btn btn-primary" onClick={() => window.print()}>
            <I.Printer size={14} /> Imprimir cupom
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PDVScreen, CupomModal });
