// Emporium da Arte — PDV Checkout screen
// Tela mais importante: busca + grid + carrinho + pagamento.
// Os produtos e categorias vêm do Supabase em tempo real.

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;

function CheckoutScreen() {
  const { cart, setCart, user, cashSession } = useApp();

  // Catálogo carregado do BD (null = carregando, [] = vazio)
  const [products,   setProducts]   = useStateP(null);
  const [categories, setCategories] = useStateP([]);
  const [customers,  setCustomers]  = useStateP([]);            // pra autocomplete do cliente
  const [loadError,  setLoadError]  = useStateP(null);

  // Busca + categoria persistem em sessionStorage — voltar pra Nova Venda
  // mantém o filtro ativo (útil pra vendas sequenciais na mesma categoria).
  const [query, setQuery]           = useStickyState("pdv:checkout.query", "");
  const [activeCat, setActiveCat]   = useStickyState("pdv:checkout.activeCat", "all");
  const [paying, setPaying]         = useStateP(false);
  const [paid,   setPaid]           = useStateP(null);          // recibo após confirmar
  const [discount, setDiscount]     = useStateP("0,00");        // string monetária
  const [paymentMethod, setPaymentMethod] = useStateP("pix");
  const [received, setReceived]     = useStateP("0,00");        // string monetária
  const [installments, setInstallments] = useStateP(1);
  const [paymentFees, setPaymentFees]   = useStateP(null);      // taxas/parcelamento (BD)
  const [customer, setCustomer]         = useStateP(null);      // cliente vinculado (opcional)
  const [delivery,    setDelivery]      = useStateP(false);     // entrega ativa (só faz sentido c/ cliente)
  const [deliveryFee, setDeliveryFee]   = useStateP("0,00");    // string monetária
  const [savingError, setSavingError]   = useStateP(null);
  const [saving, setSaving]             = useStateP(false);
  const searchRef = useRefP(null);

  // Carrega produtos, categorias, clientes e taxas no mount
  const loadCatalog = async () => {
    try {
      const [prods, cats, custs, fees] = await Promise.all([
        dbListProducts("active"),
        dbListCategories(),
        dbListCustomers().then(c => c.filter(x => x.status === "ativo")).catch(() => []),
        dbGetAppSetting("payment_fees").catch(() => null),
      ]);
      setProducts(prods);
      setCategories(cats);
      setCustomers(custs);
      setPaymentFees(fees);
      setLoadError(null);
    } catch (e) {
      setLoadError(e?.message || String(e));
      setProducts([]);
    }
  };
  useEffectP(() => { loadCatalog(); }, []);
  useEffectP(() => { searchRef.current?.focus(); }, []);

  // Restaura scroll do grid quando o catálogo termina de carregar.
  const productsScrollRef = useScrollRestore("pdv:checkout.scroll", products !== null);

  // productById local (substitui o do mock — o do mock tem só os produtos hardcoded)
  const productById = (id) => (products || []).find(p => p.id === id);
  const stockState  = (p) => !p ? "ok" : (p.stock <= 0 ? "esgotado" : (p.min > 0 && p.stock <= p.min ? "baixo" : "ok"));

  // Filtra catálogo por categoria + busca (código ou nome) e ordena por
  // código crescente (01000 → 99999). Como os códigos são zero-padded com
  // 5 dígitos, comparação lexicográfica já dá ordem numérica correta.
  const filtered = useMemoP(() => {
    const list = products || [];
    const q = query.trim().toLowerCase();
    const out = list.filter(p => {
      if (activeCat !== "all" && p.cat !== activeCat) return false;
      if (!q) return true;
      return (p.name || "").toLowerCase().includes(q)
          || (p.code || "").toLowerCase().includes(q);
    });
    return out.sort((a, b) => (a.code || "").localeCompare(b.code || "", "pt-BR"));
  }, [query, activeCat, products]);

  // Contagem por categoria (live, em cima do produtos do BD)
  const catCounts = useMemoP(() => {
    const m = {}; (products || []).forEach(p => { m[p.cat] = (m[p.cat] || 0) + 1; });
    return m;
  }, [products]);

  const addToCart = (p) => {
    if ((Number(p.stock) || 0) <= 0) return;
    setCart(c => {
      const existing = c.find(i => i.pid === p.id);
      if (existing) {
        if (existing.qty >= Number(p.stock)) return c;
        return c.map(i => i.pid === p.id ? { ...i, qty: i.qty + 1 } : i);
      }
      return [...c, { pid: p.id, qty: 1 }];
    });
  };

  const updateQty = (pid, delta) => {
    setCart(c => c.map(i => {
      if (i.pid !== pid) return i;
      const next = i.qty + delta;
      if (delta > 0) {
        const p = productById(pid);
        const stock = Number(p?.stock) || 0;
        if (next > stock) return i;
      }
      return { ...i, qty: Math.max(0, next) };
    }).filter(i => i.qty > 0));
  };

  const removeItem = (pid) => setCart(c => c.filter(i => i.pid !== pid));

  // Cálculos monetários — desconto, frete e recebido são strings BRL ("12,34")
  const discountValue = parseBRL(discount);
  // O frete só conta no total quando há cliente vinculado E "entrega" está ativa.
  const deliveryActive = !!customer && delivery;
  const deliveryValue  = deliveryActive ? parseBRL(deliveryFee) : 0;
  const subtotal = cart.reduce((s, i) => {
    const p = productById(i.pid);
    return s + (Number(p?.price) || 0) * i.qty;
  }, 0);
  const total    = Math.max(0, subtotal - discountValue + deliveryValue);
  const receivedValue = parseBRL(received);
  const change   = paymentMethod === "dinheiro" ? Math.max(0, receivedValue - total) : 0;

  const itemCount = cart.reduce((n, i) => n + i.qty, 0);

  // Reset do estado de pagamento ao reabrir o modal (mantém o método anterior)
  const openPayment = () => {
    setReceived("0,00");
    setInstallments(1);
    setSavingError(null);
    setPaying(true);
  };

  // Valida e finaliza venda — grava no BD e mostra recibo
  const finalize = async () => {
    if (saving) return;
    if (!cashSession?.id) { setSavingError("Nenhum caixa aberto. Abra o caixa para vender."); return; }
    if (cart.length === 0) { setSavingError("Carrinho vazio."); return; }
    if (paymentMethod === "dinheiro" && receivedValue < total) {
      setSavingError("Valor recebido é menor que o total.");
      return;
    }

    setSaving(true);
    setSavingError(null);

    const items = cart.map(i => {
      const p = productById(i.pid);
      return {
        product_id: i.pid,
        quantity:   i.qty,
        unit_price: Number(p?.price) || 0,
      };
    });
    const payments = [{
      method:        paymentMethod,
      amount:        total,
      installments:  paymentMethod === "credito" ? Math.max(1, Number(installments) || 1) : 1,
      change_given:  paymentMethod === "dinheiro" ? change : 0,
    }];

    try {
      const result = await dbRegisterSale({
        sessionId:   cashSession.id,
        cashierId:   user?.id || null,
        customerId:  customer?.id || null,
        items, payments,
        discount:    discountValue,
        deliveryFee: deliveryValue,
      });
      setPaid({
        id:          result?.id,
        sale_number: result?.sale_number,
        total:       Number(result?.total) || total,
        items:       [...cart],
        productsSnap: cart.map(i => {
          const p = productById(i.pid);
          return p ? { id: p.id, name: p.name, code: p.code, price: p.price } : null;
        }).filter(Boolean),
        discount:    discountValue,
        deliveryFee: deliveryValue,
        pay:         paymentMethod,
        installments:paymentMethod === "credito" ? Math.max(1, Number(installments) || 1) : 1,
        change,
        customer:    customer ? { name: customer.name, taxId: customer.taxId } : null,
        time:        new Date().toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" }),
        date:        new Date().toLocaleDateString("pt-BR", { day: "2-digit", month: "2-digit", year: "numeric" }),
        cashierName: user?.name || "",
      });
      setCart([]);
      setDiscount("0,00");
      setReceived("0,00");
      setCustomer(null);
      setDelivery(false);
      setDeliveryFee("0,00");
      setPaying(false);
    } catch (e) {
      setSavingError(e?.message || "Falha ao registrar venda.");
    } finally {
      setSaving(false);
    }
  };

  const onPostSale = async () => {
    setPaid(null);
    await loadCatalog(); // recarrega estoque após venda
  };

  if (paid) return <Receipt sale={paid} onClose={onPostSale}/>;

  return (
    <div className="pdv-grid">
      {/* LEFT — catálogo */}
      <div className="pdv-catalog">
        <div className="pdv-search">
          <div className="input-icon" style={{ flex: 1 }}>
            <Icon name="barcode" size={18}/>
            <input
              ref={searchRef}
              className="input input-lg"
              style={{ width: "100%" }}
              placeholder="Bipe o código ou digite o nome do produto…"
              value={query} onChange={e => setQuery(e.target.value)}
            />
          </div>
        </div>

        <div className="pdv-cats">
          <button className={"pdv-cat " + (activeCat === "all" ? "active" : "")}
                  onClick={() => setActiveCat("all")}>
            <span className="pdv-cat-dot" style={{ background: "var(--ink-300)" }}/>
            Todos <span className="pdv-cat-count">{(products || []).length}</span>
          </button>
          {categories.map(c => (
            <button key={c.id} className={"pdv-cat " + (activeCat === c.id ? "active" : "")}
                    onClick={() => setActiveCat(c.id)}>
              <span className="pdv-cat-dot" style={{ background: c.color || "#F94C99" }}/>
              {c.name} <span className="pdv-cat-count">{catCounts[c.id] || 0}</span>
            </button>
          ))}
        </div>

        <div ref={productsScrollRef} className="pdv-products">
          {products == null ? (
            <div className="empty-state" style={{ gridColumn: "1 / -1" }}>
              <Icon name="package" size={32}/>
              <div>Carregando catálogo...</div>
            </div>
          ) : loadError ? (
            <div className="empty-state" style={{ gridColumn: "1 / -1", color: "var(--pink-600)" }}>
              <Icon name="alert" size={32}/>
              <div style={{ fontWeight: 600 }}>Erro ao carregar produtos</div>
              <div style={{ fontSize: 12, color: "var(--text-mute)", marginTop: 6 }}>{loadError}</div>
            </div>
          ) : filtered.length === 0 ? (
            <div className="empty-state" style={{ gridColumn: "1 / -1" }}>
              <Icon name="search" size={32}/>
              <div>{(products || []).length === 0 ? "Nenhum produto cadastrado." : <>Nada encontrado para "<b>{query}</b>"</>}</div>
              <div style={{ fontSize: 13, color: "var(--text-mute)", marginTop: 6 }}>Tente outro termo ou cadastre o produto</div>
            </div>
          ) : (
            filtered.map(p => {
              const state = stockState(p);
              const isOut = state === "esgotado";
              return (
                <button key={p.id} className={"pdv-pcard " + (isOut ? "disabled" : "")}
                        onClick={() => !isOut && addToCart(p)} disabled={isOut}>
                  <div className="pdv-pcard-info">
                    <div className="pdv-pcard-code">{p.code}</div>
                    <div className="pdv-pcard-name">{p.name}</div>
                  </div>
                  <div className="pdv-pcard-bottom">
                    <div className="pdv-pcard-price">{BRL(p.price)}</div>
                    <div className="pdv-pcard-stock">
                      {isOut ? (
                        <span className="badge badge-bad" style={{ padding: "2px 8px", fontSize: 10 }}>esgotado</span>
                      ) : state === "baixo" ? (
                        <span className="badge badge-warn" style={{ padding: "2px 8px", fontSize: 10 }}>{p.stock} · baixo</span>
                      ) : (
                        <span style={{ fontSize: 11, color: "var(--text-mute)" }}>{p.stock} un</span>
                      )}
                    </div>
                  </div>
                </button>
              );
            })
          )}
        </div>
      </div>

      {/* RIGHT — carrinho */}
      <div className="pdv-cart">
        <div className="pdv-cart-head">
          <div>
            <div className="pdv-cart-title">Carrinho</div>
            <div className="pdv-cart-sub">{itemCount} {itemCount === 1 ? "item" : "itens"}</div>
          </div>
          {cart.length > 0 && (
            <button className="btn-link" onClick={() => setCart([])}>
              <Icon name="trash" size={14}/> Limpar
            </button>
          )}
        </div>

        <div className="pdv-cart-list">
          {cart.length === 0 ? (
            <div className="pdv-cart-empty">
              <div className="pdv-cart-empty-icon"><Icon name="cart" size={42} stroke={1.4}/></div>
              <div style={{ fontWeight: 600 }}>Carrinho vazio</div>
              <div style={{ fontSize: 13, color: "var(--text-mute)", marginTop: 6,
                            maxWidth: 240, marginLeft: "auto", marginRight: "auto",
                            textAlign: "center" }}>
                Bipe um código ou clique em um produto à esquerda para adicionar.
              </div>
            </div>
          ) : (
            cart.map(i => {
              const p = productById(i.pid);
              if (!p) return null;
              return (
                <div key={i.pid} className="pdv-cart-item">
                  <div className="pdv-cart-item-code">{p.code}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="pdv-cart-item-name" title={p.name}>{p.name}</div>
                    <div className="pdv-cart-item-meta">{BRL(p.price)} cada</div>
                  </div>
                  <div className="pdv-qty">
                    <button onClick={() => updateQty(p.id, -1)}><Icon name="minus" size={12}/></button>
                    <span>{i.qty}</span>
                    <button onClick={() => updateQty(p.id, 1)}><Icon name="plus" size={12}/></button>
                  </div>
                  <div style={{ width: 80, textAlign: "right", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>
                    {BRL(p.price * i.qty)}
                  </div>
                  <button className="pdv-cart-x" onClick={() => removeItem(p.id)}>
                    <Icon name="close" size={14}/>
                  </button>
                </div>
              );
            })
          )}
        </div>

        <div className="pdv-cart-foot">
          {/* Cliente (opcional) — autocomplete por nome/documento; quando
              selecionado, mostra um chip com X pra remover. Quando o cliente
              é desvinculado, a entrega é resetada automaticamente. */}
          <CustomerPicker
            customers={customers}
            value={customer}
            onChange={(c) => {
              setCustomer(c);
              if (!c) { setDelivery(false); setDeliveryFee("0,00"); }
            }}
          />

          {/* Entrega — só aparece quando há cliente vinculado.
              Toggle ativa o campo de valor; o valor entra no total como frete. */}
          {customer && (
            <div style={{
              display: "flex", flexDirection: "column", gap: 8,
              padding: "10px 12px", marginBottom: 12,
              background: "var(--bg-soft)", border: "1px solid var(--border)",
              borderRadius: "var(--r-md)",
            }}>
              <label style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
                <input type="checkbox" checked={delivery}
                       onChange={e => setDelivery(e.target.checked)}/>
                <Icon name="truck" size={14}/>
                <span style={{ fontSize: 13, fontWeight: 600 }}>Entrega</span>
                <span style={{ fontSize: 11, color: "var(--text-mute)", fontWeight: 400 }}>
                  · soma como frete no total
                </span>
              </label>
              {delivery && (
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <span style={{ fontSize: 12, color: "var(--text-soft)", fontWeight: 600, flexShrink: 0 }}>
                    Valor do frete
                  </span>
                  <div className="input-currency-wrap" style={{ flex: 1, maxWidth: 160 }}>
                    <span className="input-currency-prefix">R$</span>
                    <input className="input input-currency input-sm tabular"
                           inputMode="numeric"
                           value={deliveryFee}
                           onChange={e => setDeliveryFee(maskBRL(e.target.value))}
                           style={{ textAlign: "right" }}/>
                  </div>
                </div>
              )}
            </div>
          )}

          <div className="pdv-totals">
            <div className="pdv-total-row"><span>Subtotal</span><span className="tabular">{BRL(subtotal)}</span></div>
            <div className="pdv-total-row">
              <span>Desconto</span>
              <div className="input-currency-wrap" style={{ width: 130 }}>
                <span className="input-currency-prefix">R$</span>
                <input className="input input-currency input-sm tabular"
                       inputMode="numeric"
                       value={discount}
                       onChange={e => setDiscount(maskBRL(e.target.value))}
                       onFocus={e => {
                         const el = e.target;
                         requestAnimationFrame(() => {
                           const len = el.value.length;
                           el.setSelectionRange(len, len);
                         });
                       }}
                       onMouseUp={e => {
                         const el = e.target;
                         const len = el.value.length;
                         el.setSelectionRange(len, len);
                       }}
                       style={{ textAlign: "right" }}/>
              </div>
            </div>
            {deliveryActive && (
              <div className="pdv-total-row">
                <span>Frete</span>
                <span className="tabular" style={{ color: "var(--text-soft)" }}>
                  + {BRL(deliveryValue)}
                </span>
              </div>
            )}
            <div className="pdv-total-row pdv-total-grand">
              <span>Total</span><span className="tabular">{BRL(total)}</span>
            </div>
          </div>

          <button className="btn btn-primary btn-xl"
                  style={{ justifyContent: "center" }}
                  disabled={cart.length === 0}
                  onClick={openPayment}>
            <Icon name="check" size={18}/> Finalizar — {BRL(total)}
          </button>
        </div>
      </div>

      {paying && (
        <PaymentModal
          total={total}
          method={paymentMethod} setMethod={setPaymentMethod}
          received={received} setReceived={setReceived}
          installments={installments} setInstallments={setInstallments}
          paymentFees={paymentFees}
          change={change}
          saving={saving}
          error={savingError}
          onClose={() => !saving && setPaying(false)}
          onConfirm={finalize}
        />
      )}
    </div>
  );
}

/* ─── Customer picker (vincular cliente à venda — opcional) ──────
   Quando vazio: campo de busca com autocomplete (até 6 sugestões) por
   nome ou documento. Quando selecionado: chip com nome + X pra remover.
   ──────────────────────────────────────────────────────────────── */
function CustomerPicker({ customers, value, onChange }) {
  const [q, setQ]         = useStateP("");
  const [open, setOpen]   = useStateP(false);
  const wrapRef           = useRefP(null);

  // Fecha o dropdown ao clicar fora
  useEffectP(() => {
    if (!open) return;
    const onDoc = (e) => { if (!wrapRef.current?.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  if (value) {
    return (
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        padding: "8px 12px", marginBottom: 12,
        background: "var(--pink-50)", border: "1px solid var(--pink-200, #F5C6DA)",
        borderRadius: "var(--r-md)",
      }}>
        <Icon name="user" size={14}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: ".05em" }}>
            Cliente
          </div>
          <div style={{ fontWeight: 600, fontSize: 13 }}>
            {value.name}
            {value.taxId && <span style={{ color: "var(--text-mute)", fontWeight: 400, marginLeft: 8 }}>{value.taxId}</span>}
          </div>
        </div>
        <button className="btn-icon-mini" title="Remover cliente"
                onClick={() => onChange(null)}>
          <Icon name="close" size={14}/>
        </button>
      </div>
    );
  }

  const t        = q.trim().toLowerCase();
  const tDigits  = t.replace(/\D/g, "");                  // p/ casar com telefone/CPF mascarados
  const matches  = !t ? [] : (customers || []).filter(c => {
    const blob = [c.name, c.taxId, c.phone, c.email].filter(Boolean).join(" ").toLowerCase();
    if (blob.includes(t)) return true;
    // se o termo é só dígitos, casa contra os dígitos do telefone/CPF
    if (tDigits.length >= 2) {
      const phoneDigits = String(c.phone || "").replace(/\D/g, "");
      const taxIdDigits = String(c.taxId || "").replace(/\D/g, "");
      if (phoneDigits.includes(tDigits) || taxIdDigits.includes(tDigits)) return true;
    }
    return false;
  }).slice(0, 6);

  return (
    <div ref={wrapRef} style={{ position: "relative", marginBottom: 12 }}>
      <div className="input-icon" style={{ width: "100%" }}>
        <Icon name="user" size={14}/>
        <input className="input"
               placeholder="Vincular cliente (opcional) — nome, CPF/CNPJ ou celular"
               value={q}
               onChange={e => { setQ(e.target.value); setOpen(true); }}
               onFocus={() => setOpen(true)}/>
      </div>
      {open && t && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0,
          background: "white", border: "1px solid var(--border)",
          borderRadius: "var(--r-md)", boxShadow: "var(--sh-md)",
          zIndex: 50, maxHeight: 240, overflowY: "auto",
        }}>
          {matches.length === 0 ? (
            <div style={{ padding: 12, color: "var(--text-mute)", fontSize: 13 }}>
              Nenhum cliente encontrado. Cadastre na tela <b>Clientes</b>.
            </div>
          ) : matches.map(c => (
            <button key={c.id}
                    onClick={() => { onChange(c); setQ(""); setOpen(false); }}
                    style={{
                      width: "100%", textAlign: "left", background: "transparent",
                      border: "none", padding: "10px 12px", cursor: "pointer",
                      borderBottom: "1px solid var(--border)",
                    }}>
              <div style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</div>
              <div style={{ fontSize: 11, color: "var(--text-mute)", fontFamily: "var(--font-mono)" }}>
                {[c.taxId, c.phone].filter(Boolean).join(" · ") || "—"}
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── Payment modal ─────────────────────────────────────────────── */
function PaymentModal({ total, method, setMethod, received, setReceived,
                        installments, setInstallments, paymentFees, change,
                        saving, error, onClose, onConfirm }) {
  const methods = [
    { id: "pix",      label: "Pix",      icon: "pix",   color: "var(--pink-500)" },
    { id: "credito",  label: "Crédito",  icon: "card",  color: "var(--info-500)" },
    { id: "debito",   label: "Débito",   icon: "card",  color: "var(--ok-500)"   },
    { id: "dinheiro", label: "Dinheiro", icon: "money", color: "var(--warn-500)" },
  ];

  // Parcelas vindas das configurações (default: até 6x)
  const credito = paymentFees?.credito || { max_installments: 6, installments: [] };
  const maxInst = Math.max(1, Number(credito.max_installments) || 6);
  const feeFor = (n) => {
    const list = Array.isArray(credito.installments) ? credito.installments : [];
    const m = list.find(x => Number(x.n) === n);
    return Number(m?.fee_pct) || 0;
  };

  return (
    /* O modal NÃO fecha ao clicar no backdrop — só pelo X ou cancelar.
       Isso evita perder os dados de pagamento por acidente. */
    <div className="modal-backdrop">
      <div className="modal modal-pay" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700 }}>Pagamento</h2>
          <button className="btn-icon-mini" onClick={onClose} disabled={saving}><Icon name="close" size={18}/></button>
        </div>

        <div className="pay-amount">
          <div style={{ fontSize: 13, color: "var(--text-mute)", textTransform: "uppercase", letterSpacing: ".05em" }}>A receber</div>
          <div style={{ fontSize: 56, fontWeight: 700, color: "var(--pink-500)", letterSpacing: "-0.025em" }}>{BRL(total)}</div>
        </div>

        <div className="pay-methods">
          {methods.map(m => (
            <button key={m.id} className={"pay-method " + (method === m.id ? "active" : "")}
                    onClick={() => setMethod(m.id)} disabled={saving}
                    style={method === m.id ? { borderColor: m.color, color: m.color } : {}}>
              <Icon name={m.icon} size={26} stroke={1.5}/>
              {m.label}
            </button>
          ))}
        </div>

        {/* Pix — sem QR/copia-e-cola; o lojista confirma manualmente que recebeu */}
        {method === "pix" && (
          <div className="pay-detail">
            <div className="pay-pix-msg">
              <Icon name="pix" size={28}/>
              <div>
                <b>Pagamento via Pix</b>
                <div style={{ color: "var(--text-mute)", fontSize: 13, marginTop: 4 }}>
                  Confirme o recebimento e clique em <b>Confirmar pagamento</b> abaixo.
                </div>
              </div>
            </div>
          </div>
        )}

        {(method === "credito" || method === "debito") && (
          <div className="pay-detail">
            <div className="pay-tef">
              <Icon name="card" size={48} stroke={1.4}/>
              <div>
                <b>Insira ou aproxime o cartão na maquininha</b>
                <div style={{ color: "var(--text-mute)", fontSize: 13, marginTop: 4 }}>
                  {method === "credito"
                    ? `Crédito · até ${maxInst}x`
                    : `Débito · à vista${paymentFees?.debito?.fee_pct ? ` · taxa ${Number(paymentFees.debito.fee_pct).toFixed(2)}%` : ""}`}
                </div>
              </div>
            </div>
            {method === "credito" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ fontSize: 12, color: "var(--text-mute)", fontWeight: 600 }}>
                  Parcelamento
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {Array.from({ length: maxInst }).map((_, idx) => {
                    const x   = idx + 1;
                    const fee = feeFor(x);
                    const active = installments === x;
                    return (
                      <button key={x}
                              className={"chip-btn " + (active ? "active" : "")}
                              onClick={() => setInstallments(x)} disabled={saving}>
                        <div style={{ fontWeight: 700 }}>{x}x · {BRL(total / x)}</div>
                        {fee > 0 && (
                          <div className="chip-sub">taxa {fee.toFixed(2)}%</div>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        )}

        {method === "dinheiro" && (
          <div className="pay-detail">
            <div className="field">
              <label className="label">Valor recebido</label>
              <div className="input-currency-wrap">
                <span className="input-currency-prefix">R$</span>
                <input className="input input-currency input-lg tabular"
                       inputMode="numeric"
                       value={received}
                       onChange={e => setReceived(maskBRL(e.target.value))}
                       disabled={saving}/>
              </div>
            </div>
            <div className="pay-change">
              <span>Troco</span>
              <b style={{ fontSize: 22, color: "var(--pink-600)" }}>{BRL(change)}</b>
            </div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {[total, Math.ceil(total / 10) * 10, Math.ceil(total / 50) * 50, 100, 200]
                .filter(v => v > 0)
                .filter((v, i, a) => a.indexOf(v) === i)
                .map(v => (
                  <button key={v} className="chip-btn" onClick={() => setReceived(maskBRL(String(Math.round(v * 100))))} disabled={saving}>
                    {BRL(v)}
                  </button>
                ))}
            </div>
          </div>
        )}

        {error && (
          <div style={{ fontSize: 13, color: "var(--pink-600)", fontWeight: 600, marginTop: 12, textAlign: "center" }}>
            {error}
          </div>
        )}

        <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
          <button className="btn btn-secondary" onClick={onClose} disabled={saving}>Cancelar</button>
          <button className="btn btn-primary btn-lg pay-confirm-btn"
                  style={{ flex: 1, justifyContent: "center" }}
                  onClick={onConfirm} disabled={saving}>
            <Icon name="check" size={18}/> {saving ? "Registrando..." : "Confirmar pagamento"}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ─── Receipt / venda concluída ─────────────────────────────────── */
function Receipt({ sale, onClose }) {
  const items = sale.productsSnap || [];
  return (
    <div className="receipt-wrap">
      <div className="receipt">
        <div className="receipt-success">
          <div className="receipt-check"><Icon name="check" size={44} stroke={3}/></div>
          <div className="receipt-display-name receipt-glow">obrigada pela visita ✿</div>
          <div className="receipt-success-meta">
            Venda <b>#{sale.sale_number || "—"}</b>
            <span className="receipt-success-dot">·</span>
            {sale.time}
            <span className="receipt-success-dot">·</span>
            {PAYMENT_LABELS[sale.pay] || sale.pay}
            {sale.pay === "credito" && sale.installments > 1 ? ` ${sale.installments}x` : ""}
          </div>
          {sale.customer && (
            <div className="receipt-success-meta" style={{ marginTop: 4 }}>
              Cliente: <b>{sale.customer.name}</b>
              {sale.customer.taxId && <> <span className="receipt-success-dot">·</span> {sale.customer.taxId}</>}
            </div>
          )}
        </div>

        <div className="receipt-paper receipt-print-area">
          <img className="receipt-brand-img" src="uploads/logo.png" alt="Emporium da Arte" />
          <div className="receipt-meta">CNPJ 12.345.678/0001-99 · Cupom não fiscal</div>

          {/* Cabeçalho com nº da venda, data/hora e operador. Layout em
              grid de 2 colunas pra ficar compacto no impresso. */}
          <div className="receipt-header-block">
            <div>
              <div className="receipt-meta-label">Venda</div>
              <div className="receipt-meta-value tabular">#{sale.sale_number || "—"}</div>
            </div>
            <div style={{ textAlign: "right" }}>
              <div className="receipt-meta-label">Data</div>
              <div className="receipt-meta-value tabular">{sale.date || "—"} · {sale.time || "—"}</div>
            </div>
            {sale.cashierName && (
              <div style={{ gridColumn: "1 / -1" }}>
                <div className="receipt-meta-label">Operador(a)</div>
                <div className="receipt-meta-value">{sale.cashierName}</div>
              </div>
            )}
            {sale.customer && (
              <div style={{ gridColumn: "1 / -1" }}>
                <div className="receipt-meta-label">Cliente</div>
                <div className="receipt-meta-value">
                  {sale.customer.name}{sale.customer.taxId ? ` · ${sale.customer.taxId}` : ""}
                </div>
              </div>
            )}
          </div>

          <hr/>
          {sale.items.map((it, idx) => {
            const p = items.find(x => x.id === it.pid);
            if (!p) return null;
            return (
              <div key={idx} className="receipt-row">
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 600 }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: "var(--text-mute)" }}>
                    <span style={{ fontFamily: "var(--font-mono)" }}>{p.code}</span> · {it.qty} × {BRL(p.price)}
                  </div>
                </div>
                <div style={{ fontWeight: 600 }}>{BRL(p.price * it.qty)}</div>
              </div>
            );
          })}
          <hr/>
          {sale.discount > 0 && (
            <div className="receipt-row"><span>Desconto</span><span>− {BRL(sale.discount)}</span></div>
          )}
          {sale.deliveryFee > 0 && (
            <div className="receipt-row">
              <span>Frete</span>
              <span style={{ color: "var(--text-soft)" }}>+ {BRL(sale.deliveryFee)}</span>
            </div>
          )}
          <div className="receipt-row receipt-total"><span>Total</span><b>{BRL(sale.total)}</b></div>
          <div className="receipt-row" style={{ fontSize: 12, color: "var(--text-soft)" }}>
            <span>Pagamento</span>
            <span>
              {PAYMENT_LABELS[sale.pay] || sale.pay}
              {sale.pay === "credito" && sale.installments > 1 ? ` · ${sale.installments}x` : ""}
            </span>
          </div>
          {sale.change > 0 && (
            <div className="receipt-row" style={{ color: "var(--text-soft)" }}>
              <span>Troco</span><b>{BRL(sale.change)}</b>
            </div>
          )}

          <div className="receipt-footer">
            Obrigada pela visita! ✿<br/>
            <span style={{ fontSize: 10 }}>Documento sem valor fiscal</span>
          </div>
        </div>

        <div className="receipt-actions">
          <button className="btn btn-secondary" onClick={() => window.print()}>
            <Icon name="print" size={16}/> Imprimir
          </button>
          <button className="btn btn-primary btn-lg receipt-new-btn"
                  style={{ flex: 1, justifyContent: "center" }}
                  onClick={onClose}>
            Nova venda <Icon name="arrowR" size={16}/>
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CheckoutScreen });
