/* JMR — Calendario completo (web).
   Interactive month calendar + filterable event list + event detail/registro,
   reading the SAME shared data the app uses (window.JMR_EVENTS). Mirrors the
   app's Eventos experience (mini-calendar · filter chips · event cards ·
   detail page with "Registrarme") translated to a wide web layout, so moving
   between the app and the site feels like one product. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const t = (k) => (window.JMRWebI18N ? window.JMRWebI18N.t(k) : k);

  const MONTHS = window.JMR_EVENT_MONTHS || [];
  const WD = window.JMR_EVENT_WD || ["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"];
  const EVENTS = window.JMR_EVENTS || [];

  // Event types (match church-app-jmr/EventosScreen.jsx + admin EV_CATS). The full
  // filter list (types + the ministries actually in use) is built inside CalendarApp.
  const FILTERS = [
    { id: "todos", label: "Todos" },
    { id: "servicio-dominical", label: "Servicio Dominical" },
    { id: "estudio-biblico", label: "Estudio Bíblico" },
    { id: "campana", label: "Campaña" },
    { id: "servicio-familiar", label: "Servicio Familiar" },
    { id: "ayuno", label: "Ayuno congregacional" },
    { id: "retiro", label: "Retiro" },
    { id: "convivio", label: "Convivio" },
  ];

  const ICON_BY_CAT = { "servicio-dominical": "church", "estudio-biblico": "menu_book", "campana": "campaign", "servicio-familiar": "diversity_3", "ayuno": "no_meals", "retiro": "forest", "convivio": "celebration", aviso: "info" };
  const ICON_BY_CATEGORY = {
    "Mujeres": "woman", "Hombres": "man", "Niños": "child_care", "Familia": "diversity_3",
    "Educación": "school", "Estudio bíblico": "menu_book", "Mes especial": "auto_stories",
    "Servicio especial": "church", "Santa Cena": "local_cafe", "Ayuno": "no_meals",
    "Campaña": "campaign", "Evangelismo": "campaign", "Aniversario": "celebration", "Navidad": "celebration",
    "Nuevos miembros": "handshake", "Ujieres": "co_present", "Jóvenes": "local_fire_department",
    "Jóvenes Adultos": "local_fire_department", "Jóvenes Juveniles": "local_fire_department", "Aviso": "info",
  };
  const iconFor = (e) => ICON_BY_CATEGORY[e.category] || ICON_BY_CAT[e.cat] || "event";

  function monthWord(m) { return ((MONTHS[m] && MONTHS[m].name) || "").split(" ")[0]; }
  function daysOf(e) { return e.days || (e.day != null ? [e.day] : []); }
  function dateLabel(e, withYear) {
    const mw = monthWord(e.m).toLowerCase();
    let s;
    if (e.day == null) s = e.time;
    else if (e.days && e.days.length > 1) s = e.days[0] + "–" + e.days[e.days.length - 1] + " de " + mw;
    else s = (e.weekday ? e.weekday + " " : "") + e.day + " de " + mw;
    return withYear && e.day != null ? s + " · " + MONTHS[e.m].y : s;
  }

  const Icon = ({ name, size, style }) => (
    <span className="material-symbols-rounded" style={{ fontSize: size || 20, ...(style || {}) }}>{name}</span>
  );

  /* ---------------- Big month calendar ---------------- */
  function MonthCalendar({ monthIx, eventDays, selDay, onSelDay, onPrev, onNext, canPrev, canNext, today }) {
    const M = MONTHS[monthIx];
    const dow = ["D", "L", "M", "M", "J", "V", "S"];
    const first = new Date(M.y, M.jm, 1).getDay();
    const dim = new Date(M.y, M.jm + 1, 0).getDate();
    const cells = [];
    for (let d = 1; d <= dim; d++) cells.push(d);

    return (
      <div className="cal-card">
        <div className="cal-head">
          <div className="cal-month">{M.name}</div>
          <div className="cal-nav">
            <button className="cal-arrow" disabled={!canPrev} onClick={onPrev} aria-label={t("cal.prevMonth")}><Icon name="chevron_left" size={20} /></button>
            <button className="cal-arrow" disabled={!canNext} onClick={onNext} aria-label={t("cal.nextMonth")}><Icon name="chevron_right" size={20} /></button>
          </div>
        </div>
        <div className="cal-dow">{dow.map((x, i) => <span key={i}>{x}</span>)}</div>
        <div className="cal-grid">
          {cells.map((c, i) => {
            const has = eventDays.includes(c);
            const sel = selDay === c;
            const isToday = today && today.y === M.y && today.jm === M.jm && today.d === c;
            return (
              <button key={i}
                className={"cal-cell" + (has ? " has" : "") + (sel ? " sel" : "") + (isToday ? " today" : "")}
                style={i === 0 ? { gridColumnStart: first + 1 } : undefined}
                disabled={!has} onClick={() => onSelDay(sel ? null : c)}
                aria-label={c + (has ? " — " + t("cal.withEvents") : "")}>
                {c}
                {has && !sel && <span className="cal-dot" />}
              </button>
            );
          })}
        </div>
        <div className="cal-legend">
          <span><span className="cal-dot static" /> {t("cal.withEvents")}</span>
          <span><span className="cal-today-key" /> {t("cal.today")}</span>
        </div>
      </div>
    );
  }

  /* ---------------- Event row ---------------- */
  function EventRow({ e, onOpen }) {
    const M = MONTHS[e.m];
    return (
      <button className="evrow" onClick={() => onOpen(e.id)}>
        <span className="evrow-date">
          <small>{M.abbr}</small>
          <b>{e.dd}</b>
        </span>
        <span className="evrow-body">
          <span className="evrow-cat"><Icon name={iconFor(e)} size={15} />{e.category}</span>
          <span className="evrow-title">{e.title}</span>
          <span className="evrow-meta">
            <span><Icon name="schedule" size={16} />{e.time}</span>
            <span><Icon name="location_on" size={16} />{e.location}</span>
          </span>
        </span>
        <span className="evrow-go"><Icon name="chevron_right" size={22} /></span>
      </button>
    );
  }

  /* ---------------- Detail modal ---------------- */
  function DetailModal({ id, onClose, onRegister }) {
    const e = window.JMR_EVENT_BY_ID[id];
    useEffect(() => {
      const onKey = (ev) => { if (ev.key === "Escape") onClose(); };
      window.addEventListener("keydown", onKey);
      return () => window.removeEventListener("keydown", onKey);
    }, []);
    if (!e) return null;
    const M = MONTHS[e.m];
    const details = [
      { icon: "calendar_month", label: t("ev.date"), value: dateLabel(e, true) },
      { icon: "schedule", label: t("ev.time"), value: e.time },
      { icon: "location_on", label: t("ev.place"), value: e.location },
      { icon: "groups", label: t("ev.organizes"), value: e.ministerio },
    ];
    return (
      <div className="modal-scrim" onClick={onClose}>
        <div className="modal" onClick={(ev) => ev.stopPropagation()} role="dialog" aria-modal="true" aria-label={e.title}>
          <div className={"modal-hero" + (e.image ? " has-photo" : "")} style={e.image ? { backgroundImage: "linear-gradient(to top, rgba(27,41,107,0.92) 6%, rgba(27,41,107,0.35) 60%, rgba(27,41,107,0.5)), url('" + e.image + "')", backgroundSize: "cover", backgroundPosition: "center" } : undefined}>
            {!e.image && <Icon name={iconFor(e)} size={150} style={{ position: "absolute", right: -18, bottom: -26, color: "rgba(228,186,66,0.14)" }} />}
            <button className="modal-close" onClick={onClose} aria-label={t("cal.close")}><Icon name="close" size={22} /></button>
            <span className="modal-pill"><Icon name="event" size={15} />{e.category}</span>
            <div className="modal-hero-foot">
              <h2>{e.title}</h2>
              <div className="modal-hero-meta">
                <span><Icon name="calendar_month" size={16} />{dateLabel(e)}</span>
                <span className="dot" />
                <span><Icon name="schedule" size={16} />{e.time}</span>
              </div>
            </div>
          </div>
          <div className="modal-body">
            <div className="modal-sec-label">{t("ev.about")}</div>
            <p className="modal-desc">{e.desc}</p>
            <div className="modal-details">
              {details.map((d) => (
                <div className="md-row" key={d.label}>
                  <span className="md-ic"><Icon name={d.icon} size={21} /></span>
                  <span className="md-text"><span className="md-label">{d.label}</span><span className="md-value">{d.value}</span></span>
                </div>
              ))}
            </div>
            {e.register && (
              <div className="modal-register">
                <span className="mr-ic"><Icon name="confirmation_number" size={26} /></span>
                <div className="mr-txt">
                  <b>{t("cal.registerTitle")}</b>
                  <span>{t("cal.registerSub")}</span>
                </div>
                <button className="btn btn-gold" onClick={() => onRegister(e.id)}><Icon name="confirmation_number" size={20} />{t("cal.register")}</button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  /* ---------------- Register modal ---------------- */
  function RegisterModal({ id, onClose }) {
    const e = window.JMR_EVENT_BY_ID[id];
    const acct = (window.JMRAccount && window.JMRAccount.get) ? window.JMRAccount.get() : null;
    const [form, setForm] = useState({ nombre: (acct && acct.name) || "", tel: "", correo: (acct && acct.email) || "", personas: "1", comentarios: "" });
    const [sent, setSent] = useState(false);
    if (!e) return null;
    const set = (k) => (ev) => setForm((f) => ({ ...f, [k]: ev.target.value }));
    const valid = form.nombre.trim() && form.correo.trim() && form.tel.trim();
    const submit = () => {
      if (!valid) return;
      // Send to the church backend: records it in the admin panel (event_registrations
      // table) and emails a confirmation to the person + a notice to the church.
      try {
        fetch("/api/contact", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            type: "registro",
            lang: (window.JMRWebI18N && window.JMRWebI18N.get) ? window.JMRWebI18N.get() : "es",
            eventId: e.id,
            eventTitle: e.title,
            name: form.nombre.trim(),
            email: form.correo.trim().toLowerCase(),
            phone: form.tel.trim(),
            people: parseInt(form.personas, 10) || 1,
            message: form.comentarios.trim(),
          }),
        }).catch(function () {});
      } catch (err) {}
      setSent(true);
    };
    return (
      <div className="modal-scrim" onClick={onClose}>
        <div className="modal modal-form" onClick={(ev) => ev.stopPropagation()} role="dialog" aria-modal="true">
          <div className="form-head">
            <button className="form-back" onClick={onClose} aria-label={t("cal.close")}><Icon name={sent ? "close" : "arrow_back"} size={20} /></button>
            <b>{sent ? t("cal.regConfirmed") : t("cal.register")}</b>
          </div>
          {sent ? (
            <div className="form-done">
              <span className="form-check"><Icon name="check_circle" size={42} /></span>
              <h3>{t("cal.ready")}, {form.nombre.split(" ")[0] || t("cal.friend")}!</h3>
              <p>{t("cal.doneMsgA")} <b>{e.title}</b> ({dateLabel(e)}) {t("cal.doneMsgB")}</p>
              <button className="btn btn-navy" onClick={onClose}>{t("cal.back")}</button>
            </div>
          ) : (
            <div className="form-body">
              <div className="form-summary">
                <span className="fs-ic"><Icon name="event" size={22} /></span>
                <div><b>{e.title}</b><span>{dateLabel(e)} · {e.time}</span></div>
              </div>
              <label className="fld"><span>{t("cal.fldName")} <i>*</i></span><input value={form.nombre} onChange={set("nombre")} placeholder={t("cal.phName")} /></label>
              <label className="fld"><span>{t("cal.fldPhone")} <i>*</i></span><input value={form.tel} onChange={set("tel")} placeholder={t("cal.phPhone")} inputMode="tel" /></label>
              <label className="fld"><span>{t("cal.fldEmail")} <i>*</i></span><input value={form.correo} onChange={set("correo")} placeholder={t("cal.phEmail")} inputMode="email" /></label>
              <label className="fld"><span>{t("cal.fldPeople")}</span>
                <select value={form.personas} onChange={set("personas")}>{["1","2","3","4","5",t("cal.peopleMore")].map((n) => <option key={n} value={n}>{n}</option>)}</select>
              </label>
              <label className="fld"><span>{t("cal.fldComments")} <i className="opt">{t("cal.optional")}</i></span><textarea value={form.comentarios} onChange={set("comentarios")} placeholder={t("cal.phComments")} /></label>
              <button className="btn btn-gold form-submit" disabled={!valid} onClick={submit}><Icon name="confirmation_number" size={20} />{t("cal.confirmReg")}</button>
              <p className="form-fine">{t("cal.formFine")}</p>
            </div>
          )}
        </div>
      </div>
    );
  }

  /* ---------------- Root ---------------- */
  function CalendarApp() {
    const [, forceLang] = useState(0);
    useEffect(() => {
      const on = () => forceLang((x) => x + 1);
      document.addEventListener("jmr-lang", on);
      return () => document.removeEventListener("jmr-lang", on);
    }, []);
    const now = new Date();
    const todayIx = MONTHS.findIndex((m) => m.y === now.getFullYear() && m.jm === now.getMonth());
    const startIx = todayIx >= 0 ? todayIx : 0;
    const today = { y: now.getFullYear(), jm: now.getMonth(), d: now.getDate() };

    const [monthIx, setMonthIx] = useState(startIx);
    const [filter, setFilter] = useState("todos");
    const [selDay, setSelDay] = useState(null);
    const [detailId, setDetailId] = useState(null);
    const [registerId, setRegisterId] = useState(null);

    const M = MONTHS[monthIx];
    const monthEvents = useMemo(() => EVENTS.filter((e) => e.m === monthIx), [monthIx]);

    const eventDays = useMemo(() => {
      const set = new Set();
      monthEvents.forEach((e) => daysOf(e).forEach((d) => set.add(d)));
      return [...set];
    }, [monthEvents]);

    // Todos + event types + every ministry that has events (filter by kind OR by
    // the ministry that runs it). Ministry chip ids are prefixed "min:".
    const minLabel = (s) => (s || "").replace(/^ministerio(\s+de)?\s+/i, "").trim();
    const allFilters = useMemo(() => {
      const mins = [];
      EVENTS.forEach((e) => { const m = minLabel(e.ministerio); if (m && mins.indexOf(m) < 0) mins.push(m); });
      return FILTERS.concat(mins.map((m) => ({ id: "min:" + m, label: m })));
    }, []);

    const list = useMemo(() => {
      let l = monthEvents;
      if (filter !== "todos") {
        if (filter.indexOf("min:") === 0) { const mn = filter.slice(4); l = l.filter((e) => minLabel(e.ministerio) === mn); }
        else l = l.filter((e) => e.cat === filter);
      }
      if (selDay) l = l.filter((e) => daysOf(e).includes(selDay));
      return l.slice().sort((a, b) => (a.day == null ? -1 : b.day == null ? 1 : a.day - b.day));
    }, [monthEvents, filter, selDay]);

    const goMonth = (delta) => {
      const next = monthIx + delta;
      if (next < 0 || next > MONTHS.length - 1) return;
      setMonthIx(next); setSelDay(null);
    };
    const fmtSel = (d) => WD[new Date(M.y, M.jm, d).getDay()] + " " + d + " de " + monthWord(monthIx).toLowerCase();

    const onModalOpen = !!(detailId || registerId);
    useEffect(() => {
      document.body.style.overflow = onModalOpen ? "hidden" : "";
      return () => { document.body.style.overflow = ""; };
    }, [onModalOpen]);

    return (
      <div className="cal-layout">
        <aside className="cal-aside">
          <MonthCalendar
            monthIx={monthIx} eventDays={eventDays} selDay={selDay}
            onSelDay={setSelDay} onPrev={() => goMonth(-1)} onNext={() => goMonth(1)}
            canPrev={monthIx > 0} canNext={monthIx < MONTHS.length - 1} today={today} />
          <div className="filters">
            <div className="filters-label">{t("cal.filterBy")}</div>
            <div className="chips">
              {allFilters.map((f) => (
                <button key={f.id} className={"chip" + (filter === f.id ? " on" : "")} onClick={() => { setFilter(f.id); setSelDay(null); }}>{f.id === "todos" ? t("cal.f.todos") : f.label}</button>
              ))}
            </div>
          </div>
        </aside>

        <section className="cal-main">
          <div className="cal-main-head">
            <div>
              <h2>{selDay ? fmtSel(selDay) : M.name}</h2>
              <p>{list.length} {list.length === 1 ? t("cal.event") : t("cal.events")}{filter !== "todos" ? " · " + ((allFilters.find((f) => f.id === filter) || {}).label || "") : ""}</p>
            </div>
            {selDay && <button className="clear-day" onClick={() => setSelDay(null)}><Icon name="event" size={17} />{t("cal.viewMonth")}<Icon name="close" size={18} /></button>}
          </div>

          {list.length === 0 ? (
            <div className="empty">
              <Icon name="event_busy" size={40} />
              <b>{t("cal.emptyTitle")}</b>
              <span>{t("cal.emptySub")}</span>
            </div>
          ) : (
            <div className="evlist">
              {list.map((e) => <EventRow key={e.id} e={e} onOpen={setDetailId} />)}
            </div>
          )}
        </section>

        {detailId && <DetailModal id={detailId} onClose={() => setDetailId(null)} onRegister={(rid) => { setDetailId(null); setRegisterId(rid); }} />}
        {registerId && <RegisterModal id={registerId} onClose={() => setRegisterId(null)} />}
      </div>
    );
  }

  window.JMRCalendarApp = CalendarApp;
})();
