/* global React, Icon, Photo, Stepper, PRODUCT */

function CartDrawer({ open, onClose, items, setItems, onCheckout }) {
  const drawerRef = React.useRef(null);
  const [barWidth, setBarWidth] = React.useState(0);

  const lines = items.map(it => {
    // Kshop sells one product — match by id anyway in case future SKUs are added.
    const p = (it.productId === PRODUCT.id) ? PRODUCT : PRODUCT;
    const s = p?.sizes.find(x => x.id === it.sizeId);
    return { ...it, p, s, total: (s?.price || 0) * it.qty };
  });
  const subtotal = lines.reduce((a, l) => a + l.total, 0);
  const { shippingFreeThreshold = 75, shippingRate = 9 } = window.STORE_CONFIG || {};
  const shipping = subtotal >= shippingFreeThreshold ? 0 : shippingRate;
  const total = subtotal + shipping;

  const realBarWidth = Math.min(100, (subtotal / shippingFreeThreshold) * 100);

  // Animate progress bar on open, update on qty change
  React.useEffect(() => {
    if (!open) { setBarWidth(0); return; }
    const t = setTimeout(() => setBarWidth(realBarWidth), 16);
    return () => clearTimeout(t);
  }, [open, realBarWidth]);

  // Focus trap while drawer is open
  React.useEffect(() => {
    if (!open) return;
    const drawer = drawerRef.current;
    if (!drawer) return;
    const focusables = drawer.querySelectorAll(
      'button:not([disabled]), [href], input:not([disabled]), [tabindex]:not([tabindex="-1"])'
    );
    const first = focusables[0];
    const last  = focusables[focusables.length - 1];
    first?.focus();
    const trap = (e) => {
      if (e.key !== "Tab") return;
      if (e.shiftKey) {
        if (document.activeElement === first) { e.preventDefault(); last?.focus(); }
      } else {
        if (document.activeElement === last)  { e.preventDefault(); first?.focus(); }
      }
    };
    document.addEventListener("keydown", trap);
    return () => document.removeEventListener("keydown", trap);
  }, [open]);

  const updateQty = (idx, q) => {
    setItems(prev => prev.map((it, i) => i === idx ? { ...it, qty: Math.max(1, q) } : it));
  };
  const remove = (idx) => setItems(prev => prev.filter((_, i) => i !== idx));

  return (
    <>
      <div className={"scrim" + (open ? " open" : "")} onClick={onClose} />
      <aside ref={drawerRef} className={"drawer" + (open ? " open" : "")} aria-hidden={!open}>
        {/* Header */}
        <div className="row justify-between items-center" style={{ padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <div className="col">
            <span className="eyebrow">— <span className="km-sans">កន្ត្រករបស់អ្នក</span> · Your cart</span>
            <span className="serif" style={{ fontSize: 26 }}>
              {items.length} <span className="km-sans" style={{ fontSize: 20 }}>ទំនិញ</span> {items.length === 1 ? "item" : "items"}
            </span>
          </div>
          <button className="btn btn-ghost" onClick={onClose} aria-label="Close">
            <Icon name="close" size={18} />
          </button>
        </div>

        {/* Shipping progress */}
        {items.length > 0 && (
          <div style={{ padding: "14px 24px", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
            {subtotal >= shippingFreeThreshold ? (
              <div className="row gap-8 items-center">
                <Icon name="check" size={14} />
                <span className="mono" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                  <span className="km-sans" style={{ letterSpacing: 0, textTransform: "none" }}>ដឹកឥតគិតថ្លៃ</span> · Free shipping unlocked
                </span>
              </div>
            ) : (
              <div className="col gap-8">
                <span className="mono" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-muted)" }}>
                  <span className="km-sans" style={{ letterSpacing: 0, textTransform: "none" }}>ត្រូវការ ${(shippingFreeThreshold - subtotal).toFixed(0)} ទៀត</span> · ${(shippingFreeThreshold - subtotal).toFixed(0)} away from free shipping
                </span>
                <div style={{ height: 4, background: "var(--bg-3)", borderRadius: 99, overflow: "hidden" }}>
                  <div style={{
                    height: "100%", width: `${barWidth}%`,
                    background: "var(--accent)", transition: "width 260ms ease"
                  }} />
                </div>
              </div>
            )}
          </div>
        )}

        {/* Items */}
        <div style={{ flex: 1, overflowY: "auto", padding: items.length ? 0 : "48px 24px" }}>
          {items.length === 0 ? (
            <div className="col gap-16 items-center" style={{ padding: "80px 24px", textAlign: "center" }}>
              <div style={{
                width: 72, height: 72, borderRadius: 999, border: "1px solid var(--line-strong)",
                display: "grid", placeItems: "center", color: "var(--fg-muted)"
              }}>
                <Icon name="cart" size={28} />
              </div>
              <h3 className="serif" style={{ fontSize: "var(--text-3xl)" }}>
                <span className="km" style={{ display: "block", fontSize: "var(--text-2xl)" }}>កន្ត្រកទទេ។</span>
                <em style={{ fontStyle: "italic", fontSize: "var(--text-xl)", color: "var(--fg-muted)" }}>Cart's empty.</em>
              </h3>
              <p className="text-muted" style={{ margin: 0, maxWidth: 260 }}>
                <span className="km-sans" style={{ display: "block", color: "var(--fg)", marginBottom: 4 }}>កណ្ដៀរនឹងឆ្លើបរីករាយ ។ កុំឲ្យពួកវាឈ្នះ ។</span>
                The termites will celebrate. Don't give them the satisfaction.
              </p>
              <button className="btn btn-primary" onClick={onClose}>
                <span className="km-sans">ចាប់ផ្ដើមទិញ</span> · Start shopping
              </button>
            </div>
          ) : (
            lines.map((l, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "88px 1fr auto", gap: 16,
                padding: "20px 24px", borderBottom: "1px solid var(--line)", alignItems: "start"
              }}>
                <Photo src="uploads/termite-detail-1.jpeg" caption={l.p.sku} aspect="1 / 1" bg="#f5f1ea" />
                <div className="col gap-6">
                  <span className="mono text-muted" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.12em" }}>
                    {l.p.sku} · {l.s.label.toUpperCase()}
                  </span>
                  <span className="serif" style={{ fontSize: 20, lineHeight: 1.1 }}>{l.p.name}</span>
                  <span className="text-muted" style={{ fontSize: "var(--text-2xs)" }}>{l.s.desc}</span>
                  <div className="row gap-12 items-center" style={{ marginTop: 6 }}>
                    <Stepper
                      value={l.qty}
                      onChange={(q) => updateQty(i, q)}
                      max={(() => { const v = (window.INVENTORY||{})[l.sizeId]; return typeof v === "number" ? v : 99; })()}
                    />
                    <button
                      onClick={() => remove(i)}
                      aria-label="Remove item"
                      style={{ background: "transparent", border: 0, cursor: "pointer", color: "var(--fg-muted)",
                               fontFamily: "var(--font-mono)", fontSize: "var(--text-2xs)", letterSpacing: "0.08em",
                               textTransform: "uppercase", textDecoration: "underline",
                               padding: "10px 4px", margin: "-10px -4px" }}
                    ><span className="km-sans" style={{ letterSpacing: 0, textTransform: "none" }}>លុប</span> · Remove</button>
                  </div>
                </div>
                <span className="serif" style={{ fontSize: 20 }}>${l.total}</span>
              </div>
            ))
          )}
        </div>

        {/* Footer totals */}
        {items.length > 0 && (
          <div style={{ borderTop: "1px solid var(--line-strong)", padding: "20px 24px 24px", background: "var(--bg)" }}>
            <div className="col gap-8" style={{ marginBottom: 16 }}>
              {[
                [<><span className="km-sans">តម្លៃរង</span> · Subtotal</>, `$${subtotal.toFixed(2)}`],
                [<><span className="km-sans">ថ្លៃដឹក</span> · Shipping</>, shipping === 0 ? <><span className="km-sans">ឥតគិតថ្លៃ</span> · Free</> : `$${shipping.toFixed(2)}`],
              ].map(([k, v], i) => (
                <div key={i} className="row justify-between items-center">
                  <span className="mono text-muted" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{k}</span>
                  <span style={{ fontSize: 14 }}>{v}</span>
                </div>
              ))}
              <hr className="hr" style={{ margin: "6px 0" }} />
              <div className="row justify-between items-center">
                <span className="serif" style={{ fontSize: "var(--text-2xl)" }}><span className="km" style={{ fontSize: "var(--text-xl)" }}>សរុប</span> · Total</span>
                <span className="serif" style={{ fontSize: "var(--text-3xl)" }}>${total.toFixed(2)}</span>
              </div>
            </div>
            <button className="btn btn-primary btn-lg" style={{ width: "100%" }} onClick={onCheckout}>
              <span className="km-sans">ទូទាត់ប្រាក់</span> · Checkout <Icon name="arrow-right" size={16} />
            </button>
            <div className="row gap-8 items-center justify-center" style={{ marginTop: 12, color: "var(--fg-muted)" }}>
              <Icon name="shield" size={13} />
              <span className="mono" style={{ fontSize: "var(--text-2xs)", letterSpacing: "0.12em", textTransform: "uppercase" }}>
                <span className="km-sans" style={{ letterSpacing: 0, textTransform: "none" }}>ការទូទាត់មានសុវត្ថិភាព · ធានា ៣០ ថ្ងៃ</span> · Secure checkout · 30-day guarantee
              </span>
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

Object.assign(window, { CartDrawer });
