// Kotleto · CART drawer

function CartDrawer({ accent = "#D9461E", onCheckout }) {
  const { lang } = useLang();
  const cart = useCart();
  const deliveryConfig = useDeliveryConfig();
  const open = cart.open;
  const [promoInput, setPromoInput] = useState(cart.promo || "");
  const totals = getCartTotals(cart.subtotal, cart.promo, deliveryConfig);

  useEffect(() => { if (open) setPromoInput(cart.promo || ""); }, [open, cart.promo]);

  useEffect(() => {
    if (!open) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = event => event.key === "Escape" && cart.setOpen(false);
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = previousOverflow; window.removeEventListener("keydown", onKey); };
  }, [open]);

  const submitPromo = () => {
    if (cart.applyPromo(promoInput)) {
      notify(lang === "fa" ? "کدتخفیف اعمال شد" : "Promo code applied");
    } else {
      notify(lang === "fa" ? "این کدتخفیف معتبر نیست" : "That promo code is not valid", "error");
    }
  };

  return (
    <>
      {/* Backdrop */}
      <div onClick={() => cart.setOpen(false)} style={{
        position: "fixed", inset: 0, zIndex: 60,
        background: "rgba(26,20,16,0.4)", backdropFilter: "blur(4px)",
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none",
        transition: "opacity .25s ease",
      }} />
      {/* Panel */}
      <aside className="cart-panel" role="dialog" aria-modal="true" aria-hidden={!open} aria-label={lang === "fa" ? "سبد سفارش" : "Order bag"} dir={lang === "fa" ? "rtl" : "ltr"} style={{
        position: "fixed", top: 0, bottom: 0,
        [lang === "fa" ? "left" : "right"]: 0,
        width: "min(440px, 92vw)", zIndex: 61,
        background: "var(--paper)",
        boxShadow: "0 0 60px -10px rgba(0,0,0,0.4)",
        transform: open ? "translateX(0)" : (lang === "fa" ? "translateX(-100%)" : "translateX(100%)"),
        transition: "transform .35s cubic-bezier(.5,0,.2,1)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ padding: "22px 24px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 600 }}>{lang === "fa" ? "سبد سفارش" : "Order bag"}</div>
            <div className="display" style={{ fontSize: 26 }}>{lang === "fa" ? toFa(cart.count) : cart.count} {lang === "fa" ? "آیتم" : "items"}</div>
          </div>
          <button onClick={() => cart.setOpen(false)} aria-label={lang === "fa" ? "بستن سبد" : "Close cart"} className="btn btn-ghost btn-sm" style={{ padding: 10, borderRadius: 999, borderColor: "var(--line)" }}>
            <Ico.X />
          </button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "12px 0" }}>
          {cart.items.length === 0 ? (
            <div style={{ padding: "60px 24px", textAlign: "center" }}>
              <div style={{ fontSize: 64, marginBottom: 12 }}>🥺</div>
              <div className="display" style={{ fontSize: 22, marginBottom: 8 }}>{lang === "fa" ? "سبد خالیه!" : "Cart is empty"}</div>
              <p style={{ color: "var(--ink-3)", fontSize: 14, marginBottom: 18 }}>{lang === "fa" ? "یه کتلتی، چیزی بزن تو سبد." : "Toss something tasty in here."}</p>
              <button className="btn btn-primary" onClick={() => { cart.setOpen(false); document.querySelector("#menu")?.scrollIntoView({ behavior: "smooth" }); }}>
                {lang === "fa" ? "رفتن به منو" : "Browse menu"} →
              </button>
            </div>
          ) : (
            cart.items.map(it => (
              <div key={it.id} style={{ display: "flex", gap: 14, padding: "14px 24px", alignItems: "center" }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 16, background: it.color,
                  display: "grid", placeItems: "center", fontSize: 26, flexShrink: 0,
                  border: "1.5px solid var(--ink)", overflow: "hidden", position: "relative",
                }}>
                  <span aria-hidden="true">{it.emoji}</span>
                  {KotletoImages.resolve(it.photo, it.id) && <img src={KotletoImages.resolve(it.photo, it.id)} alt="" onError={event => { event.currentTarget.style.display = "none"; }} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="display" style={{ fontSize: 16, lineHeight: 1.2 }}>{it.name}</div>
                  <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}><Price value={it.price} /></div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 4, background: "var(--paper-2)", borderRadius: 999, padding: 4, border: "1px solid var(--line)" }}>
                  <button aria-label={lang === "fa" ? "کم کردن تعداد" : "Decrease quantity"} onClick={() => cart.setQty(it.id, it.qty - 1)} style={{ width: 36, height: 36, borderRadius: 999, background: "transparent", display: "grid", placeItems: "center" }}><Ico.Minus /></button>
                  <span className="tnum" style={{ minWidth: 22, textAlign: "center", fontWeight: 700, fontSize: 14 }}>{lang === "fa" ? toFa(it.qty) : it.qty}</span>
                  <button aria-label={lang === "fa" ? "زیاد کردن تعداد" : "Increase quantity"} onClick={() => cart.setQty(it.id, it.qty + 1)} style={{ width: 36, height: 36, borderRadius: 999, background: "var(--ink)", color: "var(--paper)", display: "grid", placeItems: "center" }}><Ico.Plus /></button>
                </div>
              </div>
            ))
          )}
        </div>

        {cart.items.length > 0 && (
          <div style={{ borderTop: "1px solid var(--line)", padding: "18px 24px", background: "var(--paper-2)" }}>
            <form onSubmit={event => { event.preventDefault(); submitPromo(); }} style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <label className="sr-only" htmlFor="cart-promo">{lang === "fa" ? "کدتخفیف" : "Promo code"}</label>
              <input id="cart-promo" value={promoInput} onChange={event => setPromoInput(event.target.value.toUpperCase())} placeholder={lang === "fa" ? "کدتخفیف" : "Promo code"} dir="ltr" style={{ minWidth: 0, flex: 1, padding: "10px 13px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--paper)", fontWeight: 700, textTransform: "uppercase" }} />
              <button className="btn btn-dark btn-sm" type="submit">{lang === "fa" ? "اعمال" : "Apply"}</button>
            </form>
            {cart.promo && <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "-4px 0 10px", fontSize: 12, color: accent }}>
              <span>{lang === "fa" ? "کد " + cart.promo + " فعال است" : cart.promo + " is active"}</span>
              <button onClick={() => { cart.setPromo(""); setPromoInput(""); }} style={{ fontWeight: 700, color: "inherit" }}>{lang === "fa" ? "حذف" : "Remove"}</button>
            </div>}
            <Row label={lang === "fa" ? "جمع کل" : "Subtotal"} value={<Price value={cart.subtotal} />} />
            <Row label={lang === "fa" ? "ارسال" : "Delivery"} value={<Price value={totals.delivery} />} />
            {totals.deliveryDiscount > 0 && <Row label={lang === "fa" ? "تخفیف ارسال" : "Delivery discount"} value={<span style={{color: accent}}>−<Price value={totals.deliveryDiscount} /></span>} />}
            {totals.promoDiscount > 0 && <Row label={lang === "fa" ? "تخفیف کد" : "Promo discount"} value={<span style={{color: accent}}>−<Price value={totals.promoDiscount} /></span>} />}
            <div style={{ height: 1, background: "var(--line)", margin: "12px 0" }} />
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <span className="display" style={{ fontSize: 18 }}>{lang === "fa" ? "پرداختی" : "Total"}</span>
              <span className="display" style={{ fontSize: 28, color: accent }}><Price value={totals.total} /></span>
            </div>
            <button className="btn btn-primary btn-lg" style={{ width: "100%" }} onClick={onCheckout} disabled={cart.subtotal < totals.minimumOrder}>
              {lang === "fa" ? "ثبت سفارش" : "Place order"} <Ico.Arrow />
            </button>
            {cart.subtotal < totals.minimumOrder && <p role="status" style={{ margin: "10px 0 0", color: accent, fontSize: 12, textAlign: "center" }}>
              {lang === "fa" ? "حداقل مبلغ سفارش: " : "Minimum order: "}<Price value={totals.minimumOrder} />
            </p>}
            <div style={{ marginTop: 10, textAlign: "center", fontSize: 12, color: "var(--ink-3)" }}>
              {lang === "fa" ? "زمان آماده‌سازی: ۲۰ دقیقه · ارسال: ۱۵ دقیقه" : "Prep 20m · delivery 15m"}
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

function Row({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 14 }}>
      <span style={{ color: "var(--ink-3)" }}>{label}</span>
      <span style={{ fontWeight: 600 }}>{value}</span>
    </div>
  );
}

window.CartDrawer = CartDrawer;
