/* Vito's Wings — Menu, Item detail, Cart drawer, Checkout */

// Small reusable radio-style chip used inside ItemDetail option groups.
function OptionChip({ active, onClick, children, small }) {
  return (
    <button onClick={onClick} style={{
      appearance: "none",
      border: active ? "2px solid #E63426" : "1px solid #0A0A0A",
      background: active ? "#E63426" : "transparent",
      color: active ? "#F6F4EF" : "#0A0A0A",
      padding: small ? "8px 12px" : "10px 14px",
      fontFamily: "'Anton', sans-serif",
      letterSpacing: "0.08em",
      fontSize: small ? 12 : 14,
      cursor: "pointer",
    }}>{children}</button>
  );
}

// ============== ITEM DETAIL MODAL ==============
function ItemDetail({ item, lang, onClose, onAdd }) {
  const [sizeKey, setSizeKey] = useState(item?.sizes ? item.sizes[0].k : null);
  const [pickedSauces, setPickedSauces] = useState(item?.saucy ? ["lp"] : []);
  const [qty, setQty] = useState(1);
  const [notes, setNotes] = useState("");
  const [sauceStyleVal, setSauceStyleVal] = useState("tossed");      // "tossed" | "side"
  const [chickenStyleVal, setChickenStyleVal] = useState("grilled"); // "grilled" | "breaded"
  const [wingTypeVal, setWingTypeVal] = useState("wings");           // "wings" | "boneless" | "mixed"

  if (!item) return null;

  const size = item.sizes ? item.sizes.find(s => s.k === sizeKey) : null;
  const basePrice = size ? size.p : item.price;
  const total = basePrice * qty;
  const heroImg = (item.sizeImg && sizeKey && item.sizeImg[sizeKey]) || item.img;

  // sauce allowance
  let sauceCap = 1;
  if (item.saucy) {
    if (item.sauceCapOverride) {
      sauceCap = item.sauceCapOverride;
    } else if (item.id === "alitas" || item.id === "boneless") {
      const n = size ? parseInt(size.k, 10) : 6;
      sauceCap = n >= 12 ? 2 : 1;
    } else if (item.id === "tenders") {
      sauceCap = 1;
    } else if (item.id === "para2")   sauceCap = 2;
    else if (item.id === "sampler")   sauceCap = 2;
    else if (item.id === "platter")   sauceCap = 2;
    else                              sauceCap = 1;
  }

  function toggleSauce(id) {
    setPickedSauces(prev => {
      if (prev.includes(id)) return prev.filter(s => s !== id);
      if (prev.length >= sauceCap) return [...prev.slice(1), id];
      return [...prev, id];
    });
  }

  return (
    <Modal open onClose={onClose} width={760}>
      <div style={{ padding: "0 0 32px" }}>
        {/* Image strip */}
        {item.bg ? (
          <div style={{ height: 280, borderBottom: "1px solid #0A0A0A" }}>
            <DrinkArt item={item} big />
          </div>
        ) : heroImg ? (
          <div style={{
            height: 280,
            backgroundImage: `url("${heroImg}")`,
            backgroundSize: "cover",
            backgroundPosition: "center",
            borderBottom: "1px solid #0A0A0A",
            transition: "background-image 0.3s",
          }} />
        ) : (
          <div style={{
            height: 220,
            background: "repeating-linear-gradient(45deg, #ece6d5 0 10px, #f1ecdd 10px 20px)",
            display: "flex", alignItems: "center", justifyContent: "center",
            borderBottom: "1px solid #0A0A0A",
            fontFamily: "ui-monospace, monospace", fontSize: 11, letterSpacing: "0.1em", color: "rgba(10,10,10,0.45)",
          }}>{`{ ${item.id}_hero.jpg }`}</div>
        )}

        <div style={{ padding: "28px 32px 0" }}>
          <h2 style={{ fontFamily: "'Anton', sans-serif", fontSize: 56, lineHeight: 0.9, margin: 0, letterSpacing: "-0.01em" }}>{item[lang].toUpperCase()}</h2>
          {item["desc_" + lang] && <p style={{ marginTop: 10, fontSize: 15, lineHeight: 1.5, color: "rgba(10,10,10,0.75)" }}>{item["desc_" + lang]}</p>}

          {/* Sizes */}
          {item.sizes && (
            <div style={{ marginTop: 24 }}>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em", marginBottom: 10 }}>{t("size", lang).toUpperCase()}</div>
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                {item.sizes.map(s => (
                  <button key={s.k} onClick={() => setSizeKey(s.k)} style={{
                    appearance: "none", padding: "12px 18px",
                    border: sizeKey === s.k ? "2px solid #E63426" : "1px solid #0A0A0A",
                    background: sizeKey === s.k ? "#E63426" : "transparent",
                    color: sizeKey === s.k ? "#F6F4EF" : "#0A0A0A",
                    fontFamily: "'Anton', sans-serif", letterSpacing: "0.06em",
                    cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center", gap: 2,
                  }}>
                    <span style={{ fontSize: 20 }}>{s.k} {lang === "es" ? "UND" : "PCS"}</span>
                    <span style={{ fontSize: 12, opacity: 0.85 }}>{fmtL(s.p)}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Wing-type choice (sampler boxes) */}
          {item.wingType && (
            <div style={{ marginTop: 24 }}>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em", marginBottom: 10 }}>
                {lang === "es" ? "TIPO DE POLLO" : "CHICKEN TYPE"}
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {[
                  { id: "wings",    en: "All Wings",    es: "Solo Alitas" },
                  { id: "boneless", en: "All Boneless", es: "Solo Boneless" },
                  { id: "mixed",    en: "Mixed (50/50)", es: "Mixto (50/50)" },
                ].map(opt => (
                  <OptionChip key={opt.id} active={wingTypeVal === opt.id} onClick={() => setWingTypeVal(opt.id)}>
                    {opt[lang].toUpperCase()}
                  </OptionChip>
                ))}
              </div>
            </div>
          )}

          {/* Chicken style choice (caesar sandwich) */}
          {item.chickenStyle && (
            <div style={{ marginTop: 24 }}>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em", marginBottom: 10 }}>
                {lang === "es" ? "PREPARACIÓN" : "STYLE"}
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                {[
                  { id: "grilled", en: "Grilled",      es: "A la Plancha" },
                  { id: "breaded", en: "Crispy / Breaded", es: "Empanizado" },
                ].map(opt => (
                  <OptionChip key={opt.id} active={chickenStyleVal === opt.id} onClick={() => setChickenStyleVal(opt.id)}>
                    {opt[lang].toUpperCase()}
                  </OptionChip>
                ))}
              </div>
            </div>
          )}

          {/* Sauces */}
          {item.saucy && (
            <div style={{ marginTop: 24 }}>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em" }}>{t("sauces", lang).toUpperCase()}</div>
                <div style={{ fontSize: 11, letterSpacing: "0.18em", color: "rgba(10,10,10,0.6)" }}>{pickedSauces.length} / {sauceCap}</div>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {window.VW_SAUCES.map(s => (
                  <SaucePill key={s.id} sauce={s} lang={lang}
                    selected={pickedSauces.includes(s.id)}
                    disabled={pickedSauces.length >= sauceCap}
                    onClick={() => toggleSauce(s.id)}
                  />
                ))}
              </div>

              {/* Sauce style: tossed vs on the side */}
              {item.sauceStyle && (
                <div style={{ marginTop: 14, display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {[
                    { id: "tossed", en: "Tossed in sauce", es: "Bañados en salsa" },
                    { id: "side",   en: "Sauce on the side", es: "Salsa aparte" },
                  ].map(opt => (
                    <OptionChip key={opt.id} active={sauceStyleVal === opt.id} onClick={() => setSauceStyleVal(opt.id)} small>
                      {opt[lang].toUpperCase()}
                    </OptionChip>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Notes */}
          <div style={{ marginTop: 24 }}>
            <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em", marginBottom: 10 }}>{t("notes", lang).toUpperCase()}</div>
            <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder={lang === "es" ? "Sin cebolla, salsas aparte, etc." : "No onion, sauces on the side, etc."}
              style={{ width: "100%", boxSizing: "border-box", border: "1px solid #0A0A0A", background: "#F6F4EF", padding: 12, fontFamily: "'DM Sans', sans-serif", fontSize: 14, minHeight: 60, resize: "vertical" }} />
          </div>

          {/* Qty + Add */}
          <div style={{ marginTop: 28, display: "flex", gap: 16, alignItems: "stretch", borderTop: "1px solid #0A0A0A", paddingTop: 22 }}>
            <div style={{ display: "flex", alignItems: "center", border: "1px solid #0A0A0A" }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ appearance: "none", border: 0, background: "transparent", width: 44, height: 52, fontSize: 22, cursor: "pointer", fontFamily: "'Anton', sans-serif" }}>−</button>
              <div style={{ width: 36, textAlign: "center", fontFamily: "'Anton', sans-serif", fontSize: 22 }}>{qty}</div>
              <button onClick={() => setQty(qty + 1)} style={{ appearance: "none", border: 0, background: "transparent", width: 44, height: 52, fontSize: 22, cursor: "pointer", fontFamily: "'Anton', sans-serif" }}>+</button>
            </div>
            <button onClick={() => onAdd({
              id: item.id + "_" + (sizeKey || "") + "_" + pickedSauces.join("-") + "_" + Date.now(),
              itemId: item.id,
              name: item[lang] + (sizeKey ? ` (${sizeKey} ${lang === "es" ? "und" : "pcs"})` : ""),
              size: sizeKey,
              sauces: pickedSauces.map(id => window.VW_SAUCES.find(s => s.id === id)[lang]),
              wingType: item.wingType ? wingTypeVal : null,
              chickenStyle: item.chickenStyle ? chickenStyleVal : null,
              sauceStyle: item.sauceStyle ? sauceStyleVal : null,
              qty, price: basePrice, notes,
            })} style={{
              flex: 1, appearance: "none", border: 0, background: "#E63426", color: "#F6F4EF",
              fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.14em", cursor: "pointer",
              padding: "16px 22px", display: "flex", justifyContent: "space-between", alignItems: "center",
            }}>
              <span>{t("add_to_order", lang).toUpperCase()}</span>
              <span>{fmtL(total)}</span>
            </button>
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ============== MENU SCREEN ==============
function ScreenMenu({ lang, openItem }) {
  const cats = window.VW_MENU;
  const [activeCat, setActiveCat] = useState(cats[0].id);
  const sectionRefs = useRef({});

  function scrollToCat(id) {
    setActiveCat(id);
    const el = sectionRefs.current[id];
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 100;
      window.scrollTo({ top, behavior: "smooth" });
    }
  }

  return (
    <div>
      <section style={{ padding: "40px 6vw 16px" }}>
        <SectionHeader
          kicker={t("nav_menu", lang)}
          title={t("menu_title", lang)}
          sub={t("menu_sub", lang)}
        />
      </section>

      {/* Sticky category nav */}
      <div style={{ position: "sticky", top: 64, zIndex: 30, background: "#F6F4EF", borderTop: "1px solid #0A0A0A", borderBottom: "1px solid #0A0A0A" }}>
        <div style={{ padding: "0 6vw", overflowX: "auto" }}>
          <div style={{ display: "flex", gap: 4, fontFamily: "'Anton', sans-serif", whiteSpace: "nowrap" }}>
            {cats.map(c => (
              <button key={c.id} onClick={() => scrollToCat(c.id)} style={{
                appearance: "none", background: activeCat === c.id ? "#0A0A0A" : "transparent",
                color: activeCat === c.id ? "#F6F4EF" : "#0A0A0A",
                border: 0, padding: "14px 18px", fontSize: 15, letterSpacing: "0.12em", cursor: "pointer",
              }}>{c[lang].toUpperCase()}</button>
            ))}
          </div>
        </div>
      </div>

      {cats.map(cat => (
        <section key={cat.id} ref={el => sectionRefs.current[cat.id] = el} style={{ padding: "56px 6vw" }}>
          <div style={{ marginBottom: 24, borderBottom: "1px solid #0A0A0A", paddingBottom: 16, display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
            <h3 style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(32px, 4.5vw, 56px)", lineHeight: 0.9, margin: 0, letterSpacing: "-0.005em" }}>{cat[lang].toUpperCase()}</h3>
            {cat["note_" + lang] && <span style={{ fontSize: 13, color: "rgba(10,10,10,0.65)", maxWidth: 360 }}>{cat["note_" + lang]}</span>}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 18 }}>
            {cat.items.map(it => (
              <ItemCard key={it.id} item={it} lang={lang} onOpen={() => openItem(it)} />
            ))}
          </div>
        </section>
      ))}
    </div>
  );
}

// ============== CART UPSELL MODULE ==============
// Smart cross-sell: looks at what's missing from the cart and suggests adds.
// Uses anchoring (compared price), urgency (only X away), and social proof.
function CartUpsell({ cart, setCart, lang }) {
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);

  // What's missing from the cart?
  const hasDrink   = cart.some(l => ["lim","limm","jam","agua","pepsi","pepsibl","lipton","7up","salva","imp","ultra","modelo","marg","moj","sang"].includes(l.itemId));
  const hasSide    = cart.some(l => ["papas","loaded","aros","truff","mozz"].includes(l.itemId));
  const hasDessert = cart.some(l => l.itemId === "popcorn");

  // Suggestion candidates — Extra Ranch and Papas Fritas are PERMANENT/always-on, then dynamic
  const allSuggestions = [
    {
      itemId: "ranchext", name: lang === "es" ? "Extra Ranch" : "Extra Ranch",
      sub: lang === "es" ? "Para acompañar" : "Side dip",
      price: 25, glyph: "🥣",
    },
    {
      itemId: "papas", name: lang === "es" ? "Una Orden de Papas" : "Order of Fries",
      sub: lang === "es" ? "Crujientes y bien sazonadas" : "Crispy & seasoned",
      price: 160, glyph: "🍟",
    },
  ];

  // One dynamic third slot based on what's missing
  if (!hasDrink) {
    allSuggestions.push({
      itemId: "lim", name: lang === "es" ? "Limonada Natural" : "Lemonade",
      sub: lang === "es" ? "Bien fría" : "Ice cold",
      price: 65, glyph: "🥤",
    });
  } else if (!hasSide) {
    allSuggestions.push({
      itemId: "loaded", name: lang === "es" ? "Loaded Fries" : "Loaded Fries",
      sub: lang === "es" ? "Queso, tocino, crema" : "Cheese, bacon, cream",
      price: 230, glyph: "🧀",
    });
  } else {
    allSuggestions.push({
      itemId: "saucext", name: lang === "es" ? "Salsa Extra" : "Extra Sauce",
      sub: lang === "es" ? "De cualquier sabor" : "Any flavor",
      price: 25, glyph: "🥫",
    });
  }

  // Show max 3
  const suggestions = allSuggestions.slice(0, 3);

  function addOne(s) {
    setCart(c => [...c, {
      id: s.itemId + "_quick_" + Date.now(),
      itemId: s.itemId,
      name: s.name,
      sauces: [],
      qty: 1,
      price: s.price,
      notes: "",
    }]);
  }

  // Free-side threshold — increases motivation to add a wing
  const FREE_THRESHOLD = 700;
  const remaining = Math.max(0, FREE_THRESHOLD - subtotal);
  const pct = Math.min(100, (subtotal / FREE_THRESHOLD) * 100);
  const unlocked = subtotal >= FREE_THRESHOLD;

  if (cart.length === 0) return null;

  return (
    <div style={{ padding: "16px 22px 0", borderTop: "1px dashed rgba(10,10,10,0.2)" }}>
      {/* Free side progress bar */}
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6, fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase" }}>
          <span style={{ fontWeight: 700 }}>
            {unlocked
              ? (lang === "es" ? "🎉 PAPAS FRITAS GRATIS" : "🎉 FREE FRIES UNLOCKED")
              : (lang === "es" ? `${fmtL(remaining)} PARA PAPAS GRATIS` : `${fmtL(remaining)} TO FREE FRIES`)}
          </span>
          <span style={{ fontFamily: "'Anton', sans-serif", color: unlocked ? "#15803D" : "#E63426" }}>{Math.round(pct)}%</span>
        </div>
        <div style={{ height: 8, background: "rgba(10,10,10,0.1)", border: "1px solid #0A0A0A", overflow: "hidden" }}>
          <div style={{
            height: "100%", width: pct + "%",
            background: unlocked ? "#15803D" : "#E63426",
            transition: "width 0.4s ease, background 0.3s",
          }} />
        </div>
      </div>

      {/* Cross-sell row */}
      <div>
        <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 13, letterSpacing: "0.2em", color: "#0A0A0A", marginBottom: 10, display: "flex", alignItems: "center", gap: 8 }}>
          <span>{lang === "es" ? "AGREGAR A TU PEDIDO" : "ADD TO YOUR ORDER"}</span>
          <span style={{ fontSize: 10, color: "rgba(10,10,10,0.5)", letterSpacing: "0.18em" }}>· {lang === "es" ? "FRECUENTE" : "FREQUENTLY ADDED"}</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {suggestions.map(s => (
            <button key={s.itemId + s.name} onClick={() => addOne(s)} style={{
              appearance: "none", border: "1px solid #0A0A0A", background: "#F6F4EF",
              padding: "10px 12px", cursor: "pointer", display: "flex", alignItems: "center", gap: 12,
              transition: "transform 0.12s, box-shadow 0.12s, background 0.12s",
            }}
              onMouseEnter={e => { e.currentTarget.style.transform = "translate(-2px,-2px)"; e.currentTarget.style.boxShadow = "4px 4px 0 #0A0A0A"; e.currentTarget.style.background = "rgba(230,52,38,0.04)"; }}
              onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.boxShadow = ""; e.currentTarget.style.background = "#F6F4EF"; }}
            >
              <div style={{ fontSize: 26, lineHeight: 1, flexShrink: 0, width: 38, height: 38, display: "flex", alignItems: "center", justifyContent: "center", background: "#F1ECDD", border: "1px solid rgba(10,10,10,0.15)" }}>{s.glyph}</div>
              <div style={{ flex: 1, textAlign: "left" }}>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 15, letterSpacing: "0.04em", lineHeight: 1 }}>{s.name.toUpperCase()}</div>
                <div style={{ fontSize: 11, color: "rgba(10,10,10,0.6)", marginTop: 2 }}>{s.sub}</div>
              </div>
              <div style={{ textAlign: "right", flexShrink: 0 }}>
                {s.anchor && <div style={{ fontSize: 11, color: "rgba(10,10,10,0.45)", textDecoration: "line-through" }}>{fmtL(s.anchor)}</div>}
                <div style={{ fontFamily: "'Anton', sans-serif", color: "#E63426", fontSize: 17, lineHeight: 1 }}>+ {fmtL(s.price)}</div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ============== CART DRAWER ==============
function CartDrawer({ open, onClose, cart, setCart, lang, goto }) {
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);

  function remove(id) { setCart(c => c.filter(l => l.id !== id)); }
  function changeQty(id, delta) {
    setCart(c => c.map(l => l.id === id ? { ...l, qty: Math.max(1, l.qty + delta) } : l));
  }

  return (
    <>
      <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(10,10,10,0.5)", zIndex: 150,
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity 0.25s",
      }} />
      <aside style={{
        position: "fixed", top: 0, right: 0, bottom: 0,
        width: "min(420px, 92vw)", background: "#F6F4EF", zIndex: 160,
        transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform 0.3s cubic-bezier(.2,1,.3,1)",
        display: "flex", flexDirection: "column",
        borderLeft: "1px solid #0A0A0A",
      }}>
        <div style={{ padding: "20px 22px", display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid #0A0A0A" }}>
          <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 24, letterSpacing: "0.06em" }}>{t("cart_title", lang).toUpperCase()}</div>
          <button onClick={onClose} aria-label="Close" style={{ appearance: "none", border: "1px solid #0A0A0A", background: "transparent", width: 36, height: 36, fontFamily: "'Anton', sans-serif", fontSize: 16, cursor: "pointer" }}>✕</button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: 22 }}>
          {cart.length === 0 ? (
            <div style={{ padding: "40px 0", textAlign: "center", color: "rgba(10,10,10,0.6)" }}>
              <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 64, color: "#0A0A0A" }}>EMPTY.</div>
              <p style={{ marginTop: 8 }}>{t("cart_empty", lang)}</p>
              <div style={{ marginTop: 16 }}><PrimaryBtn onClick={() => { onClose(); goto("menu"); }}>{t("continue_shop", lang).toUpperCase()}</PrimaryBtn></div>
            </div>
          ) : cart.map(l => (
            <div key={l.id} style={{ display: "flex", flexDirection: "column", gap: 6, padding: "14px 0", borderBottom: "1px dashed rgba(10,10,10,0.25)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 10, alignItems: "baseline" }}>
                <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 17, letterSpacing: "0.04em", lineHeight: 1.1 }}>{l.name.toUpperCase()}</div>
                <div style={{ fontFamily: "'Anton', sans-serif", color: "#E63426", whiteSpace: "nowrap" }}>{fmtL(l.price * l.qty)}</div>
              </div>
              {l.sauces && l.sauces.length > 0 && (
                <div style={{ fontSize: 11, letterSpacing: "0.14em", color: "rgba(10,10,10,0.6)" }}>+ {l.sauces.join(" · ")}</div>
              )}
              {(l.wingType || l.chickenStyle || l.sauceStyle) && (
                <div style={{ fontSize: 10, letterSpacing: "0.18em", color: "rgba(10,10,10,0.5)", textTransform: "uppercase" }}>
                  {[
                    l.wingType    && (l.wingType === "wings" ? "Solo Alitas" : l.wingType === "boneless" ? "Solo Boneless" : "Mixto"),
                    l.chickenStyle && (l.chickenStyle === "grilled" ? "A la Plancha" : "Empanizado"),
                    l.sauceStyle  && (l.sauceStyle  === "tossed"  ? "Bañado" : "Salsa Aparte"),
                  ].filter(Boolean).join(" · ")}
                </div>
              )}
              {l.notes && <div style={{ fontSize: 12, color: "rgba(10,10,10,0.6)", fontStyle: "italic" }}>“{l.notes}”</div>}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4 }}>
                <div style={{ display: "flex", alignItems: "center", border: "1px solid #0A0A0A" }}>
                  <button onClick={() => changeQty(l.id, -1)} style={{ appearance: "none", border: 0, background: "transparent", width: 28, height: 28, cursor: "pointer", fontFamily: "'Anton', sans-serif", fontSize: 14 }}>−</button>
                  <div style={{ width: 24, textAlign: "center", fontFamily: "'Anton', sans-serif", fontSize: 14 }}>{l.qty}</div>
                  <button onClick={() => changeQty(l.id, 1)} style={{ appearance: "none", border: 0, background: "transparent", width: 28, height: 28, cursor: "pointer", fontFamily: "'Anton', sans-serif", fontSize: 14 }}>+</button>
                </div>
                <button onClick={() => remove(l.id)} style={{ appearance: "none", border: 0, background: "transparent", fontSize: 11, letterSpacing: "0.18em", color: "rgba(10,10,10,0.6)", cursor: "pointer", textDecoration: "underline" }}>{t("remove", lang).toUpperCase()}</button>
              </div>
            </div>
          ))}
        </div>

        {cart.length > 0 && (
          <>
            <CartUpsell cart={cart} setCart={setCart} lang={lang} />
            <div style={{ padding: 22, borderTop: "1px solid #0A0A0A", background: "#F1ECDD" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 14 }}>
                <span>{t("subtotal", lang)}</span><span>{fmtL(subtotal)}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14, fontFamily: "'Anton', sans-serif", fontSize: 24 }}>
                <span>{t("total", lang).toUpperCase()}</span><span style={{ color: "#E63426" }}>{fmtL(subtotal)}</span>
              </div>
              <PrimaryBtn full big onClick={() => { onClose(); goto("checkout"); }}>{t("checkout", lang).toUpperCase()} →</PrimaryBtn>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

// ============== CHECKOUT SCREEN ==============
function ScreenCheckout({ lang, cart, setCart, goto }) {
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [time, setTime] = useState("ASAP");
  const [pay, setPay] = useState("pickup");
  const [done, setDone] = useState(false);
  const [sending, setSending] = useState(false);
  const subtotal = cart.reduce((s, l) => s + l.price * l.qty, 0);

  async function place(e) {
    e.preventDefault();
    if (sending) return;
    setSending(true);
    // Mapear el carrito al formato del POS (nombre, precio, cantidad, salsas/estilos, nota)
    const items = cart.map(l => ({
      name: l.name,
      price: l.price,
      qty: l.qty,
      mods: [].concat(l.sauces || [], l.wingType || [], l.chickenStyle || [], l.sauceStyle || []).filter(Boolean),
      nota: l.notes || ""
    }));
    const nota = (lang === "es" ? "Recoger: " : "Pickup: ") + time +
      (pay === "online" ? (lang === "es" ? " - Pago en linea (cobrar al entregar)" : " - Online pay (collect on pickup)")
                        : (lang === "es" ? " - Paga al recoger" : " - Pay on pickup"));
    try {
      const r = await fetch("https://app.emprendamospos.com/api/web-order/vitoswings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ customer: { name, phone }, nota, items })
      });
      const j = await r.json();
      if (!j || !j.ok) throw new Error((j && j.error) || "error");
    } catch (err) {
      setSending(false);
      alert(lang === "es"
        ? "No pudimos enviar tu pedido. Llamanos al restaurante o intenta de nuevo."
        : "We couldn't send your order. Please call the restaurant or try again.");
      return;
    }
    setSending(false);
    setDone(true);
    setTimeout(() => setCart([]), 200);
  }

  if (done) {
    return (
      <section style={{ minHeight: "70vh", padding: "80px 6vw", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", textAlign: "center" }}>
        <img src="assets/vitos-icon.png" alt="" style={{ height: 140, marginBottom: 24 }} />
        <h2 style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(48px, 8vw, 120px)", lineHeight: 0.85, margin: 0 }}>{t("order_placed_title", lang).toUpperCase()}</h2>
        <p style={{ fontSize: 18, marginTop: 16, maxWidth: 520 }}>{t("order_placed_sub", lang)}</p>
        <div style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
          <PrimaryBtn onClick={() => goto("home")}>{lang === "es" ? "VOLVER AL INICIO" : "BACK TO HOME"}</PrimaryBtn>
          <GhostBtn onClick={() => goto("menu")}>{lang === "es" ? "PEDIR DE NUEVO" : "ORDER AGAIN"}</GhostBtn>
        </div>
      </section>
    );
  }

  if (cart.length === 0) {
    return (
      <section style={{ padding: "80px 6vw", textAlign: "center" }}>
        <div style={{ fontFamily: "'Anton', sans-serif", fontSize: "clamp(48px, 6vw, 80px)" }}>{lang === "es" ? "CARRITO VACÍO" : "EMPTY CART"}</div>
        <div style={{ marginTop: 20 }}><PrimaryBtn onClick={() => goto("menu")}>{t("nav_menu", lang).toUpperCase()}</PrimaryBtn></div>
      </section>
    );
  }

  return (
    <section style={{ padding: "40px 6vw 80px" }}>
      <SectionHeader kicker={t("checkout", lang)} title={t("pickup_title", lang)} />
      <form onSubmit={place} style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 40 }} className="vw-2col">
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Field label={t("name", lang)}><input required value={name} onChange={e => setName(e.target.value)} style={inputStyle} /></Field>
          <Field label={t("phone", lang)}><input required type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+504 ____-____" style={inputStyle} /></Field>
          <Field label={t("pickup_time", lang)}>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {["ASAP", "30 min", "45 min", "1 h"].map(opt => (
                <button type="button" key={opt} onClick={() => setTime(opt)} style={{
                  appearance: "none", border: time === opt ? "2px solid #E63426" : "1px solid #0A0A0A",
                  background: time === opt ? "#E63426" : "transparent",
                  color: time === opt ? "#F6F4EF" : "#0A0A0A",
                  padding: "12px 16px", fontFamily: "'Anton', sans-serif", letterSpacing: "0.12em", cursor: "pointer",
                }}>{opt}</button>
              ))}
            </div>
          </Field>
          <Field label={t("pay_method", lang)}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {[
                { id: "online",  label: t("pay_online", lang) },
                { id: "pickup",  label: t("pay_pickup", lang) },
              ].map(opt => (
                <button type="button" key={opt.id} onClick={() => setPay(opt.id)} style={{
                  appearance: "none", textAlign: "left",
                  border: pay === opt.id ? "2px solid #E63426" : "1px solid #0A0A0A",
                  background: pay === opt.id ? "rgba(230,52,38,0.08)" : "transparent",
                  padding: "14px 16px", cursor: "pointer", display: "flex", alignItems: "center", gap: 12,
                }}>
                  <span style={{ width: 16, height: 16, borderRadius: "50%", border: "2px solid " + (pay === opt.id ? "#E63426" : "#0A0A0A"), background: pay === opt.id ? "#E63426" : "transparent" }}></span>
                  <span style={{ fontSize: 15 }}>{opt.label}</span>
                </button>
              ))}
            </div>
          </Field>

          {pay === "online" && (
            <Field label={lang === "es" ? "Tarjeta" : "Card"}>
              <div style={{ display: "flex", gap: 10 }}>
                <input placeholder="4242 4242 4242 4242" style={{ ...inputStyle, flex: 2 }} />
                <input placeholder="MM/YY" style={{ ...inputStyle, flex: 1 }} />
                <input placeholder="CVC" style={{ ...inputStyle, flex: 1 }} />
              </div>
            </Field>
          )}
        </div>

        <aside style={{ background: "#0A0A0A", color: "#F6F4EF", padding: 22, alignSelf: "start", position: "sticky", top: 84 }}>
          <div style={{ fontFamily: "'Anton', sans-serif", fontSize: 22, letterSpacing: "0.06em", borderBottom: "1px solid rgba(246,244,239,0.2)", paddingBottom: 12, marginBottom: 12 }}>{t("cart_title", lang).toUpperCase()}</div>
          {cart.map(l => (
            <div key={l.id} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", fontSize: 13, gap: 10 }}>
              <span style={{ flex: 1 }}>{l.qty} × {l.name}</span>
              <span style={{ fontFamily: "'Anton', sans-serif" }}>{fmtL(l.price * l.qty)}</span>
            </div>
          ))}
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontFamily: "'Anton', sans-serif", fontSize: 22, borderTop: "1px solid rgba(246,244,239,0.2)", paddingTop: 12 }}>
            <span>{t("total", lang).toUpperCase()}</span>
            <span style={{ color: "#E63426" }}>{fmtL(subtotal)}</span>
          </div>
          <div style={{ marginTop: 16 }}>
            <button type="submit" disabled={sending} style={{
              width: "100%", appearance: "none", border: 0, background: sending ? "#9b9b97" : "#E63426", color: "#F6F4EF",
              padding: "18px", fontFamily: "'Anton', sans-serif", fontSize: 18, letterSpacing: "0.14em", cursor: sending ? "wait" : "pointer",
            }}>{sending ? (lang === "es" ? "ENVIANDO…" : "SENDING…") : t("place_order", lang).toUpperCase() + " →"}</button>
          </div>
          <div style={{ fontSize: 11, opacity: 0.6, marginTop: 10, lineHeight: 1.5 }}>
            {lang === "es" ? "Demo: no se cobrará nada. Te avisaríamos por WhatsApp cuando esté listo." : "Demo: no real charge. We'd text you when it's ready."}
          </div>
        </aside>
      </form>
    </section>
  );
}

const inputStyle = {
  border: "1px solid #0A0A0A", background: "#F6F4EF",
  padding: "14px 16px", fontFamily: "'DM Sans', sans-serif", fontSize: 15,
  width: "100%", boxSizing: "border-box",
};

function Field({ label, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <span style={{ fontFamily: "'Anton', sans-serif", fontSize: 14, letterSpacing: "0.2em" }}>{label.toUpperCase()}</span>
      {children}
    </label>
  );
}

Object.assign(window, { ItemDetail, ScreenMenu, CartDrawer, ScreenCheckout });
