/* ============================================================
   MENU — cocktails & bottles (cards) · food (price list) ·
   hookah (flavor groups). Live data merges base + AdminMaster
   overrides (PPDB), so the admin controls everything shown here.
   ============================================================ */

/* ---------- FOOD — Vicio x Pink Pony price list ---------- */
function FoodMenu({ items, lang }) {
  const t = useT();
  const SECTIONS = [
    ["tapas", t("Pink Pony Tapas", "Pink Pony Tapas")],
    ["burgers", t("Burgers & More", "Hamburguesas y Otros")],
    ["samples", t("Sharing Boards", "Tablas para Compartir")],
    ["pizzas", t("Pizzas", "Pizzas")],
    ["extras", t("Extras & Sauces", "Extras y Salsas")],
  ];
  const known = SECTIONS.map((s) => s[0]);
  const groups = SECTIONS.map(([id, label]) => [id, label, items.filter((i) => i.section === id)]).filter(([, , arr]) => arr.length);
  const other = items.filter((i) => !known.includes(i.section));
  if (other.length) groups.push(["more", t("More", "Más"), other]);

  return (
    <div className="columns-1 md:columns-2 gap-12 [&>div]:break-inside-avoid">
      {groups.map(([id, label, arr]) => (
        <div key={id} className="reveal mb-10" data-d="1">
          <h3 className="font-black uppercase text-coral tracking-wide mb-4 text-lg flex items-center gap-2">
            {label}{id === "pizzas" && <span className="serif text-gold-soft text-base normal-case font-normal">· $15 c/u</span>}
          </h3>
          <div className="space-y-3.5">
            {arr.map((it, i) => (
              <div key={i}>
                <div className="flex items-baseline gap-2.5">
                  <span className="font-semibold text-[15px] text-white leading-snug">{it.name}</span>
                  <span className="flex-1 border-b border-dotted border-white/15 translate-y-[-3px]"></span>
                  <span className="serif text-gold-soft text-lg shrink-0">{it.price > 0 ? "$" + it.price : t("Incl.", "Incl.")}</span>
                </div>
                {it.note && <div className="text-white/45 text-xs mt-1 leading-relaxed">{it.note}</div>}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- HOOKAH — Eternal Smoke flavor menu ---------- */
function HookahMenu({ items, lang }) {
  const t = useT();
  const order = []; const byBrand = {};
  items.forEach((it) => { const b = it.brand || t("Flavors", "Sabores"); if (!byBrand[b]) { byBrand[b] = []; order.push(b); } byBrand[b].push(it); });

  return (
    <div className="space-y-12">
      {/* pricing banner */}
      <div className="reveal rounded-2xl border border-coral/35 bg-coral/[.07] px-5 py-4 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-center">
        <span className="font-black uppercase tracking-wide text-white text-lg">$100</span>
        <span className="text-white/70 text-sm">{t("for the flavor you choose", "por el sabor que elijas")}</span>
        <span className="text-white/25 mx-1 hidden sm:inline">|</span>
        <span className="font-black uppercase tracking-wide text-white text-lg">$50</span>
        <span className="text-white/70 text-sm">{t("refill", "recarga")}</span>
      </div>

      {order.map((brand) => {
        const arr = byBrand[brand];
        const secOrder = []; const bySec = {};
        arr.forEach((it) => { const s = it.section || ""; if (!(s in bySec)) { bySec[s] = []; secOrder.push(s); } bySec[s].push(it); });
        const flat = secOrder.length === 1 && secOrder[0] === "";
        return (
          <div key={brand} className="reveal" data-d="1">
            <h3 className="serif-it text-3xl md:text-4xl text-coral mb-6">{brand}</h3>
            {flat ? (
              <ul className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-x-6 gap-y-2.5">
                {bySec[""].map((it, i) => <FlavorItem key={i} name={it.name} />)}
              </ul>
            ) : (
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-7">
                {secOrder.map((sec) => (
                  <div key={sec} className="break-inside-avoid">
                    {sec && <div className="label text-gold-soft text-[11px] mb-3">{sec}</div>}
                    <ul className="space-y-2">
                      {bySec[sec].map((it, i) => <FlavorItem key={i} name={it.name} />)}
                    </ul>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })}
      <p className="text-white/40 text-xs text-center max-w-lg mx-auto leading-relaxed">{t("21+ only. Ask your server for tonight's recommendations and mix combinations.", "Solo 21+. Pregúntale a tu mesero por las recomendaciones de hoy y combinaciones de sabores.")}</p>
    </div>
  );
}
function FlavorItem({ name }) {
  return <li className="text-white/80 text-[15px] flex items-center gap-2.5"><span className="w-1.5 h-1.5 rounded-full bg-coral shrink-0"></span>{name}</li>;
}

/* ---------- BOTTLE SERVICE — price list by spirit ---------- */
function BottleMenu({ items, lang }) {
  const t = useT();
  const SECTIONS = [
    ["rum", t("Rum", "Ron")], ["tequila", "Tequila"], ["cognac", "Cognac"], ["liqueur", t("Liqueur", "Licor")],
    ["vodka", "Vodka"], ["champagne", "Champagne"], ["gin", "Gin"], ["whiskey", "Whiskey"], ["scotch", "Scotch"],
  ];
  const known = SECTIONS.map((s) => s[0]);
  const groups = SECTIONS.map(([id, label]) => [id, label, items.filter((i) => i.section === id)]).filter(([, , arr]) => arr.length);
  const other = items.filter((i) => !known.includes(i.section));
  if (other.length) groups.push(["more", t("More", "Más"), other]);

  return (
    <div>
      <div className="columns-1 md:columns-2 gap-12 [&>div]:break-inside-avoid">
        {groups.map(([id, label, arr]) => (
          <div key={id} className="reveal mb-9" data-d="1">
            <h3 className="font-black uppercase text-coral tracking-wide mb-4 text-lg">{label}</h3>
            <div className="space-y-3">
              {arr.map((it, i) => (
                <div key={i} className="flex items-baseline gap-2.5">
                  <span className="font-semibold text-[15px] text-white leading-snug flex items-center gap-2 flex-wrap">{it.name}{it.tag && <Chip color={it.tag.en === "BLACK" ? "#E9E4DA" : "var(--c-coral)"}>{L(it.tag, lang)}</Chip>}</span>
                  <span className="flex-1 border-b border-dotted border-white/15 translate-y-[-3px]"></span>
                  <span className="serif text-gold-soft text-lg shrink-0">${(it.price || 0).toLocaleString()}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
      <p className="text-white/40 text-xs text-center mt-4">{t("Prices do not include 20% service charge and 8% taxes.", "Los precios no incluyen 20% de cargo por servicio y 8% de impuestos.")}</p>
    </div>
  );
}

/* ---------- CARD (cocktails) ---------- */
function MenuCard({ it, i, lang }) {
  return (
    <div className="reveal group rounded-2xl overflow-hidden border border-white/10 bg-card hover:border-coral/40 transition-all duration-300 hover:-translate-y-1.5 hover:shadow-[0_20px_50px_rgba(0,0,0,.5)]" data-d={(i % 3) + 1}>
      <div className="relative h-64 md:h-72 overflow-hidden">
        <Photo placeholder={it.ph} src={it.img ? window.PP.SRC(it.img, 800, 720) : null} alt={it.name}
          className="absolute inset-0 w-full h-full" imgClass="object-cover transition-transform duration-[900ms] group-hover:scale-110" />
        <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/10"></div>
        <div className="absolute top-3 right-3 px-3.5 py-1.5 rounded-full bg-black/55 backdrop-blur-md border border-white/15 serif text-xl text-gold-soft">${it.price}</div>
        {it.tag && <div className="absolute top-3 left-3"><Chip color={it.tag.en === "BLACK" ? "#E9E4DA" : "var(--c-coral)"}>{L(it.tag, lang)}</Chip></div>}
        {it.cat && <div className="absolute bottom-3 left-4 label text-white/85 text-[10px]">{it.cat}</div>}
      </div>
      <div className="p-5">
        <h3 className="font-bold text-lg leading-tight mb-1.5">{it.name}</h3>
        {it.d && <p className="text-white/55 text-sm leading-relaxed">{L(it.d, lang)}</p>}
        {it.flavor && <p className="text-white/55 text-sm">{L(it.flavor, lang)}</p>}
      </div>
    </div>
  );
}

function MenuPage({ go }) {
  const t = useT(); const { lang } = useLang();
  /* live menu = base data + AdminMaster overrides (PPDB) */
  const [M, setM] = useState(() => window.PPDB.getMenu());
  useEffect(() => {
    const f = () => setM(window.PPDB.getMenu());
    window.addEventListener("pp:menu", f);
    return () => window.removeEventListener("pp:menu", f);
  }, []);

  const allCats = [
    ["food", t("Kitchen", "Cocina"), "utensils"],
    ["cocktails", t("Cocktails", "Cócteles"), "martini"],
    ["bottles", t("Bottle Service", "Botellas"), "wine"],
    ["hookah", t("Hookah", "Hookah"), "wind"],
  ];
  const cats = allCats.filter(([id]) => (M[id] || []).length > 0);
  const [cat, setCat] = useState(() => {
    let want = "";
    try { want = window.__menuCat || ""; if (want) delete window.__menuCat; } catch (e) {}
    return (want && cats.some((c) => c[0] === want)) ? want : (cats[0] ? cats[0][0] : "food");
  });
  useReveal(cat);
  const activeCat = (M[cat] || []).length ? cat : (cats[0] ? cats[0][0] : cat);
  const items = M[activeCat] || [];

  return (
    <div className="pt-28 md:pt-32 pb-24">
      <div className="container">
        <div className="reveal max-w-2xl mb-9">
          <Eyebrow num="">{t("Eat · Drink · Smoke", "Comer · Beber · Fumar")}</Eyebrow>
          <h1 className="text-5xl md:text-7xl font-black uppercase leading-[0.9] mt-4 mb-4">{t(<>The <span className="serif-it font-normal text-coral">Menu</span></>, <>El <span className="serif-it font-normal text-coral">Menú</span></>)}</h1>
          <p className="text-white/60 text-lg">{t("A chef-driven kitchen, a signature cocktail program, premium bottle service and our Eternal Smoke hookah lounge.", "Una cocina de autor, programa de cócteles de firma, servicio de botellas premium y nuestro lounge de hookah Eternal Smoke.")}</p>
        </div>

        {/* tabs */}
        <div className="sticky top-[68px] z-20 -mx-6 px-6 py-3 bg-ink/80 backdrop-blur-xl border-y border-white/8 mb-9">
          <div className="flex gap-2 overflow-x-auto">
            {cats.map(([id, lbl, ic]) => (
              <button key={id} onClick={() => setCat(id)}
                className={"shrink-0 inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-[12px] font-bold uppercase tracking-[0.14em] transition-all " +
                  (activeCat === id ? "bg-coral text-white" : "bg-white/5 text-white/65 hover:text-white border border-white/10")}>
                <Icon name={ic} className="w-4 h-4" /> {lbl}
              </button>
            ))}
          </div>
        </div>

        {activeCat === "food" ? (
          <FoodMenu items={items} lang={lang} />
        ) : activeCat === "hookah" ? (
          <HookahMenu items={items} lang={lang} />
        ) : activeCat === "bottles" ? (
          <BottleMenu items={items} lang={lang} />
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {items.map((it, i) => <MenuCard key={it.name + i} it={it} i={i} lang={lang} />)}
          </div>
        )}

        {activeCat === "bottles" && (
          <div className="reveal mt-10 rounded-2xl border border-gold/30 bg-gold/5 p-7 flex flex-col md:flex-row items-center justify-between gap-5">
            <div>
              <h3 className="text-2xl font-black uppercase mb-1">{t("Bottle packages & sparkler shows", "Paquetes de botellas y shows de luces")}</h3>
              <p className="text-white/60 text-sm">{t("Custom packages, champagne parades and VIP presentation available tableside.", "Paquetes personalizados, desfiles de champaña y presentación VIP en mesa.")}</p>
            </div>
            <PrimaryBtn icon="arrow-right" onClick={() => go("reserve")}>{t("Reserve a table", "Reservar mesa")}</PrimaryBtn>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MenuPage });
