// brodo-overlays.jsx — QuickView modal + responsive Cart (drawer / bottom sheet)
(function () {
  const { useState, useEffect } = React;
  const Icon = window.Icon;
  const { Button, Badge, Price, Rating, QtyStepper, OptionSelector, ImgPlaceholder } = window;
  const { formatCLP, SWATCH_HEX } = window.BRODO;

  const FREE_SHIP = 35000;

  function optionsSummary(options) {
    const vals = Object.values(options || {});
    return vals.length ? vals.join(" · ") : null;
  }

  // ===================== QUICK VIEW =====================
  function QuickViewPanel({ product, closing, onClose }) {
    const cart = window.useCart();
    const [opts, setOpts] = useState(() => {
      const o = {};
      (product.options || []).forEach((op) => { o[op.key] = op.values[0]; });
      return o;
    });
    const [qty, setQty] = useState(1);
    const total = product.price * qty;

    function addToCart() {
      cart.add(product, opts, qty);
      onClose();
    }

    return React.createElement("div", {
      className: `fixed inset-0 z-[60] flex items-center justify-center p-0 sm:p-6 transition-opacity duration-200 ${closing ? "opacity-0" : "opacity-100"}`,
    },
      React.createElement("div", { className: "absolute inset-0 bg-ink/45 backdrop-blur-[2px]", onClick: onClose }),
      React.createElement("div", {
        className: `relative bg-paper w-full sm:max-w-[860px] max-h-[94vh] sm:max-h-[88vh] overflow-y-auto rounded-t-[var(--radius-lg)] sm:rounded-[var(--radius-lg)] shadow-2xl mt-auto sm:mt-0 transition-transform duration-300 ${closing ? "translate-y-6 sm:translate-y-3" : "translate-y-0"}`,
      },
        React.createElement("button", { className: "absolute top-3.5 right-3.5 z-10 w-10 h-10 grid place-items-center rounded-full bg-paper/90 backdrop-blur text-ink shadow hover:bg-paper", onClick: onClose, "aria-label": "Cerrar" },
          React.createElement(Icon, { name: "X", size: 20 })),
        React.createElement("div", { className: "grid sm:grid-cols-2" },
          // image
          React.createElement("div", { className: "relative min-h-[240px] sm:min-h-[420px]" },
            React.createElement(ImgPlaceholder, { img: product.img, photo: product.photo, alt: product.name, className: "absolute inset-0 w-full h-full", iconSize: 92, rounded: "0" }),
            product.badge ? React.createElement("div", { className: "absolute top-4 left-4" }, React.createElement(Badge, { tone: product.badge.tone }, product.badge.label)) : null),
          // details
          React.createElement("div", { className: "p-6 sm:p-8 flex flex-col" },
            React.createElement(Rating, { value: product.rating, reviews: product.reviews }),
            React.createElement("h2", { className: "font-display font-extrabold text-ink text-[26px] sm:text-[30px] leading-[1.05] tracking-tight mt-2" }, product.name),
            React.createElement("p", { className: "text-sub font-body mt-2" }, product.tagline),
            React.createElement("div", { className: "mt-4" }, React.createElement(Price, { value: product.price, compareAt: product.compareAt, size: "lg" })),
            // includes for packs
            product.includes ? React.createElement("ul", { className: "mt-4 grid gap-2" },
              product.includes.map((inc, i) => React.createElement("li", { key: i, className: "flex items-center gap-2.5 text-ink font-body text-sm" },
                React.createElement("span", { className: "w-5 h-5 grid place-items-center rounded-full bg-[var(--brand-soft)] shrink-0" }, React.createElement(Icon, { name: "Check", size: 12, stroke: 3 })), inc))) : null,
            // options
            React.createElement("div", { className: "mt-5 space-y-4" },
              (product.options || []).map((op) => React.createElement("div", { key: op.key },
                React.createElement("div", { className: "font-body font-extrabold text-xs uppercase tracking-wide text-sub mb-2" },
                  op.label, op.swatch ? React.createElement("span", { className: "ml-2 normal-case text-ink/50 font-bold tracking-normal" }, opts[op.key]) : null),
                React.createElement(OptionSelector, { option: op, value: opts[op.key], onChange: (v) => setOpts((s) => ({ ...s, [op.key]: v })) })))),
            // qty + add
            React.createElement("div", { className: "mt-6" },
              React.createElement("div", { className: "font-body font-extrabold text-xs uppercase tracking-wide text-sub mb-2" }, "Cantidad"),
              React.createElement(QtyStepper, { value: qty, onChange: (q) => setQty(Math.max(1, q)) })),
            React.createElement("div", { className: "mt-auto pt-6" },
              React.createElement(Button, { size: "lg", full: true, onClick: addToCart },
                React.createElement(Icon, { name: "ShoppingCart", size: 18 }), "Añadir al carrito · " + formatCLP(total))),
            React.createElement("div", { className: "mt-3 flex flex-wrap gap-x-4 gap-y-1 justify-center text-xs font-body font-bold text-sub" },
              [["Truck", "Envío 24h"], ["Snowflake", "Apto freezer"], ["Leaf", "Libre BPA"]].map(([ic, t], i) =>
                React.createElement("span", { key: i, className: "inline-flex items-center gap-1" }, React.createElement(Icon, { name: ic, size: 13, className: "text-brand-2" }), t)))))));
  }

  function QuickView() {
    const cart = window.useCart();
    const [closing, setClosing] = useState(false);
    const product = cart.quickView;
    useEffect(() => { if (product) setClosing(false); }, [product]);
    if (!product) return null;
    function close() {
      setClosing(true);
      window.setTimeout(() => cart.setQuickView(null), 220);
    }
    return React.createElement(QuickViewPanel, { key: product.id, product, closing, onClose: close });
  }

  // ===================== CART LINE =====================
  function CartLine({ item }) {
    const cart = window.useCart();
    const sum = optionsSummary(item.options);
    return React.createElement("div", { className: "flex gap-3 py-4" },
      React.createElement(ImgPlaceholder, { img: item.img, photo: item.photo, alt: item.name, className: "w-[68px] h-[68px] shrink-0", iconSize: 26, rounded: "var(--radius)" }),
      React.createElement("div", { className: "flex-1 min-w-0" },
        React.createElement("div", { className: "flex items-start justify-between gap-2" },
          React.createElement("h4", { className: "font-display font-extrabold text-ink leading-tight truncate" }, item.name),
          React.createElement("button", { className: "text-sub/60 hover:text-brand-2 transition-colors shrink-0 p-0.5", onClick: () => cart.remove(item.key), "aria-label": "Quitar" },
            React.createElement(Icon, { name: "Trash2", size: 16 }))),
        sum ? React.createElement("div", { className: "text-xs font-body text-sub mt-0.5 truncate" }, sum) : null,
        React.createElement("div", { className: "flex items-center justify-between gap-2 mt-2" },
          React.createElement(QtyStepper, { value: item.qty, onChange: (q) => cart.setQty(item.key, q), size: "sm" }),
          React.createElement("span", { className: "font-display font-extrabold text-ink" }, formatCLP(item.price * item.qty)))));
  }

  // ===================== CART DRAWER =====================
  function CartDrawer() {
    const cart = window.useCart();
    const open = cart.drawerOpen;
    const [checkout, setCheckout] = useState(false);
    const remaining = Math.max(0, FREE_SHIP - cart.subtotal);
    const pct = Math.min(100, (cart.subtotal / FREE_SHIP) * 100);

    useEffect(() => {
      function onKey(e) { if (e.key === "Escape") cart.setDrawerOpen(false); }
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, []);
    useEffect(() => { if (!open) setCheckout(false); }, [open]);

    function doCheckout() {
      setCheckout(true);
      window.setTimeout(() => { setCheckout(false); }, 2400);
    }

    return React.createElement("div", { className: `fixed inset-0 z-50 ${open ? "" : "pointer-events-none"}`, "aria-hidden": !open },
      // backdrop
      React.createElement("div", {
        className: `absolute inset-0 bg-ink/45 backdrop-blur-[2px] transition-opacity duration-300 ${open ? "opacity-100" : "opacity-0"}`,
        onClick: () => cart.setDrawerOpen(false),
      }),
      // panel
      React.createElement("div", {
        className: `absolute bg-paper shadow-2xl flex flex-col transition-transform duration-300 ease-out
          left-0 right-0 bottom-0 max-h-[90vh] rounded-t-[var(--radius-lg)]
          sm:left-auto sm:top-0 sm:bottom-0 sm:right-0 sm:w-[420px] sm:max-h-none sm:rounded-none sm:rounded-l-[var(--radius-lg)]
          ${open ? "translate-y-0 sm:translate-x-0" : "translate-y-full sm:translate-y-0 sm:translate-x-full"}`,
      },
        // grab handle (mobile)
        React.createElement("div", { className: "sm:hidden pt-3 flex justify-center" }, React.createElement("span", { className: "w-11 h-1.5 rounded-full bg-ink/15" })),
        // header
        React.createElement("div", { className: "flex items-center justify-between px-5 pt-4 pb-3" },
          React.createElement("div", { className: "flex items-center gap-2" },
            React.createElement("h3", { className: "font-display font-extrabold text-ink text-xl whitespace-nowrap" }, "Tu carrito"),
            cart.count > 0 ? React.createElement(Badge, { tone: "soft" }, cart.count) : null),
          React.createElement("button", { className: "w-9 h-9 grid place-items-center rounded-full hover:bg-ink/5 text-ink", onClick: () => cart.setDrawerOpen(false), "aria-label": "Cerrar" },
            React.createElement(Icon, { name: "X", size: 20 }))),

        cart.items.length === 0
          ? // empty state
          React.createElement("div", { className: "flex-1 flex flex-col items-center justify-center text-center px-8 py-16" },
            React.createElement("span", { className: "w-20 h-20 grid place-items-center rounded-full bg-[var(--brand-soft)] text-ink mb-4" }, React.createElement(Icon, { name: "ShoppingCart", size: 34, stroke: 1.5 })),
            React.createElement("p", { className: "font-display font-extrabold text-ink text-lg" }, "Tu carrito está vacío"),
            React.createElement("p", { className: "text-sub font-body text-sm mt-1" }, "Suma un pack o arma tu propio set."),
            React.createElement(Button, { className: "mt-5", onClick: () => cart.setDrawerOpen(false) }, "Explorar productos"))
          : React.createElement(React.Fragment, null,
            // free ship progress
            React.createElement("div", { className: "px-5 pb-3" },
              React.createElement("div", { className: "h-2 rounded-full bg-ink/8 overflow-hidden" },
                React.createElement("div", { className: "h-full bg-brand transition-all duration-500", style: { width: pct + "%" } })),
              React.createElement("p", { className: "text-xs font-body text-sub mt-1.5" },
                remaining > 0
                  ? React.createElement(React.Fragment, null, "Te faltan ", React.createElement("b", { className: "text-ink" }, formatCLP(remaining)), " para ", React.createElement("b", { className: "text-ink" }, "envío gratis"))
                  : React.createElement("span", { className: "text-ink font-bold inline-flex items-center gap-1" }, React.createElement(Icon, { name: "Check", size: 13, stroke: 3, className: "text-brand-2" }), "¡Tienes envío gratis!"))),
            // items
            React.createElement("div", { className: "flex-1 overflow-y-auto px-5 divide-y divide-line" },
              cart.items.map((it) => React.createElement(CartLine, { key: it.key, item: it }))),
            // footer
            React.createElement("div", { className: "border-t border-line px-5 pt-4 pb-5 bg-paper" },
              React.createElement("div", { className: "flex items-center justify-between" },
                React.createElement("span", { className: "font-body text-sub" }, "Subtotal"),
                React.createElement("span", { className: "font-display font-extrabold text-ink text-2xl" }, formatCLP(cart.subtotal))),
              React.createElement("p", { className: "text-xs text-sub font-body mt-0.5" }, "Impuestos y envío calculados en el checkout"),
              React.createElement(Button, { size: "lg", full: true, className: "mt-4", onClick: doCheckout, disabled: checkout },
                checkout
                  ? React.createElement(React.Fragment, null, React.createElement("span", { className: "brodo-spin w-5 h-5 rounded-full border-2 border-ink/30 border-t-ink" }), "Redirigiendo…")
                  : React.createElement(React.Fragment, null, "Proceder al pago", React.createElement(Icon, { name: "ArrowRight", size: 18 }))),
              React.createElement("p", { className: "text-center text-xs text-sub font-body mt-2.5 inline-flex w-full items-center justify-center gap-1" },
                React.createElement(Icon, { name: "ArrowRight", size: 12 }), "Redirige al checkout seguro de Shopify")))));
  }

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