const CheckoutPage = ({ cart, setCart, setPage, lang, user }) => {
  const t = (en, id) => lang === "id" ? id : en;
  const [step, setStep] = React.useState(1);
  const [orderNumber, setOrderNumber] = React.useState("");
  const [form, setForm] = React.useState({
    name: user?.name || "", email: user?.email || "", phone: "",
    address: "", province: "", city: "", district: "", postal: "", notes: ""
  });
  const [courier,       setCourier]       = React.useState(null);
  const [couriers,      setCouriers]      = React.useState([]);
  const [shippingLoad,  setShippingLoad]  = React.useState(false);
  const [shippingErr,   setShippingErr]   = React.useState("");
  const [payment,       setPayment]       = React.useState("duitku");
  const [postalQueried, setPostalQueried] = React.useState("");
  const [submitting,    setSubmitting]    = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Validasi nomor HP Indonesia: harus diawali 08, total 10–13 digit.
  // Terima juga input berformat 62.. / +62.. / 8.. lalu dinormalkan ke 08..
  const [phoneErr, setPhoneErr] = React.useState("");
  const normalizePhone = (raw) => {
    let d = (raw || "").replace(/[^0-9]/g, "");
    if (d.startsWith("62")) d = "0" + d.slice(2);
    else if (d.startsWith("8")) d = "0" + d;
    return d;
  };
  const isValidPhone = (raw) => /^08\d{8,11}$/.test(normalizePhone(raw));

  // InitiateCheckout — sekali saat halaman checkout dibuka
  React.useEffect(() => {
    if (typeof fbq === 'function') {
      fbq('track', 'InitiateCheckout', {
        content_ids:  cart.map(i => String(i.id)),
        content_type: 'product',
        num_items:    cart.reduce((s, i) => s + i.qty, 0),
        value:        cart.reduce((s, i) => s + i.price * i.qty, 0),
        currency:     'IDR'
      });
    }
  }, []);

  // Load alamat tersimpan saat pertama buka
  React.useEffect(() => {
    if (!user) return;
    fetch("api/account.php", { credentials:"include" })
      .then(r => r.json())
      .then(d => {
        if (d.user?.saved_address) {
          const a = d.user.saved_address;
          setForm(f => ({
            ...f,
            address:  a.address  || f.address,
            district: a.district || f.district,
            city:     a.city     || f.city,
            province: a.province || f.province,
            postal:   a.postal   || f.postal,
          }));
        }
        if (d.user?.phone) setForm(f => ({ ...f, phone: f.phone || d.user.phone }));
      }).catch(() => {});
  }, [user]);
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);

  // Voucher state
  const [voucherCode,   setVoucherCode]   = React.useState("");
  const [voucherInput,  setVoucherInput]  = React.useState("");
  const [voucher,       setVoucher]       = React.useState(null);  // { code, type, value, discount }
  const [voucherErr,    setVoucherErr]    = React.useState("");
  const [voucherChecking, setVoucherChecking] = React.useState(false);

  // Free shipping state
  const [freeShip, setFreeShip] = React.useState(null);  // { eligible, rule } | null

  // Re-validate voucher kalau subtotal berubah (qty change)
  React.useEffect(() => {
    if (!voucher) return;
    fetch("api/promo.php?action=validate_voucher", {
      method:"POST", headers:{"Content-Type":"application/json"},
      body: JSON.stringify({ code: voucher.code, subtotal })
    }).then(r => r.json()).then(d => {
      if (d.success) setVoucher({ ...voucher, discount: d.discount });
      else { setVoucher(null); setVoucherErr(d.error || ""); }
    });
    // eslint-disable-next-line
  }, [subtotal]);

  // Check free shipping eligibility kalau cart/postal berubah
  React.useEffect(() => {
    if (!form.postal || cart.length === 0) { setFreeShip(null); return; }
    fetch("api/promo.php?action=check_free_shipping", {
      method:"POST", headers:{"Content-Type":"application/json"},
      body: JSON.stringify({
        items: cart.map(i => ({ id:i.id, qty:i.qty, price:i.price })),
        subtotal,
        postal: form.postal
      })
    }).then(r => r.json()).then(d => setFreeShip(d)).catch(() => {});
  }, [form.postal, cart.length, subtotal]);

  const applyVoucher = async () => {
    const code = voucherInput.trim().toUpperCase();
    if (!code) { setVoucherErr("Masukkan kode voucher"); return; }
    setVoucherChecking(true);
    setVoucherErr("");
    try {
      const r = await fetch("api/promo.php?action=validate_voucher", {
        method:"POST", headers:{"Content-Type":"application/json"},
        body: JSON.stringify({ code, subtotal })
      });
      const d = await r.json();
      if (d.success) {
        setVoucher({ ...d.voucher, discount: d.discount });
        setVoucherCode(code);
        setVoucherErr("");
      } else {
        setVoucherErr(d.error || "Voucher tidak valid");
        setVoucher(null);
      }
    } catch (e) {
      setVoucherErr("Gagal cek voucher");
    } finally {
      setVoucherChecking(false);
    }
  };

  const removeVoucher = () => {
    setVoucher(null);
    setVoucherCode("");
    setVoucherInput("");
    setVoucherErr("");
    try { localStorage.removeItem("lopobya_pending_voucher"); } catch {}
  };

  // Auto-apply voucher dari Welcome Popup (Meta ads) — sekali saja
  const autoVoucherTried = React.useRef(false);
  React.useEffect(() => {
    if (autoVoucherTried.current || voucher || subtotal <= 0) return;
    let code = "";
    try { code = (localStorage.getItem("lopobya_pending_voucher") || "").trim().toUpperCase(); } catch {}
    if (!code) return;
    autoVoucherTried.current = true;
    fetch("api/promo.php?action=validate_voucher", {
      method:"POST", headers:{"Content-Type":"application/json"},
      body: JSON.stringify({ code, subtotal })
    }).then(r => r.json()).then(d => {
      if (d.success) { setVoucher({ ...d.voucher, discount: d.discount }); setVoucherCode(code); }
    }).catch(() => {});
  }, [subtotal, voucher]);

  // Hitung ongkir & total dengan voucher + free shipping
  // max_subsidy = batas subsidi ongkir (0 = gratis penuh; >0 = gratis s/d nominal itu)
  const courierPrice = courier ? courier.price : 0;
  const isFreeShip   = freeShip?.eligible === true;
  const shipCap      = +(freeShip?.rule?.max_subsidy || 0);
  const shipSubsidy  = isFreeShip ? (shipCap > 0 ? Math.min(courierPrice, shipCap) : courierPrice) : 0;
  const ongkir       = Math.max(0, courierPrice - shipSubsidy);
  const isFullyFree  = isFreeShip && courierPrice > 0 && ongkir === 0;
  const discount     = voucher?.discount || 0;
  const codFee       = (payment === "cod" && courier) ? (Number(courier.cash_on_delivery_fee) || 0) : 0;
  const total        = Math.max(0, subtotal - discount + ongkir + codFee);

  const inputStyle = {
    width:"100%", padding:"12px 14px", background:"#fff",
    border:"1px solid #e8e6e2", fontFamily:"'DM Sans',sans-serif",
    fontSize:13, color:"#111", outline:"none", boxSizing:"border-box",
    transition:"border-color 0.2s", borderRadius:2
  };
  const labelStyle = {
    fontFamily:"'DM Sans',sans-serif", fontSize:10,
    letterSpacing:"0.14em", textTransform:"uppercase",
    color:"#888", display:"block", marginBottom:8, fontWeight:600
  };
  const btnPrimary = {
    padding:"14px 32px", background:"#111", border:"none", cursor:"pointer",
    fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.16em",
    textTransform:"uppercase", color:"#f9f8f6", fontWeight:600, borderRadius:2
  };
  const btnSecondary = {
    padding:"14px 24px", background:"none", border:"1px solid #e8e6e2", cursor:"pointer",
    fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.12em",
    textTransform:"uppercase", color:"#888", borderRadius:2
  };

  // Fetch ongkir dari Biteship
  const fetchRates = async () => {
    if (!form.postal || form.postal.length !== 5) {
      setShippingErr("Kode pos harus 5 digit"); return;
    }
    if (form.postal === postalQueried) return; // sudah pernah dicek
    setShippingLoad(true);
    setShippingErr("");
    setCouriers([]);
    setCourier(null);
    try {
      const res  = await fetch("api/shipping.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          destination_postal: form.postal,
          items: cart.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty })),
          destination_cash_on_delivery: Math.max(0, subtotal - discount)
        })
      });
      const data = await res.json();
      if (!res.ok || data.error) {
        setShippingErr(data.error || "Gagal mengambil tarif pengiriman");
        return;
      }
      const pricing = data.pricing || [];
      if (!pricing.length) {
        setShippingErr("Tidak ada kurir tersedia untuk kode pos ini");
        return;
      }
      // Buang layanan kargo/trucking (freight) yg minimal 10kg — nggak masuk akal
      // buat paket kecil & bikin ongkir kelihatan mahal (mis. JNE Trucking 55rb).
      // Sisakan hanya layanan parcel reguler/express.
      const parcelOnly = pricing.filter(p => (p.shipping_type || "parcel") !== "freight");
      const usable = parcelOnly.length ? parcelOnly : pricing;
      // Deduplikasi: ambil harga termurah per kurir+service
      const seen = new Set();
      const clean = usable
        .filter(p => {
          const key = p.courier_code + "-" + p.courier_service_code;
          if (seen.has(key)) return false;
          seen.add(key);
          return true;
        })
        .sort((a, b) => a.price - b.price);
      setCouriers(clean);
      setCourier(clean[0]); // default pilih yang termurah
      setPostalQueried(form.postal);
    } catch(e) {
      setShippingErr("Gagal terhubung ke server pengiriman");
    } finally {
      setShippingLoad(false);
    }
  };

  // Step 4 — Success
  if (step === 4) return (
    <div style={{ paddingTop:72, minHeight:"100vh", background:"#f9f8f6", display:"flex", alignItems:"center", justifyContent:"center" }}>
      <div style={{ textAlign:"center", maxWidth:520, padding:"0 32px" }}>
        <div style={{ width:72, height:72, border:"1.5px solid #111", borderRadius:"50%", display:"flex", alignItems:"center", justifyContent:"center", margin:"0 auto 32px" }}>
          <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#111" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
        </div>
        <h1 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:42, fontWeight:300, color:"#111", marginBottom:16 }}>
          {t("Order Placed!","Pesanan Diterima!")}
        </h1>
        <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:14, color:"#777", lineHeight:1.8, marginBottom:8 }}>
          {t(`Thank you, ${form.name}! We'll confirm your order shortly.`,
             `Terima kasih, ${form.name}! Kami akan segera konfirmasi pesananmu.`)}
        </p>
        <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa", marginBottom:36 }}>
          {t("Confirmation will be sent to","Konfirmasi dikirim ke")} <strong>{form.email}</strong>
        </p>

        <div style={{ background:"#fff", border:"1px solid #e8e6e2", padding:"24px 28px", marginBottom:32, textAlign:"left", borderRadius:2 }}>
          <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.14em", textTransform:"uppercase", color:"#999", marginBottom:16, fontWeight:600 }}>
            {t("Order Summary","Ringkasan Pesanan")}
          </p>
          {cart.map(item => (
            <div key={item.cartKey} style={{ display:"flex", justifyContent:"space-between", marginBottom:8 }}>
              <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#555" }}>{item.name}{item.selectedVariant ? " — " + item.selectedVariant : ""} ×{item.qty}</span>
              <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#111" }}>{formatPrice(item.price * item.qty)}</span>
            </div>
          ))}
          <div style={{ borderTop:"1px solid #f0efed", paddingTop:12, marginTop:8 }}>
            <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}>
              <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>Subtotal</span>
              <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>{formatPrice(subtotal)}</span>
            </div>
            {courier && (
              <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>{courier.courier_name} {courier.courier_service_name}</span>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>{formatPrice(courier.price)}</span>
              </div>
            )}
            {payment === "cod" && courier && Number(courier.cash_on_delivery_fee) > 0 && (
              <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>Biaya COD</span>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa" }}>{formatPrice(courier.cash_on_delivery_fee)}</span>
              </div>
            )}
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:8 }}>
              <span style={{ fontFamily:"'Cormorant Garant',serif", fontSize:20, color:"#111" }}>Total</span>
              <span style={{ fontFamily:"'Cormorant Garant',serif", fontSize:20, color:"#111" }}>{formatPrice(total)}</span>
            </div>
          </div>
        </div>

        {orderNumber && (
          <div style={{ marginBottom:20 }}>
            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa", marginBottom:8 }}>Nomor Pesananmu:</p>
            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:16, fontWeight:700, letterSpacing:"0.06em", color:"#111", marginBottom:12 }}>{orderNumber}</p>
            <a href={"tracking.html?order="+orderNumber} target="_blank"
              style={{ display:"inline-block", padding:"10px 24px", border:"1px solid #111", color:"#111", textDecoration:"none", fontFamily:"'DM Sans',sans-serif", fontSize:11, letterSpacing:"0.12em", textTransform:"uppercase", marginBottom:16 }}>
              🚚 Lacak Pesanan
            </a>
          </div>
        )}
        <button onClick={() => { setCart([]); setPage("home"); }} style={btnPrimary}>
          {t("Back to Home","Kembali ke Beranda")}
        </button>
      </div>
    </div>
  );

  const steps = [t("Information","Informasi"), t("Shipping","Pengiriman"), t("Payment","Pembayaran")];

  return (
    <div style={{ paddingTop:72, minHeight:"100vh", background:"#f9f8f6" }}>
      <div className="lpb-checkout-wrap" style={{ maxWidth:1100, margin:"0 auto", padding:"48px 24px" }}>
        {/* Header */}
        <div style={{ textAlign:"center", marginBottom:48 }}>
          <img src="uploads/logo-1777527805215.jpg" alt="LOPOBYA" style={{ height:36, marginBottom:32 }} />
          <div className="lpb-checkout-steps" style={{ display:"flex", justifyContent:"center", alignItems:"center" }}>
            {steps.map((s, i) => (
              <React.Fragment key={i}>
                <div style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:6 }}>
                  <div style={{
                    width:28, height:28, borderRadius:"50%",
                    background: step > i+1 ? "#111" : step === i+1 ? "#111" : "#e8e6e2",
                    display:"flex", alignItems:"center", justifyContent:"center"
                  }}>
                    {step > i+1
                      ? <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#f9f8f6" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>
                      : <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:step===i+1?"#f9f8f6":"#aaa", fontWeight:600 }}>{i+1}</span>
                    }
                  </div>
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.1em", textTransform:"uppercase", color:step===i+1?"#111":"#bbb" }}>{s}</span>
                </div>
                {i < steps.length-1 && <div className="lpb-step-line" style={{ width:60, height:1, background:step>i+1?"#111":"#e8e6e2", margin:"0 8px", marginBottom:24, flexShrink:0 }} />}
              </React.Fragment>
            ))}
          </div>
        </div>

        <div className="lpb-checkout-grid" style={{ display:"grid", gridTemplateColumns:"1fr 360px", gap:40, alignItems:"start" }}>
          {/* Form */}
          <div className="lpb-checkout-card" style={{ background:"#fff", border:"1px solid #e8e6e2", padding:"36px 40px", borderRadius:2 }}>

            {/* ── Step 1: Informasi Kontak ── */}
            {step === 1 && (
              <div>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:28, fontWeight:400, color:"#111", marginBottom:32 }}>
                  {t("Contact Information","Informasi Kontak")}
                </h2>
                <div style={{ display:"flex", flexDirection:"column", gap:20 }}>
                  <div>
                    <label style={labelStyle}>{t("Full Name","Nama Lengkap")} *</label>
                    <input style={inputStyle} value={form.name} onChange={e => set("name",e.target.value)} placeholder={t("Your full name","Nama lengkap kamu")} />
                  </div>
                  <div className="lpb-form-2col" style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:16 }}>
                    <div>
                      <label style={labelStyle}>Email *</label>
                      <input style={inputStyle} type="email" value={form.email} onChange={e => set("email",e.target.value)} placeholder="email@example.com" />
                    </div>
                    <div>
                      <label style={labelStyle}>{t("Phone / WhatsApp","HP / WhatsApp")} *</label>
                      <input style={{ ...inputStyle, ...(phoneErr ? { borderColor:"#e55" } : {}) }} value={form.phone}
                        onChange={e => { set("phone", e.target.value); if (phoneErr) setPhoneErr(""); }}
                        placeholder="08xx xxxx xxxx" inputMode="numeric" />
                      {phoneErr && <p style={{ color:"#e55", fontSize:12, marginTop:6 }}>{phoneErr}</p>}
                    </div>
                  </div>
                </div>
                <button
                  onClick={() => {
                    if (!form.name || !form.email) return;
                    if (!isValidPhone(form.phone)) {
                      setPhoneErr(t("Enter a valid Indonesian mobile number, e.g. 081234567890","Masukkan nomor HP yang valid, contoh 081234567890"));
                      return;
                    }
                    setStep(2);
                  }}
                  style={{ ...btnPrimary, marginTop:32 }}
                >{t("Continue to Shipping","Lanjut ke Pengiriman")}</button>
              </div>
            )}

            {/* ── Step 2: Alamat + Kurir ── */}
            {step === 2 && (
              <div>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:28, fontWeight:400, color:"#111", marginBottom:32 }}>
                  {t("Shipping Address","Alamat Pengiriman")}
                </h2>
                <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
                  <div>
                    <label style={labelStyle}>{t("Street Address","Alamat Jalan")} *</label>
                    <input style={inputStyle} value={form.address} onChange={e => set("address",e.target.value)} placeholder={t("Street, No., RT/RW","Jalan, No., RT/RW")} />
                  </div>
                  <AreaSearch
                    value={form.city}
                    district={form.district}
                    province={form.province}
                    postal={form.postal}
                    onChange={(city, district, province, postal, area_id) => {
                      set("city", city);
                      set("district", district);
                      set("province", province);
                      if (postal) {
                        set("postal", postal);
                        setPostalQueried("");
                        setCouriers([]);
                        setCourier(null);
                      }
                    }}
                  />
                  <div>
                    <label style={labelStyle}>{t("ZIP Code","Kode Pos")} *</label>
                    <div style={{ display:"flex", gap:8 }}>
                      <input
                        style={{ ...inputStyle, flex:1 }}
                        value={form.postal}
                        onChange={e => { set("postal",e.target.value.replace(/\D/g,"")); setPostalQueried(""); setCouriers([]); setCourier(null); }}
                        maxLength={5}
                        placeholder="16680"
                        onKeyDown={e => e.key==="Enter" && fetchRates()}
                      />
                      <button
                        onClick={fetchRates}
                        disabled={shippingLoad || form.postal.length !== 5}
                        style={{ ...btnPrimary, padding:"12px 16px", fontSize:10, flexShrink:0, opacity:(shippingLoad||form.postal.length!==5)?0.5:1 }}
                      >{shippingLoad ? "..." : t("Check","Cek")}</button>
                    </div>
                  </div>

                  <div>
                    <label style={labelStyle}>{t("Notes (optional)","Catatan (opsional)")}</label>
                    <textarea style={{ ...inputStyle, height:72, resize:"vertical" }} value={form.notes} onChange={e => set("notes",e.target.value)} placeholder={t("Landmark, floor, etc.","Patokan, lantai, dll.")} />
                  </div>
                </div>

                {/* Shipping error */}
                {shippingErr && (
                  <div style={{ marginTop:20, padding:"12px 16px", background:"#fff5f5", border:"1px solid #fcc", borderRadius:2 }}>
                    <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#c55" }}>⚠ {shippingErr}</p>
                  </div>
                )}

                {/* Kurir list */}
                {shippingLoad && (
                  <div style={{ marginTop:24, textAlign:"center", padding:"24px" }}>
                    <div style={{ display:"inline-block", width:24, height:24, border:"2px solid #e8e6e2", borderTopColor:"#111", borderRadius:"50%", animation:"spin 0.8s linear infinite" }} />
                    <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#aaa", marginTop:12 }}>Mengambil tarif pengiriman...</p>
                    <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
                  </div>
                )}

                {couriers.length > 0 && (
                  <div style={{ marginTop:24 }}>
                    <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.14em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:12 }}>
                      {t("Choose Courier","Pilih Kurir")} — {couriers.length} {t("options available","opsi tersedia")}
                    </p>
                    <div style={{ display:"flex", flexDirection:"column", gap:10, maxHeight:300, overflowY:"auto" }}>
                      {couriers.map((c, i) => (
                        <div
                          key={i}
                          onClick={() => setCourier(c)}
                          style={{
                            padding:"14px 18px", cursor:"pointer", borderRadius:2,
                            border: courier && courier.courier_code===c.courier_code && courier.courier_service_code===c.courier_service_code
                              ? "2px solid #111" : "1px solid #e8e6e2",
                            display:"flex", justifyContent:"space-between", alignItems:"center",
                            transition:"border-color 0.15s", background:"#fff"
                          }}
                        >
                          <div>
                            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, fontWeight:500, color:"#111", margin:0 }}>
                              {c.courier_name} <span style={{ fontWeight:400, color:"#888" }}>{c.courier_service_name}</span>
                            </p>
                            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:"#aaa", margin:"3px 0 0", display:"flex", alignItems:"center", gap:6 }}>
                              <span>{c.duration || "Estimasi 2-5 hari"}</span>
                              {c.available_for_cash_on_delivery && (
                                <span style={{ background:"#e6f4ea", color:"#137333", fontSize:9, padding:"2px 6px", borderRadius:10, fontWeight:700 }}>BISA COD</span>
                              )}
                            </p>
                          </div>
                          <div style={{ textAlign:"right" }}>
                            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:14, fontWeight:600, color:"#111", margin:0 }}>
                              {formatPrice(c.price)}
                            </p>
                            <div style={{ width:16, height:16, borderRadius:"50%", border:"2px solid", borderColor:courier && courier.courier_code===c.courier_code && courier.courier_service_code===c.courier_service_code?"#111":"#ddd", display:"flex", alignItems:"center", justifyContent:"center", marginLeft:"auto", marginTop:4 }}>
                              {courier && courier.courier_code===c.courier_code && courier.courier_service_code===c.courier_service_code && <div style={{ width:7, height:7, borderRadius:"50%", background:"#111" }} />}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div style={{ display:"flex", gap:12, marginTop:32 }}>
                  <button onClick={() => setStep(1)} style={btnSecondary}>{t("Back","Kembali")}</button>
                  <button
                    onClick={() => {
                      if (form.address && form.city && form.postal && courier) {
                        if (payment === "cod" && !courier.available_for_cash_on_delivery) {
                          setPayment("duitku");
                        }
                        setStep(3);
                      }
                    }}
                    disabled={!courier}
                    style={{ ...btnPrimary, opacity:!courier?0.45:1, cursor:!courier?"not-allowed":"pointer" }}
                  >
                    {couriers.length === 0 && !shippingLoad
                      ? t("Check postal code first","Cek kode pos dulu")
                      : t("Continue to Payment","Lanjut ke Pembayaran")
                    }
                  </button>
                </div>
              </div>
            )}

            {/* ── Step 3: Pembayaran ── */}
            {step === 3 && (
              <div>
                <h2 style={{ fontFamily:"'Cormorant Garant',serif", fontSize:28, fontWeight:400, color:"#111", marginBottom:32 }}>
                  {t("Payment Method","Metode Pembayaran")}
                </h2>

                {/* Ringkasan pengiriman */}
                <div style={{ background:"#f9f8f6", border:"1px solid #e8e6e2", padding:"14px 18px", borderRadius:2, marginBottom:24 }}>
                  <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#aaa", fontWeight:600, marginBottom:8 }}>Pengiriman Dipilih</p>
                  <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
                    <div>
                      <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color:"#111", margin:0, fontWeight:500 }}>
                        {courier.courier_name} — {courier.courier_service_name}
                      </p>
                      <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:"#aaa", margin:"2px 0 0" }}>
                        {form.city}, {form.postal} · {courier.duration || "2-5 hari"}
                      </p>
                    </div>
                    <div style={{ display:"flex", alignItems:"center", gap:12 }}>
                      <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:14, fontWeight:600, color:"#111", margin:0 }}>{formatPrice(courier.price)}</p>
                      <button onClick={() => setStep(2)} style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:"#888", background:"none", border:"none", cursor:"pointer", textDecoration:"underline" }}>Ubah</button>
                    </div>
                  </div>
                </div>

                <div style={{ display:"flex", flexDirection:"column", gap:10, marginBottom:32 }}>
                  {[
                    { id:"duitku", label:"Bayar Sekarang", sub:"QRIS / Transfer Bank / GoPay / OVO / DANA / Kartu Kredit", highlight:true },
                    { id:"cod",    label:t("Cash on Delivery","Bayar di Tempat (COD)"), sub:t("Available in select areas","Tersedia di area tertentu"), disabled: courier && !courier.available_for_cash_on_delivery },
                  ].map(m => {
                    const isDisabled = m.disabled;
                    return (
                      <div key={m.id}
                        onClick={() => { if (!isDisabled) setPayment(m.id); }}
                        style={{
                          padding:"16px 20px",
                          border: payment===m.id && !isDisabled ? "2px solid #111" : "1px solid #e8e6e2",
                          cursor: isDisabled ? "not-allowed" : "pointer",
                          display:"flex",
                          justifyContent:"space-between",
                          alignItems:"center",
                          transition:"border-color 0.15s",
                          borderRadius:2,
                          opacity: isDisabled ? 0.55 : 1,
                          background: isDisabled ? "#fcfcfc" : "#fff"
                        }}
                      >
                        <div>
                          <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:13, color: isDisabled ? "#888" : "#111", margin:0, fontWeight:payment===m.id && !isDisabled?600:400 }}>
                            {m.highlight && <span style={{ background:"#22c55e", color:"#fff", fontSize:9, padding:"2px 6px", borderRadius:10, marginRight:6, fontWeight:700 }}>RECOMMENDED</span>}
                            {m.label}
                          </p>
                          <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color: isDisabled ? "#e55" : "#aaa", margin:"2px 0 0" }}>
                            {isDisabled ? "⚠ Kurir yang dipilih tidak mendukung COD" : m.sub}
                          </p>
                        </div>
                        <div style={{ width:18, height:18, borderRadius:"50%", border:"2px solid", borderColor:payment===m.id && !isDisabled?"#111":"#ddd", display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}>
                          {payment===m.id && !isDisabled && <div style={{ width:8, height:8, borderRadius:"50%", background:"#111" }} />}
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div style={{ display:"flex", gap:12 }}>
                  <button onClick={() => setStep(2)} style={btnSecondary}>{t("Back","Kembali")}</button>
                  <button
                    disabled={submitting}
                    onClick={async () => {
                      if (submitting) return;
                      setSubmitting(true);
                      try {
                        // 1. Simpan order ke DB
                        const res = await fetch("api/order.php", {
                          method:"POST",
                          headers:{"Content-Type":"application/json"},
                          body: JSON.stringify({
                            name: form.name, email: form.email, phone: form.phone,
                            address: form.address, district: form.district,
                            city: form.city, province: form.province,
                            postal: form.postal, notes: form.notes,
                            items: cart.map(i => ({ id:i.id, name:i.name, price:i.price, qty:i.qty, image:i.image, selectedColor:i.selectedColor||"", selectedSize:i.selectedSize||"", selectedVariant:i.selectedVariant||"" })),
                            subtotal, shipping_cost: ongkir, total,
                            discount_amount: discount,
                            voucher_code: voucher?.code || null,
                            free_shipping_rule_id: isFreeShip ? freeShip?.rule?.id : null,
                            courier_name: courier?.courier_code||"",
                            courier_service: courier?.courier_service_code||"",
                            courier_etd: courier?.duration||"",
                            payment_method: payment,
                            cod_fee: codFee,
                            // Meta CAPI match params — dibaca server utk match quality + dedup
                            fbp: (document.cookie.match(/_fbp=([^;]+)/)||[])[1] || "",
                            fbc: (document.cookie.match(/_fbc=([^;]+)/)||[])[1] || "",
                            event_source_url: window.location.href
                          })
                        });
                        const data = await res.json();
                        if (!data.success) {
                          alert("Gagal membuat pesanan: " + (data.error||""));
                          setSubmitting(false);
                          return;
                        }

                        setOrderNumber(data.order_number);

                        // 2. Kalau Duitku, tampilkan POP popup
                        if (payment === "duitku") {
                          const payRes = await fetch("api/payment.php", {
                            method:"POST", headers:{"Content-Type":"application/json"},
                            body: JSON.stringify({ order_number: data.order_number })
                          });
                          const payData = await payRes.json();
                          if (!payData.success || !payData.reference) {
                            alert("Gagal init pembayaran: " + (payData.error || "Unknown error"));
                            setSubmitting(false);
                            return;
                          }

                          // Load Duitku POP script
                          if (!window.checkout || typeof window.checkout.process !== "function") {
                            await new Promise((resolve, reject) => {
                              const s = document.createElement("script");
                              s.src = payData.popUrl || "https://app-sandbox.duitku.com/lib/js/duitku.js";
                              s.onload  = resolve;
                              s.onerror = () => reject(new Error("Failed to load Duitku script"));
                              document.head.appendChild(s);
                            }).catch(err => {
                              alert("Gagal memuat Duitku: " + err.message);
                              setSubmitting(false);
                              throw err;
                            });
                          }

                          const firePurchase = () => {
                            if (typeof fbq === 'function') {
                              fbq('track', 'Purchase', {
                                content_ids:  cart.map(i => String(i.id)),
                                content_type: 'product',
                                value:        total,
                                currency:     'IDR',
                                num_items:    cart.reduce((s, i) => s + i.qty, 0)
                              }, { eventID: 'purchase_' + data.id });
                            }
                          };
                          window.checkout.process(payData.reference, {
                            successEvent: () => { firePurchase(); setStep(4); },
                            pendingEvent: () => setStep(4),
                            errorEvent:   (e) => {
                              alert("Pembayaran gagal: " + (e?.message || JSON.stringify(e)));
                              setSubmitting(false);
                            },
                            closeEvent:   () => {
                              setSubmitting(false);
                            },
                          });
                        } else {
                          // COD - langsung ke step 4
                          if (typeof fbq === 'function') {
                            fbq('track', 'Purchase', {
                              content_ids:  cart.map(i => String(i.id)),
                              content_type: 'product',
                              value:        total,
                              currency:     'IDR',
                              num_items:    cart.reduce((s, i) => s + i.qty, 0)
                            }, { eventID: 'purchase_' + data.id });
                          }
                          setStep(4);
                        }
                      } catch(e) {
                        alert("Gagal terhubung ke server: " + e.message);
                        setSubmitting(false);
                      }
                    }}
                    style={{
                      ...btnPrimary,
                      opacity: submitting ? 0.6 : 1,
                      cursor: submitting ? "not-allowed" : "pointer"
                    }}
                  >
                    {submitting ? t("Processing...", "Memproses...") : t("Place Order", "Buat Pesanan")}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* ── Sidebar Ringkasan ── */}
          <div style={{ background:"#fff", border:"1px solid #e8e6e2", padding:"28px 32px", borderRadius:2, position:"sticky", top:100 }}>
            <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.16em", textTransform:"uppercase", color:"#999", marginBottom:20, fontWeight:600 }}>
              {t("Order Summary","Ringkasan Pesanan")}
            </p>
            {cart.map(item => (
              <div key={item.cartKey} style={{ display:"flex", gap:14, marginBottom:16 }}>
                <div style={{ width:56, height:56, background:"#f0efed", flexShrink:0, overflow:"hidden", position:"relative", borderRadius:2 }}>
                  <img src={item.image} alt={item.name} style={{ width:"100%", height:"100%", objectFit:"cover" }} />
                  <span style={{ position:"absolute", top:-6, right:-6, background:"#111", color:"#fff", borderRadius:"50%", width:18, height:18, fontSize:9, display:"flex", alignItems:"center", justifyContent:"center", fontFamily:"'DM Sans',sans-serif" }}>{item.qty}</span>
                </div>
                <div style={{ flex:1 }}>
                  <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#111", margin:0, fontWeight:500 }}>{item.name}</p>
                  {(() => {
                    const sameCV = item.selectedColor && item.selectedVariant
                      && String(item.selectedColor).toLowerCase().trim() === String(item.selectedVariant).toLowerCase().trim();
                    const opts = [item.selectedVariant, sameCV ? null : item.selectedColor, item.selectedSize].filter(Boolean);
                    return opts.length > 0 ? <p style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:"#777", margin:"2px 0 0", fontWeight:500 }}>{opts.join(" · ")}</p> : null;
                  })()}
                </div>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#111", whiteSpace:"nowrap" }}>{formatPrice(item.price*item.qty)}</span>
              </div>
            ))}
            <div style={{ borderTop:"1px solid #e8e6e2", paddingTop:16, marginTop:8 }}>
              {/* ── Voucher input ────────────────────────── */}
              {!voucher ? (
                <div style={{ marginBottom:14 }}>
                  <label style={{ display:"block", fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", color:"#888", fontWeight:600, marginBottom:6 }}>
                    🎟 {t("Voucher Code","Kode Voucher")}
                  </label>
                  <div style={{ display:"flex", gap:6 }}>
                    <input value={voucherInput}
                      onChange={e => setVoucherInput(e.target.value.toUpperCase())}
                      onKeyDown={e => { if (e.key === "Enter") applyVoucher(); }}
                      placeholder={t("Enter code","Masukkan kode")}
                      style={{ flex:1, padding:"9px 12px", border:"1px solid #e0deda", background:"#fff", fontFamily:"monospace", fontSize:12, letterSpacing:"0.05em", color:"#111", outline:"none", borderRadius:2 }} />
                    <button onClick={applyVoucher} disabled={voucherChecking}
                      style={{ padding:"9px 14px", background:"#111", color:"#fff", border:"none", fontFamily:"'DM Sans',sans-serif", fontSize:10, letterSpacing:"0.12em", textTransform:"uppercase", fontWeight:600, cursor:"pointer", borderRadius:2 }}>
                      {voucherChecking ? "..." : t("Apply","Terapkan")}
                    </button>
                  </div>
                  {voucherErr && (
                    <p style={{ fontSize:11, color:"#c55", marginTop:6 }}>⚠ {voucherErr}</p>
                  )}
                </div>
              ) : (
                <div style={{ background:"#f0fdf4", border:"1px solid #86efac", padding:"10px 12px", borderRadius:3, marginBottom:14, display:"flex", justifyContent:"space-between", alignItems:"center" }}>
                  <div>
                    <p style={{ fontSize:10, letterSpacing:"0.1em", color:"#15803d", fontWeight:600, textTransform:"uppercase" }}>✓ Voucher Aktif</p>
                    <p style={{ fontFamily:"monospace", fontSize:12, color:"#111", marginTop:2 }}>{voucher.code}</p>
                  </div>
                  <button onClick={removeVoucher}
                    style={{ background:"none", border:"none", color:"#c55", fontSize:11, cursor:"pointer", textDecoration:"underline" }}>
                    Hapus
                  </button>
                </div>
              )}

              <div style={{ display:"flex", justifyContent:"space-between", marginBottom:8 }}>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#888" }}>Subtotal</span>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#888" }}>{formatPrice(subtotal)}</span>
              </div>

              {/* Voucher discount */}
              {voucher && voucher.discount > 0 && (
                <div style={{ display:"flex", justifyContent:"space-between", marginBottom:8 }}>
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#15803d" }}>
                    {t("Voucher discount","Diskon voucher")}
                  </span>
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#15803d", fontWeight:600 }}>
                    -{formatPrice(voucher.discount)}
                  </span>
                </div>
              )}

              <div style={{ display:"flex", justifyContent:"space-between", marginBottom: (isFreeShip && shipSubsidy > 0) ? 4 : 16 }}>
                <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#888" }}>{t("Shipping","Ongkir")}</span>
                {isFreeShip && shipSubsidy > 0 ? (
                  <span style={{ display:"flex", gap:6, alignItems:"center" }}>
                    <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:11, color:"#aaa", textDecoration:"line-through" }}>
                      {courier ? formatPrice(courier.price) : ""}
                    </span>
                    <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#15803d", fontWeight:700 }}>
                      {isFullyFree ? t("FREE","GRATIS") : formatPrice(ongkir)}
                    </span>
                  </span>
                ) : (
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color: courier?"#111":"#aaa" }}>
                    {courier ? formatPrice(courier.price) : t("Select courier","Pilih kurir dulu")}
                  </span>
                )}
              </div>
              {isFreeShip && shipSubsidy > 0 && freeShip?.rule && (
                <p style={{ fontSize:10, color:"#15803d", marginBottom:16, lineHeight:1.5 }}>
                  🎁 {freeShip.rule.name}
                  {!isFullyFree && ` · ${t("shipping subsidy","subsidi ongkir")} -${formatPrice(shipSubsidy)}`}
                </p>
              )}

              {payment === "cod" && courier && Number(courier.cash_on_delivery_fee) > 0 && (
                <div style={{ display:"flex", justifyContent:"space-between", marginBottom: 16 }}>
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#888" }}>Biaya COD</span>
                  <span style={{ fontFamily:"'DM Sans',sans-serif", fontSize:12, color:"#111", fontWeight: 600 }}>{formatPrice(courier.cash_on_delivery_fee)}</span>
                </div>
              )}

              <div style={{ borderTop:"1px solid #f0efed", paddingTop:12, display:"flex", justifyContent:"space-between" }}>
                <span style={{ fontFamily:"'Cormorant Garant',serif", fontSize:20, color:"#111" }}>Total</span>
                <span style={{ fontFamily:"'Cormorant Garant',serif", fontSize:20, color:"#111" }}>{formatPrice(total)}</span>
              </div>
            </div>
            {courier && (
              <div style={{ marginTop:16, padding:"10px 14px", background:"#f9f8f6", borderRadius:2, fontSize:11, color:"#888", fontFamily:"'DM Sans',sans-serif" }}>
                🚚 {courier.courier_name} {courier.courier_service_name} · {courier.duration||"2-5 hari"}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};
Object.assign(window, { CheckoutPage });
