// CartBar + CartModal + ProductDetailModal — light theme

function CartBar({ cart, products, onOpen }) {
  const totalItems = Object.values(cart).reduce((a, b) => a + b, 0);
  const totalPrice = Object.entries(cart).reduce((sum, [id, qty]) => {
    const p = products.find(x => x.id === id);
    return sum + (p ? p.price * qty : 0);
  }, 0);
  if (totalItems === 0) return null;
  return (
    <div data-sui="cart-bar" onClick={onOpen} style={{
      position: "fixed", bottom: 20, left: 16, right: 16,
      maxWidth: 488, marginLeft: "auto", marginRight: "auto",
      background: "#1a1008", borderRadius: 16,
      padding: "14px 20px", display: "flex", alignItems: "center",
      justifyContent: "space-between", cursor: "pointer",
      boxShadow: "0 8px 32px rgba(26,16,8,0.35)",
      zIndex: 200, animation: "slideUp 0.25s ease",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          background: "#d97706", color: "#fff", borderRadius: "50%",
          width: 28, height: 28, display: "flex", alignItems: "center",
          justifyContent: "center", fontWeight: 800, fontSize: 13
        }}>{totalItems}</div>
        <span style={{ fontWeight: 700, fontSize: 14, color: "#fef3c7", fontFamily: "'DM Sans', sans-serif", display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ fontSize: 16 }}>🛒</span> Ver pedido
        </span>
      </div>
      <span style={{ fontWeight: 800, fontSize: 18, color: "#fbbf24", fontFamily: "'Bebas Neue', cursive", letterSpacing: "0.04em" }}>
        ${totalPrice.toLocaleString("es-AR")}
      </span>
    </div>
  );
}

const CAT_EMOJI = { hambeconom:"🍔", hambpremium:"🍔", superpanchos:"🌭", panchos:"🌭", aderezos:"🧂", snacks:"🍟", congelados:"🧊", gaseosas:"🥤", carbon:"🪵" };
const CATEGORY_LABELS = Object.fromEntries((window.CATEGORIES || []).map(c => [c.id, c.label]));

function CartModal({ cart, products, onClose, onUpdateQty, onCheckout, shippingCfg, accent: accentColor, paused }) {
  const entries = Object.entries(cart).filter(([_, qty]) => qty > 0);
  const totalPrice = entries.reduce((sum, [id, qty]) => {
    const p = products.find(x => x.id === id);
    return sum + (p ? p.price * qty : 0);
  }, 0);
  const ship = shippingCfg ? shippingFor(totalPrice, shippingCfg) : { ok: true, fee: 0, free: true };

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={{ ...sheetStyle, maxHeight: "88vh", display: "flex", flexDirection: "column" }} onClick={e => e.stopPropagation()}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16, flexShrink: 0 }}>
          <h2 style={{ color: "#1a1008", fontFamily: "'Bebas Neue', cursive", fontSize: 26, letterSpacing: "0.05em", margin: 0 }}>
            Tu Pedido
          </h2>
          <button onClick={onClose} style={closeBtnStyle}>✕</button>
        </div>

        {entries.length === 0 ? (
          <div style={{ color: "#8a7a66", textAlign: "center", padding: "40px 0", fontFamily: "'DM Sans', sans-serif" }}>
            Tu carrito está vacío
          </div>
        ) : (
          <>
            <div style={{ overflowY: "auto", flex: 1, minHeight: 0, display: "flex", flexDirection: "column", gap: 10, margin: "0 -24px", padding: "0 24px" }}>
              {entries.map(([id, qty]) => {
                const p = products.find(x => x.id === id);
                if (!p) return null;
                const { accent } = categoryColors(p.category);
                return (
                  <div key={id} style={{
                    display: "flex", alignItems: "center", gap: 10,
                    background: "#fdfaf3", borderRadius: 10, padding: "6px 12px",
                    border: "1px solid #e8dcc8"
                  }}>
                    <div style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "baseline", gap: 8, overflow: "hidden" }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: "#1a1008", fontFamily: "'DM Sans', sans-serif", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</span>
                      <span style={{ fontSize: 12, color: accent, fontFamily: "'DM Sans', sans-serif", fontWeight: 700, whiteSpace: "nowrap", flexShrink: 0 }}>
                        ${(p.price * qty).toLocaleString("es-AR")}
                      </span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, background: "#fff", borderRadius: 30, padding: "2px 6px", border: "1px solid #e8dcc8", flexShrink: 0 }}>
                      <button onClick={() => onUpdateQty(id, qty - 1)} style={qtyBtnLight}>−</button>
                      <span style={{ color: accent, fontWeight: 800, fontSize: 13, minWidth: 16, textAlign: "center" }}>{qty}</span>
                      <button onClick={() => onUpdateQty(id, qty + 1)} style={qtyBtnLight}>+</button>
                    </div>
                  </div>
                );
              })}
            </div>

            <CrossSell cart={cart} products={products} onAdd={(id) => onUpdateQty(id, (cart[id] || 0) + 1)} shippingCfg={shippingCfg} subtotal={totalPrice} accent={accentColor || "#d97706"} />

            <div style={{ borderTop: "1px solid #e8dcc8", marginTop: 12, paddingTop: 14, flexShrink: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 14 }}>
                <div style={{ flex: "1 1 50%", minWidth: 0 }}>
                  {shippingCfg && <ShippingProgress subtotal={totalPrice} cfg={shippingCfg} accent={accentColor || "#d97706"} />}
                </div>
                <div style={{ flex: "0 0 auto", display: "flex", flexDirection: "column", gap: 2, fontFamily: "'DM Sans', sans-serif", minWidth: 140 }}>
                  {!(shippingCfg && ship.ok && ship.free) && (
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 16, fontSize: 14, color: "#6b5d4e" }}>
                      <span>Subtotal</span><span>${totalPrice.toLocaleString("es-AR")}</span>
                    </div>
                  )}
                  {shippingCfg && ship.ok && (
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 16, fontSize: 14, color: ship.free ? "#15803d" : "#6b5d4e", fontWeight: ship.free ? 800 : 400 }}>
                      <span>Envío</span><span>{ship.free ? "GRATIS 🎉" : "$" + ship.fee.toLocaleString("es-AR")}</span>
                    </div>
                  )}
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16, borderTop: "1px solid #f0e6d2", marginTop: 3, paddingTop: 3 }}>
                    <span style={{ color: "#6b5d4e", fontSize: 14 }}>Total</span>
                    <span style={{ color: "#1a1008", fontFamily: "'Bebas Neue', cursive", fontSize: 30, letterSpacing: "0.03em" }}>
                      ${(totalPrice + (ship.ok && !ship.free ? ship.fee : 0)).toLocaleString("es-AR")}
                    </span>
                  </div>
                </div>
              </div>
              {paused ? (
                <div style={{ background: "#fef2f2", border: "1px solid #fecaca", color: "#991b1b", borderRadius: 12, padding: "13px 14px", fontSize: 13, fontWeight: 700, textAlign: "center", fontFamily: "'DM Sans', sans-serif" }}>
                  ⏸️ Hoy no estamos entregando. Volvé a intentarlo más tarde.
                </div>
              ) : ship.ok ? (
                <div style={{ display: "flex", gap: 8 }}>
                  <button onClick={onClose} style={{
                    flex: "0 0 42%", background: "transparent", color: "#6b5d4e",
                    border: "1.5px solid #e8dcc8", borderRadius: 14, padding: "14px 0",
                    fontWeight: 700, fontSize: 13.5, cursor: "pointer",
                    fontFamily: "'DM Sans', sans-serif"
                  }}>← Seguir agregando</button>
                  <button onClick={onCheckout} style={{
                    flex: 1, background: accentColor || "#d97706", color: "#fff",
                    border: "none", borderRadius: 14, padding: "14px 0",
                    fontWeight: 800, fontSize: 15, cursor: "pointer",
                    fontFamily: "'DM Sans', sans-serif",
                    boxShadow: "0 4px 16px rgba(217,119,6,0.3)"
                  }}>Hacer el pedido →</button>
                </div>
              ) : (
                <button onClick={onClose} style={{
                  width: "100%", background: accentColor || "#d97706", color: "#fff",
                  border: "none", borderRadius: 14, padding: "15px 0",
                  fontWeight: 800, fontSize: 16, cursor: "pointer",
                  fontFamily: "'DM Sans', sans-serif",
                  boxShadow: "0 4px 16px rgba(217,119,6,0.3)"
                }}>← Agregar más productos</button>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function CrossSell({ cart, products, onAdd, shippingCfg, subtotal, accent }) {
  const suggestions = crossSellFor(cart, products, 6);
  if (!suggestions.length) return null;
  const ship = shippingCfg ? shippingFor(subtotal, shippingCfg) : { ok: true, free: true };
  let title = "Sumá a tu pedido";
  let sub = "Lo que la gente suele agregar";
  if (shippingCfg && ship.ok && !ship.free) {
    const bridge = bridgeToFreeShip(cart, products, ship.missingToFree);
    if (bridge && bridge.price >= ship.missingToFree) {
      title = "¡Estás a un paso del envío GRATIS!";
      sub = `Agregá $${ship.missingToFree.toLocaleString("es-AR")} más y no pagás envío`;
    }
  }
  return (
    <div style={{ borderTop: "1px solid #e8dcc8", marginTop: 12, paddingTop: 10, flexShrink: 0 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
        <span style={{ fontSize: 13.5, fontWeight: 800, color: "#1a1008", fontFamily: "'DM Sans', sans-serif" }}>{title}</span>
        <span style={{ fontSize: 11.5, color: "#8a7a66", fontFamily: "'DM Sans', sans-serif" }}>{sub}</span>
      </div>
      <div style={{ display: "flex", gap: 8, overflowX: "auto", margin: "0 -4px", padding: "0 4px 4px" }}>
        {suggestions.map(p => (
          <div key={p.id} style={{
            flexShrink: 0, width: 92, background: "#fff", border: "1px solid #e8dcc8",
            borderRadius: 10, overflow: "hidden", display: "flex", flexDirection: "column"
          }}>
            <div style={{ background: categoryColors(p.category).bg, height: 42, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <ProductIcon category={p.category} size={22} image={p.image_url} />
            </div>
            <div style={{ padding: "5px 6px", display: "flex", flexDirection: "column", gap: 3, flex: 1 }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: "#1a1008", lineHeight: 1.15, fontFamily: "'DM Sans', sans-serif", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", minHeight: 24 }}>{p.name}</div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto" }}>
                <span style={{ fontSize: 12.5, fontWeight: 800, color: categoryColors(p.category).accent, fontFamily: "'Bebas Neue', cursive", letterSpacing: "0.03em" }}>${p.price.toLocaleString("es-AR")}</span>
                <button onClick={() => onAdd(p.id)} style={{ background: accent, color: "#fff", border: "none", borderRadius: "50%", width: 22, height: 22, fontSize: 14, fontWeight: 800, cursor: "pointer", lineHeight: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>+</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProductDetailModal({ product, cartQty, onClose, onAdd, onRemove }) {
  if (!product) return null;
  const { bg, accent } = categoryColors(product.category);
  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={{ ...sheetStyle }} onClick={e => e.stopPropagation()}>
        <div style={{
          background: bg, height: 160, borderRadius: "16px 16px 0 0",
          display: "flex", alignItems: "center", justifyContent: "center",
          marginLeft: -24, marginRight: -24, marginTop: -24, marginBottom: 20,
          position: "relative"
        }}>
          <ProductIcon category={product.category} size={80} image={product.image_url} />
          {product.discount > 0 && product.discount <= 100 && (
            <div style={{
              position: "absolute", top: 14, left: 14,
              background: "#d97706", color: "#fff",
              fontSize: 13, fontWeight: 800, padding: "3px 10px", borderRadius: 20
            }}>-{product.discount}%</div>
          )}
          <button onClick={onClose} style={{ ...closeBtnStyle, position: "absolute", top: 12, right: 12 }}>✕</button>
        </div>

        <div style={{ marginBottom: 4, display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{
            background: bg, color: accent,
            fontSize: 11, fontWeight: 700, padding: "2px 8px", borderRadius: 20,
            textTransform: "uppercase", letterSpacing: "0.06em", fontFamily: "'DM Sans', sans-serif"
          }}>{CATEGORY_LABELS[product.category] || product.category}</span>
          {product.available === false ? (
            <span style={{
              background: "#1a1008", color: "#fff",
              fontSize: 11, fontWeight: 800, padding: "2px 8px", borderRadius: 20,
              fontFamily: "'DM Sans', sans-serif", textTransform: "uppercase", letterSpacing: "0.06em"
            }}>Agotado</span>
          ) : product.badge && product.badge.trim() ? (
            <span style={{
              background: "#fee2e2", color: "#b91c1c",
              fontSize: 11, fontWeight: 700, padding: "2px 8px", borderRadius: 20,
              fontFamily: "'DM Sans', sans-serif"
            }}>{product.badge}</span>
          ) : null}
        </div>

        <h2 style={{ color: "#1a1008", fontFamily: "'DM Sans', sans-serif", fontSize: 20, fontWeight: 800, margin: "8px 0 8px", lineHeight: 1.25 }}>
          {product.name}
        </h2>
        <p style={{ color: "#6b5d4e", fontFamily: "'DM Sans', sans-serif", fontSize: 14, lineHeight: 1.6, margin: "0 0 18px" }}>
          {product.description}
        </p>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: "auto" }}>
          <div>
            <div style={{ color: "#8a7a66", fontSize: 11, fontFamily: "'DM Sans', sans-serif" }}>Precio</div>
            <div style={{ color: accent, fontFamily: "'Bebas Neue', cursive", fontSize: 32, letterSpacing: "0.04em" }}>
              ${product.price.toLocaleString("es-AR")}
            </div>
          </div>
          {product.available === false ? (
            <button disabled style={{
              background: "#e8dcc8", color: "#8a7a66", border: "none",
              borderRadius: 30, padding: "12px 28px",
              fontWeight: 700, fontSize: 15, cursor: "not-allowed",
              fontFamily: "'DM Sans', sans-serif"
            }}>Sin stock</button>
          ) : cartQty > 0 ? (
            <div style={{ display: "flex", alignItems: "center", gap: 12, background: "#fdf3e1", borderRadius: 30, padding: "8px 14px", border: `1px solid ${accent}33` }}>
              <button onClick={onRemove} style={{ ...qtyBtnLight, fontSize: 22 }}>−</button>
              <span style={{ color: accent, fontWeight: 800, fontSize: 18, minWidth: 24, textAlign: "center" }}>{cartQty}</span>
              <button onClick={onAdd} style={{ ...qtyBtnLight, fontSize: 22 }}>+</button>
            </div>
          ) : (
            <button onClick={onAdd} style={{
              background: accent, color: "#fff", border: "none",
              borderRadius: 30, padding: "12px 28px",
              fontWeight: 800, fontSize: 15, cursor: "pointer",
              fontFamily: "'DM Sans', sans-serif"
            }}>Agregar al pedido</button>
          )}
        </div>
      </div>
    </div>
  );
}

function LoginModal({ onClose, onLogin }) {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [loading, setLoading] = React.useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!name.trim() || !email.trim()) return;
    setLoading(true);
    setTimeout(() => {
      onLogin({ name, email });
      setLoading(false);
    }, 800);
  };

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={sheetStyle} onClick={e => e.stopPropagation()}>
        <div style={{ textAlign: "center", marginBottom: 24 }}>
          <img src="assets/logo.png" alt="HLPRaf" style={{ height: 80, marginBottom: 12 }} />
          <h2 style={{ color: "#1a1008", fontFamily: "'Bebas Neue', cursive", fontSize: 24, letterSpacing: "0.05em", margin: 0 }}>
            Identificate para hacer tu pedido
          </h2>
          <p style={{ color: "#8a7a66", fontSize: 13, fontFamily: "'DM Sans', sans-serif", marginTop: 6 }}>
            Solo necesitamos tu nombre y email
          </p>
        </div>
        <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <input
            value={name} onChange={e => setName(e.target.value)}
            placeholder="Nombre y Apellido"
            required
            style={inputStyle}
          />
          <input
            value={email} onChange={e => setEmail(e.target.value)}
            placeholder="Email"
            type="email" required
            style={inputStyle}
          />
          <button type="submit" disabled={loading} style={{
            background: loading ? "#e8dcc8" : "#d97706",
            color: "#fff", border: "none", borderRadius: 14,
            padding: "14px 0", fontWeight: 800, fontSize: 15,
            cursor: loading ? "not-allowed" : "pointer", marginTop: 4,
            fontFamily: "'DM Sans', sans-serif", transition: "background 0.2s"
          }}>
            {loading ? "Verificando..." : "Continuar con mi pedido →"}
          </button>
        </form>
        <p style={{ color: "#a89882", fontSize: 11, textAlign: "center", marginTop: 16, fontFamily: "'DM Sans', sans-serif" }}>
          Tu información solo se usa para gestionar pedidos
        </p>
      </div>
    </div>
  );
}

const overlayStyle = {
  position: "fixed", inset: 0,
  background: "rgba(40,25,10,0.5)", zIndex: 300,
  display: "flex", alignItems: "flex-end", justifyContent: "center",
  backdropFilter: "blur(4px)"
};
const sheetStyle = {
  background: "#fdfaf3",
  borderRadius: "20px 20px 0 0",
  padding: 24, width: "100%", maxWidth: 520,
  boxShadow: "0 -8px 40px rgba(26,16,8,0.25)"
};
const closeBtnStyle = {
  background: "#f5ede1", border: "none",
  color: "#6b5d4e", borderRadius: "50%",
  width: 32, height: 32, cursor: "pointer", fontSize: 14,
  display: "flex", alignItems: "center", justifyContent: "center"
};
const inputStyle = {
  background: "#fff", border: "1px solid #e8dcc8",
  borderRadius: 12, padding: "13px 16px", color: "#1a1008",
  fontSize: 15, fontFamily: "'DM Sans', sans-serif", outline: "none",
  width: "100%", boxSizing: "border-box"
};
const qtyBtnLight = {
  background: "none", border: "none", color: "#1a1008",
  fontSize: 18, cursor: "pointer", padding: "0 4px",
  lineHeight: 1, fontWeight: 700
};

Object.assign(window, { CartBar, CartModal, CrossSell, ProductDetailModal, LoginModal });
