// mb-cart.jsx — Product sheet, Cart, Checkout, Success, Review

function Stepper({ qty, onDec, onInc, big }) {
  const s = big ? 44 : 34;
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: big ? 16 : 10, background: "var(--bg)", borderRadius: 999, padding: big ? 5 : 4 }}>
      <button onClick={onDec} style={{ width: s, height: s, borderRadius: 999, border: "none", background: "var(--surface)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: qty <= 0 ? "var(--line)" : "var(--accent)", boxShadow: "0 1px 4px rgba(16,18,45,.08)" }}>
        <Icon name={qty <= 1 && big ? "trash" : "minus"} size={big ? 19 : 16} sw={2.4} color={qty <= 0 ? "var(--line)" : "var(--accent)"} />
      </button>
      <span style={{ font: `800 ${big ? 18 : 15}px var(--ui)`, color: "var(--text)", minWidth: 18, textAlign: "center" }}>{qty}</span>
      <button onClick={onInc} style={{ width: s, height: s, borderRadius: 999, border: "none", background: "var(--accent)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
        <Icon name="plus" size={big ? 19 : 16} sw={2.4} color="var(--accent-ink)" />
      </button>
    </div>
  );
}

function ProductSheet({ item, totalCb, startQty, onConfirm }) {
  const [qty, setQty] = React.useState(startQty || 1);
  const [note, setNote] = React.useState("");
  if (!item) return null;
  return (
    <div>
      {item.img && item.img.startsWith("http")
        ? <img src={item.img} alt={item.name} style={{ width: "100%", height: 170, objectFit: "cover", borderRadius: 16, display: "block" }} />
        : <Ph label={item.img || item.name} h={170} r={16} />}
      <h2 style={{ margin: "16px 0 0", font: "800 21px var(--ui)", color: "var(--text)" }}>{item.name}</h2>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 8 }}>
        <span style={{ font: "800 18px var(--ui)", color: "var(--text)" }}>{money(item.price)}</span>
        <Cashback pct={totalCb} />
      </div>
      <p style={{ font: "500 14px var(--ui)", color: "var(--muted)", lineHeight: 1.5, marginTop: 12 }}>{item.desc}</p>

      <div style={{ marginTop: 14 }}>
        <div style={{ font: "700 13.5px var(--ui)", color: "var(--text)", marginBottom: 7 }}>Alguma observação?</div>
        <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Ex: sem cebola, ponto da carne…" rows={2}
          style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 12, padding: "11px 13px", font: "500 14px var(--ui)", color: "var(--text)", resize: "none", outline: "none", background: "var(--bg)" }} />
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 20 }}>
        <Stepper qty={qty} onDec={() => setQty(q => Math.max(1, q - 1))} onInc={() => setQty(q => q + 1)} big />
        <Btn full onClick={() => onConfirm(qty, note)} style={{ flex: 1 }}>
          Adicionar · {money(item.price * qty)}
        </Btn>
      </div>
    </div>
  );
}

// ── Cart ─────────────────────────────────────────────────────
function CartScreen({ cart, partner, mode, setMode, onInc, onDec, onCheckout, onBack, onAddMore }) {
  const p = partner;
  const entries = Object.values(cart.items);
  const subtotal = entries.reduce((s, e) => s + e.item.price * e.qty, 0);
  const fee = mode === "delivery" ? p.fee : 0;
  const totalCb = p.cashback + p.turbo;
  const cbBase = subtotal * p.cashback / 100;
  const cbTurbo = subtotal * p.turbo / 100;

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <TopBar title="Sua sacola" onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "8px 0 20px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 16px 14px" }}>
          <div style={{ width: 38, height: 38, borderRadius: 11, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={segIcon(p.seg)} size={20} color="var(--accent)" />
          </div>
          <div><div style={{ font: "700 15px var(--ui)", color: "var(--text)" }}>{p.name}</div><div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>{p.area}</div></div>
        </div>

        {/* items */}
        <div style={{ background: "var(--surface)", margin: "0 12px", borderRadius: 18, overflow: "hidden" }}>
          {entries.map((e, i) => (
            <div key={e.item.id} style={{ display: "flex", gap: 12, padding: 14, borderTop: i ? "1px solid var(--line)" : "none" }}>
              {e.item.img && e.item.img.startsWith("http")
                ? <img src={e.item.img} alt={e.item.name} style={{ width: 58, height: 58, objectFit: "cover", borderRadius: 11, flexShrink: 0 }} />
                : <Ph label={e.item.img || e.item.name} h={58} style={{ width: 58, flexShrink: 0 }} r={11} />}
              <div style={{ flex: 1 }}>
                <div style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>{e.item.name}</div>
                {e.note && <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{e.note}</div>}
                <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginTop: 6 }}>{money(e.item.price * e.qty)}</div>
              </div>
              <div style={{ alignSelf: "flex-end" }}><Stepper qty={e.qty} onDec={() => onDec(e.item.id)} onInc={() => onInc(e.item.id)} /></div>
            </div>
          ))}
          <button onClick={onAddMore} style={{ width: "100%", padding: "13px", border: "none", borderTop: "1px solid var(--line)", background: "none", cursor: "pointer", font: "700 13.5px var(--ui)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
            <Icon name="plus" size={16} sw={2.4} color="var(--accent)" />Adicionar mais itens
          </button>
        </div>

        {/* mode */}
        <div style={{ display: "flex", gap: 8, background: "var(--surface)", margin: "12px 12px 0", padding: 5, borderRadius: 14 }}>
          {[["delivery", "Entrega", "bike", p.delivery], ["pickup", "Retirada", "store", p.pickup]].map(([id, lbl, ic, ok]) => (
            <button key={id} disabled={!ok} onClick={() => setMode(id)} style={{ flex: 1, height: 44, borderRadius: 11, border: "none", cursor: ok ? "pointer" : "not-allowed", opacity: ok ? 1 : .4, background: mode === id ? "var(--brand)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", gap: 6, font: "700 13.5px var(--ui)", color: mode === id ? "#fff" : "var(--text)" }}>
              <Icon name={ic} size={17} sw={2} color={mode === id ? "#fff" : "var(--text)"} />{lbl}
            </button>
          ))}
        </div>

        {/* summary */}
        <div style={{ background: "var(--surface)", margin: "12px 12px 0", borderRadius: 18, padding: "14px 16px" }}>
          <Row label="Subtotal" value={money(subtotal)} />
          <Row label={mode === "delivery" ? "Taxa de entrega" : "Retirada na loja"} value={fee === 0 ? "Grátis" : money(fee)} green={fee === 0} />
          <div style={{ height: 1, background: "var(--line)", margin: "10px 0" }} />
          <Row label="Total" value={money(subtotal + fee)} bold />
        </div>

        {/* cashback estimate */}
        <div style={{ margin: "12px 12px 0", borderRadius: 18, padding: "14px 16px", background: "var(--cb-bg)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, font: "800 14px var(--ui)", color: "var(--cb-ink)" }}>
            <Icon name="coin" size={18} color="var(--cb)" sw={1.8} />Você recebe de volta
          </div>
          <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 4 }}>
            <Row small label="Cashback" value={money(cbBase)} />
            {cbTurbo > 0 && <Row small label={<span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="bolt" size={13} color="var(--cb)" fill="var(--cb)" sw={1.5} />Cashback Turbo</span>} value={money(cbTurbo)} />}
            <div style={{ height: 1, background: "color-mix(in srgb,var(--cb) 22%,transparent)", margin: "5px 0" }} />
            <Row label={<b style={{ color: "var(--cb-ink)" }}>Total em BemCash ({totalCb}%)</b>} value={<b style={{ color: "var(--cb)" }}>{money(cbBase + cbTurbo)}</b>} />
          </div>
        </div>
      </div>

      <BottomBar>
        <Btn full onClick={onCheckout}>
          <span style={{ display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between" }}>
            <span>Continuar</span><span>{money(subtotal + fee)}</span>
          </span>
        </Btn>
      </BottomBar>
    </div>
  );
}

function Row({ label, value, bold, green, small }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: small ? "2px 0" : "3px 0" }}>
      <span style={{ font: `${bold ? 800 : 600} ${bold ? 16 : small ? 12.5 : 13.5}px var(--ui)`, color: bold ? "var(--text)" : "var(--muted)" }}>{label}</span>
      <span style={{ font: `${bold ? 800 : 700} ${bold ? 16 : small ? 12.5 : 13.5}px var(--ui)`, color: green ? "var(--cb)" : "var(--text)" }}>{value}</span>
    </div>
  );
}

function BottomBar({ children }) {
  return <div style={{ padding: "12px 14px 26px", background: "var(--surface)", borderTop: "1px solid var(--line)" }}>{children}</div>;
}

function SumLine({ ic, label, value, last }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 0", borderBottom: last ? "none" : "1px solid var(--line)" }}>
      <Icon name={ic} size={18} color="var(--accent)" sw={1.9} />
      <span style={{ flex: 1, font: "600 13px var(--ui)", color: "var(--muted)" }}>{label}</span>
      <span style={{ font: "700 13.5px var(--ui)", color: "var(--text)", textAlign: "right", maxWidth: 200 }}>{value}</span>
    </div>
  );
}

// ── CEP lookup via ViaCEP ────────────────────────────────────
async function lookupCep(cep) {
  const digits = cep.replace(/\D/g, "");
  if (digits.length !== 8) return null;
  try {
    const r = await fetch(`https://viacep.com.br/ws/${digits}/json/`);
    const d = await r.json();
    if (d.erro) return null;
    return { street: d.logradouro || "", neighborhood: d.bairro || "", city: d.localidade || "", uf: d.uf || "" };
  } catch (_) { return null; }
}

// ── Address form (shared) ─────────────────────────────────────
function AddressForm({ form, setForm, onSave, onCancel, saving }) {
  const [cepLoading, setCepLoading] = React.useState(false);
  const [cepError, setCepError] = React.useState("");
  const set = k => v => setForm(f => ({ ...f, [k]: v }));

  const handleCep = async (v) => {
    const digits = v.replace(/\D/g, "");
    const formatted = digits.length > 5 ? digits.slice(0,5) + "-" + digits.slice(5,8) : digits;
    set("cep")(formatted);
    if (digits.length === 8) {
      setCepLoading(true); setCepError("");
      const data = await lookupCep(digits);
      setCepLoading(false);
      if (data) {
        setForm(f => ({ ...f, cep: formatted, street: data.street, neighborhood: data.neighborhood, city: data.city, uf: data.uf }));
      } else {
        setCepError("CEP não encontrado. Preencha manualmente.");
      }
    }
  };

  const fields = [
    { k: "label", lb: "Identificação", ph: "Casa, Trabalho, Entrega…" },
    { k: "cep",   lb: "CEP *",         ph: "49000-000", handler: handleCep, extra: cepLoading ? "Buscando…" : cepError },
    { k: "street", lb: "Rua / Avenida *", ph: "Av. Santos Dumont" },
    { k: "number", lb: "Número *", ph: "1200" },
    { k: "complement", lb: "Complemento", ph: "Apto 12, Bloco B…" },
    { k: "neighborhood", lb: "Bairro *", ph: "Atalaia" },
    { k: "reference", lb: "Ponto de referência", ph: "Próximo ao Shopping, em frente à padaria…" },
    { k: "city", lb: "Cidade", ph: "Aracaju" },
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {fields.map(({ k, lb, ph, handler, extra }) => (
        <div key={k}>
          <div style={{ font: "700 12px var(--ui)", color: "var(--text)", marginBottom: 4 }}>{lb}</div>
          <input value={form[k] || ""} placeholder={ph}
            onChange={e => (handler || set(k))(e.target.value)}
            style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 11, padding: "12px 13px", font: "500 14px var(--ui)", color: "var(--text)", background: "var(--bg)", outline: "none" }} />
          {extra && <div style={{ font: "500 11px var(--ui)", color: extra.startsWith("Buscando") ? "var(--muted)" : "#D4493A", marginTop: 3 }}>{extra}</div>}
        </div>
      ))}
      <div style={{ display: "flex", gap: 8, marginTop: 4 }}>
        {onCancel && <button onClick={onCancel} style={{ flex: 1, height: 46, borderRadius: 13, border: "1.5px solid var(--line)", background: "var(--surface)", cursor: "pointer", font: "700 14px var(--ui)", color: "var(--muted)" }}>Voltar</button>}
        <button onClick={onSave} disabled={saving || !form.street || !form.number}
          style={{ flex: 2, height: 46, borderRadius: 13, border: "none", background: "var(--accent)", cursor: "pointer", font: "700 14px var(--ui)", color: "#fff", opacity: saving ? .7 : 1 }}>
          {saving ? "Salvando…" : "Salvar endereço"}
        </button>
      </div>
    </div>
  );
}

// ── Address picker / cadastro inline ─────────────────────────
function AddressPickerSheet({ addresses, selAddr, onSelect, onClose, onAdded }) {
  const [adding, setAdding] = React.useState(addresses.length === 0);
  const [form, setForm] = React.useState({ label: "", cep: "", street: "", number: "", complement: "", neighborhood: "", reference: "", city: "Aracaju", uf: "SE" });
  const [saving, setSaving] = React.useState(false);

  const saveAddr = async () => {
    if (!form.street || !form.number || !form.neighborhood) return;
    setSaving(true);
    try {
      const d = await API.me.addAddress({
        label: form.label || "Casa",
        cep: form.cep,
        street: form.street,
        number: form.number,
        complement: form.complement || undefined,
        neighborhood: form.neighborhood,
        reference: form.reference || undefined,
        city: form.city,
        uf: form.uf,
        is_default: addresses.length === 0,
      });
      onAdded(d.address || { ...form, id: Date.now(), is_default: false });
    } catch (_) {
      onAdded({ ...form, id: Date.now(), is_default: false });
    } finally { setSaving(false); }
  };

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 1200, background: "rgba(0,0,0,.4)", display: "flex", flexDirection: "column", justifyContent: "flex-end" }}
         onClick={onClose}>
      <div style={{ background: "var(--bg)", borderRadius: "20px 20px 0 0", padding: 20, maxHeight: "85vh", overflowY: "auto" }}
           onClick={e => e.stopPropagation()}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
          <span style={{ font: "800 16px var(--ui)", color: "var(--text)" }}>
            {adding ? "Novo endereço" : "Escolha o endereço"}
          </span>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)" }}>✕</button>
        </div>

        {!adding && addresses.map(a => (
          <button key={a.id} onClick={() => onSelect(a)}
            style={{ width: "100%", textAlign: "left", border: selAddr?.id === a.id ? "1.5px solid var(--accent)" : "1.5px solid var(--line)", borderRadius: 13, padding: "12px 14px", marginBottom: 8, background: selAddr?.id === a.id ? "var(--accent-50)" : "var(--surface)", cursor: "pointer" }}>
            <b style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>{a.label}</b>
            <div style={{ font: "500 12px var(--ui)", color: "var(--muted)", marginTop: 2 }}>{a.street}, {a.number} — {a.neighborhood}, {a.city}/{a.uf}</div>
          </button>
        ))}

        {!adding && (
          <button onClick={() => setAdding(true)}
            style={{ width: "100%", height: 46, borderRadius: 13, border: "1.5px dashed var(--accent)", background: "var(--accent-50)", cursor: "pointer", font: "700 14px var(--ui)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: 4 }}>
            <Icon name="plus" size={16} sw={2.4} color="var(--accent)" />Adicionar endereço
          </button>
        )}

        {adding && (
          <AddressForm form={form} setForm={setForm} saving={saving}
            onSave={saveAddr}
            onCancel={addresses.length > 0 ? () => setAdding(false) : undefined}
          />
        )}

      </div>
    </div>
  );
}

// ── Checkout ─────────────────────────────────────────────────
function CheckoutScreen({ cart, partner, mode, setMode, wallet, onConfirm, onBack }) {
  const p = partner;
  const [useBal, setUseBal] = React.useState(false);
  const [pay, setPay] = React.useState("pix");
  const [loading, setLoading] = React.useState(false);
  const [payError, setPayError] = React.useState("");
  const [addresses, setAddresses] = React.useState([]);
  const [selAddr, setSelAddr] = React.useState(null);
  const [showAddrPicker, setShowAddrPicker] = React.useState(false);

  React.useEffect(() => {
    if (!Auth.isLogged()) return;
    API.me.addresses().then(d => {
      const list = d.addresses || [];
      setAddresses(list);
      setSelAddr(list.find(a => a.is_default) || list[0] || null);
    }).catch(() => {});
  }, []);

  const entries = Object.values(cart.items);
  const subtotal = entries.reduce((s, e) => s + e.item.price * e.qty, 0);
  const fee = mode === "delivery" ? p.fee : 0;
  const totalCb = p.cashback + p.turbo;
  const cb = subtotal * totalCb / 100;
  const used = useBal ? Math.min(wallet.balance, subtotal + fee) : 0;
  const total = subtotal + fee - used;

  // Apenas Mercado Pago Split (Pix + Cartão)
  const payMap = { pix: "pix", card: "credito" };
  const pays = [
    ["pix",  "Pix",                   "coin", "Via Mercado Pago · instantâneo"],
    ["card", "Cartão de crédito",     "card", "Via Mercado Pago · até 12x"],
  ];

  const handleConfirm = async () => {
    setLoading(true);
    setPayError("");
    try {
      const companyId = p._raw?.id || p.id;
      const items = entries.map(e => ({
        product_id: typeof e.item.id === "string" && e.item.id.includes("-") ? e.item.id : undefined,
        name: e.item.name,
        unit_price: e.item.price,
        quantity: e.qty,
        note: e.note || undefined,
      }));
      const orderBody = {
        company_id: companyId,
        mode: mode === "delivery" ? "entrega" : "retirada",
        items,
        payment_method: payMap[pay] || "pix",
        bemcash_usado: used,
        delivery_address: mode === "delivery" && selAddr ? {
          label: selAddr.label, street: selAddr.street, number: selAddr.number,
          neighborhood: selAddr.neighborhood, city: selAddr.city, uf: selAddr.uf, cep: selAddr.cep
        } : undefined,
      };
      const order = await API.orders.create(orderBody);

      // If MP checkout URL returned, redirect customer to pay
      if (order.mp_checkout_url) {
        window.location.href = order.mp_checkout_url;
        return; // page will navigate away; loader stays until redirect
      }

      // Cash payment or MP not configured — confirm immediately
      onConfirm({ subtotal, fee, used, total,
        cb: parseFloat(order.bemcash_creditado) || cb,
        cbTurbo: parseFloat(order.bemcash_turbo_creditado) || 0,
        mode, pay, orderId: order.id });
    } catch (e) {
      const msg = e?.detail || e?.title || e?.message || "Erro ao processar pagamento. Tente novamente.";
      setPayError(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <TopBar title="Pagamento" onBack={onBack} />
      <div style={{ flex: 1, overflow: "auto", padding: "10px 12px 20px" }}>
        {/* delivery/pickup detail */}
        <Card>
          <CardHead icon={mode === "delivery" ? "bike" : "store"} title={mode === "delivery" ? "Entrega" : "Retirada na loja"} action={mode === "delivery" ? "Trocar" : null} onAction={mode === "delivery" ? () => setShowAddrPicker(true) : null} />
          {mode === "delivery" ? (
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.5 }}>
              {selAddr ? (
                <>
                  <b style={{ color: "var(--text)" }}>{selAddr.label} · {selAddr.neighborhood}</b><br />
                  {selAddr.street}, {selAddr.number} — {selAddr.neighborhood}, {selAddr.city}/{selAddr.uf}<br />
                  Chega em ~{p.time}
                </>
              ) : (
                <b style={{ color: "#D4493A" }}>Nenhum endereço cadastrado. Adicione um antes de continuar.</b>
              )}
            </div>
          ) : (
            <div style={{ font: "500 13px var(--ui)", color: "var(--muted)", lineHeight: 1.5 }}>
              Retire em <b style={{ color: "var(--text)" }}>{p.name}</b> — {p.area}<br />Pronto para retirada em ~15 min
            </div>
          )}
        </Card>

        {/* payment */}
        <Card>
          <CardHead icon="card" title="Forma de pagamento" />
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {pays.map(([id, lbl, ic, sub]) => (
              <button key={id} onClick={() => setPay(id)} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 12px", borderRadius: 12, cursor: "pointer", background: pay === id ? "var(--accent-50)" : "var(--bg)", border: pay === id ? "1.5px solid var(--accent)" : "1.5px solid transparent" }}>
                <Icon name={ic} size={20} color={pay === id ? "var(--accent)" : "var(--muted)"} />
                <div style={{ flex: 1, textAlign: "left" }}>
                  <div style={{ font: "600 14px var(--ui)", color: "var(--text)" }}>{lbl}</div>
                  {sub && <div style={{ font: "500 11.5px var(--ui)", color: "var(--muted)", marginTop: 1 }}>{sub}</div>}
                </div>
                <span style={{ width: 20, height: 20, borderRadius: 999, border: pay === id ? "6px solid var(--accent)" : "2px solid var(--line)" }} />
              </button>
            ))}
          </div>
        </Card>

        {/* use balance */}
        <Card>
          <button onClick={() => setUseBal(v => !v)} style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, background: "none", border: "none", cursor: "pointer", padding: 0 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: "var(--cb-bg)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="wallet" size={21} color="var(--cb)" />
            </div>
            <div style={{ flex: 1, textAlign: "left" }}>
              <div style={{ font: "700 14px var(--ui)", color: "var(--text)" }}>Usar saldo BemCash</div>
              <div style={{ font: "500 12px var(--ui)", color: "var(--muted)" }}>Disponível {money(wallet.balance)}</div>
            </div>
            <span style={{ width: 46, height: 28, borderRadius: 999, background: useBal ? "var(--cb)" : "var(--line)", position: "relative", transition: "background .2s" }}>
              <span style={{ position: "absolute", top: 3, left: useBal ? 21 : 3, width: 22, height: 22, borderRadius: 999, background: "#fff", transition: "left .2s" }} />
            </span>
          </button>
        </Card>

        {/* summary */}
        <Card>
          <Row label="Subtotal" value={money(subtotal)} />
          <Row label={mode === "delivery" ? "Entrega" : "Retirada"} value={fee === 0 ? "Grátis" : money(fee)} green={fee === 0} />
          {used > 0 && <Row label="Saldo usado" value={"− " + money(used)} green />}
          <div style={{ height: 1, background: "var(--line)", margin: "10px 0" }} />
          <Row label="Total a pagar" value={money(total)} bold />
          <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 7, background: "var(--cb-bg)", borderRadius: 10, padding: "9px 11px" }}>
            <Icon name="coin" size={17} color="var(--cb)" sw={1.8} />
            <span style={{ font: "700 12.5px var(--ui)", color: "var(--cb-ink)" }}>Você ganha {money(cb)} de volta ({totalCb}%)</span>
          </div>
        </Card>
      </div>

      {showAddrPicker && (
        <AddressPickerSheet
          addresses={addresses}
          selAddr={selAddr}
          onSelect={a => { setSelAddr(a); setShowAddrPicker(false); }}
          onClose={() => setShowAddrPicker(false)}
          onAdded={a => { setAddresses(prev => [...prev, a]); setSelAddr(a); setShowAddrPicker(false); }}
        />
      )}

      {payError && (
        <div style={{ margin: "0 12px 8px", padding: "12px 14px", background: "#FDECEA", borderRadius: 12, border: "1px solid #F5C6C2", font: "600 13px var(--ui)", color: "#C5402F", lineHeight: 1.45 }}>
          ⚠️ {payError}
        </div>
      )}

      <BottomBar>
        <Btn full variant="dark" disabled={loading || (mode === "delivery" && !selAddr)} onClick={handleConfirm}>
          {loading ? "Aguardando Mercado Pago…" : `Confirmar e ir para pagamento · ${money(total)}`}
        </Btn>
      </BottomBar>
    </div>
  );
}

function Card({ children }) {
  return <div style={{ background: "var(--surface)", borderRadius: 18, padding: 16, marginBottom: 12, boxShadow: "0 3px 12px rgba(16,18,45,.05)" }}>{children}</div>;
}
function CardHead({ icon, title, action, onAction }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
      <Icon name={icon} size={19} color="var(--accent)" />
      <h3 style={{ flex: 1, margin: 0, font: "700 15px var(--ui)", color: "var(--text)" }}>{title}</h3>
      {action && (
        <span
          style={{ font: "700 12.5px var(--ui)", color: "var(--accent)", cursor: onAction ? "pointer" : "default" }}
          onClick={onAction || undefined}
        >{action}</span>
      )}
    </div>
  );
}

// ── Success (pedido / agendamento / contato) ─────────────────
function SuccessScreen({ order, partner, onReview, onClose, onGoToCompras }) {
  const kind = order.kind || "pedido";
  const cfg = {
    pedido: { ic: "check", title: "Pedido confirmado!", sub: partner.name + " · " + (order.mode === "delivery" ? "Entrega" : "Retirada") },
    agendamento: { ic: "clock", title: "Agendamento confirmado!", sub: partner.name },
    contato: { ic: "headset", title: "Solicitação enviada!", sub: partner.name },
  }[kind];
  const steps = order.mode === "delivery"
    ? ["Pedido confirmado", "Em preparo", "Saiu para entrega", "Entregue"]
    : ["Pedido confirmado", "Em preparo", "Pronto para retirada"];

  return (
    <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", background: "var(--bg)" }}>
      <div style={{ flex: 1, overflow: "auto", padding: "70px 20px 20px", textAlign: "center" }}>
        <div style={{ width: 78, height: 78, borderRadius: 999, background: kind === "contato" ? "var(--accent)" : "var(--cb)", margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "center", animation: "mbPop .4s cubic-bezier(.2,1.4,.4,1)" }}>
          <Icon name={cfg.ic} size={40} color="#fff" sw={2.4} />
        </div>
        <h2 style={{ margin: "20px 0 4px", font: "800 23px var(--ui)", color: "var(--text)" }}>{cfg.title}</h2>
        <p style={{ font: "500 14px var(--ui)", color: "var(--muted)", margin: 0 }}>{cfg.sub}</p>

        {/* PEDIDO: cashback + tracking */}
        {kind === "pedido" && <>
          <div style={{ margin: "22px 0 0", borderRadius: 20, padding: 20, background: "var(--turbo-grad)", color: "#fff", boxShadow: "0 10px 28px var(--turbo-shadow)" }}>
            <Icon name="coin" size={30} color="#fff" sw={1.8} style={{ margin: "0 auto" }} />
            <div style={{ font: "500 13px var(--ui)", marginTop: 8, opacity: .95 }}>BemCash creditado na sua conta</div>
            <div style={{ font: "900 38px var(--ui)", marginTop: 2 }}>{money(order.cb)}</div>
            {order.cbTurbo > 0 && <div style={{ display: "inline-flex", alignItems: "center", gap: 5, font: "700 12px var(--ui)", background: "rgba(255,255,255,.2)", padding: "4px 10px", borderRadius: 999, marginTop: 8 }}><Icon name="bolt" size={13} color="#fff" fill="#fff" sw={1.5} />Inclui {money(order.cbTurbo)} de Turbo</div>}
          </div>
          <div style={{ background: "var(--surface)", borderRadius: 20, padding: "20px 18px", marginTop: 14, textAlign: "left" }}>
            <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 16 }}>Acompanhe seu pedido</div>
            {steps.map((s, i) => (
              <div key={s} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                  <div style={{ width: 22, height: 22, borderRadius: 999, background: i === 0 ? "var(--accent)" : "var(--bg)", border: i === 0 ? "none" : "2px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    {i === 0 && <Icon name="check" size={13} color="var(--accent-ink)" sw={3} />}
                  </div>
                  {i < steps.length - 1 && <div style={{ width: 2, height: 26, background: "var(--line)" }} />}
                </div>
                <div style={{ font: `${i === 0 ? 700 : 500} 13.5px var(--ui)`, color: i === 0 ? "var(--text)" : "var(--muted)", paddingTop: 1 }}>{s}{i === 0 && <span style={{ font: "500 12px var(--ui)", color: "var(--accent)", display: "block" }}>agora</span>}</div>
              </div>
            ))}
          </div>
        </>}

        {/* AGENDAMENTO: summary */}
        {kind === "agendamento" && (
          <div style={{ background: "var(--surface)", borderRadius: 20, padding: "18px", marginTop: 22, textAlign: "left", boxShadow: "0 4px 16px rgba(16,18,45,.06)" }}>
            <SumLine ic="edit" label="Serviço" value={order.service} />
            <SumLine ic="clock" label="Data e hora" value={order.date + " · " + order.time} />
            <SumLine ic={order.local === "loja" ? "store" : "home"} label="Local" value={order.local === "loja" ? "No estabelecimento" : "Na sua casa"} last />
            <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 8, background: "var(--accent-50)", borderRadius: 10, padding: "10px 12px" }}>
              <Icon name="info" size={16} color="var(--accent)" sw={2} /><span style={{ font: "600 12px var(--ui)", color: "var(--text)" }}>O prestador vai confirmar o horário pelo app. Pagamento na conclusão do serviço.</span>
            </div>
          </div>
        )}

        {/* CONTATO: lead info */}
        {kind === "contato" && (
          <div style={{ background: "var(--surface)", borderRadius: 20, padding: "20px 18px", marginTop: 22, textAlign: "left", boxShadow: "0 4px 16px rgba(16,18,45,.06)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <Icon name="headset" size={20} color="var(--accent)" /><span style={{ font: "700 14.5px var(--ui)", color: "var(--text)" }}>Tudo certo!</span>
            </div>
            <p style={{ font: "500 13.5px var(--ui)", color: "var(--muted)", lineHeight: 1.5, margin: "6px 0 0" }}>
              Enviamos seu interesse para <b style={{ color: "var(--text)" }}>{partner.name}</b>. A empresa vai entrar em contato por <b style={{ color: "var(--text)" }}>{order.pref === "call" ? "ligação" : "WhatsApp"}</b> em breve. Você não paga nada pela divulgação.
            </p>
          </div>
        )}
      </div>
      <BottomBar>
        {kind === "pedido" ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {order.mode === "Retirada" && partner?._raw?.latitude && (
              <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
                <a href={`https://www.google.com/maps/dir/?api=1&destination=${partner._raw.latitude},${partner._raw.longitude}`}
                   target="_blank" rel="noopener noreferrer"
                   style={{ flex: 1, height: 44, borderRadius: 13, background: "#4285F4", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", gap: 6, font: "700 13px var(--ui)", textDecoration: "none" }}>
                  Google Maps
                </a>
                <a href={`https://waze.com/ul?ll=${partner._raw.latitude},${partner._raw.longitude}&navigate=yes`}
                   target="_blank" rel="noopener noreferrer"
                   style={{ flex: 1, height: 44, borderRadius: 13, background: "#33CCFF", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", gap: 6, font: "700 13px var(--ui)", textDecoration: "none" }}>
                  Waze
                </a>
              </div>
            )}
            <div style={{ display: "flex", gap: 10 }}>
              <Btn variant="ghost" onClick={onClose} style={{ flex: 1 }}>Voltar ao início</Btn>
              <Btn onClick={onGoToCompras} style={{ flex: 1 }}>Acompanhar pedido</Btn>
            </div>
          </div>
        ) : (
          <Btn full onClick={onClose}>Voltar ao início</Btn>
        )}
      </BottomBar>
    </div>
  );
}

// ── Review ───────────────────────────────────────────────────
function ReviewSheet({ partner, mode, onSubmit }) {
  const [overall, setOverall] = React.useState(0);
  const [food, setFood] = React.useState(0);
  const [deliv, setDeliv] = React.useState(0);
  const [tags, setTags] = React.useState([]);
  const [txt, setTxt] = React.useState("");
  const tagList = ["Caprichado", "Bem embalado", "Chegou quente", "No prazo", "Recomendo", "Bom preço"];
  const tg = (t) => setTags(s => s.includes(t) ? s.filter(x => x !== t) : [...s, t]);

  const StarPick = ({ value, set, size = 34 }) => (
    <div style={{ display: "flex", gap: 6 }}>
      {[1, 2, 3, 4, 5].map(i => (
        <button key={i} onClick={() => set(i)} style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}>
          <Icon name="star" size={size} sw={1.5} color={i <= value ? "#F5A524" : "var(--line)"} fill={i <= value ? "#F5A524" : "none"} />
        </button>
      ))}
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: "var(--accent-50)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={segIcon(partner.seg)} size={23} color="var(--accent)" /></div>
        <div><div style={{ font: "700 16px var(--ui)", color: "var(--text)" }}>{partner.name}</div><div style={{ font: "500 12.5px var(--ui)", color: "var(--muted)" }}>Como foi seu pedido?</div></div>
      </div>

      <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
        <div style={{ font: "700 14px var(--ui)", color: "var(--text)", marginBottom: 12 }}>Avaliação geral</div>
        <div style={{ display: "flex", justifyContent: "center" }}><StarPick value={overall} set={setOverall} size={40} /></div>
      </div>

      <div style={{ display: "flex", gap: 12 }}>
        <div style={{ flex: 1, background: "var(--bg)", borderRadius: 14, padding: "12px 14px" }}>
          <div style={{ font: "600 12.5px var(--ui)", color: "var(--muted)", marginBottom: 8 }}>Qualidade</div>
          <StarPick value={food} set={setFood} size={22} />
        </div>
        <div style={{ flex: 1, background: "var(--bg)", borderRadius: 14, padding: "12px 14px" }}>
          <div style={{ font: "600 12.5px var(--ui)", color: "var(--muted)", marginBottom: 8 }}>{mode === "delivery" ? "Entrega" : "Atendimento"}</div>
          <StarPick value={deliv} set={setDeliv} size={22} />
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {tagList.map(t => <Chip key={t} active={tags.includes(t)} onClick={() => tg(t)}>{t}</Chip>)}
      </div>

      <textarea value={txt} onChange={e => setTxt(e.target.value)} rows={3} placeholder="Conte como foi sua experiência (opcional)"
        style={{ width: "100%", boxSizing: "border-box", border: "1.5px solid var(--line)", borderRadius: 12, padding: "12px 13px", font: "500 14px var(--ui)", color: "var(--text)", resize: "none", outline: "none", background: "var(--bg)" }} />

      <Btn full disabled={overall === 0} onClick={() => onSubmit(overall)}>Enviar avaliação</Btn>
    </div>
  );
}

Object.assign(window, { Stepper, ProductSheet, CartScreen, Row, BottomBar, SumLine, CheckoutScreen, Card, CardHead, SuccessScreen, ReviewSheet, AddressForm, AddressPickerSheet, lookupCep });
