/* ============================================================
   AfricaSpares — Cart Context (shared state)
   Used by: PartCard → CartPanel → CheckoutModal
   ============================================================ */

const CartCtx = React.createContext({ cart: [], addItem: () => {}, removeItem: () => {}, updateQty: () => {}, clearCart: () => {} });
const useCart = () => React.useContext(CartCtx);

function CartProvider({ children }) {
  const [cart, setCart] = React.useState(() => {
    try { const s = localStorage.getItem("gg_as_cart"); return s ? JSON.parse(s) : []; } catch { return []; }
  });
  const save = (items) => { setCart(items); try { localStorage.setItem("gg_as_cart", JSON.stringify(items)); } catch {} };

  const addItem = (part) => {
    setCart(prev => {
      const exists = prev.find(i => i.sku === part.sku);
      const next = exists
        ? prev.map(i => i.sku === part.sku ? { ...i, qty: i.qty + 1 } : i)
        : [...prev, { ...part, qty: 1 }];
      try { localStorage.setItem("gg_as_cart", JSON.stringify(next)); } catch {}
      return next;
    });
  };
  const removeItem = (sku) => save(cart.filter(i => i.sku !== sku));
  const updateQty  = (sku, qty) => {
    if (qty < 1) { removeItem(sku); return; }
    save(cart.map(i => i.sku === sku ? { ...i, qty } : i));
  };
  const clearCart = () => save([]);
  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);

  return (
    <CartCtx.Provider value={{ cart, addItem, removeItem, updateQty, clearCart, total }}>
      {children}
    </CartCtx.Provider>
  );
}

/* ─── Cart icon button (used in page header) ─────────────── */
function CartButton({ onClick }) {
  const { cart } = useCart();
  const count = cart.reduce((s, i) => s + i.qty, 0);
  return (
    <button onClick={onClick} style={{ position: "relative", display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 16px", borderRadius: 3, border: "1.5px solid var(--spares)", background: "transparent", color: "var(--spares-d)", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13.5, cursor: "pointer", transition: "all .18s" }}
      onMouseEnter={e => { e.currentTarget.style.background = "var(--spares)"; e.currentTarget.style.color = "#fff"; }}
      onMouseLeave={e => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--spares-d)"; }}>
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4zM3 6h18M16 10a4 4 0 0 1-8 0"/></svg>
      {L("Cart", "Panier")}
      {count > 0 && (
        <span style={{ position: "absolute", top: -7, right: -7, background: "var(--spares)", color: "#fff", borderRadius: "50%", width: 20, height: 20, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, border: "2px solid var(--paper)" }}>{count}</span>
      )}
    </button>
  );
}

/* ─── Cart slide-in panel ────────────────────────────────── */
function CartPanel({ open, onClose, onCheckout }) {
  const { cart, removeItem, updateQty, total } = useCart();
  if (!open) return null;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(28,20,9,.5)", display: "flex", justifyContent: "flex-end" }}>
      <div onClick={e => e.stopPropagation()} style={{ width: "min(480px,100vw)", background: "var(--paper)", display: "flex", flexDirection: "column", height: "100%" }}>
        {/* Header */}
        <div style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 22 }}>
            {L("Your Cart", "Votre Panier")} <span style={{ fontSize: 14, color: "var(--muted)", fontFamily: "var(--fbody)", fontWeight: 400 }}>({cart.reduce((s,i)=>s+i.qty,0)} {L("items","articles")})</span>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)", padding: 4 }}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </button>
        </div>

        {/* Items */}
        <div style={{ flex: 1, overflowY: "auto", padding: "16px 24px" }}>
          {cart.length === 0 ? (
            <div style={{ textAlign: "center", padding: "60px 0", color: "var(--muted)" }}>
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.2" style={{ margin: "0 auto 16px" }}><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4zM3 6h18M16 10a4 4 0 0 1-8 0"/></svg>
              <p style={{ fontFamily: "var(--fdisp)", fontWeight: 700, fontSize: 18 }}>{L("Your cart is empty", "Votre panier est vide")}</p>
              <p style={{ fontSize: 14, marginTop: 6 }}>{L("Add parts from the catalogue", "Ajoutez des pièces depuis le catalogue")}</p>
            </div>
          ) : (
            cart.map(item => (
              <div key={item.sku} style={{ display: "flex", gap: 14, padding: "14px 0", borderBottom: "1px solid var(--line)" }}>
                {/* Image */}
                <div style={{ width: 64, height: 64, flexShrink: 0, background: "var(--paper-2)", borderRadius: 3, overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  {item.img ? <img src={item.img} alt={item.name} style={{ width: "100%", height: "100%", objectFit: "contain", mixBlendMode: "multiply" }} /> : <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M9 21V9"/></svg>}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 14.5, lineHeight: 1.25 }}>{item.name}</div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 3 }}>{item.sku} · {item.fit}</div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                    {/* Qty */}
                    <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid var(--line)", borderRadius: 3, overflow: "hidden" }}>
                      <button onClick={() => updateQty(item.sku, item.qty - 1)} style={{ width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", background: "none", border: "none", cursor: "pointer", color: "var(--ink)", fontSize: 16 }}>−</button>
                      <span style={{ width: 28, textAlign: "center", fontSize: 14, fontWeight: 700 }}>{item.qty}</span>
                      <button onClick={() => updateQty(item.sku, item.qty + 1)} style={{ width: 28, height: 28, display: "flex", alignItems: "center", justifyContent: "center", background: "none", border: "none", cursor: "pointer", color: "var(--ink)", fontSize: 16 }}>+</button>
                    </div>
                    <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 17 }}>{(item.price * item.qty).toLocaleString("fr-FR")} <span style={{ fontSize: 12 }}>XOF</span></div>
                    <button onClick={() => removeItem(item.sku)} style={{ background: "none", border: "none", cursor: "pointer", color: "#991B1B", padding: 4 }}>
                      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/></svg>
                    </button>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Footer */}
        {cart.length > 0 && (
          <div style={{ padding: "20px 24px", borderTop: "1px solid var(--line)", background: "var(--paper)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 16 }}>
              <span style={{ fontFamily: "var(--fsemi)", fontWeight: 600, fontSize: 15 }}>{L("Subtotal", "Sous-total")}</span>
              <span style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 22 }}>{total.toLocaleString("fr-FR")} <span style={{ fontSize: 13 }}>XOF</span></span>
            </div>
            <p style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 14 }}>{L("Shipping and taxes calculated at checkout", "Livraison et taxes calculées à la commande")}</p>
            <button onClick={onCheckout} className="btn" style={{ width: "100%", justifyContent: "center", background: "var(--spares)", color: "#fff", fontSize: 15, padding: "13px 0" }}>
              {L("Proceed to Checkout →", "Passer la commande →")}
            </button>
            <button onClick={onClose} style={{ width: "100%", textAlign: "center", marginTop: 10, background: "none", border: "none", cursor: "pointer", color: "var(--muted)", fontSize: 13.5 }}>{L("Continue shopping", "Continuer mes achats")}</button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ─── Checkout modal ─────────────────────────────────────── */
const PAYMENT_METHODS = [
  { id: "card",         label: L("Bank card", "Carte bancaire"), icon: "💳", color: "#1A1F71", sub: "Visa · Mastercard · GIM-UEMOA", full: true },
  { id: "orange_money", label: "Orange Money", icon: "📱", color: "#FF7900", sub: "+227 XX XX XX XX" },
  { id: "airtel_money", label: "Airtel Money",  icon: "📱", color: "#E40000", sub: "+227 XX XX XX XX" },
  { id: "bank",         label: L("Bank Transfer", "Virement bancaire"), icon: "🏦", color: "#1F4E79", sub: "BSIC / Ecobank / BIA" },
  { id: "cash",         label: L("Cash on delivery", "Paiement à la livraison"), icon: "💵", color: "#2D6A4F", sub: L("Niamey only", "Niamey uniquement") },
];

function CheckoutModal({ open, onClose }) {
  const { cart, total, clearCart } = useCart();
  const [step,    setStep]    = React.useState(1); // 1=info, 2=payment, 3=confirm
  const [method,  setMethod]  = React.useState("card");
  const [card,    setCard]    = React.useState({ number: "", name: "", exp: "", cvv: "" });
  const [form,    setForm]    = React.useState({ name: "", phone: "", email: "", address: "", notes: "" });
  const [placed,  setPlaced]  = React.useState(false);
  const [orderId, setOrderId] = React.useState("");

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const fInp = { width: "100%", border: "1px solid var(--line)", borderRadius: 3, padding: "9px 12px", fontSize: 14.5, background: "var(--paper-0)", outline: "none", fontFamily: "inherit", color: "var(--ink)", boxSizing: "border-box" };
  const lbl  = { display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 };
  const setC = (k, v) => setCard(c => ({ ...c, [k]: v }));
  const fmtCardNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(\d{4})(?=\d)/g, "$1 ");
  const fmtExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length > 2 ? d.slice(0, 2) + "/" + d.slice(2) : d; };
  const cardOk = method !== "card" || (card.number.replace(/\s/g, "").length >= 15 && card.name.trim() !== "" && /^\d{2}\/\d{2}$/.test(card.exp) && card.cvv.length >= 3);

  const placeOrder = () => {
    const id = "AS-" + Date.now().toString(36).toUpperCase();
    setOrderId(id);
    setPlaced(true);
    clearCart();
  };

  if (!open) return null;

  if (placed) return (
    <div style={{ position: "fixed", inset: 0, zIndex: 210, background: "rgba(28,20,9,.6)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <div style={{ background: "var(--paper)", borderRadius: 5, maxWidth: 480, width: "100%", padding: "40px 40px 44px", textAlign: "center", boxShadow: "0 30px 80px rgba(0,0,0,.3)" }}>
        <div style={{ width: 72, height: 72, borderRadius: "50%", background: "#D1FAE5", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 20px" }}>
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#065F46" strokeWidth="2.5"><path d="M20 6 9 17l-5-5"/></svg>
        </div>
        <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 28 }}>{L("Order Placed!", "Commande reçue !")}</div>
        <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13, color: "var(--spares)", marginTop: 8, letterSpacing: ".1em" }}># {orderId}</div>
        <p style={{ color: "var(--muted)", fontSize: 14.5, lineHeight: 1.65, marginTop: 14, maxWidth: 340, margin: "14px auto 0" }}>
          {method === "card"
            ? L(`Payment accepted. Our team will contact you on ${form.phone} to arrange delivery.`,
                `Paiement accepté. Notre équipe vous contactera au ${form.phone} pour organiser la livraison.`)
            : L(`Our team will contact you on ${form.phone} to confirm your order and arrange delivery.`,
                `Notre équipe vous contactera au ${form.phone} pour confirmer votre commande et organiser la livraison.`)}
        </p>
        <p style={{ color: "var(--muted)", fontSize: 13, marginTop: 10 }}>{L("A confirmation will be sent to", "Une confirmation sera envoyée à")} <strong>{form.email || L("your email", "votre email")}</strong></p>
        <button onClick={onClose} className="btn" style={{ marginTop: 28, background: "var(--spares)", color: "#fff", padding: "11px 32px" }}>{L("Back to catalogue →", "Retour au catalogue →")}</button>
      </div>
    </div>
  );

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 210, background: "rgba(28,20,9,.6)", overflow: "auto", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "40px 20px" }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--paper)", borderRadius: 5, maxWidth: 680, width: "100%", boxShadow: "0 30px 80px rgba(0,0,0,.3)" }}>
        {/* Header */}
        <div style={{ padding: "20px 28px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 22 }}>{L("Checkout", "Finaliser la commande")}</div>
          <div style={{ display: "flex", gap: 8 }}>
            {[1,2,3].map(s => (
              <span key={s} style={{ width: 28, height: 28, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 800, fontFamily: "var(--fsemi)", background: step >= s ? "var(--spares)" : "var(--paper-2)", color: step >= s ? "#fff" : "var(--muted)", transition: "all .2s" }}>{s}</span>
            ))}
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)" }}><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg></button>
        </div>

        <div style={{ padding: "24px 28px 28px" }}>
          {/* Step 1 — Contact info */}
          {step === 1 && (
            <div>
              <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--muted)", marginBottom: 18 }}>■ {L("01 / CONTACT INFORMATION", "01 / INFORMATIONS DE CONTACT")}</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <div style={{ gridColumn: "1/-1" }}>
                  <label style={{ display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 }}>{L("Full name", "Nom complet")} *</label>
                  <input value={form.name} onChange={e => set("name", e.target.value)} required style={fInp} placeholder="Ibrahim Moussa" />
                </div>
                <div>
                  <label style={{ display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 }}>{L("Phone / WhatsApp", "Téléphone / WhatsApp")} *</label>
                  <input value={form.phone} onChange={e => set("phone", e.target.value)} required style={fInp} placeholder="+227 XX XX XX XX" />
                </div>
                <div>
                  <label style={{ display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 }}>Email</label>
                  <input type="email" value={form.email} onChange={e => set("email", e.target.value)} style={fInp} placeholder="vous@exemple.com" />
                </div>
                <div style={{ gridColumn: "1/-1" }}>
                  <label style={{ display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 }}>{L("Delivery address", "Adresse de livraison")} *</label>
                  <input value={form.address} onChange={e => set("address", e.target.value)} required style={fInp} placeholder={L("Niamey — Plateau, Koira Tegui…", "Niamey — Plateau, Koira Tegui…")} />
                </div>
                <div style={{ gridColumn: "1/-1" }}>
                  <label style={{ display: "block", fontSize: 11.5, fontFamily: "var(--fsemi)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: "var(--muted)", marginBottom: 5 }}>{L("Notes (optional)", "Notes (facultatif)")}</label>
                  <textarea value={form.notes} onChange={e => set("notes", e.target.value)} rows={2} style={{ ...fInp, resize: "vertical" }} placeholder={L("Vehicle details, urgent need, etc.", "Détails du véhicule, urgence, etc.")} />
                </div>
              </div>
              <button onClick={() => setStep(2)} disabled={!form.name || !form.phone || !form.address} className="btn" style={{ marginTop: 22, background: !form.name || !form.phone || !form.address ? "var(--paper-3)" : "var(--spares)", color: !form.name || !form.phone || !form.address ? "var(--muted)" : "#fff", padding: "11px 28px", cursor: !form.name || !form.phone || !form.address ? "not-allowed" : "pointer" }}>
                {L("Continue to payment →", "Continuer vers le paiement →")}
              </button>
            </div>
          )}

          {/* Step 2 — Payment method */}
          {step === 2 && (
            <div>
              <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--muted)", marginBottom: 18 }}>■ {L("02 / PAYMENT METHOD", "02 / MODE DE PAIEMENT")}</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 22 }}>
                {PAYMENT_METHODS.map(m => (
                  <button key={m.id} onClick={() => setMethod(m.id)} style={{ gridColumn: m.full ? "1/-1" : undefined, display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderRadius: 4, border: `2px solid ${method === m.id ? m.color : "var(--line)"}`, background: method === m.id ? "rgba(0,0,0,.03)" : "var(--paper)", cursor: "pointer", textAlign: "left", transition: "border-color .18s" }}>
                    <span style={{ fontSize: 24 }}>{m.icon}</span>
                    <div>
                      <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{m.label}</div>
                      <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{m.sub}</div>
                    </div>
                    {method === m.id && <span style={{ marginLeft: "auto", width: 20, height: 20, borderRadius: "50%", background: m.color, display: "flex", alignItems: "center", justifyContent: "center" }}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><path d="M20 6 9 17l-5-5"/></svg></span>}
                  </button>
                ))}
              </div>

              {method === "card" && (
                <div style={{ border: "1px solid var(--line)", borderRadius: 4, padding: "16px 18px", marginBottom: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, background: "var(--paper-0)" }}>
                  <div style={{ gridColumn: "1/-1" }}>
                    <label style={lbl}>{L("Card number", "Numéro de carte")} *</label>
                    <input value={card.number} onChange={e => setC("number", fmtCardNum(e.target.value))} inputMode="numeric" autoComplete="cc-number" placeholder="4242 4242 4242 4242" style={fInp} />
                  </div>
                  <div style={{ gridColumn: "1/-1" }}>
                    <label style={lbl}>{L("Name on card", "Nom sur la carte")} *</label>
                    <input value={card.name} onChange={e => setC("name", e.target.value)} autoComplete="cc-name" placeholder="IBRAHIM MOUSSA" style={fInp} />
                  </div>
                  <div>
                    <label style={lbl}>{L("Expiry (MM/YY)", "Expiration (MM/AA)")} *</label>
                    <input value={card.exp} onChange={e => setC("exp", fmtExp(e.target.value))} inputMode="numeric" autoComplete="cc-exp" placeholder="08/27" style={fInp} />
                  </div>
                  <div>
                    <label style={lbl}>CVV *</label>
                    <input value={card.cvv} onChange={e => setC("cvv", e.target.value.replace(/\D/g, "").slice(0, 4))} type="password" inputMode="numeric" autoComplete="cc-csc" placeholder="123" style={fInp} />
                  </div>
                  <div style={{ gridColumn: "1/-1", display: "flex", alignItems: "center", gap: 7, fontSize: 12, color: "var(--muted)" }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="11" width="16" height="9" rx="1.5"></rect><path d="M8 11V7a4 4 0 0 1 8 0v4"></path></svg>
                    {L("Secure SSL payment — your card details are never stored.", "Paiement sécurisé SSL — vos données de carte ne sont jamais conservées.")}
                  </div>
                </div>
              )}

              <div style={{ background: "var(--paper-2)", borderRadius: 4, padding: "14px 18px", marginBottom: 20, fontSize: 13.5, color: "var(--muted)", lineHeight: 1.55 }}>
                {method === "card"         && L("Pay securely by card — Visa, Mastercard and GIM-UEMOA accepted. Your card is debited once the order is confirmed.", "Paiement sécurisé par carte — Visa, Mastercard et GIM-UEMOA acceptées. Votre carte est débitée à la confirmation de la commande.")}
                {method === "orange_money" && L("You will receive an Orange Money payment request on your phone. Payment must be completed within 15 minutes.", "Vous recevrez une demande de paiement Orange Money sur votre téléphone. Le paiement doit être effectué dans les 15 minutes.")}
                {method === "airtel_money" && L("You will receive an Airtel Money payment request. Ensure your account has sufficient balance.", "Vous recevrez une demande de paiement Airtel Money. Assurez-vous que votre compte a un solde suffisant.")}
                {method === "bank"         && L("Our team will send you bank transfer details (BSIC / Ecobank / BIA Niger) after order confirmation.", "Notre équipe vous enverra les coordonnées bancaires (BSIC / Ecobank / BIA Niger) après confirmation de la commande.")}
                {method === "cash"         && L("Pay on delivery — Niamey only. Our driver will collect payment upon delivery.", "Paiement à la livraison — Niamey uniquement. Notre livreur collecte le paiement à la remise des pièces.")}
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <button onClick={() => setStep(1)} style={{ padding: "11px 20px", background: "transparent", border: "1.5px solid var(--line)", borderRadius: 3, cursor: "pointer", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13 }}>← {L("Back", "Retour")}</button>
                <button onClick={() => setStep(3)} disabled={!cardOk} className="btn" style={{ flex: 1, justifyContent: "center", background: cardOk ? "var(--spares)" : "var(--paper-3)", color: cardOk ? "#fff" : "var(--muted)", padding: "11px 0", cursor: cardOk ? "pointer" : "not-allowed" }}>{L("Review order →", "Vérifier la commande →")}</button>
              </div>
            </div>
          )}

          {/* Step 3 — Order summary */}
          {step === 3 && (
            <div>
              <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 11, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--muted)", marginBottom: 18 }}>■ {L("03 / ORDER SUMMARY", "03 / RÉCAPITULATIF")}</div>
              <div style={{ background: "var(--paper-2)", borderRadius: 4, padding: "14px 18px", marginBottom: 14 }}>
                {cart.map(i => (
                  <div key={i.sku} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid var(--line)", fontSize: 14 }}>
                    <span style={{ fontWeight: 600 }}>{i.name} <span style={{ color: "var(--muted)", fontWeight: 400 }}>×{i.qty}</span></span>
                    <span style={{ fontFamily: "var(--fdisp)", fontWeight: 700 }}>{(i.price * i.qty).toLocaleString("fr-FR")} XOF</span>
                  </div>
                ))}
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 20 }}>
                  <span>{L("Total", "Total")}</span>
                  <span style={{ color: "var(--spares)" }}>{total.toLocaleString("fr-FR")} XOF</span>
                </div>
              </div>
              <div style={{ background: "var(--paper-2)", borderRadius: 4, padding: "12px 16px", marginBottom: 20, fontSize: 13.5 }}>
                <div><strong>{form.name}</strong> · {form.phone}</div>
                <div style={{ color: "var(--muted)", marginTop: 4 }}>{form.address}</div>
                <div style={{ color: "var(--spares)", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13, marginTop: 6 }}>
                  {PAYMENT_METHODS.find(m => m.id === method)?.icon} {PAYMENT_METHODS.find(m => m.id === method)?.label}{method === "card" && card.number ? " •••• " + card.number.replace(/\s/g, "").slice(-4) : ""}
                </div>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <button onClick={() => setStep(2)} style={{ padding: "11px 20px", background: "transparent", border: "1.5px solid var(--line)", borderRadius: 3, cursor: "pointer", fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 13 }}>← {L("Back", "Retour")}</button>
                <button onClick={placeOrder} className="btn" style={{ flex: 1, justifyContent: "center", background: "var(--ink)", color: "var(--paper)", padding: "11px 0", fontSize: 15 }}>
                  {method === "card" ? L("Pay " + total.toLocaleString("fr-FR") + " XOF →", "Payer " + total.toLocaleString("fr-FR") + " XOF →") : L("Place Order →", "Confirmer la commande →")}
                </button>
              </div>
              <p style={{ fontSize: 12, color: "var(--muted)", marginTop: 12, textAlign: "center" }}>
                {L("By placing your order you accept our Terms of Service. Prices in XOF (UEMOA).", "En confirmant, vous acceptez nos CGV. Prix en XOF (UEMOA).")}
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

/* ─── Nav basket button (page header, AfricaSpares) ──────── */
function CartNavButton() {
  const { go } = React.useContext(NavCtx);
  const { cart } = useCart();
  const count = cart.reduce((s, i) => s + i.qty, 0);
  return (
    <button onClick={() => go("basket")} className="btn" style={{ marginLeft: 10, background: "var(--spares)", color: "#fff" }}>
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4zM3 6h18M16 10a4 4 0 0 1-8 0"></path></svg>
      {L("Basket", "Panier")}
      {count > 0 && <span style={{ background: "rgba(255,255,255,.28)", borderRadius: 99, padding: "1px 9px", fontSize: 12.5, lineHeight: "18px" }}>{count}</span>}
    </button>
  );
}

Object.assign(window, { CartProvider, CartCtx, useCart, CartButton, CartPanel, CheckoutModal, CartNavButton });
