// Cart drawer for the Xedap.vn website kit.
const { Button, IconButton } = window.XedapVnDesignSystem_03b1c0;

function CartDrawerSuggestRow({ lines, onAdd, fmt }) {
  const { IMG, PRODUCTS } = window.KitData;
  const inCart = new Set(lines.map((l) => l.product.slug));
  const items = (PRODUCTS || []).filter((p) => !inCart.has(p.slug)).slice(0, 6);
  if (!items.length) return null;
  const img = (p) => (window.XedapApiImage && window.XedapApiImage(p)) || p.img || IMG(p.seed, 160, 160);
  return (
    <div style={{ padding: "16px 20px 4px", borderTop: "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
        <i className="ph ph-sparkle" style={{ fontSize: "calc(13px + 2px*var(--ts))", color: "var(--primary)" }} />
        <span style={{ fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: 13, textTransform: "uppercase", letterSpacing: ".04em" }}>Gợi ý mua cùng</span>
      </div>
      <div style={{ display: "flex", gap: 10, overflowX: "auto", paddingBottom: 12, scrollbarWidth: "thin" }}>
        {items.map((p) => (
          <div key={p.slug} style={{ flex: "0 0 132px", width: 132, border: "1px solid var(--border)", borderRadius: "var(--radius-sm)", padding: 8, display: "flex", flexDirection: "column", gap: 6, background: "#fff" }}>
            <img src={img(p)} alt="" style={{ width: "100%", height: 72, objectFit: "contain", background: "var(--secondary)", borderRadius: "var(--radius-sm)" }} />
            <span style={{ fontSize: 12, lineHeight: 1.3, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", textWrap: "pretty" }}>{p.name}</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--danger)" }}>{fmt(p.price)}</span>
            <button onClick={() => onAdd && onAdd(p)} style={{ marginTop: "auto", border: "1px solid var(--primary)", background: "transparent", color: "var(--primary)", borderRadius: "var(--radius-sm)", padding: "5px 0", fontSize: 12, fontWeight: 600, fontFamily: "var(--font-sans)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 4 }}><i className="ph ph-plus" style={{ fontSize: 12 }} /> Thêm</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function CartDrawer({ open, lines, onClose, onRemove, onCheckout, onAdd }) {
  const { IMG } = window.KitData;
  const total = lines.reduce((s, l) => s + l.product.price * l.qty, 0);
  const fmt = (n) => new Intl.NumberFormat("vi-VN").format(Math.round(n)) + "đ";
  const [flash, setFlash] = React.useState(null);
  const prevRef = React.useRef({});
  React.useEffect(() => {
    const now = {}; lines.forEach((l) => (now[l.product.slug] = l.qty));
    const changed = Object.keys(now).find((s) => now[s] !== (prevRef.current[s] || 0));
    prevRef.current = now;
    if (!changed) return;
    setFlash(changed);
    const t = setTimeout(() => setFlash(null), 1400);
    return () => clearTimeout(t);
  }, [lines]);
  return (
    <React.Fragment>
    <style>{"@keyframes cartLineIn{from{opacity:0;transform:translateX(24px)}to{opacity:1;transform:none}}"}</style>
    <React.Fragment>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.35)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .3s", zIndex: 1000 }} />
      <aside style={{ position: "fixed", top: 0, right: 0, height: "100%", width: 420, maxWidth: "90vw", background: "#fff", boxShadow: "var(--shadow-lg)", transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .3s var(--ease-out)", zIndex: 1001, display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-heading)", fontWeight: 700, fontSize: "calc(13px + 5px*var(--ts))" }}><i className="ph ph-shopping-cart" /> Giỏ hàng của bạn</span>
          <IconButton label="Đóng" onClick={onClose}><i className="ph ph-x" /></IconButton>
        </div>
        {lines.length === 0 ? (
          <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 12, color: "var(--muted-foreground)" }}>
            <i className="ph ph-shopping-cart" style={{ fontSize: "calc(13px + 27px*var(--ts))" }} />
            <p style={{ margin: 0, fontSize: "calc(13px + 1px*var(--ts))" }}>Giỏ hàng của bạn đang trống.</p>
            <Button onClick={onClose} style={{ boxShadow: "none" }}>Tiếp tục mua sắm</Button>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ flex: 1, overflowY: "auto", padding: "0 20px" }}>
              {lines.map((l) => (
                <div key={l.product.slug} style={{ display: "flex", gap: 12, padding: "16px 0", borderBottom: "1px solid var(--border)", animation: flash === l.product.slug ? "cartLineIn .32s var(--ease-out) both" : "none", background: flash === l.product.slug ? "color-mix(in oklab, var(--primary) 8%, transparent)" : "transparent", transition: "background .5s", borderRadius: 8, paddingInline: flash === l.product.slug ? 8 : 0, marginInline: flash === l.product.slug ? -8 : 0 }}>
                  <img src={(window.XedapApiImage && window.XedapApiImage(l.product)) || l.product.img || IMG(l.product.seed, 128, 128)} alt="" style={{ width: 64, height: 64, borderRadius: "var(--radius-sm)", objectFit: "contain", background: "var(--secondary)" }} />
                  <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 2 }}>
                    <span style={{ fontSize: 11, fontWeight: 500, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--muted-foreground)" }}>{l.product.brand}</span>
                    <span style={{ fontSize: "calc(13px + 1px*var(--ts))", fontWeight: 500 }}>{l.product.name}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--danger)" }}>{fmt(l.product.price)} × {l.qty}</span>
                  </div>
                  <button onClick={() => onRemove(l.product.slug)} aria-label="Xóa" style={{ border: "none", background: "none", cursor: "pointer", color: "var(--muted-foreground)", height: "fit-content" }}><i className="ph ph-trash" style={{ fontSize: "calc(13px + 5px*var(--ts))" }} /></button>
                </div>
              ))}
            </div>
            <CartDrawerSuggestRow lines={lines} onAdd={onAdd} fmt={fmt} />
            <div style={{ padding: "16px 20px", borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: "calc(13px + 3px*var(--ts))", fontWeight: 600 }}><span>Tạm tính</span><span style={{ fontFamily: "var(--font-mono)" }}>{fmt(total)}</span></div>
              <Button size="lg" style={{ width: "100%", boxShadow: "none" }} onClick={() => (onCheckout ? onCheckout() : (window.location.href = "./cart.html"))}>Tiến hành thanh toán</Button>
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
    </React.Fragment>
  );
}

Object.assign(window, { CartDrawer, CartDrawerSuggestRow });
