// PepLab Co — Reusable UI components

const WhatsAppIcon = ({ size = 18, color = "currentColor" }) => (
  <svg className="wa-icon" width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
  </svg>
);

const ArrowRight = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <line x1="5" y1="12" x2="19" y2="12" />
    <polyline points="12 5 19 12 12 19" />
  </svg>
);

const PlMolecule = ({ size = 28, color = "currentColor" }) => (
  // Original mark: two linked hexagonal nodes (abstract molecule), thin lines
  <svg width={size} height={size} viewBox="0 0 56 32" fill="none" stroke={color} strokeWidth="1.5" aria-hidden="true">
    <polygon points="14,4 24,10 24,22 14,28 4,22 4,10" />
    <polygon points="42,4 52,10 52,22 42,28 32,22 32,10" />
    <line x1="24" y1="16" x2="32" y2="16" />
    <circle cx="14" cy="16" r="2" fill={color} stroke="none" />
    <circle cx="42" cy="16" r="2" fill={color} stroke="none" />
  </svg>
);

const Logo = ({ color = "var(--navy-deep)", size = 22 }) => (
  <a href="/" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none", color }}>
    <PlMolecule size={28} color={color} />
    <span className="serif" style={{ fontSize: size, fontWeight: 500, letterSpacing: "0.01em", color }}>
      PepLab<span style={{ color: "var(--champagne)", marginLeft: 4 }}>Co</span>
    </span>
  </a>
);

// Vial illustration — original geometric SVG (not branded)
const Vial = ({ accent = "var(--navy-deep)", label = "GHK-Cu", dose = "50 MG", size = 240 }) => {
  const w = size;
  const h = size * 1.4;
  return (
    <svg width={w} height={h} viewBox="0 0 200 280" xmlns="http://www.w3.org/2000/svg" aria-label={`${label} vial`}>
      <defs>
        <linearGradient id={`vialGlass-${label}`} x1="0" y1="0" x2="1" y2="0">
          <stop offset="0" stopColor="rgba(255,255,255,0)" />
          <stop offset="0.45" stopColor="rgba(255,255,255,0.55)" />
          <stop offset="0.55" stopColor="rgba(255,255,255,0.55)" />
          <stop offset="1" stopColor="rgba(255,255,255,0)" />
        </linearGradient>
        <linearGradient id={`label-${label}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#FAF7F0" />
          <stop offset="1" stopColor="#F2ECDC" />
        </linearGradient>
      </defs>
      {/* shadow */}
      <ellipse cx="100" cy="270" rx="60" ry="6" fill="rgba(11, 37, 69, 0.18)" />
      {/* cap */}
      <rect x="72" y="14" width="56" height="10" rx="1" fill="#1A1A1A" />
      <rect x="68" y="22" width="64" height="22" rx="2" fill="#E8E4DC" />
      <rect x="68" y="22" width="64" height="3" fill="#D4CFC2" />
      <rect x="68" y="38" width="64" height="2" fill="#D4CFC2" />
      {/* neck */}
      <rect x="80" y="42" width="40" height="14" fill="rgba(220,225,225,0.55)" stroke="rgba(11,37,69,0.15)" strokeWidth="0.6" />
      {/* body */}
      <rect x="56" y="56" width="88" height="200" rx="4" fill="rgba(232,236,240,0.45)" stroke="rgba(11,37,69,0.15)" strokeWidth="0.6" />
      {/* glass highlight */}
      <rect x="56" y="56" width="88" height="200" rx="4" fill={`url(#vialGlass-${label})`} opacity="0.4" />
      {/* powder inside */}
      <rect x="60" y="180" width="80" height="74" rx="2" fill="rgba(255,255,255,0.85)" />
      <rect x="60" y="178" width="80" height="3" fill="rgba(255,255,255,0.65)" />
      {/* label */}
      <rect x="50" y="84" width="100" height="148" rx="2" fill={`url(#label-${label})`} stroke="rgba(11,37,69,0.08)" strokeWidth="0.5" />
      {/* tiny molecule */}
      <g transform="translate(64, 96)" stroke={accent} strokeWidth="0.8" fill="none">
        <polygon points="6,1 11,4 11,10 6,13 1,10 1,4" />
        <polygon points="20,1 25,4 25,10 20,13 15,10 15,4" />
        <line x1="11" y1="7" x2="15" y2="7" />
        <circle cx="6" cy="7" r="1.2" fill={accent} stroke="none" />
        <circle cx="20" cy="7" r="1.2" fill={accent} stroke="none" />
      </g>
      <text x="98" y="106" fontFamily="Inter, sans-serif" fontSize="7" fontWeight="600" fill={accent} letterSpacing="0.08em">PEPLAB CO</text>
      {/* hairline */}
      <line x1="60" y1="118" x2="140" y2="118" stroke="rgba(201, 169, 97, 0.7)" strokeWidth="0.5" />
      {/* product name */}
      <text x="100" y="146" fontFamily="Cormorant Garamond, serif" fontSize="20" fontWeight="500" fill={accent} textAnchor="middle" letterSpacing="0.02em">{label}</text>
      {/* dose pill */}
      <rect x="74" y="160" width="52" height="18" rx="9" fill="none" stroke={accent} strokeWidth="0.7" />
      <text x="100" y="172" fontFamily="JetBrains Mono, monospace" fontSize="9" fontWeight="500" fill={accent} textAnchor="middle" letterSpacing="0.12em">{dose}</text>
      {/* navy bottom band */}
      <rect x="50" y="208" width="100" height="24" fill={accent} />
      <text x="100" y="223" fontFamily="Inter, sans-serif" fontSize="6" fontWeight="600" fill="white" textAnchor="middle" letterSpacing="0.18em">PUREZA &gt; 99% · AUSTRALIA</text>
    </svg>
  );
};

// Header
const PlHeader = ({ scrolled, onCartOpen }) => {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const linkColor = scrolled ? "var(--graphite)" : "var(--white)";
  const navItems = [
    { label: "Tienda", href: "/#productos" },
    { label: "Usos", href: "/#usos" },
    { label: "Cómo comprar", href: "/#como-comprar" },
    { label: "Guía", href: "/#articulos" },
    { label: "FAQ", href: "/#faq" },
  ];

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  return (
  <header
    style={{
      position: "fixed", top: 0, left: 0, right: 0,
      zIndex: 50,
      background: scrolled || mobileOpen ? "rgba(255,255,255,0.92)" : "transparent",
      backdropFilter: scrolled || mobileOpen ? "blur(12px) saturate(120%)" : "none",
      borderBottom: scrolled ? "1px solid var(--gray-line)" : "1px solid transparent",
      transition: "all 0.3s cubic-bezier(0.2, 0.8, 0.2, 1)",
    }}
  >
    <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 76 }}>
      <Logo color={scrolled || mobileOpen ? "var(--navy-deep)" : "var(--white)"} />

      {/* Desktop nav */}
      <nav className="pl-nav-desktop" style={{ display: "flex", alignItems: "center", gap: 36 }}>
        {navItems.map((item) => (
          <a key={item.label} href={item.href} style={{
            color: linkColor,
            textDecoration: "none",
            fontSize: 14,
            fontWeight: 500,
            letterSpacing: "0.01em",
            transition: "color 0.2s",
          }}>
            {item.label}
          </a>
        ))}
        <CartButton onClick={() => onCartOpen && onCartOpen()} color={linkColor} />
        <a href={waUrl()} target="_blank" rel="noopener noreferrer" className="btn btn-whatsapp btn-sm">
          <WhatsAppIcon size={16} color="white" />
          WhatsApp
        </a>
      </nav>

      {/* Mobile controls (Cart + WhatsApp icon + hamburger) */}
      <div className="pl-nav-mobile" style={{ display: "none", alignItems: "center", gap: 8 }}>
        <CartButton onClick={() => onCartOpen && onCartOpen()} color={scrolled || mobileOpen ? "var(--graphite)" : "var(--white)"} compact />
        <a
          href={waUrl()}
          target="_blank"
          rel="noopener noreferrer"
          aria-label="WhatsApp"
          style={{
            width: 40, height: 40, borderRadius: "50%",
            background: "var(--whatsapp)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}
        >
          <WhatsAppIcon size={18} color="white" />
        </a>
        <button
          type="button"
          onClick={() => setMobileOpen((v) => !v)}
          aria-label={mobileOpen ? "Cerrar menú" : "Abrir menú"}
          aria-expanded={mobileOpen}
          style={{
            width: 40, height: 40,
            background: "transparent",
            border: "1px solid " + (scrolled || mobileOpen ? "var(--gray-line)" : "rgba(255,255,255,0.4)"),
            borderRadius: 4,
            display: "flex", flexDirection: "column",
            alignItems: "center", justifyContent: "center",
            gap: 5,
            cursor: "pointer",
            padding: 0,
          }}
        >
          <span style={{
            display: "block", width: 16, height: 1.5,
            background: scrolled || mobileOpen ? "var(--graphite)" : "var(--white)",
            transition: "transform 0.25s, opacity 0.25s",
            transform: mobileOpen ? "translateY(3px) rotate(45deg)" : "none",
          }} />
          <span style={{
            display: "block", width: 16, height: 1.5,
            background: scrolled || mobileOpen ? "var(--graphite)" : "var(--white)",
            transition: "transform 0.25s, opacity 0.25s",
            transform: mobileOpen ? "translateY(-3px) rotate(-45deg)" : "none",
          }} />
        </button>
      </div>
    </div>

    {/* Mobile dropdown panel */}
    {mobileOpen && (
      <div
        className="pl-nav-mobile-panel"
        style={{
          position: "absolute", top: 76, left: 0, right: 0,
          background: "rgba(255, 255, 255, 0.98)",
          backdropFilter: "blur(20px) saturate(140%)",
          borderBottom: "1px solid var(--gray-line)",
          padding: "20px 0 28px",
          animation: "fadeUp 0.25s ease-out",
        }}
      >
        <div className="container" style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          {navItems.map((item) => (
            <a
              key={item.label}
              href={item.href}
              onClick={() => setMobileOpen(false)}
              style={{
                color: "var(--navy-deep)",
                textDecoration: "none",
                fontSize: 18,
                fontWeight: 500,
                padding: "14px 0",
                borderBottom: "1px solid var(--gray-line)",
              }}
            >
              {item.label}
            </a>
          ))}
          <a
            href={waUrl()}
            target="_blank"
            rel="noopener noreferrer"
            onClick={() => setMobileOpen(false)}
            className="btn btn-whatsapp"
            style={{ marginTop: 20, width: "100%" }}
          >
            <WhatsAppIcon size={16} color="white" />
            Conversemos por WhatsApp
          </a>
        </div>
      </div>
    )}
  </header>
  );
};

// Sticky WhatsApp
const StickyWA = () => (
  <a
    href={waUrl()}
    target="_blank"
    rel="noopener noreferrer"
    aria-label="Conversemos por WhatsApp"
    style={{
      position: "fixed", bottom: 28, right: 28, zIndex: 40,
      width: 60, height: 60, borderRadius: "50%",
      background: "var(--whatsapp)",
      display: "flex", alignItems: "center", justifyContent: "center",
      boxShadow: "0 12px 30px rgba(37, 211, 102, 0.4), 0 4px 12px rgba(0,0,0,0.1)",
      color: "white",
      transition: "transform 0.2s",
    }}
    onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.08)"}
    onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
  >
    <WhatsAppIcon size={28} color="white" />
  </a>
);

// Cart icon (SVG) with optional badge counter
const CartIcon = ({ size = 22, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M3 3h2.4l2.4 12.5a2 2 0 0 0 2 1.5h7.5a2 2 0 0 0 2-1.5L21 7H6" />
    <circle cx="10" cy="20.5" r="1.2" fill={color} stroke="none" />
    <circle cx="17" cy="20.5" r="1.2" fill={color} stroke="none" />
  </svg>
);

// Cart button — opens the cart drawer. Used inside the header.
const CartButton = ({ onClick, color = "var(--graphite)", compact = false }) => {
  const cart = (typeof useCart === "function") ? useCart() : { items: [] };
  const count = (cart.items || []).reduce((a, i) => a + i.quantity, 0);

  return (
    <button
      type="button"
      onClick={onClick}
      aria-label={`Abrir carrito (${count} items)`}
      style={{
        position: "relative",
        background: "transparent",
        border: "none",
        cursor: "pointer",
        padding: compact ? 6 : 8,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        color,
        transition: "color 0.2s",
      }}
    >
      <CartIcon size={compact ? 20 : 22} color={color} />
      {count > 0 && (
        <span
          style={{
            position: "absolute",
            top: compact ? -2 : 0,
            right: compact ? -2 : 0,
            minWidth: 18,
            height: 18,
            padding: "0 5px",
            background: "var(--champagne)",
            color: "var(--navy-deep)",
            fontFamily: "var(--mono)",
            fontSize: 10,
            fontWeight: 700,
            lineHeight: 1,
            borderRadius: 999,
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            boxShadow: "0 0 0 2px " + (color === "var(--white)" ? "rgba(11,37,69,0.95)" : "var(--white)"),
            animation: "fadeUp 0.3s ease-out",
          }}
        >
          {count > 99 ? "99+" : count}
        </span>
      )}
    </button>
  );
};

// CartToast — appears top-right after adding an item, dismisses in 4s
// Listens to PEPLAB_CART.lastAdded changes via useCart hook
const CartToast = ({ onCartOpen }) => {
  const cartState = (typeof useCart === "function") ? useCart() : { lastAdded: null };
  const [visible, setVisible] = React.useState(false);
  const [displayed, setDisplayed] = React.useState(null);
  const lastSeenTs = React.useRef(0);
  const dismissTimer = React.useRef(null);

  React.useEffect(() => {
    const la = cartState.lastAdded;
    if (!la || !la.ts || la.ts === lastSeenTs.current) return;
    lastSeenTs.current = la.ts;
    setDisplayed(la);
    setVisible(true);
    if (dismissTimer.current) clearTimeout(dismissTimer.current);
    dismissTimer.current = setTimeout(() => {
      setVisible(false);
      // Give the slide-out animation time before clearing the cached display
      setTimeout(() => setDisplayed(null), 350);
    }, 4000);
    return () => {
      if (dismissTimer.current) clearTimeout(dismissTimer.current);
    };
  }, [cartState.lastAdded]);

  const handleViewCart = () => {
    setVisible(false);
    if (dismissTimer.current) clearTimeout(dismissTimer.current);
    if (window.PEPLAB_CART) window.PEPLAB_CART.clearLastAdded();
    if (onCartOpen) onCartOpen();
  };

  const handleDismiss = () => {
    setVisible(false);
    if (dismissTimer.current) clearTimeout(dismissTimer.current);
  };

  if (!displayed) return null;

  const product = (window.PEPLAB_PRODUCTS || []).find((p) => p.slug === displayed.slug);
  if (!product) return null;

  const count = (cartState.items || []).reduce((a, i) => a + i.quantity, 0);

  return (
    <div
      role="status"
      aria-live="polite"
      className="cart-toast"
      style={{
        position: "fixed",
        top: 96,
        right: 24,
        zIndex: 80,
        width: "min(360px, calc(100vw - 48px))",
        background: "var(--white)",
        borderLeft: "3px solid var(--success)",
        borderRadius: 4,
        boxShadow: "0 20px 50px rgba(11, 37, 69, 0.18), 0 0 0 1px rgba(11, 37, 69, 0.04)",
        padding: "18px 18px 18px 20px",
        display: "flex",
        gap: 14,
        alignItems: "flex-start",
        opacity: visible ? 1 : 0,
        transform: visible ? "translateX(0)" : "translateX(120%)",
        transition: "transform 0.4s cubic-bezier(0.2, 0.8, 0.2, 1), opacity 0.3s",
        pointerEvents: visible ? "auto" : "none",
      }}
    >
      {/* Product thumbnail */}
      <div style={{
        width: 48, height: 56,
        background: "var(--ivory)",
        borderRadius: 4,
        display: "flex", alignItems: "center", justifyContent: "center",
        overflow: "hidden",
        flexShrink: 0,
      }}>
        {product.image ? (
          <img src={product.image} alt="" style={{ width: "auto", height: "100%", objectFit: "contain" }} />
        ) : (
          <Vial size={36} label={product.name.split(" ")[0].toUpperCase()} dose={product.dose.toUpperCase().replace(" ", "")} />
        )}
      </div>

      {/* Body */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 6,
          marginBottom: 4,
        }}>
          <span style={{
            width: 16, height: 16,
            borderRadius: "50%",
            background: "var(--success)",
            color: "white",
            display: "inline-flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: 10,
            fontWeight: 700,
            flexShrink: 0,
          }}>✓</span>
          <span className="mono" style={{
            fontSize: 10,
            color: "var(--success)",
            letterSpacing: "0.15em",
            textTransform: "uppercase",
            fontWeight: 600,
          }}>
            Agregado al carrito
          </span>
        </div>
        <div className="serif" style={{
          fontSize: 15,
          color: "var(--navy-deep)",
          fontWeight: 500,
          lineHeight: 1.25,
          marginBottom: 12,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}>
          {product.name}
        </div>
        <button
          type="button"
          onClick={handleViewCart}
          style={{
            background: "var(--navy-deep)",
            color: "var(--champagne)",
            border: "none",
            borderRadius: 4,
            padding: "9px 14px",
            fontFamily: "var(--sans)",
            fontSize: 12,
            fontWeight: 600,
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            cursor: "pointer",
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            transition: "all 0.2s",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = "var(--navy-mid)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = "var(--navy-deep)"; }}
        >
          Ver carrito · {count} {count === 1 ? "item" : "items"} <ArrowRight size={12} />
        </button>
      </div>

      {/* Dismiss */}
      <button
        type="button"
        onClick={handleDismiss}
        aria-label="Cerrar notificación"
        style={{
          background: "none",
          border: "none",
          color: "var(--gray-text)",
          cursor: "pointer",
          padding: 2,
          fontSize: 18,
          lineHeight: 1,
          flexShrink: 0,
        }}
      >
        ×
      </button>
    </div>
  );
};

// CartDrawer — slide-in from the right with the full cart UI
const CartDrawer = ({ open, onClose }) => {
  const cartState = (typeof useCart === "function") ? useCart() : { items: [], region: null };
  const cart = window.PEPLAB_CART;
  const items = cartState.items || [];
  const region = cartState.region;
  const shipping = window.calcShipping ? window.calcShipping(items, region) : null;
  const subtotal = items.reduce((a, i) => {
    const p = (window.PEPLAB_PRODUCTS || []).find((p) => p.slug === i.slug);
    return a + (p?.priceNum || 0) * i.quantity;
  }, 0);
  const total = subtotal + (shipping || 0);
  const promoApplied = window.hasFreeShippingPromo ? window.hasFreeShippingPromo(items) : false;
  const upsellEligible = cart && cart.isEligibleForPromoUpsell ? cart.isEligibleForPromoUpsell() : false;
  const [checkoutLoading, setCheckoutLoading] = React.useState(false);
  const [checkoutError, setCheckoutError] = React.useState(null);
  const fmt = window.formatCLP || ((n) => "$" + n);

  // Lock body scroll while open
  React.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  if (!open) return null;

  const regions = (window.PEPLAB_SHIPPING && window.PEPLAB_SHIPPING.regions) || [];

  const handleCheckout = async () => {
    if (items.length === 0) return;
    if (!region) {
      setCheckoutError("Selecciona tu región para calcular el envío.");
      return;
    }
    setCheckoutError(null);
    setCheckoutLoading(true);
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items: items.map((i) => ({ slug: i.slug, quantity: i.quantity })),
          region,
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.init_point) {
        throw new Error(data.error || "No se pudo crear el pago");
      }
      window.location.href = data.init_point;
    } catch (err) {
      console.error("Cart checkout error:", err);
      setCheckoutError("No pudimos procesar tu pedido. Probá de nuevo o escribínos por WhatsApp.");
      setCheckoutLoading(false);
    }
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed", inset: 0, zIndex: 95,
        background: "rgba(11, 37, 69, 0.55)",
        backdropFilter: "blur(6px)",
        display: "flex", justifyContent: "flex-end",
        animation: "fadeUp 0.25s ease-out",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "min(520px, 100%)",
          height: "100vh",
          background: "var(--white)",
          overflow: "auto",
          animation: "slideRight 0.35s cubic-bezier(0.2, 0.8, 0.2, 1)",
          display: "flex", flexDirection: "column",
        }}
      >
        {/* Header */}
        <div
          style={{
            position: "sticky", top: 0, zIndex: 2,
            background: "var(--white)",
            padding: "20px 28px",
            borderBottom: "1px solid var(--gray-line)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
          }}
        >
          <div>
            <span className="uppercase-eyebrow" style={{ color: "var(--gray-text)" }}>
              Tu pedido
            </span>
            <h2 className="serif" style={{ fontSize: 24, color: "var(--navy-deep)", fontWeight: 500, marginTop: 2 }}>
              Carrito {items.length > 0 && <span style={{ color: "var(--champagne)" }}>· {items.length}</span>}
            </h2>
          </div>
          <button
            onClick={onClose}
            aria-label="Cerrar carrito"
            style={{
              background: "none", border: "none", cursor: "pointer",
              fontSize: 28, color: "var(--graphite)", padding: 4, lineHeight: 1,
            }}
          >
            ×
          </button>
        </div>

        {/* Body */}
        {items.length === 0 ? (
          <div style={{ flex: 1, padding: "48px 28px", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center" }}>
            <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--cream)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 24 }}>
              <CartIcon size={32} color="var(--champagne)" />
            </div>
            <h3 className="serif" style={{ fontSize: 22, color: "var(--navy-deep)", fontWeight: 500, marginBottom: 8 }}>
              Tu carrito está vacío
            </h3>
            <p style={{ fontSize: 14, color: "var(--gray-text)", maxWidth: 280, lineHeight: 1.5, marginBottom: 24 }}>
              Explorá la tienda y armá tu pedido. Recordá que sumando agua bacteriostática tenés envío gratis.
            </p>
            <a href="/#productos" onClick={onClose} className="btn btn-primary" style={{ height: 48 }}>
              Ver productos
            </a>
          </div>
        ) : (
          <>
            {/* Promo banner (when applied OR when eligible) */}
            {(promoApplied || upsellEligible) && (
              <div style={{
                margin: "20px 28px 0",
                padding: "14px 16px",
                background: promoApplied ? "rgba(45, 106, 79, 0.08)" : "var(--cream)",
                border: "1px dashed " + (promoApplied ? "var(--success)" : "var(--champagne)"),
                borderRadius: 4,
                display: "flex", gap: 12, alignItems: "center",
              }}>
                <span style={{
                  background: promoApplied ? "var(--success)" : "var(--champagne)",
                  color: promoApplied ? "white" : "var(--navy-deep)",
                  padding: "4px 10px", borderRadius: 2,
                  fontFamily: "var(--mono)", fontSize: 9, fontWeight: 700,
                  letterSpacing: "0.15em", textTransform: "uppercase",
                  flexShrink: 0,
                }}>
                  {promoApplied ? "Envío gratis ✓" : "Tip"}
                </span>
                <span style={{ fontSize: 13, color: "var(--graphite)", lineHeight: 1.4 }}>
                  {promoApplied
                    ? "Tu pedido califica para envío gratis a todo Chile."
                    : (
                      <>Sumá <button onClick={() => cart.addItem("agua-bacteriostatica", 1)} style={{ background: "none", border: "none", color: "var(--navy-deep)", fontWeight: 600, padding: 0, borderBottom: "1px solid var(--champagne)", cursor: "pointer", fontSize: 13 }}>agua bacteriostática</button> y el envío te sale gratis a todo Chile.</>
                    )}
                </span>
              </div>
            )}

            {/* Items */}
            <div style={{ padding: "20px 28px 0", flex: 1 }}>
              {items.map((item) => {
                const product = (window.PEPLAB_PRODUCTS || []).find((p) => p.slug === item.slug);
                if (!product) return null;
                return (
                  <div key={item.slug} style={{
                    display: "grid",
                    gridTemplateColumns: "72px 1fr auto",
                    gap: 16,
                    padding: "16px 0",
                    borderBottom: "1px solid var(--gray-line)",
                    alignItems: "center",
                  }}>
                    {/* image */}
                    <div style={{
                      width: 72, height: 88,
                      background: "var(--ivory)",
                      borderRadius: 4,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      overflow: "hidden",
                    }}>
                      {product.image ? (
                        <img src={product.image} alt={product.name} style={{ width: "auto", height: "100%", objectFit: "contain" }} />
                      ) : (
                        <Vial size={48} label={product.name.split(" ")[0].toUpperCase()} dose={product.dose.toUpperCase().replace(" ", "")} />
                      )}
                    </div>

                    {/* info */}
                    <div>
                      <div className="serif" style={{ fontSize: 17, color: "var(--navy-deep)", fontWeight: 500, lineHeight: 1.2 }}>
                        {product.name}
                      </div>
                      <div style={{ fontSize: 12, color: "var(--gray-text)", marginTop: 2 }}>
                        {product.dose} · <span className="mono">{fmt(product.priceNum)}</span>
                      </div>

                      {/* quantity controls */}
                      <div style={{ display: "inline-flex", alignItems: "center", marginTop: 10, border: "1px solid var(--gray-line)", borderRadius: 4 }}>
                        <button
                          type="button"
                          aria-label="Quitar uno"
                          onClick={() => cart.decrementItem(item.slug)}
                          style={{ width: 28, height: 28, background: "transparent", border: "none", cursor: "pointer", color: "var(--navy-deep)", fontSize: 16 }}
                        >−</button>
                        <span className="mono" style={{ minWidth: 24, textAlign: "center", fontSize: 13, fontWeight: 600, color: "var(--navy-deep)" }}>
                          {item.quantity}
                        </span>
                        <button
                          type="button"
                          aria-label="Agregar uno"
                          onClick={() => cart.incrementItem(item.slug)}
                          disabled={item.quantity >= 10}
                          style={{ width: 28, height: 28, background: "transparent", border: "none", cursor: item.quantity >= 10 ? "not-allowed" : "pointer", color: "var(--navy-deep)", fontSize: 16, opacity: item.quantity >= 10 ? 0.4 : 1 }}
                        >+</button>
                      </div>
                    </div>

                    {/* line total + delete */}
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
                      <span className="serif" style={{ fontSize: 16, color: "var(--navy-deep)", fontWeight: 500 }}>
                        {fmt(product.priceNum * item.quantity)}
                      </span>
                      <button
                        type="button"
                        onClick={() => cart.removeItem(item.slug)}
                        aria-label="Eliminar producto"
                        style={{ background: "none", border: "none", color: "var(--gray-text)", cursor: "pointer", fontSize: 11, padding: 0, textDecoration: "underline" }}
                      >
                        Eliminar
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Region selector + totals */}
            <div style={{ padding: "20px 28px 0", background: "var(--ivory)", borderTop: "1px solid var(--gray-line)" }}>
              <label style={{ display: "block", fontSize: 12, color: "var(--gray-text)", marginBottom: 8, fontFamily: "var(--mono)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                Región de envío
              </label>
              <select
                value={region || ""}
                onChange={(e) => cart.setRegion(e.target.value || null)}
                style={{
                  width: "100%",
                  padding: "12px 14px",
                  fontSize: 14,
                  fontFamily: "var(--sans)",
                  background: "var(--white)",
                  border: "1px solid var(--gray-line)",
                  borderRadius: 4,
                  color: "var(--graphite)",
                  cursor: "pointer",
                  appearance: "menulist",
                }}
              >
                <option value="">— Selecciona tu región —</option>
                {regions.map((r) => (
                  <option key={r.id} value={r.id}>{r.label}</option>
                ))}
              </select>

              {/* Breakdown */}
              <div style={{ padding: "20px 0 0", display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--gray-text)" }}>
                  <span>Subtotal</span>
                  <span className="mono" style={{ color: "var(--graphite)" }}>{fmt(subtotal)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--gray-text)" }}>
                  <span>Envío</span>
                  <span className="mono" style={{ color: shipping === 0 ? "var(--success)" : "var(--graphite)", fontWeight: shipping === 0 ? 600 : 400 }}>
                    {shipping == null ? "Selecciona región" : shipping === 0 ? "GRATIS" : fmt(shipping)}
                  </span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 12, marginTop: 4, borderTop: "1px solid var(--gray-line)" }}>
                  <span className="serif" style={{ fontSize: 18, color: "var(--navy-deep)", fontWeight: 500 }}>Total</span>
                  <span className="serif" style={{ fontSize: 22, color: "var(--navy-deep)", fontWeight: 500 }}>
                    {fmt(total)}
                  </span>
                </div>
              </div>
            </div>

            {/* Checkout footer */}
            <div style={{ padding: "20px 28px 28px", borderTop: "1px solid var(--gray-line)", background: "var(--white)" }}>
              {checkoutError && (
                <p style={{
                  fontSize: 12, color: "#B23A48",
                  marginBottom: 12, padding: "8px 12px",
                  background: "rgba(178, 58, 72, 0.06)",
                  border: "1px solid rgba(178, 58, 72, 0.2)",
                  borderRadius: 4, textAlign: "center",
                }}>{checkoutError}</p>
              )}
              <button
                type="button"
                onClick={handleCheckout}
                disabled={checkoutLoading || items.length === 0}
                style={{
                  width: "100%",
                  height: 56,
                  background: checkoutLoading ? "#008CD0" : "#009EE3",
                  border: "1.5px solid " + (checkoutLoading ? "#008CD0" : "#009EE3"),
                  borderRadius: 4,
                  color: "#FFFFFF",
                  fontFamily: "var(--sans)",
                  fontSize: 14,
                  fontWeight: 600,
                  letterSpacing: "0.04em",
                  textTransform: "uppercase",
                  cursor: checkoutLoading ? "wait" : "pointer",
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 10,
                  transition: "all 0.2s",
                }}
              >
                {checkoutLoading ? (
                  <>
                    <span style={{
                      width: 18, height: 18,
                      border: "2.5px solid rgba(255,255,255,0.3)",
                      borderTopColor: "#FFFFFF",
                      borderRadius: "50%",
                      animation: "spin 0.7s linear infinite",
                    }} />
                    Creando pago…
                  </>
                ) : (
                  <>Pagar con Mercado Pago · {fmt(total)}</>
                )}
              </button>
              {/* PayPal as USD shortcut — only when cart has exactly 1 item, qty 1 */}
              {(() => {
                if (items.length !== 1 || items[0].quantity !== 1) return null;
                const paypalUrl = window.PEPLAB_PAYMENTS?.paypal?.[items[0].slug];
                if (!paypalUrl) return null;
                return (
                  <a
                    href={paypalUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      gap: 10,
                      width: "100%",
                      height: 48,
                      marginTop: 10,
                      background: "#FFC439",
                      border: "1.5px solid #FFC439",
                      borderRadius: 4,
                      color: "#253B80",
                      textDecoration: "none",
                      fontFamily: "var(--sans)",
                      fontSize: 13,
                      fontWeight: 600,
                      transition: "all 0.2s",
                    }}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.background = "#F0B72A";
                      e.currentTarget.style.borderColor = "#F0B72A";
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.background = "#FFC439";
                      e.currentTarget.style.borderColor = "#FFC439";
                    }}
                  >
                    <PayPalMark size={16} />
                    <span style={{
                      fontFamily: "var(--mono)",
                      fontSize: 10,
                      fontWeight: 600,
                      letterSpacing: "0.18em",
                      textTransform: "uppercase",
                      opacity: 0.7,
                    }}>
                      o pagar en USD
                    </span>
                  </a>
                );
              })()}

              <p style={{ fontSize: 11, color: "var(--gray-text)", textAlign: "center", marginTop: 12, lineHeight: 1.5 }}>
                Pago seguro · Importado desde Australia · Solo para mayores de 18 años
              </p>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

// Age gate persistence — once user confirms 18+, remember for 30 days across pages
const AGE_KEY = "peplab-age-verified";
const AGE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const ageVerified = () => {
  try {
    const v = window.localStorage && localStorage.getItem(AGE_KEY);
    if (!v) return false;
    const ts = parseInt(v, 10);
    if (isNaN(ts)) return false;
    return Date.now() - ts < AGE_TTL_MS;
  } catch (e) { return false; }
};
const markAgeVerified = () => {
  try { localStorage.setItem(AGE_KEY, Date.now().toString()); } catch (e) {}
};
window.ageVerified = ageVerified;
window.markAgeVerified = markAgeVerified;

// PayPal mark — official two-color lockup ("Pay" navy + "Pal" cyan)
const PayPalMark = ({ size = 28 }) => (
  <svg width={size * 3.5} height={size} viewBox="0 0 100 28" aria-hidden="true">
    <text x="0" y="22" fontFamily="Inter, system-ui, sans-serif" fontWeight="800" fontSize="26" fill="#253B80" letterSpacing="-0.02em">Pay</text>
    <text x="44" y="22" fontFamily="Inter, system-ui, sans-serif" fontWeight="800" fontSize="26" fill="#179BD7" letterSpacing="-0.02em">Pal</text>
  </svg>
);

// Mercado Pago mark — white version (used over brand cyan background)
const MercadoPagoMark = ({ size = 22, color = "#FFFFFF" }) => (
  <svg width={size * 5.2} height={size} viewBox="0 0 145 28" aria-hidden="true">
    <text x="0" y="22" fontFamily="Inter, system-ui, sans-serif" fontWeight="600" fontSize="22" fill={color} letterSpacing="-0.01em">mercado</text>
    <text x="83" y="22" fontFamily="Inter, system-ui, sans-serif" fontWeight="800" fontSize="22" fill={color} letterSpacing="-0.01em">pago</text>
  </svg>
);

// Payment options block — PRIMARY CTA in ProductDrawer for available products
// Just "Agregar al carrito" (full-width). PayPal and Mercado Pago live in the CartDrawer now.
const PaymentOptions = ({ slug, productName, onAdded }) => {
  const [added, setAdded] = React.useState(false);

  // Add to cart — el CartToast global da el feedback ("ver carrito").
  // onAdded (opcional) cierra el panel de detalle para que la notificación quede visible.
  const handleAddToCart = () => {
    if (window.PEPLAB_CART) {
      window.PEPLAB_CART.addItem(slug, 1);
      setAdded(true);
      setTimeout(() => setAdded(false), 1500);
      // Cerrar el sidebar tras un instante para revelar la notificación del carrito
      if (onAdded) setTimeout(() => onAdded(), 450);
    }
  };

  if (!window.PEPLAB_CART) return null;

  const cartStyle = {
    width: "100%",
    height: 64,
    display: "inline-flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    gap: 12,
    borderRadius: 6,
    fontFamily: "var(--sans)",
    cursor: "pointer",
    transition: "all 0.25s cubic-bezier(0.2, 0.8, 0.2, 1)",
    boxShadow: "0 2px 0 rgba(0,0,0,0.04)",
    background: added ? "var(--success)" : "var(--champagne)",
    border: "1.5px solid " + (added ? "var(--success)" : "var(--champagne)"),
    color: added ? "#FFFFFF" : "var(--navy-deep)",
    fontSize: 14,
    fontWeight: 600,
    letterSpacing: "0.08em",
    textTransform: "uppercase",
  };

  const hoverCart = (e) => {
    if (added) return;
    e.currentTarget.style.background = "#B8985A";
    e.currentTarget.style.borderColor = "#B8985A";
    e.currentTarget.style.transform = "translateY(-3px)";
    e.currentTarget.style.boxShadow = "0 16px 36px rgba(201, 169, 97, 0.45)";
  };
  const leaveCart = (e) => {
    if (added) return;
    e.currentTarget.style.background = "var(--champagne)";
    e.currentTarget.style.borderColor = "var(--champagne)";
    e.currentTarget.style.transform = "translateY(0)";
    e.currentTarget.style.boxShadow = "0 2px 0 rgba(0,0,0,0.04)";
  };

  return (
    <button
      type="button"
      onClick={handleAddToCart}
      aria-label={`Agregar ${productName} al carrito`}
      style={cartStyle}
      onMouseEnter={hoverCart}
      onMouseLeave={leaveCart}
    >
      {added ? (
        <>
          <span style={{ fontSize: 18, lineHeight: 1, color: "#FFFFFF" }}>✓</span>
          <span>Agregado al carrito</span>
        </>
      ) : (
        <>
          <CartIcon size={18} color="var(--navy-deep)" />
          <span>Agregar al carrito</span>
        </>
      )}
    </button>
  );
};

// Vial image — uses real product photography when available, falls back to SVG Vial
const VialImage = ({ product, size = 240 }) => {
  if (product.image) {
    return (
      <img
        src={product.image}
        alt={`Vial ${product.name} ${product.dose}`}
        loading="lazy"
        decoding="async"
        style={{
          width: "auto",
          height: size * 1.4,
          maxWidth: "100%",
          objectFit: "contain",
          filter: "drop-shadow(0 24px 48px rgba(11, 37, 69, 0.18))",
        }}
      />
    );
  }
  return (
    <Vial
      label={product.name.split(" ")[0].toUpperCase()}
      dose={product.dose.toUpperCase().replace(" ", "")}
      size={size}
    />
  );
};

Object.assign(window, { WhatsAppIcon, ArrowRight, PlMolecule, Logo, Vial, VialImage, PlHeader, StickyWA, PayPalMark, MercadoPagoMark, PaymentOptions, CartIcon, CartButton, CartDrawer, CartToast });
