// Checkout v2 — 3 pasos (dirección → banda → pago MP simulado). Prepago, sin efectivo.

function CheckoutFlow({ branchId, cart, products, accent, onClose, onPaid }) {
  const cfg = loadDeliveryCfg(branchId);
  const items = Object.entries(cart).filter(([_, q]) => q > 0).map(([id, qty]) => {
    const p = products.find(x => x.id === id);
    return p ? { id, name: p.name, qty, price: p.price } : null;
  }).filter(Boolean);
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const ship = shippingFor(subtotal, cfg);

  const [step, setStep] = React.useState(1); // 1 dirección · 2 banda · 3 resumen · 4 MP
  const [addr, setAddr] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("hlpraf_last_address") || "null") || { name: "", phone: "", street: "", ref: "" }; }
    catch (e) { return { name: "", phone: "", street: "", ref: "" }; }
  });
  const hasSaved = !!(addr.name && addr.street);
  const [savedCollapsed, setSavedCollapsed] = React.useState(hasSaved);
  const [geoStatus, setGeoStatus] = React.useState("idle"); // idle | checking | ok | outside | notfound | error
  const [coords, setCoords] = React.useState(null);
  const [manualGeo, setManualGeo] = React.useState(false);
  const [pinConfirm, setPinConfirm] = React.useState(false);
  const mapsReady = !!(window.hlprafMaps && hlprafMaps.hasMapsKey());
  const [band, setBand] = React.useState(null);
  const [order, setOrder] = React.useState(null);
  const bands = availableBands(cfg);
  const setA = (k, v) => { setAddr(a => ({ ...a, [k]: v })); setGeoStatus("idle"); setManualGeo(false); };

  const proceedManually = () => {
    setCoords({ lat: cfg.center.lat, lng: cfg.center.lng });
    setManualGeo(true);
    setGeoStatus("ok");
    localStorage.setItem("hlpraf_last_address", JSON.stringify(addr));
    if (mapsReady) setPinConfirm(true); else setStep(2);
  };

  const confirmPin = () => {
    // si movió el pin fuera de zona, igual lo dejamos avanzar (el depósito revisa)
    localStorage.setItem("hlpraf_last_address", JSON.stringify(addr));
    setStep(2);
  };

  const validateAddress = async () => {
    if (!addr.name.trim() || !addr.phone.trim() || !addr.street.trim()) return;
    setGeoStatus("checking");
    try {
      const geocode = (window.hlprafMaps && hlprafMaps.hasMapsKey()) ? hlprafMaps.geocodeGoogle : geocodeAddress;
      const geo = await geocode(addr.street);
      if (!geo) { setGeoStatus("notfound"); return; }
      const c = { lat: geo.lat, lng: geo.lng };
      if (!insideCoverage(c, cfg)) { setGeoStatus("outside"); return; }
      setCoords(c);
      setGeoStatus("ok");
      localStorage.setItem("hlpraf_last_address", JSON.stringify(addr));
      if (mapsReady) setPinConfirm(true); else setStep(2);
    } catch (e) { setGeoStatus("error"); }
  };
  const useSaved = async () => { setSavedCollapsed(true); await validateAddress(); };

  const goPay = () => {
    const o = createOrder({
      branchId, items, subtotal, shippingFee: ship.fee,
      customer: { ...addr, geoReview: manualGeo || undefined }, coords,
      band: { key: band.key, date: band.date, dayLabel: band.dayLabel, id: band.band.id, label: band.band.label, start: band.band.start, end: band.band.end },
    });
    setOrder(o);
    setStep(4);
  };

  const stepTitles = { 1: "¿A dónde te lo llevamos?", 2: "¿Cuándo?", 3: "Revisá tu pedido" };

  if (step === 4 && order) {
    return <MPSimulator order={order} accent={accent}
      onResult={(result) => {
        if (result === "approved") { approvePayment(order.id); onPaid(order.id); }
        else if (result === "rejected") { rejectPayment(order.id); setStep(3); setOrder(null); alert("El pago fue rechazado. Probá con otro medio de pago."); }
        else { onClose(); } // abandonado: queda pending_payment, expira solo
      }} />;
  }

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(40,25,10,0.5)", zIndex: 400, display: "flex", alignItems: "flex-end", justifyContent: "center", backdropFilter: "blur(6px)" }} onClick={onClose}>
      <div style={{ background: "#fdfaf3", borderRadius: "22px 22px 0 0", padding: "20px 20px 30px", width: "100%", maxWidth: 520, maxHeight: "92vh", overflowY: "auto", fontFamily: "'DM Sans', sans-serif" }} onClick={e => e.stopPropagation()}>

        {/* header + progreso */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            {step > 1 && <button onClick={() => setStep(step - 1)} style={{ background: "#f5ede1", border: "none", borderRadius: "50%", width: 30, height: 30, cursor: "pointer", fontSize: 14, color: "#6b5d4e" }}>←</button>}
            <h2 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 24, letterSpacing: "0.04em", margin: 0, color: "#1a1008" }}>{stepTitles[step]}</h2>
          </div>
          <button onClick={onClose} style={{ background: "#f5ede1", border: "none", color: "#6b5d4e", borderRadius: "50%", width: 32, height: 32, cursor: "pointer", fontSize: 14 }}>✕</button>
        </div>
        <div style={{ display: "flex", gap: 5, marginBottom: 16 }}>
          {[1, 2, 3].map(n => <div key={n} style={{ flex: 1, height: 4, borderRadius: 2, background: n <= step ? accent : "#e8dcc8" }}></div>)}
        </div>

        {/* mini resumen persistente */}
        <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 12, padding: "10px 14px", marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13 }}>
          <span style={{ color: "#6b5d4e", fontWeight: 600 }}>{items.reduce((s, i) => s + i.qty, 0)} productos</span>
          <span style={{ fontWeight: 800, color: "#1a1008" }}>
            ${subtotal.toLocaleString("es-AR")}
            {ship.fee > 0 && !ship.free && <span style={{ color: "#8a7a66", fontWeight: 600 }}> + envío ${ship.fee.toLocaleString("es-AR")}</span>}
            {ship.free && <span style={{ color: "#15803d", fontWeight: 800 }}> · envío GRATIS 🎉</span>}
          </span>
        </div>

        {step === 1 && pinConfirm && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <PinPicker coords={coords} accent={accent} onChange={setCoords} />
            <button onClick={confirmPin} style={{ background: accent, color: "#fff", border: "none", borderRadius: 12, padding: "14px 0", fontWeight: 800, fontSize: 15, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>Confirmar ubicación →</button>
            <button onClick={() => { setPinConfirm(false); setGeoStatus("idle"); }} style={{ background: "transparent", border: "none", color: "#8a7a66", fontWeight: 700, fontSize: 13, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>← Editar dirección</button>
          </div>
        )}

        {step === 1 && !pinConfirm && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {hasSaved && savedCollapsed ? (
              <div style={{ background: "linear-gradient(135deg,#fff7ed,#ffedd5)", border: `2px solid ${accent}`, borderRadius: 14, padding: 16 }}>
                <div style={{ fontSize: 11, fontWeight: 800, color: accent, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>📍 Como la última vez</div>
                <div style={{ fontWeight: 800, fontSize: 15, color: "#1a1008" }}>{addr.street}</div>
                <div style={{ fontSize: 13, color: "#6b5d4e" }}>{addr.name} · {addr.phone}{addr.ref ? ` · ${addr.ref}` : ""}</div>
                <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                  <button onClick={() => setSavedCollapsed(false)} style={{ flex: 1, background: "#fff", border: "1px solid #e8dcc8", borderRadius: 10, padding: "11px 0", fontWeight: 700, fontSize: 13, cursor: "pointer", color: "#6b5d4e" }}>Cambiar datos</button>
                  <button onClick={useSaved} disabled={geoStatus === "checking"} style={{ flex: 2, background: accent, border: "none", color: "#fff", borderRadius: 10, padding: "11px 0", fontWeight: 800, fontSize: 14, cursor: "pointer" }}>
                    {geoStatus === "checking" ? "Verificando zona..." : "Sí, llevalo ahí →"}
                  </button>
                </div>
              </div>
            ) : (
              <React.Fragment>
                <input value={addr.name} onChange={e => setA("name", e.target.value)} placeholder="Nombre y apellido" style={ckInput} />
                <input value={addr.phone} onChange={e => setA("phone", e.target.value)} placeholder="Celular (con WhatsApp)" type="tel" style={ckInput} />
                <input value={addr.street} onChange={e => setA("street", e.target.value)} placeholder="Calle y número — ej: Alvear 320" style={ckInput} />
                <input value={addr.ref} onChange={e => setA("ref", e.target.value)} placeholder="Referencia (opcional) — portón negro, timbre no anda…" style={ckInput} />
                <button onClick={validateAddress} disabled={geoStatus === "checking" || !addr.name.trim() || !addr.phone.trim() || !addr.street.trim()}
                  style={{ background: accent, color: "#fff", border: "none", borderRadius: 12, padding: "14px 0", fontWeight: 800, fontSize: 15, cursor: "pointer", opacity: (!addr.name.trim() || !addr.phone.trim() || !addr.street.trim()) ? 0.5 : 1 }}>
                  {geoStatus === "checking" ? "📍 Verificando cobertura..." : "Continuar →"}
                </button>
              </React.Fragment>
            )}
            {geoStatus === "outside" && (
              <div style={ckWarn}>😔 Esa dirección queda fuera de nuestra zona de entrega (hasta {cfg.radiusKm} km del centro de Rafaela). Podés retirar en una sucursal física o probar con otra dirección.</div>
            )}
            {geoStatus === "notfound" && (
              <React.Fragment>
                <div style={ckWarn}>No encontramos esa dirección. Revisá que sea calle y número de Rafaela — ej: "Alvear 320".</div>
                <button onClick={proceedManually} style={{ background: "transparent", border: `1.5px solid ${accent}`, color: accent, borderRadius: 12, padding: "12px 0", fontWeight: 700, fontSize: 13.5, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>Mi dirección es correcta, continuar igual →</button>
                <div style={{ fontSize: 11, color: "#8a7a66", textAlign: "center", marginTop: -4 }}>El depósito confirma tu ubicación antes de salir.</div>
              </React.Fragment>
            )}
            {geoStatus === "error" && (
              <React.Fragment>
                <div style={ckWarn}>No pudimos verificar la dirección (sin conexión al mapa). Podés reintentar o continuar igual.</div>
                <button onClick={proceedManually} style={{ background: "transparent", border: `1.5px solid ${accent}`, color: accent, borderRadius: 12, padding: "12px 0", fontWeight: 700, fontSize: 13.5, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" }}>Continuar igual →</button>
                <div style={{ fontSize: 11, color: "#8a7a66", textAlign: "center", marginTop: -4 }}>El depósito confirma tu ubicación antes de salir.</div>
              </React.Fragment>
            )}
          </div>
        )}

        {step === 2 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ fontSize: 13, color: "#6b5d4e", marginBottom: 2 }}>Entrega en <strong>{addr.street}</strong> · elegí tu franja:</div>
            {bands.length === 0 && <div style={ckWarn}>No hay franjas disponibles en este momento. Volvé a intentar más tarde.</div>}
            {bands.map(b => {
              const sel = band?.key === b.key;
              return (
                <button key={b.key} onClick={() => setBand(b)} style={{
                  display: "flex", alignItems: "center", gap: 14, textAlign: "left",
                  background: sel ? "linear-gradient(135deg,#fff7ed,#ffedd5)" : "#fff",
                  border: sel ? `2px solid ${accent}` : "1.5px solid #e8dcc8",
                  borderRadius: 14, padding: "16px 18px", cursor: "pointer", fontFamily: "'DM Sans', sans-serif"
                }}>
                  <span style={{ fontSize: 26 }}>{b.band.id === "mediodia" ? "🌤️" : "🌙"}</span>
                  <span style={{ flex: 1 }}>
                    <span style={{ display: "block", fontWeight: 800, fontSize: 16, color: "#1a1008" }}>{b.dayLabel} · {b.band.label}</span>
                    <span style={{ display: "block", fontSize: 13, color: "#6b5d4e" }}>Entre las {b.band.start} y las {b.band.end}hs</span>
                  </span>
                  {sel && <span style={{ color: accent, fontSize: 20, fontWeight: 800 }}>✓</span>}
                </button>
              );
            })}
            <button onClick={() => band && setStep(3)} disabled={!band} style={{ background: accent, color: "#fff", border: "none", borderRadius: 12, padding: "14px 0", fontWeight: 800, fontSize: 15, cursor: "pointer", opacity: band ? 1 : 0.5, marginTop: 4 }}>Continuar →</button>
          </div>
        )}

        {step === 3 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 14, padding: 16 }}>
              {items.map(it => (
                <div key={it.id} style={{ display: "flex", justifyContent: "space-between", fontSize: 13, padding: "4px 0", color: "#1a1008" }}>
                  <span>{it.qty}× {it.name}</span>
                  <span style={{ color: "#8a7a66", flexShrink: 0, marginLeft: 10 }}>${(it.price * it.qty).toLocaleString("es-AR")}</span>
                </div>
              ))}
              <div style={{ borderTop: "1px solid #f0e6d2", marginTop: 8, paddingTop: 8, fontSize: 13, display: "flex", flexDirection: "column", gap: 4 }}>
                <div style={{ display: "flex", justifyContent: "space-between", color: "#6b5d4e" }}><span>Subtotal</span><span>${subtotal.toLocaleString("es-AR")}</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", color: ship.free ? "#15803d" : "#6b5d4e", fontWeight: ship.free ? 800 : 400 }}>
                  <span>Envío</span><span>{ship.free ? "GRATIS 🎉" : "$" + ship.fee.toLocaleString("es-AR")}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontWeight: 800, fontSize: 16, color: "#1a1008", marginTop: 2 }}>
                  <span>Total</span><span>${(subtotal + ship.fee).toLocaleString("es-AR")}</span>
                </div>
              </div>
            </div>
            <div style={{ background: "#fff", border: "1px solid #e8dcc8", borderRadius: 14, padding: 16, fontSize: 13, display: "flex", flexDirection: "column", gap: 6 }}>
              <div><span style={{ color: "#8a7a66" }}>📍 Entrega:</span> <strong>{addr.street}</strong>{addr.ref ? ` (${addr.ref})` : ""}</div>
              <div><span style={{ color: "#8a7a66" }}>🕐 Franja:</span> <strong>{band.dayLabel} de {band.band.start} a {band.band.end}hs</strong></div>
              <div><span style={{ color: "#8a7a66" }}>👤</span> {addr.name} · {addr.phone}</div>
            </div>
            <button onClick={goPay} style={{
              background: "#009ee3", color: "#fff", border: "none", borderRadius: 12,
              padding: "15px 0", fontWeight: 800, fontSize: 16, cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8
            }}>
              <span style={{ background: "#fff", color: "#009ee3", borderRadius: 4, padding: "1px 5px", fontSize: 11, fontWeight: 900 }}>MP</span>
              Pagar con Mercado Pago
            </button>
            <div style={{ fontSize: 11, color: "#8a7a66", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: 5 }}>
              <span style={{ background: "#009ee3", color: "#fff", borderRadius: 3, padding: "0 4px", fontSize: 9, fontWeight: 900 }}>MP</span>
              Pago protegido por Mercado Pago · Sin efectivo · Tus datos de tarjeta nunca pasan por nuestra app
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ---- Simulador de Checkout Pro ----
function MPSimulator({ order, onResult }) {
  const [processing, setProcessing] = React.useState(false);
  const pay = () => { setProcessing(true); setTimeout(() => onResult("approved"), 1600); };
  return (
    <div style={{ position: "fixed", inset: 0, background: "#f5f5f5", zIndex: 500, display: "flex", flexDirection: "column", fontFamily: "'DM Sans', sans-serif" }}>
      <div style={{ background: "#009ee3", padding: "14px 18px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, color: "#fff", fontWeight: 800, fontSize: 15 }}>
          <span style={{ background: "#fff", color: "#009ee3", borderRadius: 4, padding: "2px 6px", fontSize: 12, fontWeight: 900 }}>MP</span>
          Mercado Pago <span style={{ fontWeight: 400, fontSize: 11, opacity: 0.8 }}>· simulación</span>
        </div>
        <button onClick={() => onResult("abandoned")} style={{ background: "rgba(255,255,255,0.2)", border: "none", color: "#fff", borderRadius: 8, padding: "6px 12px", fontSize: 12, fontWeight: 700, cursor: "pointer" }}>✕ Salir</button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", display: "flex", justifyContent: "center", padding: 20 }}>
        <div style={{ width: "100%", maxWidth: 420 }}>
          <div style={{ background: "#fff", borderRadius: 12, padding: 20, boxShadow: "0 2px 10px rgba(0,0,0,0.08)", marginBottom: 14 }}>
            <div style={{ fontSize: 13, color: "#666" }}>Estás pagando a</div>
            <div style={{ fontWeight: 800, fontSize: 17, color: "#333" }}>HLP Raf · Hamburguesas La Plata</div>
            <div style={{ fontSize: 32, fontWeight: 800, color: "#333", marginTop: 10 }}>${order.total.toLocaleString("es-AR")}</div>
            <div style={{ fontSize: 12, color: "#999", marginTop: 2 }}>Pedido {order.id} · {order.items.reduce((s, i) => s + i.qty, 0)} productos</div>
          </div>
          {!processing ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <button onClick={pay} style={mpBtn("#009ee3")}>💳 Pagar con tarjeta guardada ····4242</button>
              <button onClick={pay} style={mpBtn("#00a650")}>💰 Pagar con dinero en cuenta</button>
              <div style={{ height: 8 }}></div>
              <div style={{ fontSize: 11, color: "#999", textAlign: "center", textTransform: "uppercase", letterSpacing: "0.05em" }}>Simular otros resultados</div>
              <button onClick={() => onResult("rejected")} style={{ ...mpBtn("#fff"), color: "#e02020", border: "1.5px solid #e02020" }}>✕ Simular pago rechazado</button>
              <button onClick={() => onResult("abandoned")} style={{ ...mpBtn("#fff"), color: "#666", border: "1.5px solid #ccc" }}>← Abandonar el pago</button>
            </div>
          ) : (
            <div style={{ background: "#fff", borderRadius: 12, padding: 40, textAlign: "center", boxShadow: "0 2px 10px rgba(0,0,0,0.08)" }}>
              <div style={{ fontSize: 40, animation: "mpspin 1.2s linear infinite", display: "inline-block" }}>⏳</div>
              <div style={{ fontWeight: 700, color: "#333", marginTop: 12 }}>Procesando tu pago...</div>
            </div>
          )}
        </div>
      </div>
      <style>{`@keyframes mpspin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}
const mpBtn = (bg) => ({ background: bg, color: "#fff", border: "none", borderRadius: 10, padding: "14px 0", fontWeight: 700, fontSize: 14, cursor: "pointer", fontFamily: "'DM Sans', sans-serif" });

const ckInput = { background: "#fff", border: "1.5px solid #e8dcc8", borderRadius: 12, padding: "13px 14px", color: "#1a1008", fontSize: 14, fontFamily: "'DM Sans', sans-serif", outline: "none", width: "100%", boxSizing: "border-box" };
const ckWarn = { background: "#fef2f2", border: "1px solid #fecaca", color: "#991b1b", borderRadius: 12, padding: "12px 14px", fontSize: 13, lineHeight: 1.5 };

// Barra de progreso de envío para el carrito
function ShippingProgress({ subtotal, cfg, accent }) {
  if (!cfg) return null;
  const ship = shippingFor(subtotal, cfg);
  const target = ship.ok ? cfg.freeFrom : cfg.min;
  const pct = Math.min(100, Math.round((subtotal / target) * 100));
  let title, msg, color;
  if (!ship.ok) { title = `Faltan $${ship.missingToMin.toLocaleString("es-AR")}`; msg = `para el mínimo de $${cfg.min.toLocaleString("es-AR")}`; color = "#dc2626"; }
  else if (!ship.free) { title = `Sumá $${ship.missingToFree.toLocaleString("es-AR")}`; msg = "y el envío es GRATIS"; color = "#ea580c"; }
  else { title = "Envío GRATIS"; msg = "¡lo tenés! 🎉"; color = "#15803d"; }
  const R = 26, C = 2 * Math.PI * R, off = C - (pct / 100) * C;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, fontFamily: "'DM Sans', sans-serif" }}>
      <div style={{ position: "relative", width: 60, height: 60, flexShrink: 0 }}>
        <svg width="60" height="60" style={{ transform: "rotate(-90deg)" }}>
          <circle cx="30" cy="30" r={R} fill="none" stroke="#f0e6d2" strokeWidth="7" />
          <circle cx="30" cy="30" r={R} fill="none" stroke={color} strokeWidth="7" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={off} style={{ transition: "stroke-dashoffset 0.4s, stroke 0.3s" }} />
        </svg>
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 800, color }}>{pct}%</div>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 800, color, lineHeight: 1.15 }}>{title}</div>
        <div style={{ fontSize: 11.5, color: "#6b5d4e", lineHeight: 1.2 }}>{msg}</div>
      </div>
    </div>
  );
}

Object.assign(window, { CheckoutFlow, MPSimulator, ShippingProgress });
