/* ============================================================
   EVENTS — hub with sub-tabs:
   Calendar (live month · real matchdays · ICS export) ·
   Weekly · Sports · Live Performance · Special Events
   ============================================================ */

/* download a real .ics so guests add the night to their phone calendar */
function downloadICS(title, iso, time) {
  const m = String(time || "").match(/(\d+)(?::(\d+))?\s*(AM|PM)?/i);
  let h = 21, mn = 0;
  if (m) { h = +m[1]; mn = +(m[2] || 0); const ap = (m[3] || "").toUpperCase(); if (ap === "PM" && h < 12) h += 12; if (ap === "AM" && h === 12) h = 0; }
  const start = new Date(iso + "T00:00:00"); start.setHours(h, mn, 0, 0);
  const end = new Date(start.getTime() + 4 * 3600e3);
  const f = (d) => d.getFullYear() + String(d.getMonth() + 1).padStart(2, "0") + String(d.getDate()).padStart(2, "0") + "T" + String(d.getHours()).padStart(2, "0") + String(d.getMinutes()).padStart(2, "0") + "00";
  const ics = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Pink Pony Club//Events//EN", "BEGIN:VEVENT",
    "UID:" + iso + "-" + Date.now() + "@clubpinkpony", "DTSTART:" + f(start), "DTEND:" + f(end),
    "SUMMARY:" + String(title).replace(/[\n,;]/g, " "), "LOCATION:Pink Pony Club · 7971 NW 33rd St · Doral FL 33122",
    "END:VEVENT", "END:VCALENDAR"].join("\r\n");
  const a = document.createElement("a");
  a.href = "data:text/calendar;charset=utf-8," + encodeURIComponent(ics);
  a.download = String(title).replace(/\W+/g, "-").toLowerCase() + ".ics";
  document.body.appendChild(a); a.click(); a.remove();
}

/* events on a given local date: weekly night + real matchdays +
   admin-added events (PPDB) + any legacy dated specials */
function dayEvents(date, mdByIso) {
  const { NIGHTS, CAL_SPECIALS } = window.PP;
  const iso = date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, "0") + "-" + String(date.getDate()).padStart(2, "0");
  const n = NIGHTS[(date.getDay() + 6) % 7];
  const list = [{ type: "weekly", title: n.name, time: (n.time.split(/[–—-]/)[0] || "8PM").trim(), dj: n.dj, bottle: n.bottle, img: n.img }];
  (mdByIso[iso] || []).forEach((md) => list.push({ type: "sport", title: md.match, time: md.time, img: md.img, flyer: true }));
  try {
    (window.PPDB && window.PPDB.events ? window.PPDB.events.forIso(iso) : []).forEach((ev) =>
      list.push({ type: ev.type || "special", title: ev.title, time: ev.time, note: ev.note, img: ev.img, admin: true }));
  } catch (e) {}
  CAL_SPECIALS.filter((s) => s.day === date.getDate() && (s.month == null || s.month === date.getMonth())).forEach((s) => list.push(s));
  return list;
}

function CalendarView({ go }) {
  const t = useT(); const { lang } = useLang();
  const { CAL_TYPES, MATCHDAYS } = window.PP;
  const loc = lang === "es" ? "es" : "en";

  /* live "today" — the calendar opens on the real current month/day */
  const now = new Date();
  const todayIso = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0") + "-" + String(now.getDate()).padStart(2, "0");
  const [ym, setYm] = useState([now.getFullYear(), now.getMonth()]);
  const [Y, M] = ym;
  const isThisMonth = Y === now.getFullYear() && M === now.getMonth();
  const [sel, setSel] = useState(now.getDate());

  const mdByIso = useMemo(() => {
    const map = {};
    (MATCHDAYS || []).forEach((md) => { if (md.iso) (map[md.iso] = map[md.iso] || []).push(md); });
    return map;
  }, [MATCHDAYS]);

  // re-render when admin adds/edits events (PPDB) so the calendar stays live
  const [, bump] = useState(0);
  useEffect(() => {
    const f = () => bump((x) => x + 1);
    window.addEventListener("pp:events", f);
    return () => window.removeEventListener("pp:events", f);
  }, []);

  const isoOf = (d) => Y + "-" + String(M + 1).padStart(2, "0") + "-" + String(d).padStart(2, "0");
  const eventsForDay = (d) => dayEvents(new Date(Y, M, d), mdByIso);

  const monthName = new Date(Y, M, 1).toLocaleString(loc, { month: "long", year: "numeric" });
  const startDow = (new Date(Y, M, 1).getDay() + 6) % 7; // Mon=0
  const daysIn = new Date(Y, M + 1, 0).getDate();
  const cells = []; for (let i = 0; i < startDow; i++) cells.push(null); for (let d = 1; d <= daysIn; d++) cells.push(d);
  const dow = lang === "es" ? ["L", "M", "X", "J", "V", "S", "D"] : ["M", "T", "W", "T", "F", "S", "S"];

  const nav = (dir) => {
    const d = new Date(Y, M + dir, 1);
    setYm([d.getFullYear(), d.getMonth()]);
    setSel(d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() ? now.getDate() : 1);
  };
  const goToday = () => { setYm([now.getFullYear(), now.getMonth()]); setSel(now.getDate()); };

  const selEvents = sel ? eventsForDay(sel) : [];
  const todayEvents = dayEvents(now, mdByIso);
  const tonightNight = todayEvents[0];
  const tonightMatch = todayEvents.find((e) => e.type === "sport");

  return (
    <div className="container">
      {/* TONIGHT banner */}
      <div className="reveal relative rounded-3xl overflow-hidden border border-coral/30 mb-10">
        <Photo src={window.PP.SRC(tonightNight.img, 1400, 500)} alt="" className="absolute inset-0 w-full h-full" imgClass="object-cover" style={{ filter: "brightness(.35)" }} />
        <div className="absolute inset-0 bg-gradient-to-r from-ink/90 via-ink/60 to-transparent"></div>
        <div className="relative z-10 p-6 md:p-9 flex flex-col md:flex-row md:items-center gap-6">
          <div className="flex-1">
            <div className="label text-coral text-[10px] mb-2 flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-coral pulse-dot"></span>{t("Tonight at Pink Pony", "Hoy en Pink Pony")} · <span className="capitalize">{now.toLocaleDateString(loc, { weekday: "long", day: "numeric", month: "long" })}</span></div>
            <h3 className="text-3xl md:text-5xl font-black uppercase leading-[0.95] mb-2">{tonightNight.title}</h3>
            <p className="text-white/65 text-sm md:text-base">{tonightNight.dj} · {t("from", "desde")} {tonightNight.time}{tonightNight.bottle && <> · <span className="text-gold-soft font-bold">{tonightNight.bottle} {t("bottles", "botellas")}</span></>}</p>
            {tonightMatch && <p className="text-white/80 text-sm mt-2 flex items-center gap-2"><Icon name="trophy" className="w-4 h-4 text-coral" /><span className="font-bold">{tonightMatch.title}</span> · {tonightMatch.time} · {t("Watch Party", "Watch Party")}</p>}
            <div className="flex flex-wrap gap-3 mt-5">
              <button onClick={() => go("reserve")} className="gbtn px-6 py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] transition-all">{t("Reserve tonight", "Reserva hoy")}</button>
              <button onClick={() => downloadICS(tonightNight.title + " — Pink Pony Club", todayIso, tonightNight.time)} className="px-6 py-3 rounded-full border border-white/25 text-white/85 text-[12px] font-bold uppercase tracking-[0.14em] hover:bg-white/10 transition-all inline-flex items-center gap-2"><Icon name="calendar-plus" className="w-4 h-4" />{t("Add to my calendar", "Agregar a mi calendario")}</button>
            </div>
          </div>
          {tonightMatch && (
            <div className="hidden md:block w-36 lg:w-44 shrink-0 rounded-2xl overflow-hidden border border-white/15 bg-black">
              <img src={tonightMatch.img} alt={tonightMatch.title} loading="lazy" className="w-full h-auto object-contain" />
            </div>
          )}
        </div>
      </div>

      {/* header + month nav */}
      <div className="reveal mb-6 flex items-end justify-between gap-4 flex-wrap">
        <Heading>{t(<>Event <span className="serif-it font-normal text-coral">Calendar</span></>, <>Calendario de <span className="serif-it font-normal text-coral">Eventos</span></>)}</Heading>
        <div className="flex items-center gap-2">
          <button onClick={() => nav(-1)} aria-label={t("Previous month", "Mes anterior")} className="w-10 h-10 rounded-full border border-white/15 flex items-center justify-center text-white/70 hover:bg-white/10 transition-colors"><Icon name="chevron-left" className="w-5 h-5" /></button>
          <span className="text-lg md:text-2xl font-black uppercase tracking-wide min-w-[150px] md:min-w-[190px] text-center capitalize">{monthName}</span>
          <button onClick={() => nav(1)} aria-label={t("Next month", "Mes siguiente")} className="w-10 h-10 rounded-full border border-white/15 flex items-center justify-center text-white/70 hover:bg-white/10 transition-colors"><Icon name="chevron-right" className="w-5 h-5" /></button>
          {!isThisMonth && <button onClick={goToday} className="ml-1 px-4 py-2 rounded-full bg-white/10 border border-white/15 text-white text-[11px] font-bold uppercase tracking-wider hover:bg-white/20 transition-colors">{t("Today", "Hoy")}</button>}
        </div>
      </div>
      {/* legend */}
      <div className="reveal flex flex-wrap gap-4 mb-5">
        {Object.entries(CAL_TYPES).map(([k, v]) => <div key={k} className="flex items-center gap-2 text-[11px] text-white/60"><span className="w-2.5 h-2.5 rounded-full" style={{ background: v.color }}></span>{L(v.label, lang)}</div>)}
      </div>

      <div className="grid lg:grid-cols-12 gap-6 items-start">
        {/* month grid */}
        <div className="lg:col-span-8 reveal">
          <div className="grid grid-cols-7 gap-1.5 mb-2">{dow.map((d, i) => <div key={i} className="text-center label text-white/40 text-[10px] py-1">{d}</div>)}</div>
          <div className="grid grid-cols-7 gap-1.5">
            {cells.map((d, i) => {
              if (!d) return <div key={i}></div>;
              const iso = isoOf(d);
              const evs = eventsForDay(d); const types = [...new Set(evs.map((e) => e.type))];
              const isSel = sel === d;
              const isToday = iso === todayIso;
              const isPast = iso < todayIso;
              const hasMatch = !!mdByIso[iso];
              return (
                <button key={i} onClick={() => setSel(d)}
                  className={"relative aspect-square rounded-xl border p-1.5 flex flex-col transition-all " +
                    (isSel ? "border-coral bg-coral/15 " : isToday ? "border-gold/70 bg-gold/10 " : "border-white/10 hover:border-white/30 bg-card ") +
                    (isPast && !isSel ? "opacity-40" : "")}>
                  <span className={"text-[11px] font-bold " + (isSel || isToday ? "text-white" : "text-white/60")}>{d}</span>
                  {isToday && <span className="absolute top-1 right-1.5 label text-gold-soft text-[7px] hidden sm:block">{t("TODAY", "HOY")}</span>}
                  {hasMatch && <Icon name="trophy" className="absolute bottom-1.5 right-1.5 w-3 h-3" style={{ color: "#5FBFA8" }} />}
                  <div className="mt-auto flex flex-wrap gap-1">{types.slice(0, 4).map((ty, j) => <span key={j} className="w-1.5 h-1.5 rounded-full" style={{ background: (CAL_TYPES[ty] || CAL_TYPES.weekly).color }}></span>)}</div>
                </button>
              );
            })}
          </div>
        </div>

        {/* day detail */}
        <div className="lg:col-span-4 lg:sticky lg:top-28 reveal" data-d="1">
          <div className="rounded-2xl border border-white/12 bg-card p-6">
            <div className="label text-gold text-[10px] mb-1 capitalize">{new Date(Y, M, sel).toLocaleDateString(loc, { weekday: "long", day: "numeric", month: "long" })}</div>
            <div className="text-2xl font-black uppercase mb-4">{selEvents.length} {selEvents.length === 1 ? t("event", "evento") : t("events", "eventos")}</div>
            <div className="space-y-4">
              {selEvents.map((e, i) => (
                <div key={i} className="flex items-start gap-3 pb-4 border-b border-white/8 last:border-0 last:pb-0">
                  {e.flyer
                    ? <div className="w-14 shrink-0 rounded-lg overflow-hidden border border-white/10 bg-black"><img src={e.img} alt="" loading="lazy" className="w-full h-auto object-contain" /></div>
                    : e.img
                      ? <Photo src={window.PP.SRC(e.img, 120, 120)} alt="" className="w-14 h-14 shrink-0 rounded-lg overflow-hidden border border-white/10" imgClass="object-cover" />
                      : <span className="w-2.5 h-2.5 rounded-full mt-1.5 shrink-0" style={{ background: (CAL_TYPES[e.type] || CAL_TYPES.weekly).color }}></span>}
                  <div className="flex-1 min-w-0">
                    <div className="font-bold text-sm leading-tight">{e.title}</div>
                    <div className="text-white/45 text-xs mt-0.5">{L((CAL_TYPES[e.type] || CAL_TYPES.weekly).label, lang)} · {e.time}{e.dj ? " · " + e.dj : ""}</div>
                    {e.bottle && <div className="text-gold-soft text-[11px] font-bold mt-0.5">{e.bottle} {t("bottle specials", "especiales de botella")}</div>}
                    <button onClick={() => downloadICS(e.title + " — Pink Pony Club", isoOf(sel), e.time)} className="mt-1.5 text-coral text-[10px] font-bold uppercase tracking-wider inline-flex items-center gap-1 hover:text-white transition-colors"><Icon name="calendar-plus" className="w-3 h-3" />{t("Add to calendar", "Agregar al calendario")}</button>
                  </div>
                </div>
              ))}
            </div>
            <button onClick={() => go("reserve")} className="gbtn w-full mt-5 py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] transition-all">{t("Reserve this night", "Reservar esta noche")}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function EventsPage({ go, initial }) {
  const t = useT(); const { lang } = useLang();
  const [tab, setTab] = useState(initial || "calendar");
  useReveal(tab);
  const tabs = [
    ["calendar", t("Calendar", "Calendario"), "calendar-days"],
    ["weekly", t("Weekly Events", "Eventos Semanales"), "calendar-clock"],
    ["sports", t("Sports", "Deportes"), "tv"],
    ["live", t("Live Performance", "Shows en Vivo"), "mic-vocal"],
    ["special", t("Special Events", "Eventos Especiales"), "sparkles"],
  ];

  const Weekly = (
    <div className="container">
      <div className="mb-10 reveal">
        <Heading>{t(<>Seven Nights, One <span className="serif-it font-normal text-coral">Address</span></>, <>Siete Noches, Una <span className="serif-it font-normal text-coral">Dirección</span></>)}</Heading>
        <p className="text-white/55 mt-4 max-w-xl">{t("A rotating cast of world-class DJs and signature programming, every night of the week.", "Un elenco rotativo de DJs de clase mundial y programación de firma, cada noche de la semana.")}</p>
      </div>
      <NightsAccordion />
    </div>
  );

  const Live = (
    <div className="container">
      <div className="mb-9 reveal"><Heading>{t(<>Live on <span className="serif-it font-normal text-coral">Stage</span></>, <>En Vivo en la <span className="serif-it font-normal text-coral">Tarima</span></>)}</Heading></div>
      <div className="grid sm:grid-cols-2 gap-5">
        {window.PP.PERFORMANCES.map((p, i) => (
          <div key={i} className="reveal group relative h-80 rounded-2xl overflow-hidden border border-white/10" data-d={(i % 3) + 1}>
            <Photo src={window.PP.SRC(p.img, 800, 600)} alt={p.name} className="absolute inset-0 w-full h-full" imgClass="object-cover transition-transform duration-[900ms] group-hover:scale-105" style={{ filter: "brightness(.7)" }} />
            <div className="absolute inset-0 bg-gradient-to-t from-black via-black/30 to-transparent"></div>
            {p.tag && <div className="absolute top-4 left-4"><Chip color="var(--c-coral)">{L(p.tag, lang)}</Chip></div>}
            <div className="absolute inset-x-0 bottom-0 p-6">
              <div className="label text-gold-soft text-[10px] mb-2">{L(p.date, lang)}</div>
              <h3 className="text-3xl font-black uppercase leading-none mb-1">{p.name}</h3>
              <p className="serif-it text-white/70 text-lg">{L(p.role, lang)}</p>
            </div>
          </div>
        ))}
      </div>
      <div className="reveal mt-9 text-center"><PrimaryBtn icon="ticket" onClick={() => go("reserve")}>{t("Reserve for a show", "Reserva para un show")}</PrimaryBtn></div>
    </div>
  );

  const Special = (
    <div className="container">
      <div className="mb-9 reveal"><Heading>{t(<>The <span className="serif-it font-normal text-coral">Big Nights</span></>, <>Las <span className="serif-it font-normal text-coral">Grandes Noches</span></>)}</Heading></div>
      <div className="space-y-5">
        {window.PP.SPECIAL_EVENTS.map((e, i) => (
          <div key={i} className="reveal group grid md:grid-cols-12 gap-0 rounded-2xl overflow-hidden border border-white/10 bg-card hover:border-coral/40 transition-all" data-d={(i % 3) + 1}>
            <div className="md:col-span-5 relative h-56 md:h-auto overflow-hidden">
              <Photo src={window.PP.SRC(e.img, 800, 600)} alt={e.name} className="absolute inset-0 w-full h-full" imgClass="object-cover transition-transform duration-[900ms] group-hover:scale-105" style={{ filter: "brightness(.8)" }} />
              <div className="absolute inset-0 bg-gradient-to-r from-transparent to-card/80 hidden md:block"></div>
            </div>
            <div className="md:col-span-7 p-7 flex flex-col justify-center">
              <div className="label text-coral text-[11px] mb-2">{L(e.date, lang)}</div>
              <h3 className="text-3xl md:text-4xl font-black uppercase leading-none mb-3">{e.name}</h3>
              <p className="text-white/60 mb-5 max-w-lg">{L(e.d, lang)}</p>
              <div className="flex items-center gap-4">
                <button onClick={() => go("reserve")} className="gbtn px-6 py-3 rounded-full bg-coral hover:bg-coral-deep text-white text-[12px] font-bold uppercase tracking-[0.14em] transition-all">{t("RSVP / Table", "RSVP / Mesa")}</button>
                <span className="label text-gold-soft/70 text-[10px]">{e.hash}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="pt-28 md:pt-32 pb-24">
      <div className="container mb-9">
        <div className="reveal"><Eyebrow num="">{t("What's On", "Cartelera")}</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">Events</span></>, <>Los <span className="serif-it font-normal text-coral">Eventos</span></>)}</h1></div>
      </div>
      {/* sub-tabs */}
      <div className="container mb-10">
        <div className="flex gap-2 overflow-x-auto pb-1">
          {tabs.map(([id, lbl, ic]) => (
            <button key={id} onClick={() => setTab(id)}
              className={"shrink-0 inline-flex items-center gap-2 px-5 py-2.5 rounded-full text-[12px] font-bold uppercase tracking-[0.12em] transition-all " + (tab === id ? "bg-coral text-white" : "bg-white/5 text-white/65 border border-white/10 hover:text-white")}>
              <Icon name={ic} className="w-4 h-4" /> {lbl}
            </button>
          ))}
        </div>
      </div>
      <div key={tab} className="fade-view">
        {tab === "calendar" && <CalendarView go={go} />}
        {tab === "weekly" && Weekly}
        {tab === "sports" && <div className="-mt-6"><SportsPage go={go} /></div>}
        {tab === "live" && Live}
        {tab === "special" && Special}
      </div>
    </div>
  );
}

Object.assign(window, { EventsPage, downloadICS });
