/* Cart drawer + Tweaks panel */

// Governorate values stay English (stored/sent to the backend unchanged) but
// carry an Arabic display label so the checkout select reads correctly in RTL.
const EG_GOVS = [
  { value: "Cairo",          ar: "القاهرة" },
  { value: "Giza",           ar: "الجيزة" },
  { value: "Alexandria",     ar: "الإسكندرية" },
  { value: "Qalyubia",       ar: "القليوبية" },
  { value: "Sharqia",        ar: "الشرقية" },
  { value: "Dakahlia",       ar: "الدقهلية" },
  { value: "Beheira",        ar: "البحيرة" },
  { value: "Monufia",        ar: "المنوفية" },
  { value: "Gharbia",        ar: "الغربية" },
  { value: "Kafr el-Sheikh", ar: "كفر الشيخ" },
  { value: "Damietta",       ar: "دمياط" },
  { value: "Port Said",      ar: "بورسعيد" },
  { value: "Ismailia",       ar: "الإسماعيلية" },
  { value: "Suez",           ar: "السويس" },
  { value: "North Sinai",    ar: "شمال سيناء" },
  { value: "South Sinai",    ar: "جنوب سيناء" },
  { value: "Red Sea",        ar: "البحر الأحمر" },
  { value: "New Valley",     ar: "الوادي الجديد" },
  { value: "Matruh",         ar: "مطروح" },
  { value: "Fayoum",         ar: "الفيوم" },
  { value: "Beni Suef",      ar: "بني سويف" },
  { value: "Minya",          ar: "المنيا" },
  { value: "Asyut",          ar: "أسيوط" },
  { value: "Sohag",          ar: "سوهاج" },
  { value: "Qena",           ar: "قنا" },
  { value: "Luxor",          ar: "الأقصر" },
  { value: "Aswan",          ar: "أسوان" },
];

// Pluralize the bag's piece count. EN: "1 item" / "2 items". AR follows
// Arabic grammatical number: 1 → قطعة, 2 → قطعتان, 3–10 → قطع, 0/11+ → قطعة.
function fmtItemCount(n, lang) {
  if (lang === "en") return `${n} ${n === 1 ? "item" : "items"}`;
  const num = Number(n).toLocaleString("ar-EG");
  let word;
  if (n === 1) word = "قطعة";
  else if (n === 2) word = "قطعتان";
  else if (n >= 3 && n <= 10) word = "قطع";
  else word = "قطعة";
  return `${num} ${word}`;
}

function CheckoutModal({ open, onClose, items, setItems, lang, session }) {
  const [step, setStep] = React.useState("form"); // form | syncing | done | error
  const [err, setErr] = React.useState({ en: "", ar: "", code: "" });
  const [conflictItem, setConflictItem] = React.useState(null); // {product_name_en, product_name_ar, available, requested, product_id}
  const [orderNum, setOrderNum] = React.useState("");
  const [addr, setAddr] = React.useState({
    recipient: "", phone: "", line1: "",
    building: "", floor: "", apartment: "", landmark: "",
    area: "", city: "Cairo", governorate: "Cairo",
  });
  const [notes, setNotes] = React.useState("");
  // Submit guard — survives React re-renders. Prevents double-submission
  // from rapid clicks, Enter-key chord, or page-level keypress.
  const submittingRef = React.useRef(false);
  // Idempotency key — a fresh UUID per checkout intent. The Edge Function
  // doesn't yet use this server-side, but client carries it so we can wire
  // an Idempotency-Key header later without breaking older flows.
  const idemRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setStep("form"); setErr({ en: "", ar: "", code: "" });
      setOrderNum(""); setConflictItem(null);
      submittingRef.current = false;
      idemRef.current = (crypto?.randomUUID && crypto.randomUUID()) || ("idem-" + Date.now() + "-" + Math.random().toString(36).slice(2, 10));
    }
  }, [open]);

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

  const submit = async (e) => {
    e.preventDefault();
    if (submittingRef.current) return;                    // double-submit guard
    if (!addr.recipient || !addr.phone || !addr.line1 || !addr.city || !addr.governorate) return;
    submittingRef.current = true;
    setStep("syncing"); setErr({ en: "", ar: "", code: "" }); setConflictItem(null);

    let translated = null;
    try {
      const body = { address: addr, customer_notes: notes || null };

      if (session) {
        // Logged-in: sync cart to cart_items, Edge Function reads from DB
        const uid = session.user.id;
        await window.sb.from("cart_items").delete().eq("user_id", uid);
        // Collapse to one row per product_id before inserting. The cart UI already
        // merges quantities per piece, but de-duping here guarantees a repeated
        // product can't create two cart_items rows that the checkout function would
        // then double-count (there is no unique (user_id, product_id) constraint).
        // The preceding delete clears the user's cart, so a plain insert never
        // conflicts — "replace the whole cart", idempotent.
        const byProduct = {};
        items.filter(i => i.id).forEach(i => { byProduct[i.id] = { user_id: uid, product_id: i.id, quantity: i.qty }; });
        const rows = Object.values(byProduct);
        if (rows.length) await window.sb.from("cart_items").insert(rows);
      } else {
        // Guest: pass items directly — Edge Function re-prices from DB
        body.guest_email = addr.email || "";
        body.guest_name = addr.recipient;
        body.client_items = items.filter(i => i.id).map(i => ({ product_id: i.id, quantity: i.qty }));
      }

      const headers = {
        "Content-Type": "application/json",
        "apikey": window.SB_ANON,
        // Edge Functions require a Bearer token. Use user JWT when logged in, otherwise the anon key.
        "Authorization": "Bearer " + (session?.access_token || window.SB_ANON),
        // Carries the per-intent key for future server-side dedup.
        "X-Idempotency-Key": idemRef.current,
      };

      // Network + timeout wrapper — never let a hung fetch lock the UI forever.
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 30_000);
      let res, data;
      try {
        res = await fetch(`${window.SB_URL}/functions/v1/checkout_create_order`, {
          method: "POST", headers, body: JSON.stringify(body), signal: controller.signal,
        });
        data = await res.json().catch(() => ({}));
      } finally {
        clearTimeout(timeoutId);
      }

      if (!res.ok) {
        // Structured error: { code, friendly_en, friendly_ar, details }
        translated = window.translateError(data, "generic_5xx");
        if (data?.details?.product_name_en) {
          setConflictItem({
            product_id: data.details.product_id,
            product_name_en: data.details.product_name_en,
            product_name_ar: data.details.product_name_ar,
            available: data.details.available,
            requested: data.details.requested,
          });
        }
        // If the server says we need fresh auth, kick the silent recovery.
        if (translated.code === "auth_required") {
          await window._handleAuthFailure?.({ message: "auth_required" });
        }
        // Log for ops — never visible to customer.
        window._logClientError?.("checkout_error:" + translated.code,
                                 JSON.stringify(data).slice(0, 800),
                                 { url: window.location.href });
        throw new Error(translated.code);
      }

      setOrderNum(data.order_number);
      setItems([]);
      setStep("done");
    } catch (ex) {
      // Final translation — covers AbortError, network failure, any thrown shape.
      const t = translated || window.translateError(ex, "network");
      setErr({ en: t.en, ar: t.ar, code: t.code });
      setStep("error");
    } finally {
      submittingRef.current = false;
    }
  };

  if (!open) return null;

  const inp = { display: "block", width: "100%", marginTop: 6, padding: "11px 14px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper)", fontFamily: "var(--ff-sans)", fontSize: 14, outline: 0, boxSizing: "border-box" };

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(28,26,21,0.6)", zIndex: 82 }} />
      <div className="modal-card" style={{ position: "fixed", top: "50%", left: "50%", transform: "translate(-50%,-50%)", zIndex: 83, background: "var(--paper)", borderRadius: 20, padding: "36px 36px 32px", boxShadow: "0 30px 80px -20px rgba(28,26,21,0.5)" }}>
        <button onClick={onClose} style={{ position: "absolute", top: 18, right: 22, background: "transparent", border: 0, fontSize: 22, cursor: "pointer", color: "var(--muted)" }}>×</button>

        {step === "done" ? (
          <div style={{ textAlign: "center", padding: "24px 0" }}>
            <Star8 size={36} color="var(--olive)" />
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 40, marginTop: 20 }}>
              {lang === "en" ? "Order placed." : "تمّ الطلب."}
            </h2>
            <p style={{ marginTop: 12, color: "var(--olive)", fontSize: 15 }}>
              {lang === "en" ? `Order ${orderNum} is confirmed. We'll be in touch soon.` : `طلبك ${orderNum} مُؤكَّد. سنتواصل معك قريبًا.`}
            </p>
            <button className="btn" onClick={onClose} style={{ marginTop: 28 }}>
              {lang === "en" ? "Continue browsing" : "تابع التصفّح"} →
            </button>
          </div>
        ) : step === "error" ? (
          <div style={{ padding: "8px 0 4px" }}>
            <div style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--terracotta)" }}>
              {lang === "en" ? "A small pause" : "وقفة قصيرة"}
            </div>
            <h2 style={{ marginTop: 6, fontFamily: "var(--ff-display)", fontSize: 32, lineHeight: 1.1 }}>
              {(() => {
                if (err.code === "stock_unavailable" || err.code === "stock_race") {
                  return lang === "en" ? "We need to update your bag." : "نحتاج إلى تحديث حقيبتك.";
                }
                if (err.code === "auth_required") {
                  return lang === "en" ? "Your session needs a refresh." : "تحتاج جلستك إلى تحديث.";
                }
                if (err.code === "cart_empty") {
                  return lang === "en" ? "Your bag is empty." : "حقيبتك فارغة.";
                }
                if (err.code === "address_required" || err.code === "invalid_phone" || err.code === "email_required") {
                  return lang === "en" ? "Almost there." : "كاد الطلب يكتمل.";
                }
                return lang === "en" ? "Something needs our attention." : "هناك ما يحتاج اهتمامنا.";
              })()}
            </h2>
            <p style={{ marginTop: 14, fontSize: 15, color: "var(--olive)", lineHeight: 1.65 }}>
              {lang === "ar" ? (err.ar || err.en) : (err.en || err.ar)}
            </p>
            {conflictItem && (
              <div style={{ marginTop: 18, padding: "14px 16px", background: "var(--paper-2)", borderRadius: 12, fontSize: 13, color: "var(--ink)", lineHeight: 1.6 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", color: "var(--muted)", textTransform: "uppercase" }}>
                  {lang === "en" ? "Affected piece" : "القطعة المتأثّرة"}
                </div>
                <div style={{ marginTop: 4, fontFamily: "var(--ff-display)", fontSize: 18 }}>
                  {lang === "ar" ? (conflictItem.product_name_ar || conflictItem.product_name_en) : conflictItem.product_name_en}
                </div>
                {Number.isFinite(conflictItem.available) && (
                  <div style={{ marginTop: 6, fontSize: 13, color: "var(--olive)" }}>
                    {lang === "en"
                      ? (conflictItem.available > 0
                          ? `Only ${conflictItem.available} now available — you asked for ${conflictItem.requested}.`
                          : "Currently sold out.")
                      : (conflictItem.available > 0
                          ? `المتاح الآن ${conflictItem.available} — طلبت ${conflictItem.requested}.`
                          : "نفدت حاليًّا.")}
                  </div>
                )}
              </div>
            )}
            <div style={{ marginTop: 26, display: "flex", gap: 10, flexWrap: "wrap" }}>
              <button className="btn" onClick={() => {
                // Adjust cart for stock conflicts before retrying.
                if (conflictItem && conflictItem.product_id) {
                  const updated = items
                    .map(i => i.id === conflictItem.product_id
                      ? { ...i, qty: Math.min(i.qty, Math.max(0, conflictItem.available || 0)) }
                      : i)
                    .filter(i => i.qty > 0);
                  setItems(updated);
                }
                setStep("form");
              }}>
                {err.code === "auth_required"
                  ? (lang === "en" ? "Sign in & continue" : "سجّل ثم تابع")
                  : (lang === "en" ? "Try again" : "حاول مرة أخرى")} →
              </button>
              {err.code === "auth_required" && (
                <a href="#/account" onClick={onClose} className="btn ghost" style={{ display: "inline-flex" }}>
                  {lang === "en" ? "Go to account" : "إلى الحساب"} →
                </a>
              )}
            </div>
          </div>
        ) : (
          <form onSubmit={submit}>
            <h2 style={{ fontFamily: "var(--ff-display)", fontSize: 36, marginBottom: 24 }}>
              {lang === "en" ? "Delivery details" : "بيانات التوصيل"}
            </h2>

            {!session && (
              <div style={{ padding: "12px 16px", background: "var(--paper-2)", borderRadius: 10, marginBottom: 20, fontSize: 13, color: "var(--olive)" }}>
                {lang === "en" ? (
                  <>Checking out as guest. <a href="#/account" onClick={onClose} style={{ color: "var(--terracotta)" }}>Sign in</a> to track your order.</>
                ) : (
                  <>دفع كضيف. <a href="#/account" onClick={onClose} style={{ color: "var(--terracotta)" }}>سجّل الدخول</a> لمتابعة طلبك.</>
                )}
              </div>
            )}

            {!session && (
              <div style={{ marginBottom: 16 }}>
                <label htmlFor="co-email" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Email" : "البريد الإلكتروني"}</label>
                <input id="co-email" name="email" autoComplete="email" required type="email" value={addr.email || ""} onChange={e => set("email", e.target.value)} style={inp} placeholder="your@email.com" />
              </div>
            )}

            <div className="modal-form-row form-row-2" style={{ marginBottom: 16 }}>
              <div>
                <label htmlFor="co-recipient" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Full name" : "الاسم"}</label>
                <input id="co-recipient" name="name" autoComplete="name" required value={addr.recipient} onChange={e => set("recipient", e.target.value)} style={inp} />
              </div>
              <div>
                <label htmlFor="co-phone" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Phone" : "الهاتف"}</label>
                <input id="co-phone" name="tel" type="tel" autoComplete="tel" required value={addr.phone} onChange={e => set("phone", e.target.value)} style={inp} placeholder="+20 1XX XXX XXXX" />
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <label htmlFor="co-line1" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Street address" : "اسم الشارع"}</label>
              <input id="co-line1" name="address-line1" autoComplete="address-line1" required value={addr.line1} onChange={e => set("line1", e.target.value)} style={inp} placeholder={lang === "en" ? "Street name" : "اسم الشارع"} />
            </div>

            {/* Operational address fields — building / floor / apt / landmark
                — required for SANAA fulfillment + Bosta/Aramex courier handover */}
            <div className="modal-form-row form-row-3" style={{ marginBottom: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
              <div>
                <label htmlFor="co-building" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Building" : "العمارة"}</label>
                <input id="co-building" name="building" required value={addr.building} onChange={e => set("building", e.target.value)} style={inp} placeholder={lang === "en" ? "14B" : "١٤"} />
              </div>
              <div>
                <label htmlFor="co-floor" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Floor" : "الدور"}</label>
                <input id="co-floor" name="floor" value={addr.floor} onChange={e => set("floor", e.target.value)} style={inp} placeholder="3" />
              </div>
              <div>
                <label htmlFor="co-apartment" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Apartment" : "الشقة"}</label>
                <input id="co-apartment" name="apartment" value={addr.apartment} onChange={e => set("apartment", e.target.value)} style={inp} placeholder="12" />
              </div>
            </div>

            <div style={{ marginBottom: 16 }}>
              <label htmlFor="co-landmark" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Landmark (helps the courier find you)" : "علامة مميّزة (تساعد المندوب)"}</label>
              <input id="co-landmark" name="landmark" value={addr.landmark} onChange={e => set("landmark", e.target.value)} style={inp} placeholder={lang === "en" ? "Next to the old cinema" : "بجوار السينما القديمة"} />
            </div>

            <div className="modal-form-row form-row-3" style={{ marginBottom: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
              <div>
                <label htmlFor="co-area" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Area" : "المنطقة"}</label>
                <input id="co-area" name="area" value={addr.area} onChange={e => set("area", e.target.value)} style={inp} placeholder={lang === "en" ? "Zamalek" : "الزمالك"} />
              </div>
              <div>
                <label htmlFor="co-city" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "City" : "المدينة"}</label>
                <input id="co-city" name="city" autoComplete="address-level2" required value={addr.city} onChange={e => set("city", e.target.value)} style={inp} />
              </div>
              <div>
                <label htmlFor="co-governorate" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Governorate" : "المحافظة"}</label>
                <window.BrandSelect
                  id="co-governorate"
                  name="governorate"
                  lang={lang}
                  dir={lang === "ar" ? "rtl" : "ltr"}
                  ariaLabel={lang === "en" ? "Governorate" : "المحافظة"}
                  value={addr.governorate}
                  onChange={(v) => set("governorate", v)}
                  options={EG_GOVS.map(g => ({ value: g.value, label: lang === "ar" ? g.ar : g.value }))}
                  placeholder={lang === "en" ? "Select governorate" : "اختر المحافظة"}
                  style={{ marginTop: 6 }}
                />
              </div>
            </div>

            <div style={{ marginBottom: 24 }}>
              <label htmlFor="co-notes" style={{ fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)" }}>{lang === "en" ? "Delivery notes (optional)" : "ملاحظات للتوصيل"}</label>
              <textarea id="co-notes" name="notes" rows={2} value={notes} onChange={e => setNotes(e.target.value)} style={{ ...inp, resize: "vertical", marginTop: 6 }} placeholder={lang === "en" ? "Anything we should tell the courier?" : "أيّ ملاحظة للمندوب؟"} />
            </div>

            <button type="submit" className="btn" disabled={step === "syncing"} style={{ width: "100%", justifyContent: "center", opacity: step === "syncing" ? 0.6 : 1 }}>
              {step === "syncing" ? (lang === "en" ? "Placing order…" : "جاري الطلب…") : (lang === "en" ? "Place order" : "تأكيد الطلب")} →
            </button>
            <div style={{ marginTop: 12, fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", textAlign: "center" }}>
              {lang === "en" ? "Cash on delivery" : "الدفع عند الاستلام"} · Paymob · Fawry · InstaPay
            </div>
          </form>
        )}
      </div>
    </>
  );
}

function CartDrawer({ open, onClose, items, setItems, lang }) {
  const [checkoutOpen, setCheckoutOpen] = React.useState(false);
  const { session } = useAuth();
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const [giftOpen, setGiftOpen] = React.useState(false);
  const [giftNote, setGiftNote] = React.useState("");
  const [delivery, setDelivery] = React.useState("bosta"); // bosta | aramex | pickup | intl

  // ESC closes the drawer (and the checkout modal if it's open).
  // Body scroll is locked while open so background content doesn't drift.
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => {
      if (e.key !== "Escape") return;
      if (checkoutOpen) setCheckoutOpen(false);
      else if (giftOpen) setGiftOpen(false);
      else onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [open, checkoutOpen, giftOpen, onClose]);
  const SHIP = {
    bosta: { en: "Bosta · next-day Cairo", ar: "بوسطة · القاهرة", price: 60 },
    aramex: { en: "Aramex · 3–7 days Egypt", ar: "أراميكس · ٣-٧ أيام", price: 120 },
    pickup: { en: "Pickup · Zamalek atelier", ar: "استلام · المحترف", price: 0 },
    intl:   { en: "Worldwide · 5–14 days", ar: "دولي · ٥-١٤ يوم", price: 480 },
  };
  const ship = SHIP[delivery];
  const total = subtotal + ship.price;

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: "fixed", inset: 0, background: "rgba(28,26,21,0.5)",
          opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none",
          transition: "opacity 0.3s", zIndex: 80,
        }}
      />
      <aside aria-label={lang === "en" ? "Shopping bag" : "حقيبة"} style={{
        position: "fixed", top: 0, right: 0, bottom: 0,
        width: 460, maxWidth: "100vw",
        background: "var(--paper)", zIndex: 81,
        transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform 0.4s ease",
        display: "flex", flexDirection: "column",
        boxShadow: "-20px 0 60px -20px rgba(28,26,21,0.3)",
      }}>
        <div style={{ padding: "24px 28px", borderBottom: "1px solid var(--line-2)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontFamily: "var(--ff-display)", fontSize: 24 }}>
            {lang === "en" ? "Your bag" : "حقيبتك"}
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 11, letterSpacing: "0.2em", color: "var(--muted)", marginLeft: 12 }}>
              {fmtItemCount(items.length, lang)}
            </span>
          </div>
          <button onClick={onClose} aria-label={lang === "en" ? "Close bag" : "إغلاق الحقيبة"} style={{ background: "transparent", border: 0, fontSize: 22, cursor: "pointer", color: "var(--ink)", minWidth: 44, minHeight: 44, display: "inline-flex", alignItems: "center", justifyContent: "center", padding: 0, lineHeight: 1 }}>×</button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "20px 28px" }}>
          {items.length === 0 && (
            <div style={{ textAlign: "center", padding: "80px 0", color: "var(--muted)" }}>
              <Star8 size={32} color="var(--gold-soft)" />
              <p style={{ marginTop: 20, fontFamily: "var(--ff-display)", fontSize: 22, color: "var(--ink)" }}>
                {lang === "en" ? "Your bag is empty." : "حقيبتك فارغة."}
              </p>
            </div>
          )}
          {items.map((it, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "80px 1fr auto", gap: 16, padding: "18px 0", borderBottom: "1px solid var(--line-2)" }}>
              <div style={{ width: 80, height: 90, overflow: "hidden" }}>
                <Placeholder tone={it.tone} shape="arch" label=" " meta=" " />
              </div>
              <div>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 20 }}>{it.name}</div>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)", marginTop: 3 }}>{it.num}</div>
                <div style={{ marginTop: 10, display: "flex", gap: 10, alignItems: "center" }}>
                  <button onClick={() => setItems(items.map((x, j) => j === i ? { ...x, qty: Math.max(1, x.qty - 1) } : x))} aria-label="Decrease" style={qBtn}>−</button>
                  <span style={{ fontFamily: "var(--ff-mono)", fontSize: 12 }}>{it.qty}</span>
                  <button onClick={() => setItems(items.map((x, j) => j === i ? { ...x, qty: x.qty + 1 } : x))} aria-label="Increase" style={qBtn}>+</button>
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 18 }}>{window.fmtPrice(it.price * it.qty, lang)}</div>
                <button onClick={() => setItems(items.filter((_, j) => j !== i))} style={{ background: "transparent", border: 0, fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)", cursor: "pointer", textDecoration: "underline", marginTop: 6 }}>
                  {lang === "en" ? "Remove" : "حذف"}
                </button>
              </div>
            </div>
          ))}

          {items.length > 0 && (
            <>
              {/* Delivery selector */}
              <div style={{ marginTop: 24 }}>
                <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>{lang === "en" ? "Delivery" : "التوصيل"}</div>
                {Object.entries(SHIP).map(([k, s]) => (
                  <label key={k} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", border: delivery === k ? "1px solid var(--ink)" : "1px solid var(--line-2)", borderRadius: 12, marginBottom: 8, cursor: "pointer", background: delivery === k ? "var(--paper-2)" : "transparent" }}>
                    <input type="radio" name="ship" checked={delivery === k} onChange={() => setDelivery(k)} style={{ accentColor: "var(--terracotta)" }} />
                    <div style={{ color: "var(--terracotta)" }}><Icon name={k === "pickup" ? "pin" : k === "intl" ? "box" : "truck"} size={18} /></div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "var(--ff-sans)", fontSize: 13, color: "var(--ink)" }}>{s[lang]}</div>
                      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)" }}>
                        {s.price === 0 ? (lang === "en" ? "Free" : "مجّاني") : window.fmtPrice(s.price, lang)}
                      </div>
                    </div>
                  </label>
                ))}
              </div>

              {/* Gift note */}
              <div style={{ marginTop: 18 }}>
                <button onClick={() => setGiftOpen(!giftOpen)} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "12px 14px", border: "1px dashed var(--line)", borderRadius: 12, background: "transparent", cursor: "pointer", color: "var(--ink)", fontFamily: "var(--ff-sans)", fontSize: 13, textAlign: "left" }}>
                  <span style={{ color: "var(--terracotta)" }}><Icon name="gift" size={18} /></span>
                  <span style={{ flex: 1 }}>{giftOpen ? (lang === "en" ? "A handwritten note will be included" : "بطاقة بخطّ اليد") : (lang === "en" ? "Add a handwritten gift note" : "أضف بطاقة هديّة")}</span>
                  <span style={{ fontFamily: "var(--ff-mono)", fontSize: 11, color: "var(--muted)" }}>{giftOpen ? "−" : "+"}</span>
                </button>
                {giftOpen && (
                  <textarea
                    value={giftNote}
                    onChange={e => setGiftNote(e.target.value.slice(0, 240))}
                    rows={3}
                    placeholder={lang === "en" ? "We'll write it by hand on cotton card and tuck it inside the box…" : "سنكتبها بخطّ اليد على كرتٍ قطنيّ…"}
                    style={{ marginTop: 8, width: "100%", padding: "12px 14px", border: "1px solid var(--line)", borderRadius: 10, background: "var(--paper-2)", fontFamily: "var(--ff-display)", fontStyle: "italic", fontSize: 15, lineHeight: 1.5, color: "var(--ink)", outline: 0, resize: "vertical" }}
                  />
                )}
                {giftOpen && (
                  <div style={{ textAlign: "right", fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)", marginTop: 4 }}>
                    {giftNote.length} / 240
                  </div>
                )}
              </div>
            </>
          )}
        </div>
        <div style={{ padding: "22px 28px", borderTop: "1px solid var(--line)", background: "var(--paper-2)" }}>
          {items.length > 0 && (
            <div style={{ marginBottom: 12, fontSize: 13, color: "var(--olive)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}>
                <span>{lang === "en" ? "Subtotal" : "المجموع"}</span>
                <span>{window.fmtPrice(subtotal, lang)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", color: "var(--muted)" }}>
                <span>{lang === "en" ? "Shipping" : "الشحن"} · {ship[lang]}</span>
                <span>{ship.price === 0 ? (lang === "en" ? "Free" : "مجّاني") : window.fmtPrice(ship.price, lang)}</span>
              </div>
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4, fontFamily: "var(--ff-mono)", fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
            <span>{lang === "en" ? "Total" : "الإجمالي"}</span>
            <span>{lang === "en" ? "EGP" : "ج.م"}</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontFamily: "var(--ff-display)", fontSize: 36 }}>{total.toLocaleString(lang === "ar" ? "ar-EG" : "en-US")}</span>
            <span style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", color: "var(--muted)", display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name="lock" size={11} /> {lang === "en" ? "Secure" : "آمن"}
            </span>
          </div>
          <button className="btn" disabled={items.length === 0} onClick={() => items.length > 0 && setCheckoutOpen(true)} style={{ width: "100%", justifyContent: "center", marginTop: 18, opacity: items.length === 0 ? 0.5 : 1 }}>
            {lang === "en" ? "Proceed to checkout" : "متابعة الدفع"} →
          </button>
          <div style={{ marginTop: 14, fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", textAlign: "center" }}>
            Paymob · Fawry · InstaPay
          </div>
        </div>
      </aside>
      <CheckoutModal
        open={checkoutOpen}
        onClose={() => setCheckoutOpen(false)}
        items={items}
        setItems={setItems}
        lang={lang}
        session={session}
      />
    </>
  );
}
const qBtn = { width: 24, height: 24, borderRadius: "50%", border: "1px solid var(--line)", background: "transparent", cursor: "pointer", fontFamily: "var(--ff-sans)", fontSize: 12 };

/* Tweaks panel */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "sand",
  "displayFont": "cormorant",
  "density": "spacious",
  "pattern": true
}/*EDITMODE-END*/;

const PALETTES = {
  sand:       { paper: "#F4EDE2", paper2: "#EDE3D2", ink: "#1C1A15", olive: "#2E3528", terra: "#B5502E", gold: "#B8904C", line: "#CFBFA3", line2: "#E3D6BC", muted: "#6E6558" },
  nile:       { paper: "#EAECE4", paper2: "#DEE3D7", ink: "#14251E", olive: "#25382C", terra: "#8A6B3A", gold: "#A88B4F", line: "#BCC4B0", line2: "#D3D9C7", muted: "#5E6B5A" },
  ochre:      { paper: "#F8EEDE", paper2: "#F1E4C9", ink: "#2A1E10", olive: "#5E3D1B", terra: "#C05824", gold: "#D6A34A", line: "#D4BB88", line2: "#E6D3A8", muted: "#7A5E36" },
  midnight:   { paper: "#EFE8D9", paper2: "#E5DCC8", ink: "#0E0D10", olive: "#1D2332", terra: "#B35234", gold: "#C9A560", line: "#C6BAA0", line2: "#DACEB4", muted: "#5F5A4C" },
};

const FONTS = {
  cormorant: { display: "'Cormorant Garamond', Georgia, serif" },
  instrument: { display: "'Instrument Serif', Georgia, serif" },
  garamond: { display: "'EB Garamond', Georgia, serif" },
  dmserif: { display: "'DM Serif Display', Georgia, serif" },
};

function useTweaks() {
  const [vals, setVals] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("sanaa_tweaks") || "null");
      return { ...TWEAK_DEFAULTS, ...(saved || {}) };
    } catch { return TWEAK_DEFAULTS; }
  });
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // Apply palette
  React.useEffect(() => {
    const p = PALETTES[vals.palette] || PALETTES.sand;
    const r = document.documentElement;
    r.style.setProperty("--paper", p.paper);
    r.style.setProperty("--paper-2", p.paper2);
    r.style.setProperty("--ink", p.ink);
    r.style.setProperty("--olive", p.olive);
    r.style.setProperty("--terracotta", p.terra);
    r.style.setProperty("--gold", p.gold);
    r.style.setProperty("--gold-soft", p.gold);
    r.style.setProperty("--line", p.line);
    r.style.setProperty("--line-2", p.line2);
    r.style.setProperty("--muted", p.muted);

    const f = FONTS[vals.displayFont] || FONTS.cormorant;
    r.style.setProperty("--ff-display", f.display);

    localStorage.setItem("sanaa_tweaks", JSON.stringify(vals));
  }, [vals]);

  const update = (k, v) => {
    const next = { ...vals, [k]: v };
    setVals(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  return { vals, update, open, setOpen };
}

function TweaksPanel({ tweaks }) {
  if (!tweaks.open) return null;
  const { vals, update } = tweaks;
  return (
    <div style={{
      position: "fixed", right: 24, bottom: 24, zIndex: 90,
      width: 320, background: "var(--paper)", color: "var(--ink)",
      border: "1px solid var(--ink)", borderRadius: 18,
      padding: 22,
      boxShadow: "0 20px 60px -20px rgba(28,26,21,0.5)",
      fontFamily: "var(--ff-sans)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
        <div style={{ fontFamily: "var(--ff-display)", fontSize: 22 }}>Tweaks</div>
        <Star8 size={16} color="var(--terracotta)" />
      </div>

      <TweakRow label="Palette">
        <div style={{ display: "flex", gap: 8 }}>
          {Object.entries(PALETTES).map(([k, p]) => (
            <button key={k} onClick={() => update("palette", k)} title={k} style={{
              width: 44, height: 44, borderRadius: 10, cursor: "pointer",
              border: vals.palette === k ? "2px solid var(--ink)" : "1px solid var(--line)",
              padding: 0, overflow: "hidden", background: p.paper,
              display: "grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr",
            }}>
              <div style={{ background: p.paper }} />
              <div style={{ background: p.terra }} />
              <div style={{ background: p.olive }} />
              <div style={{ background: p.gold }} />
            </button>
          ))}
        </div>
      </TweakRow>

      <TweakRow label="Display font">
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {Object.keys(FONTS).map(k => (
            <button key={k} onClick={() => update("displayFont", k)} style={{
              padding: "8px 12px", borderRadius: 999, cursor: "pointer",
              fontFamily: FONTS[k].display, fontSize: 13,
              background: vals.displayFont === k ? "var(--ink)" : "transparent",
              color: vals.displayFont === k ? "var(--paper)" : "var(--ink)",
              border: "1px solid var(--line)",
            }}>Aa · {k}</button>
          ))}
        </div>
      </TweakRow>

      <TweakRow label="Geometric pattern">
        <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", fontSize: 13 }}>
          <input type="checkbox" checked={vals.pattern} onChange={(e) => update("pattern", e.target.checked)} />
          Show subtle background
        </label>
      </TweakRow>

      <div style={{
        marginTop: 18, paddingTop: 14, borderTop: "1px solid var(--line-2)",
        fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)",
      }}>
        SANAA · صَنعة · house tweaks
      </div>
    </div>
  );
}

function TweakRow({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontFamily: "var(--ff-mono)", fontSize: 9, letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 8 }}>{label}</div>
      {children}
    </div>
  );
}

Object.assign(window, { CartDrawer, useTweaks, TweaksPanel });
