/* ============================================================
   STORE — merch shop with colorways + add-to-bag
   ============================================================ */
function StorePage({ go }) {
  const t = useT(); const { lang } = useLang();
  const M = window.PP.MERCH;
  const [bag, setBag] = useState([]);
  const [cat, setCat] = useState("all");
  const [toast, setToast] = useState(null);
  useReveal(cat);

  const cats = ["all", ...Array.from(new Set(M.map((m) => m.cat.en)))];
  const list = cat === "all" ? M : M.filter((m) => m.cat.en === cat);
  const add = (m) => { setBag((b) => [...b, m]); setToast(m.name); setTimeout(() => setToast(null), 1600); };
  const total = bag.reduce((s, m) => s + m.price, 0);

  // Send the bag as an order summary to the club's WhatsApp.
  const checkout = () => {
    if (!bag.length) return;
    const counts = {};
    bag.forEach((m) => { counts[m.name] = (counts[m.name] || 0) + 1; });
    const fields = Object.keys(counts).map((name) => [name, "×" + counts[name]]);
    fields.push([t("Total", "Total"), "$" + total]);
    window.PP.track("InitiateCheckout", { value: total, currency: "USD", num_items: bag.length });
    window.PP.waOpen(
      t("New merch order — Pink Pony Club", "Nuevo pedido de merch — Pink Pony Club"),
      fields,
      t("Sent from clubpinkpony.com", "Enviado desde clubpinkpony.com"),
    );
  };

  return (
    <div className="pt-28 md:pt-32 pb-24">
      <div className="container">
        <div className="reveal flex flex-col sm:flex-row sm:items-end justify-between gap-5 mb-9">
          <div>
            <Eyebrow num="">{t("Official Merch", "Merch Oficial")}</Eyebrow>
            <h1 className="text-5xl md:text-7xl font-black uppercase leading-[0.9] mt-4">{t(<>The <span className="serif-it font-normal text-coral">Store</span></>, <>La <span className="serif-it font-normal text-coral">Tienda</span></>)}</h1>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-3 rounded-full border border-white/15 bg-card px-5 py-3">
              <Icon name="shopping-bag" className="w-5 h-5 text-coral" />
              <span className="text-sm font-semibold">{bag.length} {t("items", "artículos")}</span>
              {bag.length > 0 && <span className="serif text-gold-soft text-lg">${total}</span>}
            </div>
            {bag.length > 0 && (
              <button onClick={checkout} className="gbtn inline-flex items-center gap-2 px-6 py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] transition-all"><Icon name="message-circle" className="w-4 h-4" />{t("Checkout", "Finalizar")}</button>
            )}
          </div>
        </div>

        {/* category filter */}
        <div className="flex gap-2 overflow-x-auto pb-1 mb-8">
          {cats.map((c) => (
            <button key={c} onClick={() => setCat(c)} className={"shrink-0 px-4 py-2 rounded-full text-[11px] font-bold uppercase tracking-[0.12em] transition-all " + (cat === c ? "bg-coral text-white" : "bg-white/5 text-white/60 border border-white/10 hover:text-white")}>
              {c === "all" ? t("All", "Todo") : c}
            </button>
          ))}
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-5">
          {list.map((m, i) => (
            <div key={m.name} className="reveal group rounded-2xl overflow-hidden border border-white/10 bg-card hover:border-coral/40 transition-all hover:-translate-y-1" data-d={(i % 3) + 1}>
              <div className="relative aspect-square overflow-hidden">
                <Photo placeholder={m.ph} src={m.img ? window.PP.SRC(m.img, 600, 600) : null} alt={m.name} className="absolute inset-0 w-full h-full" imgClass="object-cover transition-transform duration-[900ms] group-hover:scale-110" style={{ filter: "brightness(.95)" }} />
                {m.tag && <div className="absolute top-3 left-3"><Chip color="var(--c-coral)">{L(m.tag, lang)}</Chip></div>}
                <button onClick={() => add(m)} className="absolute bottom-3 right-3 w-10 h-10 rounded-full bg-coral text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all hover:scale-110 shadow-lg" title={t("Add to bag", "Agregar")}>
                  <Icon name="plus" className="w-5 h-5" />
                </button>
              </div>
              <div className="p-4">
                <div className="label text-white/40 text-[9px] mb-1">{L(m.cat, lang)}</div>
                <div className="flex items-start justify-between gap-2">
                  <h3 className="font-bold text-sm leading-tight">{m.name}</h3>
                  <span className="serif text-lg text-gold-soft shrink-0">${m.price}</span>
                </div>
                <div className="flex items-center gap-1.5 mt-3">
                  {m.colorways.map((c, j) => <span key={j} className="w-4 h-4 rounded-full border border-white/25" style={{ background: c }}></span>)}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* shipping note */}
        <p className="reveal text-center text-white/40 text-sm mt-10">{t("Free pickup at the venue · Ships across the US · Members get 15% off.", "Recogida gratis en el venue · Envíos en todo EE.UU. · Miembros 15% off.")}</p>
      </div>

      {/* add toast */}
      <div className={"fixed bottom-24 left-1/2 -translate-x-1/2 z-50 transition-all duration-300 " + (toast ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3 pointer-events-none")}>
        <div className="flex items-center gap-3 bg-white text-black rounded-full pl-4 pr-5 py-3 shadow-2xl">
          <Icon name="check" className="w-4 h-4 text-coral" /><span className="text-sm font-bold">{toast} {t("added", "agregado")}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { StorePage });
