/* ============================================================
   AfricaSpares — Basket page (standard e-commerce cart)
   Route: #basket — cart state is shared via localStorage
   ============================================================ */

function BasketPage() {
  return (
    <CartProvider>
      <div className="view" data-screen-label="Basket" style={{ "--accent": "var(--spares)", "--accent-d": "var(--spares-d)", minHeight: "100vh", display: "flex", flexDirection: "column" }}>
        <Nav variant="spares" />
        <BasketBody />
        <Footer variant="spares" />
      </div>
    </CartProvider>
  );
}

function BasketBody() {
  const { cart, clearCart } = useCart();
  const { go } = useContext(NavCtx);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const count = cart.reduce((s, i) => s + i.qty, 0);

  return (
    <section style={{ paddingTop: 136, paddingBottom: 100, background: "var(--paper)", flex: 1 }}>
      <style>{`@media (max-width:560px){.bk-row{grid-template-columns:72px 1fr !important}.bk-total{grid-column:1/-1;text-align:left !important;margin-top:2px}}`}</style>
      <div className="wrap">
        <Reveal><SectionTag color="var(--spares-d)">{L("AfricaSpares · Secure checkout", "AfricaSpares · Commande sécurisée")}</SectionTag></Reveal>
        <Reveal delay={60}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 18, flexWrap: "wrap", marginTop: 18 }}>
            <h1 style={{ fontSize: "clamp(40px,5.5vw,76px)" }}>{L("Your Basket", "Votre Panier")}<span style={{ color: "var(--spares)" }}>.</span></h1>
            {count > 0 && <span style={{ color: "var(--muted)", fontSize: 17 }}>{count} {count > 1 ? L("items", "articles") : L("item", "article")}</span>}
          </div>
        </Reveal>

        {cart.length === 0 ? (
          <EmptyBasket onBrowse={() => go("spares")} />
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "1.65fr 1fr", gap: 56, marginTop: 40, alignItems: "start" }} className="g2">
            {/* ITEMS */}
            <div>
              <div style={{ borderTop: "2px solid var(--ink)" }}>
                {cart.map((item) => <BasketRow key={item.sku} item={item} />)}
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 20, flexWrap: "wrap", gap: 12 }}>
                <button onClick={() => go("spares")} className="lnk" style={{ color: "var(--spares-d)" }}>← {L("Continue shopping", "Continuer mes achats")}</button>
                <button onClick={clearCart} style={{ color: "var(--muted)", fontSize: 13.5, textDecoration: "underline", background: "none", border: "none", cursor: "pointer" }}>{L("Empty basket", "Vider le panier")}</button>
              </div>
            </div>
            {/* SUMMARY */}
            <BasketSummary onCheckout={() => setCheckoutOpen(true)} />
          </div>
        )}
      </div>
      <CheckoutModal open={checkoutOpen} onClose={() => setCheckoutOpen(false)} />
    </section>
  );
}

/* ─── Single basket line ─────────────────────────────────── */
const basketQtyBtn = { width: 34, height: 34, display: "flex", alignItems: "center", justifyContent: "center", background: "none", border: "none", cursor: "pointer", color: "var(--ink)", fontSize: 17 };

function BasketRow({ item }) {
  const { updateQty, removeItem } = useCart();
  const img = item.img || (window.PARTS_IMGS ? window.PARTS_IMGS[item.name] : null);
  return (
    <div className="bk-row" style={{ display: "grid", gridTemplateColumns: "96px 1fr auto", gap: 20, alignItems: "start", padding: "22px 0", borderBottom: "1px solid var(--line)" }}>
      <div style={{ width: "100%", aspectRatio: "1", background: "var(--paper-0)", border: "1px solid var(--line)", borderRadius: 4, overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center", padding: 8 }}>
        {img
          ? <img src={img} alt={item.name} style={{ width: "100%", height: "100%", objectFit: "contain", mixBlendMode: "multiply" }} loading="lazy" />
          : <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--muted)" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="2"></rect><path d="M3 9h18M9 21V9"></path></svg>}
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 17.5, lineHeight: 1.25 }}>{item.name}</div>
        <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 4 }}>{item.sku} · {L("Fits", "Compatible")}: {item.fit}</div>
        <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginTop: 4 }}>{item.price.toLocaleString("fr-FR")} FCFA {L("each", "/ unité")}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 12, flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--line)", borderRadius: 3, overflow: "hidden", background: "var(--paper-0)" }}>
            <button onClick={() => updateQty(item.sku, item.qty - 1)} aria-label={L("Decrease quantity", "Diminuer la quantité")} style={basketQtyBtn}>−</button>
            <span style={{ width: 36, textAlign: "center", fontSize: 14.5, fontWeight: 700 }}>{item.qty}</span>
            <button onClick={() => updateQty(item.sku, item.qty + 1)} aria-label={L("Increase quantity", "Augmenter la quantité")} style={basketQtyBtn}>+</button>
          </div>
          <button onClick={() => removeItem(item.sku)} style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "#991B1B", fontSize: 13, background: "none", border: "none", cursor: "pointer", fontFamily: "var(--fsemi)", fontWeight: 700 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"></path></svg>
            {L("Remove", "Retirer")}
          </button>
        </div>
      </div>
      <div className="bk-total" style={{ textAlign: "right", fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 22, lineHeight: 1 }}>
        {(item.price * item.qty).toLocaleString("fr-FR")} <span style={{ fontSize: 13, color: "var(--muted)", fontFamily: "var(--fbody)", fontWeight: 600 }}>FCFA</span>
      </div>
    </div>
  );
}

/* ─── Order summary (sticky) ─────────────────────────────── */
function BasketSummary({ onCheckout }) {
  const { cart, total } = useCart();
  const count = cart.reduce((s, i) => s + i.qty, 0);
  return (
    <div style={{ position: "sticky", top: 96 }}>
      <div style={{ background: "var(--paper-0)", border: "1px solid var(--line)", borderRadius: 5, padding: "26px 26px 28px" }}>
        <div style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 24 }}>{L("Order Summary", "Récapitulatif")}</div>
        <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 11, fontSize: 14.5 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span style={{ color: "var(--ink-2)" }}>{L("Subtotal", "Sous-total")} ({count} {count > 1 ? L("items", "articles") : L("item", "article")})</span>
            <span style={{ fontWeight: 700 }}>{total.toLocaleString("fr-FR")} FCFA</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <span style={{ color: "var(--ink-2)" }}>{L("Delivery — Niamey (25 km)", "Livraison — Niamey (25 km)")}</span>
            <span style={{ color: "oklch(0.5 0.1 150)", fontWeight: 700 }}>{L("Free", "Offerte")}</span>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--muted)", lineHeight: 1.5 }}>{L("Outside Niamey: shipping quoted after order confirmation.", "Hors Niamey : frais de livraison calculés après confirmation de la commande.")}</div>
        </div>
        <hr className="rule" style={{ margin: "16px 0" }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <span style={{ fontFamily: "var(--fsemi)", fontWeight: 700, fontSize: 16 }}>Total</span>
          <span style={{ fontFamily: "var(--fdisp)", fontWeight: 800, fontSize: 28 }}>{total.toLocaleString("fr-FR")} <span style={{ fontSize: 14, fontFamily: "var(--fbody)", fontWeight: 600, color: "var(--muted)" }}>FCFA</span></span>
        </div>
        <button onClick={onCheckout} className="btn" style={{ width: "100%", justifyContent: "center", background: "var(--spares)", color: "#fff", fontSize: 15, padding: "14px 0", marginTop: 18 }}>
          {L("Proceed to payment →", "Passer au paiement →")}
        </button>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, marginTop: 12, fontSize: 12.5, 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("100% secure payment", "Paiement 100% sécurisé")}
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "center", marginTop: 10 }}>
          {["VISA", "Mastercard", "Orange Money", "Airtel Money"].map((p) => (
            <span key={p} style={{ border: "1px solid var(--line)", borderRadius: 3, padding: "3px 9px", fontSize: 11, fontFamily: "var(--fsemi)", fontWeight: 700, letterSpacing: ".04em", color: "var(--ink-2)", background: "var(--paper)" }}>{p}</span>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 9 }}>
        {[
          ["shield", L("Fitment & quality warranty on every part", "Garantie conformité & qualité sur chaque pièce")],
          ["truck", L("Fast dispatch across Niger", "Expédition rapide dans tout le Niger")],
          ["users", L("Technical support — send your VIN to confirm fitment", "Support technique — envoyez votre VIN pour confirmer la compatibilité")],
        ].map(([ic, t]) => (
          <div key={ic} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13.5, color: "var(--ink-2)" }}>
            <span style={{ color: "var(--spares-d)", display: "flex" }}><Icon name={ic} size={17} /></span>{t}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Empty state ────────────────────────────────────────── */
function EmptyBasket({ onBrowse }) {
  return (
    <div style={{ textAlign: "center", padding: "80px 20px 50px", maxWidth: 460, margin: "0 auto" }}>
      <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="var(--muted)" strokeWidth="1.2" style={{ margin: "0 auto 18px", display: "block" }}><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>
      <h3 style={{ fontSize: 30 }}>{L("Your basket is empty", "Votre panier est vide")}</h3>
      <p style={{ color: "var(--muted)", marginTop: 10, fontSize: 15.5, lineHeight: 1.6 }}>{L("Browse the AfricaSpares catalogue and add the parts you need.", "Parcourez le catalogue AfricaSpares et ajoutez les pièces dont vous avez besoin.")}</p>
      <button onClick={onBrowse} className="btn" style={{ marginTop: 24, background: "var(--spares)", color: "#fff" }}>{L("Browse the catalogue →", "Parcourir le catalogue →")}</button>
    </div>
  );
}

Object.assign(window, { BasketPage });
