// Events — two sections on one page:
//   1) Events Calendar  → embedded Google Calendar (agenda view, America/New_York)
//                          in a themed container. Calendar's internal UI is
//                          Google's and only lightly themeable.
//   2) Upcoming Events   → "keep an eye out" cards, driven from a Google Sheet
//                          via the same-origin proxy (/api/sheet?src=events) so
//                          the client self-updates. Nothing hard-coded.
//
// Sheet columns (headers in row 1; data row 2 down; auto-grow):
//   Event Title | Date | Location | Note | Sign-Up Link

// --- Section 1: Google Calendar embed (agenda) ---
// Public calendar embed provided by RDB. Agenda/schedule view, ET timezone.
// We append light theming params (dark bg, hide Google chrome) — the event list
// itself is rendered by Google and only lightly themeable.
const EVENTS_CAL_ID = "b10bd7bef14989d878d3c60f3d115b82f28ccadc2bd07f9407a65ec5b137b3a2%40group.calendar.google.com";
const EVENTS_CAL_SRC =
  "https://calendar.google.com/calendar/embed" +
  "?src=" + EVENTS_CAL_ID +
  "&ctz=America/New_York" +
  "&mode=MONTH" +
  "&bgcolor=%230D0D0D" +
  "&showTitle=0&showPrint=0&showTabs=0&showCalendars=0&showTz=0&showNav=1&showDate=1";

// --- Section 2: Upcoming Events sheet (proxied, self-updated by RDB) ---
const EVENTS_UPCOMING_CSV = "/api/sheet?src=events";

// Seed sample (offline / preview fallback). Mirrors the real column headers,
// including a fully-TBD row to demonstrate the "Date & location TBD" state.
const EVENTS_UPCOMING_SEED = [
  { "Event Title": "Cruise Partner Showcase", "Date": "September 15", "Location": "NYC", "Note": "More information to come!", "Sign-Up Link": "" },
  { "Event Title": "FROSCH Air Booking Workshop", "Date": "", "Location": "Virtual · Zoom", "Note": "Hands-on session — registration opens soon.", "Sign-Up Link": "https://example.com/frosch-workshop" },
  { "Event Title": "Year-End Awards Dinner", "Date": "TBD", "Location": "TBD", "Note": "Invitations to top producers go out in November.", "Sign-Up Link": "" },
  { "Event Title": "New Agent Onboarding Cohort", "Date": "TBD", "Location": "TBD", "Note": "Rolling sessions — keep an eye out for the next start date.", "Sign-Up Link": "" },
];

function buildUpcoming(text) {
  const { rows } = rdbParseSheetObjects(text);
  return rows.filter(r => (r["Event Title"] || "").trim());
}

function isTbd(v) {
  const t = (v || "").trim().toLowerCase();
  return t === "" || t === "tbd";
}

// Compose the "Date · Location" meta line per the spec.
function eventMeta(e) {
  const dateTbd = isTbd(e["Date"]);
  const locTbd = isTbd(e["Location"]);
  if (dateTbd && locTbd) return { text: "Date & location TBD", muted: true };
  const parts = [];
  if (!dateTbd) parts.push((e["Date"] || "").trim());
  if (!locTbd) parts.push((e["Location"] || "").trim());
  return { text: parts.join(" · "), muted: false };
}

function EventSignUp({ url, compact }) {
  const [hover, setHover] = React.useState(false);
  return (
    <a href={url} target="_blank" rel="noopener noreferrer"
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 9,
        padding: "11px 20px", width: compact ? "100%" : "auto",
        background: hover ? "var(--rdb-gold-bright)" : "var(--rdb-gold)",
        color: "#0D0D0D", textDecoration: "none",
        fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 13, letterSpacing: "0.04em",
        cursor: "pointer", transition: "background 160ms",
      }}>
      <Icon name="ticket" size={16} color="#0D0D0D" />
      Sign Up
      <Icon name="arrow-up-right" size={15} color="#0D0D0D" />
    </a>
  );
}

function UpcomingCard({ e, compact }) {
  const [hover, setHover] = React.useState(false);
  const meta = eventMeta(e);
  const url = (e["Sign-Up Link"] || "").trim();
  const note = (e["Note"] || "").trim();
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: "relative", background: "var(--ink-0)",
        border: "1px solid " + (hover ? "rgba(201,168,76,0.6)" : "var(--ink-3)"),
        padding: "22px 24px 22px 28px", overflow: "hidden",
        display: "flex", flexDirection: "column", gap: 14, transition: "border-color 160ms" }}>
      <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--rdb-gold)" }} />
      <div>
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 18 : 20, color: "var(--fg-1)", margin: "0 0 9px", letterSpacing: "-0.01em", lineHeight: 1.15 }}>{e["Event Title"]}</h3>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8,
          fontFamily: "var(--font-mono)", fontSize: 12.5,
          color: meta.muted ? "var(--ink-6)" : "var(--rdb-gold)",
          fontStyle: meta.muted ? "italic" : "normal" }}>
          <Icon name={meta.muted ? "clock" : "calendar"} size={13} color={meta.muted ? "var(--ink-6)" : "var(--rdb-gold)"} />
          {meta.text}
        </div>
      </div>
      {note && <p style={{ fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.6, color: "var(--fg-3)", margin: 0 }}>{note}</p>}
      {url && (
        <div style={{ marginTop: "auto", paddingTop: 4 }}>
          <EventSignUp url={url} compact={compact} />
        </div>
      )}
    </div>
  );
}

function EventsPage({ compact }) {
  const upcoming = useSheet(EVENTS_UPCOMING_CSV, EVENTS_UPCOMING_SEED, buildUpcoming);
  const pad = compact ? "22px 18px 60px" : "48px 64px 96px";
  const calHeight = compact ? 520 : 600;

  return (
    <div style={{ padding: pad, maxWidth: compact ? "100%" : 1240, margin: "0 auto" }}>
      {/* Page header */}
      <div style={{ marginBottom: 12 }}>
        <div className="rdb-eyebrow" style={{ marginBottom: 14 }}>Backstage · Community</div>
        <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 30 : 48, letterSpacing: "-0.02em", color: "var(--fg-1)", margin: 0, lineHeight: 1.02 }}>Events</h1>
        <p style={{ fontFamily: "var(--font-body)", fontSize: compact ? 14 : 16, lineHeight: 1.6, color: "var(--fg-2)", margin: "16px 0 0", maxWidth: 620 }}>
          Webinars, workshops, and gatherings for RDB contractors. Browse the calendar below — and watch this space for what's coming.
        </p>
      </div>

      <div style={{ height: 1, background: "var(--rdb-gold-soft)", margin: compact ? "26px 0" : "36px 0 32px" }} />

      {/* Section 1 — Events Calendar */}
      <section style={{ marginBottom: compact ? 40 : 60 }}>
        <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 20 : 26, color: "var(--fg-1)", margin: "0 0 8px", letterSpacing: "-0.01em" }}>Upcoming Webinars &amp; Events</h2>
        <p style={{ fontFamily: "var(--font-body)", fontSize: compact ? 13 : 14, lineHeight: 1.55, color: "var(--fg-3)", margin: "0 0 18px", maxWidth: 580 }}>
          Click any event for full details and the sign-up link.
        </p>

        {/* Themed calendar container */}
        <div style={{ position: "relative", border: "1px solid var(--ink-3)", background: "var(--ink-0)", overflow: "hidden" }}>
          <span style={{ position: "absolute", left: 0, right: 0, top: 0, height: 2, background: "var(--rdb-gold)", zIndex: 1 }} />
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: compact ? "14px 16px" : "16px 22px", borderBottom: "1px solid var(--ink-2)", flexWrap: "wrap" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Icon name="calendar-days" size={16} color="var(--rdb-gold)" />
              <span style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, letterSpacing: "0.04em", color: "var(--fg-1)" }}>Events Calendar</span>
            </div>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-6)", letterSpacing: "0.04em" }}>
              <Icon name="globe" size={12} color="var(--ink-6)" />Times shown in ET (America/New_York)
            </span>
          </div>
          <iframe
            title="RDB Backstage Events Calendar"
            src={EVENTS_CAL_SRC}
            style={{ width: "100%", height: calHeight, border: "none", display: "block", background: "var(--ink-0)" }}
            loading="lazy"
          ></iframe>
        </div>
      </section>

      {/* Section 2 — Upcoming Events ("keep an eye out") */}
      <section>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, marginBottom: 8, flexWrap: "wrap" }}>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: compact ? 20 : 26, color: "var(--fg-1)", margin: 0, letterSpacing: "-0.01em" }}>Upcoming Events</h2>
          <SyncPill status={upcoming.status} liveLabel="Live · self-updated by RDB" sampleLabel="Sample events · live when hosted" />
        </div>
        <p style={{ fontFamily: "var(--font-body)", fontSize: compact ? 13 : 14, lineHeight: 1.55, color: "var(--fg-3)", margin: "0 0 20px", maxWidth: 580 }}>
          Not on the calendar yet — keep an eye out. Details land here as they're confirmed.
        </p>

        {upcoming.rows.length === 0 ? (
          <div style={{ border: "1px solid var(--ink-3)", padding: "40px 24px", textAlign: "center", fontFamily: "var(--font-body)", fontSize: 14, color: "var(--ink-6)" }}>
            Nothing on the horizon just yet — check back soon.
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "repeat(2, 1fr)", gap: 20 }}>
            {upcoming.rows.map((e, i) => <UpcomingCard key={i} e={e} compact={compact} />)}
          </div>
        )}
      </section>
    </div>
  );
}

Object.assign(window, { EventsPage, UpcomingCard, EventSignUp });
