// Calendar page — filters, list of events, lunar legend, monthly mini-calendar
function eventCategoryTheme(id) {
  const themes = {
    all: { bg: "var(--ink)", soft: "var(--gold-soft)", ink: "var(--ink)", activeInk: "var(--bg)", border: "var(--ink)", dot: "var(--accent)" },
    ceremony: { bg: "var(--accent)", soft: "var(--gold-soft)", ink: "var(--accent-deep)", activeInk: "#191107", border: "rgba(198,154,43,0.42)", dot: "var(--accent)" },
    meditation: { bg: "var(--forest)", soft: "var(--forest-soft)", ink: "var(--forest)", activeInk: "var(--bg)", border: "rgba(82,98,70,0.34)", dot: "var(--forest)" },
    community: { bg: "var(--sakura)", soft: "var(--sakura-soft)", ink: "var(--sakura)", activeInk: "var(--bg)", border: "rgba(185,111,127,0.34)", dot: "var(--sakura)" },
    language: { bg: "var(--nordic)", soft: "var(--nordic-soft)", ink: "var(--nordic)", activeInk: "var(--bg)", border: "rgba(49,90,115,0.34)", dot: "var(--nordic)" },
  };
  return themes[id] || themes.all;
}

function CalendarPage({ t, setPage }) {
  const lang = t.locale;
  const [filter, setFilter] = useState("all");

  const filtered = window.EVENT_BANK.filter((e) => filter === "all" || e.category === filter);

  const filters = [
    { id: "all", label: t.calendar.filterAll },
    { id: "ceremony", label: t.calendar.filterCeremony },
    { id: "meditation", label: t.calendar.filterMeditation },
    { id: "community", label: t.calendar.filterCommunity },
    { id: "language", label: t.calendar.filterLanguage },
  ];

  return (
    <div>
      <div className="wn-container">
        <PageHeading eyebrow={t.calendar.eyebrow} title={t.calendar.title} intro={t.calendar.intro} />
      </div>
      <CalendarRegistrationPanel t={t} />

      {/* Legend / filter row */}
      <section style={{ paddingTop: "20px", paddingBottom: "40px" }}>
        <div className="wn-container" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "32px", paddingTop: "24px", paddingBottom: "24px", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)" }}>
          <div className="wn-filter-row" style={{ display: "flex", gap: "10px", flexWrap: "wrap" }}>
            {filters.map((f) => {
              const active = filter === f.id;
              const theme = eventCategoryTheme(f.id);
              return (
                <button
                  key={f.id}
                  onClick={() => setFilter(f.id)}
                  aria-pressed={active}
                  style={{
                    background: active ? theme.bg : theme.soft,
                    border: `1px solid ${active ? theme.bg : theme.border}`,
                    borderRadius: "999px",
                    cursor: "pointer",
                    padding: "11px 17px",
                    minHeight: "44px",
                    fontFamily: "var(--font-body)",
                    fontSize: "13px",
                    letterSpacing: "0.04em",
                    color: active ? theme.activeInk : theme.ink,
                    boxShadow: active ? "0 10px 24px rgba(43,33,24,0.14)" : "none",
                    display: "inline-flex",
                    alignItems: "center",
                    gap: "8px",
                    transition: "background-color 160ms ease, border-color 160ms ease, box-shadow 160ms ease",
                  }}
                >
                  <span style={{ width: "6px", height: "6px", borderRadius: "50%", background: active ? theme.activeInk : theme.dot }} />
                  {f.label}
                </button>
              );
            })}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: "24px", fontFamily: "var(--font-body)", fontSize: "12px", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--muted)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: "8px", color: "var(--accent)" }}>
              <MoonIcon kind="full" size={14} />
              <span style={{ color: "var(--muted)" }}>{t.calendar.legendFull}</span>
            </span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: "8px", color: "var(--accent)" }}>
              <MoonIcon kind="new" size={14} />
              <span style={{ color: "var(--muted)" }}>{t.calendar.legendNew}</span>
            </span>
          </div>
        </div>
      </section>

      {/* Two-column: mini calendar + event list */}
      <section style={{ paddingBottom: "80px" }}>
        <div className="wn-container wn-r2" style={{ display: "grid", gridTemplateColumns: "1fr 1.6fr", gap: "64px", alignItems: "start" }}>
          <div className="wn-unstick" style={{ position: "sticky", top: "120px" }}>
            <LunarMiniCalendar t={t} />
            <div style={{ marginTop: "32px", padding: "24px", border: "1px solid var(--line)", background: "var(--bg-deep)" }}>
              <div style={{ fontFamily: "var(--font-body)", fontSize: "11px", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--accent)", marginBottom: "10px" }}>
                ☽ {lang === "th" ? "วันพระถัดไป" : lang === "no" ? "Neste helligdag" : "Next holy day"}
              </div>
              <div style={{ fontFamily: "var(--font-display)", fontSize: "28px", color: "var(--ink)", lineHeight: 1.2 }}>
                {window.EVENT_BANK[0].title[lang]}
              </div>
              <div style={{ fontFamily: "var(--font-body)", fontSize: "13px", color: "var(--muted)", marginTop: "8px" }}>
                {window.EVENT_BANK[0].dateKey[lang]} · {window.EVENT_BANK[0].time}
              </div>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column" }}>
            {filtered.map((e, i) => (
              <EventRow key={e.id} e={e} t={t} first={i === 0} />
            ))}
            {filtered.length === 0 && (
              <div style={{ padding: "80px 0", textAlign: "center", fontFamily: "var(--font-body)", color: "var(--muted)" }}>
                —
              </div>
            )}
          </div>
        </div>
      </section>

      <WeeklySchedule t={t} />
      <TempleVideos t={t} />

      {/* Social feed teaser */}
      <SocialFeed t={t} />
    </div>
  );
}

function calendarEventEmail(e, t) {
  const lang = t.locale;
  const subject = encodeURIComponent(`${t.calendar.registerSubject}: ${e.title[lang]}`);
  const body = encodeURIComponent([
    `${t.calendar.register}: ${e.title[lang]}`,
    `${e.dateKey[lang]} · ${e.weekday[lang]} · ${e.time}`,
    "",
    lang === "th" ? "ชื่อผู้ติดต่อ:" : lang === "no" ? "Kontaktperson:" : "Contact name:",
    lang === "th" ? "เบอร์โทร:" : lang === "no" ? "Telefon:" : "Phone:",
    lang === "th" ? "จำนวนผู้เข้าร่วม:" : lang === "no" ? "Antall deltakere:" : "Number of participants:",
    "",
    e.body[lang],
  ].join("\n"));
  return `mailto:info@watthainorway.com?subject=${subject}&body=${body}`;
}

function calendarGoogleUrl(e, t) {
  const lang = t.locale;
  const text = encodeURIComponent(e.title[lang]);
  const details = encodeURIComponent(`${e.dateKey[lang]} · ${e.weekday[lang]} · ${e.time}\n\n${e.body[lang]}\n\nWat Thai Norway`);
  const location = encodeURIComponent("Wat Thai Norway, Trondheimsvegen 582, 2016 Frogner, Norway");
  return `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${text}&details=${details}&location=${location}`;
}

function CalendarRegistrationPanel({ t }) {
  const lang = t.locale;
  return (
    <section style={{ paddingTop: "6px", paddingBottom: "24px" }}>
      <div className="wn-container">
        <div className="wn-register-panel" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: "24px", alignItems: "center", padding: "24px 28px", border: "1px solid rgba(49,90,115,0.22)", background: "linear-gradient(135deg, var(--nordic) 0%, #263f51 100%)", color: "var(--bg)", boxShadow: "0 18px 46px rgba(49,90,115,0.16)" }}>
          <div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: "10px", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--accent)", marginBottom: "8px" }}>
              {lang === "th" ? "แจ้งความประสงค์เข้าร่วม" : lang === "no" ? "Enkel påmelding" : "Simple registration"}
            </div>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: "clamp(24px, 2.3vw, 34px)", fontWeight: 400, lineHeight: 1.15, margin: 0 }}>
              {t.calendar.registrationTitle}
            </h2>
            <p style={{ fontFamily: "var(--font-body)", fontSize: "14px", lineHeight: 1.6, color: "rgba(250,247,242,0.72)", marginTop: "10px", marginBottom: 0, maxWidth: "760px" }}>
              {t.calendar.registrationBody}
            </p>
          </div>
          <a href={calendarEventEmail(window.EVENT_BANK[0], t)} style={{ background: "var(--accent)", color: "var(--ink)", border: "none", padding: "15px 24px", borderRadius: "999px", fontFamily: "var(--font-body)", fontSize: "13px", letterSpacing: "0.04em", textDecoration: "none", whiteSpace: "nowrap", display: "inline-flex", alignItems: "center", justifyContent: "center", minHeight: "48px" }}>
            {t.calendar.registrationButton} →
          </a>
        </div>
      </div>
    </section>
  );
}

function EventRow({ e, t, first }) {
  const lang = t.locale;
  const [open, setOpen] = useState(false);
  const theme = eventCategoryTheme(e.category);
  return (
    <article className="wn-r-event wn-event-card" style={{ display: "grid", gridTemplateColumns: "120px 1fr auto", gap: "32px", alignItems: "start", padding: "32px 0", borderTop: first ? "1px solid var(--ink)" : "1px solid var(--line)" }}>
      <div>
        <div style={{ fontFamily: "var(--font-display)", fontSize: "56px", lineHeight: 0.95, color: "var(--ink)" }}>
          {e.dateNum}
        </div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: "11px", letterSpacing: "0.22em", textTransform: "uppercase", color: "var(--accent)", marginTop: "8px" }}>
          {e.monthKey[lang]}
        </div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: "11px", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", marginTop: "2px" }}>
          {e.weekday[lang]} · {e.time}
        </div>
      </div>

      <div>
        <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "10px" }}>
          <span style={{ fontFamily: "var(--font-body)", fontSize: "10px", letterSpacing: "0.18em", textTransform: "uppercase", color: theme.ink, padding: "6px 11px", border: "1px solid " + theme.border, borderRadius: "999px", background: theme.soft, display: "inline-flex", alignItems: "center", gap: "7px" }}>
            <span style={{ width: "5px", height: "5px", borderRadius: "50%", background: theme.dot }} />
            {e.category === "ceremony" ? t.calendar.filterCeremony
              : e.category === "meditation" ? t.calendar.filterMeditation
              : e.category === "community" ? t.calendar.filterCommunity
              : t.calendar.filterLanguage}
          </span>
          {e.moon && (
            <span style={{ display: "inline-flex", alignItems: "center", gap: "6px", color: "var(--accent)", fontFamily: "var(--font-body)", fontSize: "10px", letterSpacing: "0.22em", textTransform: "uppercase" }}>
              <MoonIcon kind={e.moon} size={14} />
              {e.moon === "full" ? t.calendar.legendFull : t.calendar.legendNew}
            </span>
          )}
          {e.live && (
            <span style={{ display: "inline-flex", alignItems: "center", gap: "6px", color: "#a02020", fontFamily: "var(--font-body)", fontSize: "10px", letterSpacing: "0.22em", textTransform: "uppercase" }}>
              <span style={{ width: "6px", height: "6px", borderRadius: "50%", background: "#a02020", animation: "wn-pulse 1.6s infinite" }} />
              Live
            </span>
          )}
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontSize: "30px", fontWeight: 400, lineHeight: 1.2, color: "var(--ink)", margin: 0 }}>
          {e.title[lang]}
        </h3>
        <p style={{ fontFamily: "var(--font-body)", fontSize: "15px", lineHeight: 1.6, color: "var(--muted)", marginTop: "10px", marginBottom: 0, maxWidth: "560px" }}>
          {e.body[lang]}
        </p>
        {open && (
          <div style={{ marginTop: "18px", padding: "18px 20px", background: "var(--bg-deep)", border: "1px solid var(--line)", fontFamily: "var(--font-body)", fontSize: "13px", lineHeight: 1.65, color: "var(--muted)", maxWidth: "620px" }}>
            <strong style={{ color: "var(--ink)", fontWeight: 500 }}>{t.calendar.moreInfo}</strong>
            <div style={{ marginTop: "6px" }}>
              {e.dateKey[lang]} · {e.weekday[lang]} · {e.time} · Wat Thai Norway, Trondheimsvegen 582
            </div>
            <div style={{ marginTop: "8px" }}>{t.calendar.registerHint}</div>
          </div>
        )}
      </div>

      <div className="wn-event-actions" style={{ display: "flex", flexDirection: "column", gap: "10px", alignItems: "flex-end" }}>
        <a href={calendarEventEmail(e, t)} style={{ background: "var(--accent)", color: "var(--ink)", border: "none", padding: "11px 18px", borderRadius: "999px", fontFamily: "var(--font-body)", fontSize: "12px", letterSpacing: "0.04em", textDecoration: "none", whiteSpace: "nowrap", minHeight: "44px", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          {t.calendar.register}
        </a>
        <a href={calendarGoogleUrl(e, t)} target="_blank" rel="noopener noreferrer" style={{ background: "var(--ink)", color: "var(--bg)", border: "none", padding: "10px 18px", borderRadius: "999px", fontFamily: "var(--font-body)", fontSize: "12px", letterSpacing: "0.04em", cursor: "pointer", whiteSpace: "nowrap", textDecoration: "none", minHeight: "44px", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
          {t.calendar.addToCalendar}
        </a>
        <button onClick={() => setOpen((v) => !v)} aria-expanded={open} style={{ background: "none", color: "var(--muted)", border: "none", fontFamily: "var(--font-body)", fontSize: "12px", letterSpacing: "0.04em", cursor: "pointer", padding: "10px 18px", minHeight: "44px" }}>
          {t.calendar.moreInfo} {open ? "↑" : "↓"}
        </button>
      </div>
    </article>
  );
}

function LunarMiniCalendar({ t }) {
  const lang = t.locale;
  const monthLabel = lang === "th" ? "กรกฎาคม ๒๕๖๙" : lang === "no" ? "Juli 2026" : "July 2026";
  const dows = lang === "th" ? ["จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"] : lang === "no" ? ["M", "T", "O", "T", "F", "L", "S"] : ["M", "T", "W", "T", "F", "S", "S"];

  // July 2026 highlights: Asalha Puja full moon and Khao Phansa the following day.
  const fullMoonDay = 29;
  const newMoonDay = 30;
  const eventDays = [29, 30];

  // Build a 5x7 grid starting Monday. July 1, 2026 is a Wednesday.
  const startCol = 2; // 0-indexed Monday=0
  const days = [];
  for (let i = 0; i < startCol; i++) days.push(null);
  for (let d = 1; d <= 31; d++) days.push(d);
  while (days.length % 7) days.push(null);

  return (
    <div style={{ padding: "28px", border: "1px solid var(--line)", background: "var(--bg)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "20px" }}>
        <button style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", fontSize: "16px", padding: 0 }}>←</button>
        <div style={{ fontFamily: "var(--font-display)", fontSize: "20px", color: "var(--ink)" }}>{monthLabel}</div>
        <button style={{ background: "none", border: "none", color: "var(--muted)", cursor: "pointer", fontSize: "16px", padding: 0 }}>→</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: "4px", fontFamily: "var(--font-body)" }}>
        {dows.map((d, i) => (
          <div key={i} style={{ fontSize: "10px", letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--muted)", textAlign: "center", paddingBottom: "8px" }}>
            {d}
          </div>
        ))}
        {days.map((d, i) => {
          if (d === null) return <div key={i} />;
          const isFull = d === fullMoonDay;
          const isNew = d === newMoonDay;
          const isEvent = eventDays.includes(d);
          return (
            <div key={i} style={{ position: "relative", aspectRatio: "1", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontSize: "13px", color: isEvent ? "var(--accent)" : "var(--ink)", fontWeight: isEvent ? 500 : 400 }}>
                {d}
              </span>
              {isFull && (
                <span style={{ position: "absolute", bottom: "2px", color: "var(--accent)" }}>
                  <MoonIcon kind="full" size={6} />
                </span>
              )}
              {isNew && (
                <span style={{ position: "absolute", bottom: "2px", color: "var(--accent)" }}>
                  <MoonIcon kind="new" size={6} />
                </span>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function SocialFeed({ t }) {
  const lang = t.locale;
  const posts = [
    {
      type: "facebook",
      author: "Wat Thai Norge",
      time: lang === "th" ? "๒ ชั่วโมงที่แล้ว" : lang === "no" ? "2 timer siden" : "2 hours ago",
      body: lang === "th"
        ? "ภาพบรรยากาศตักบาตรเช้าวันนี้ ขออนุโมทนาบุญกับทุกท่านที่ร่วมทำบุญ 🙏"
        : lang === "no"
        ? "Bilder fra morgenens almissegivning. Takk til alle som deltok. 🙏"
        : "Photos from this morning's almsgiving. Thank you to everyone who joined. 🙏",
      img: "Almsgiving — line of monks, lay people offering food.",
    },
    {
      type: "instagram",
      author: "@watthainorge",
      time: lang === "th" ? "เมื่อวาน" : lang === "no" ? "I går" : "Yesterday",
      body: lang === "th"
        ? "ดอกบัวบานในสระน้ำของวัด สัญลักษณ์แห่งความบริสุทธิ์"
        : lang === "no"
        ? "Lotusen blomstrer i tempelets dam – et symbol på renhet."
        : "Lotus blooms in the temple pond — a symbol of purity.",
      img: "Lotus flowers floating on a still pond, morning light.",
    },
    {
      type: "facebook",
      author: "Wat Thai Norge",
      time: lang === "th" ? "๓ วันที่แล้ว" : lang === "no" ? "For 3 dager siden" : "3 days ago",
      body: lang === "th"
        ? "เชิญร่วมงานวิสาขบูชา ๒๑ พฤษภาคมนี้ พิธีเริ่ม ๐๗:๐๐ น."
        : lang === "no"
        ? "Velkommen til Vesak-feiringen 21. mai. Seremonien starter kl. 07:00."
        : "Join us for Vesak Day on 21 May. Ceremony begins at 07:00.",
      img: "Banner artwork for Vesak Day with candles.",
    },
  ];
  return (
    <section style={{ paddingTop: "60px", paddingBottom: "20px", backgroundColor: "var(--bg-deep)" }}>
      <div className="wn-container" style={{ paddingTop: "80px", paddingBottom: "80px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: "48px", flexWrap: "wrap", gap: "24px" }}>
          <div>
            <Eyebrow>{lang === "th" ? "ติดตามข่าวจากวัด" : lang === "no" ? "Følg med" : "From our community"}</Eyebrow>
            <SectionTitle size="md">
              {lang === "th" ? "อัปเดตจาก Facebook ของวัด" : lang === "no" ? "Oppdateringer fra tempelet" : "Latest from our social channels"}
            </SectionTitle>
          </div>
          <div style={{ display: "flex", gap: "12px" }}>
            {[{ label: "Facebook", href: "https://www.facebook.com/watthainorway" }].map((s) => (
              <a key={s.label} href={s.href} target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: "8px", padding: "10px 18px", border: "1px solid var(--ink)", borderRadius: "999px", textDecoration: "none", color: "var(--ink)", fontFamily: "var(--font-body)", fontSize: "13px" }}>
                <span style={{ width: "6px", height: "6px", borderRadius: "50%", background: "var(--accent)" }} />
                {s.label}
              </a>
            ))}
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "center" }}>
          <div style={{ width: "100%", maxWidth: "500px", border: "1px solid var(--line)", background: "var(--bg)", overflow: "hidden" }}>
            <iframe
              title="Facebook — Wat Thai Norway"
              src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Fwatthainorway&tabs=timeline&width=500&height=680&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true"
              width="500"
              height="680"
              style={{ display: "block", border: "none", width: "100%", maxWidth: "500px" }}
              scrolling="no"
              frameBorder="0"
              allowFullScreen={true}
              allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"
            ></iframe>
          </div>
        </div>
        <div style={{ textAlign: "center", marginTop: "20px", fontFamily: "var(--font-body)", fontSize: "12px", color: "var(--muted)", letterSpacing: "0.04em" }}>
          {lang === "th"
            ? "ฟีดนี้อัปเดตอัตโนมัติทุกครั้งที่วัดโพสต์บน Facebook"
            : lang === "no"
            ? "Denne strømmen oppdateres automatisk hver gang tempelet publiserer på Facebook."
            : "This feed updates automatically whenever the temple posts on Facebook."}
        </div>
      </div>
    </section>
  );
}

window.CalendarPage = CalendarPage;
