// Events.jsx — Calendar + List + filter chips + event detail modal.

function TgEvents({ city, setCity, setOpenCityPicker, openEvent }) {
  const [view, setView] = React.useState("list"); // list | calendar
  const [type, setType] = React.useState("all");
  const [filterCity, setFilterCity] = React.useState(city);
  const [month, setMonth] = React.useState(4); // May 2026

  React.useEffect(() => { setFilterCity(city); }, [city]);

  const filtered = window.TG_EVENTS.filter(e => {
    if (filterCity !== "all" && e.city !== filterCity) return false;
    if (type !== "all" && e.type !== type) return false;
    return true;
  });

  const cityObj = window.TG_CITIES.find(c => c.id === filterCity);
  const cityLabel = filterCity === "all" ? "All cities" : (cityObj ? cityObj.name : "—");

  return (
    <main className="container" style={{ paddingTop: 8, paddingBottom: 60 }}>
      {/* --- HEAD --- */}
      <div className="tg-events-head">
        <span className="eyebrow"><span className="spark">✦</span> Calendar · {cityLabel}</span>
        <h1>What&rsquo;s on <span className="script" style={{ fontSize: "0.6em" }}>this week</span></h1>
        <p className="lede">A culture calendar, not a booking portal. RSVP through the chat or join the waitlist — we'll holler back inside 24 hours.</p>
      </div>

      {/* --- TOOLBAR --- */}
      <div className="tg-events-toolbar">
        <div className="tg-filter-group">
          <span className="label">City</span>
          <button className={"tg-chip " + (filterCity === "all" ? "is-active" : "")} onClick={() => setFilterCity("all")}>All</button>
          {window.TG_CITIES.map(c => (
            <button key={c.id} className={"tg-chip " + (filterCity === c.id ? "is-active" : "")} onClick={() => { setFilterCity(c.id); setCity(c.id); }}>
              <span className="dot" style={{ background: c.color }}></span>{c.name}
            </button>
          ))}
        </div>
        <div className="tg-filter-group">
          <span className="label">Type</span>
          <button className={"tg-chip " + (type === "all" ? "is-active" : "")} onClick={() => setType("all")}>All</button>
          {window.TG_EVENT_TYPES.map(t => (
            <button key={t.id} className={"tg-chip " + (type === t.id ? "is-active" : "")} onClick={() => setType(t.id)}>{t.label}</button>
          ))}
        </div>
        <div className="tg-view-toggle">
          <button className={view === "list" ? "is-active" : ""} onClick={() => setView("list")}>List</button>
          <button className={view === "calendar" ? "is-active" : ""} onClick={() => setView("calendar")}>Calendar</button>
        </div>
      </div>

      {view === "list" ? (
        <ListView events={filtered} openEvent={openEvent} />
      ) : (
        <CalendarView events={filtered} month={month} setMonth={setMonth} openEvent={openEvent} />
      )}

      {filtered.length === 0 && <EmptyState onChange={() => { setFilterCity("all"); setType("all"); }} />}
    </main>
  );
}

function ListView({ events, openEvent }) {
  // Group by week-ish (month + first/second half) for editorial rhythm
  const grouped = events.reduce((acc, e) => {
    const k = `${e.month} ${e.year}`;
    (acc[k] = acc[k] || []).push(e);
    return acc;
  }, {});

  // Featured top 3 in poster grid + rest as list
  const top = events.slice(0, 3);
  const rest = events.slice(3);

  return (
    <div className="tg-events-list">
      {top.length > 0 && (
        <div className="tg-events__grid" style={{ marginBottom: 18 }}>
          {top.map(e => (
            <button key={e.id} className="tg-event--poster" style={{ backgroundImage: `url(${e.bg})` }} onClick={() => openEvent(e)}>
              {e.soldOut && <span className="tg-event__badge">SOLD OUT</span>}
              {!e.soldOut && e.status === "Few spots left" && <span className="tg-event__badge tg-event__badge--peach">FEW SPOTS</span>}
              <span className="tg-event__spark">✦</span>
              <div>
                <div className="tg-event__cat">{e.typeLabel} · {e.cityLabel}</div>
                <h3 className="tg-event__title">{e.title}</h3>
              </div>
              <div className="tg-event__when">
                <span className="d">{e.day}</span>
                <div>
                  <span className="m">{e.month} · {e.time}</span>
                  <span className="where">{e.venue}</span>
                </div>
              </div>
            </button>
          ))}
        </div>
      )}

      {rest.map(e => (
        <button key={e.id} className="tg-event--list" onClick={() => openEvent(e)}>
          <div className="tg-event__date" style={{ background: e.dateColor }}>
            <span className="m">{e.month}</span>
            <span className="d">{e.day}</span>
          </div>
          <div className="tg-event__body">
            <div className="tg-event__cat">{e.typeLabel} · {e.cityLabel}</div>
            <h3>{e.title}</h3>
            <p>{e.subtitle}</p>
            <div className="tg-event__meta">
              <span>{e.time}</span><span>·</span>
              <span>{e.venue}</span><span>·</span>
              <span className={"pill " + (
                e.status === "Sold out" ? "pill--mag" :
                e.status === "Few spots left" ? "pill--peach" :
                e.status === "Members first" ? "pill--soft" : ""
              )}>{e.status}</span>
            </div>
          </div>
          <span className="tg-event__cta">{e.soldOut ? "Waitlist" : "Pull up"} →</span>
        </button>
      ))}
    </div>
  );
}

function CalendarView({ events, month, setMonth, openEvent }) {
  // 2026 — show May (4) by default. Fixed: May 2026 starts Friday (day 5).
  const monthsData = [
    { name: "April",    year: 2026, days: 30, start: 3 }, // Wed
    { name: "May",      year: 2026, days: 31, start: 5 }, // Fri
    { name: "June",     year: 2026, days: 30, start: 1 }, // Mon
  ];
  const idx = Math.max(0, Math.min(monthsData.length - 1, month - 3));
  const m = monthsData[idx] || monthsData[1];

  // Build day cells
  const cells = [];
  for (let i = 0; i < m.start; i++) cells.push({ empty: true, key: `e${i}` });
  for (let d = 1; d <= m.days; d++) {
    const monthLabel = m.name.slice(0, 3).toUpperCase();
    const dayEvents = events.filter(e => e.month === monthLabel && e.day === d);
    cells.push({ d, monthLabel, dayEvents, key: `d${d}` });
  }

  const today = { d: 20, month: "MAY" }; // current date
  const dows = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

  // colour map by type
  const evtClass = (type) => ({
    watch:  "tg-cal__evt tg-cal__evt--mag",
    play:   "tg-cal__evt tg-cal__evt--orange",
    dinner: "tg-cal__evt tg-cal__evt--peach",
    social: "tg-cal__evt tg-cal__evt--lilac",
    popup:  "tg-cal__evt",
  }[type] || "tg-cal__evt");

  return (
    <div className="tg-calendar">
      <div className="tg-cal__head">
        <h3>{m.name} <span className="script">{m.year}</span></h3>
        <div className="tg-cal__nav">
          <button onClick={() => setMonth(Math.max(3, month - 1))}>‹</button>
          <button onClick={() => setMonth(Math.min(5, month + 1))}>›</button>
        </div>
      </div>

      <div className="tg-cal__grid">
        {dows.map(d => <div key={d} className="tg-cal__dow">{d}</div>)}
        {cells.map(c => {
          if (c.empty) return <div key={c.key} className="tg-cal__day is-empty"></div>;
          const isToday = c.d === today.d && c.monthLabel === today.month;
          return (
            <div key={c.key} className={"tg-cal__day " + (isToday ? "is-today" : "")}>
              <div className="n">{c.d}</div>
              {c.dayEvents.map(e => (
                <button key={e.id} className={evtClass(e.type)}
                  onClick={() => openEvent(e)}
                  style={{ border: "none", textAlign: "left", cursor: "pointer", font: "inherit" }}>
                  {e.title}
                </button>
              ))}
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: 14, marginTop: 24, fontSize: 11, fontWeight: 800, letterSpacing: "0.1em", textTransform: "uppercase" }}>
        {window.TG_EVENT_TYPES.map(t => (
          <span key={t.id} style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>
            <span style={{ width: 12, height: 12, borderRadius: 4, background: t.color, display: "inline-block" }}></span>
            {t.label}
          </span>
        ))}
      </div>
    </div>
  );
}

function EmptyState({ onChange }) {
  return (
    <div style={{ padding: "60px 24px", textAlign: "center", background: "var(--tg-cream)", borderRadius: 24, border: "2px dashed rgba(17,17,17,0.15)", marginTop: 24 }}>
      <div style={{ fontSize: 38 }}>✦</div>
      <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 36, textTransform: "uppercase", letterSpacing: "-0.025em", margin: "16px 0 8px" }}>
        Nothing on the calendar yet.
      </h3>
      <p style={{ fontFamily: "var(--font-serif)", fontSize: 16, maxWidth: 44 + 'ch', margin: "0 auto 18px", color: "var(--tg-ink-soft)" }}>
        Try a different city or type — or join the waitlist and we'll holler when we land somewhere new.
      </p>
      <button className="btn btn--ink" onClick={onChange}>Reset filters <span className="arr">→</span></button>
    </div>
  );
}


function TgEventModal({ event, onClose }) {
  if (!event) return null;
  return (
    <div className="tg-modal-bg" onClick={onClose}>
      <div className="tg-modal" onClick={(e) => e.stopPropagation()}>
        <div className="tg-modal__img" style={{ backgroundImage: `url(${event.bg})` }}>
          <button className="tg-modal__close" onClick={onClose}>✕</button>
          {event.soldOut && <span className="tg-event__badge" style={{ top: 20, left: 20 }}>SOLD OUT</span>}
          <div style={{ position: "absolute", left: 20, bottom: 20, color: "var(--tg-cream)" }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 900, fontSize: 64, lineHeight: 0.9, letterSpacing: "-0.04em" }}>{event.day}</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 13, letterSpacing: "0.12em", textTransform: "uppercase", marginTop: 4 }}>{event.month} {event.year}</div>
          </div>
        </div>
        <div className="tg-modal__body">
          <div className="tg-modal__cat">✦ {event.typeLabel} · {event.cityLabel}</div>
          <h2 className="tg-modal__title">{event.title}</h2>
          <div className="tg-modal__meta">
            <div className="row"><span className="k">When</span><span className="v">{event.day} {event.month} {event.year} · {event.time}</span></div>
            <div className="row"><span className="k">Where</span><span className="v">{event.venue}, {event.cityLabel}</span></div>
            <div className="row"><span className="k">Host</span><span className="v">{event.host}</span></div>
            <div className="row"><span className="k">Status</span><span className="v" style={{ color: event.soldOut ? "var(--tg-magenta)" : "var(--tg-ink-soft)", fontWeight: 700 }}>{event.status} · {event.spots} spots</span></div>
          </div>
          <p>{event.description}</p>

          <div className="tg-modal__cta">
            {event.soldOut ? (
              <React.Fragment>
                <button className="btn btn--ink">Join waitlist <span className="arr">→</span></button>
                <button className="btn btn--ghost" onClick={onClose}>Back to calendar</button>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <button className="btn btn--pri">Save me a spot <span className="arr">→</span></button>
                <button className="btn btn--ghost">Bring a friend</button>
              </React.Fragment>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.TgEvents = TgEvents;
window.TgEventModal = TgEventModal;
