// ============================================================
// OBPC — Extra sections (Agenda, Contato)
// ============================================================

const { useState: useStateX, useEffect: useEffectX } = React;

// ---------- AGENDA ----------
const GCAL_API_KEY_HOME   = window.OBPC_CONFIG?.gcal?.apiKey     || "";
const GCAL_CALENDAR_HOME  = window.OBPC_CONFIG?.gcal?.calendarId || "obpcjundiai@gmail.com";
const GCAL_EMBED_HOME     = "https://calendar.google.com/calendar/embed?src=obpcjundiai%40gmail.com&ctz=America%2FSao_Paulo&showTitle=0&showPrint=0&showCalendars=0&showNav=1&mode=AGENDA";
const GCAL_SUBSCRIBE_HOME = "https://calendar.google.com/calendar/u/0?cid=b2JwY2p1bmRpYWlAZ21haWwuY29t";

const DIAS_LABEL_HOME  = ["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"];

function formatHoraHome(dateTimeStr) {
  const d = new Date(dateTimeStr);
  return `${String(d.getHours()).padStart(2,"0")}h${String(d.getMinutes()).padStart(2,"0")}`;
}

function parseLocalDateHome(dateStr) {
  if (!dateStr) return new Date();
  if (dateStr.includes('T')) return new Date(dateStr);
  const [y, m, d] = dateStr.split('-').map(Number);
  return new Date(y, m - 1, d);
}

function useAgendaHome() {
  const [events,  setEvents]  = useStateX([]);
  const [loading, setLoading] = useStateX(!!GCAL_API_KEY_HOME);
  const [failed,  setFailed]  = useStateX(false);

  useEffectX(() => {
    if (!GCAL_API_KEY_HOME) return;
    const now    = new Date().toISOString();
    const futuro = new Date(); futuro.setDate(futuro.getDate() + 30);
    const url = "https://www.googleapis.com/calendar/v3/calendars/"
      + encodeURIComponent(GCAL_CALENDAR_HOME) + "/events"
      + "?key=" + GCAL_API_KEY_HOME
      + "&timeMin=" + now
      + "&timeMax=" + futuro.toISOString()
      + "&singleEvents=true&orderBy=startTime&maxResults=8";
    fetch(url)
      .then(r => r.ok ? r.json() : Promise.reject())
      .then(d => { setEvents((d.items || []).filter(e => e.status !== "cancelled")); setLoading(false); })
      .catch(() => { setFailed(true); setLoading(false); });
  }, []);

  return { events, loading, failed };
}

const SectionAgenda = ({ palette }) => {
  const inicio = window.OBPC_SITE.useSite().inicio; // título da seção, editado pelo sistema
  const { events, loading, failed } = useAgendaHome();
  const hasKey = !!GCAL_API_KEY_HOME;
  const semAgenda = !hasKey || failed;
  // Em telas pequenas o iframe do Google Calendar nem é carregado (muito pesado).
  const [mobile, setMobile] = useStateX(() => window.matchMedia("(max-width: 860px)").matches);
  useEffectX(() => {
    const mq = window.matchMedia("(max-width: 860px)");
    const h = (e) => setMobile(e.matches);
    mq.addEventListener("change", h);
    return () => mq.removeEventListener("change", h);
  }, []);

  return (
    <section id="agenda" className="obpc-section obpc-section--agenda" style={{ background: palette.surface, color: palette.fg }}>
      <div className="obpc-sec-head">
        <span className="obpc-sec-num" style={{ color: palette.accent }}>03 /</span>
        <span className="obpc-sec-kicker" style={{ color: palette.muted }}>Agenda · Vila Arens · Jundiaí</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 60, alignItems: "start" }} className="obpc-grid-collapse">
        {/* Lista de eventos */}
        <div>
          <Reveal>
            <h2 className="obpc-sec-title" style={{ marginBottom: 32 }}>
              {window.OBPC_SITE.marcas(inicio.agenda_titulo, { acento: palette.accent })}
            </h2>
          </Reveal>
          <div>
            {loading && [...Array(5)].map((_, i) => (
              <div key={i} className="obpc-agenda-event-row" style={{ borderTop: `1px solid ${palette.fg}12` }}>
                <div style={{ height: 12, background: `${palette.fg}10`, borderRadius: 3 }} />
                <div style={{ height: 20, background: `${palette.fg}10`, borderRadius: 3 }} />
                <div style={{ height: 16, background: `${palette.fg}10`, borderRadius: 3 }} />
              </div>
            ))}
            {!loading && semAgenda && (
              <div style={{ padding: "16px 0", fontFamily: "Fraunces, serif", fontSize: 16, color: palette.muted, lineHeight: 1.6 }}>
                A lista de eventos está indisponível no momento.{" "}
                <a href={GCAL_SUBSCRIBE_HOME} target="_blank" rel="noopener noreferrer" style={{ color: palette.accent }}>Abrir o calendário no Google</a>
                {" "}ou veja a <a href="/agenda" style={{ color: palette.accent }}>agenda completa</a>.
              </div>
            )}
            {!loading && !semAgenda && events.map((ev, i) => {
              const start = parseLocalDateHome(ev.start.dateTime || ev.start.date);
              return (
                <Reveal key={ev.id || i} delay={i * 40}>
                  <div className="obpc-agenda-event-row" style={{ borderTop: `1px solid ${palette.fg}12` }}>
                    <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.15em", textTransform: "uppercase", color: palette.muted }}>
                      {DIAS_LABEL_HOME[start.getDay()]} {String(start.getDate()).padStart(2,"0")}
                    </div>
                    <div style={{ fontFamily: "Fraunces, serif", fontSize: 22, fontWeight: 300, color: palette.accent }}>
                      {ev.start.dateTime ? formatHoraHome(ev.start.dateTime) : "—"}
                    </div>
                    <div style={{ fontFamily: "Fraunces, serif", fontSize: 18, fontWeight: 400 }}>{ev.summary}</div>
                  </div>
                </Reveal>
              );
            })}
            <div style={{ borderTop: `1px solid ${palette.fg}12`, marginBottom: 32 }}/>
          </div>
          <Reveal delay={200}>
            <a href="/agenda" className="obpc-btn obpc-btn--ghost" style={{ borderColor: palette.accent, color: palette.accent }}>
              Ver agenda completa
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
          </Reveal>
        </div>

        {/* Google Calendar embed */}
        <Reveal delay={120}>
          {!mobile && <div className="obpc-gcal-embed" style={{ borderRadius: 8, overflow: "hidden", border: `1px solid ${palette.fg}15` }}>
            <EmbedGoogle palette={palette} src={GCAL_EMBED_HOME} titulo="Agenda OBPC Jundiaí" alvo="a agenda" altura={480} compacto />
          </div>}
          <div style={{ marginTop: 12, display: "flex", justifyContent: "flex-end" }}>
            <a href={GCAL_SUBSCRIBE_HOME} target="_blank" rel="noopener"
              style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: palette.muted, textDecoration: "none", display: "flex", alignItems: "center", gap: 6 }}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
              Assinar agenda OBPC
            </a>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

// ---------- CONTATO ----------
const SectionContato = ({ palette }) => {
  const S = window.OBPC_SITE;
  const site = S.useSite();
  const c = site.inicio.contato; // chamada final editada pelo sistema (página inicial)
  const { endereco: e, redes: r, pastor: pt } = site.dados_igreja; // endereço, pastor e redes: Dados da igreja
  const botao = window.OBPC_SITE.destino(c.botao.destino);
  return (
    <section id="contato" className="obpc-section obpc-section--contato" style={{ background: palette.accent, color: palette.bg }}>
      <Reveal>
        <div className="obpc-contato-kicker">
          <span className="obpc-tag-dot" style={{ background: palette.bg }}/>
          <span>{c.kicker}</span>
        </div>
      </Reveal>

      <Reveal delay={80}>
        <h2 className="obpc-contato-title">
          {window.OBPC_SITE.marcas(c.titulo, {})}
        </h2>
      </Reveal>

      <Reveal delay={120}>
        <div style={{ margin: "0 0 48px" }}>
          <a href={botao.href} {...(botao.externo ? { target: "_blank", rel: "noopener noreferrer" } : {})}
            style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "16px 32px", borderRadius: 999, background: palette.bg, color: palette.accent, fontFamily: "JetBrains Mono, monospace", fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase", textDecoration: "none", fontWeight: 500, transition: "opacity 200ms" }}
            onMouseEnter={e => e.currentTarget.style.opacity = "0.85"}
            onMouseLeave={e => e.currentTarget.style.opacity = "1"}>
            {c.botao.rotulo}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </a>
        </div>
      </Reveal>

      <div className="obpc-contato-grid">
        <Reveal delay={140}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Endereço</span>
            <p>{e.rua}<br/>{e.bairro} · {e.cidade} — {e.uf}<br/>CEP {e.cep}</p>
          </div>
        </Reveal>
        <Reveal delay={200}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Pastor</span>
            <p>{pt.nome}<br/>
              {pt.instagram && <a href={S.insta(pt.instagram)} target="_blank" rel="noopener"
                style={{ color: "inherit", opacity: 0.75, fontSize: 13 }}>@{pt.instagram}</a>}
            </p>
          </div>
        </Reveal>
        <Reveal delay={260}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Redes sociais</span>
            <p>
              <a href={S.insta(r.instagram)} target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>Instagram @{r.instagram}</a>
              <a href={S.destino(r.facebook).href} target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>Facebook</a>
              <a href={S.destino(r.youtube).href} target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>YouTube {r.youtube_nome}</a>
            </p>
          </div>
        </Reveal>
        <Reveal delay={320}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Como chegar</span>
            <p>
              <a href={S.destino(e.mapa).href} target="_blank" rel="noopener"
                 style={{ color: "inherit", textDecoration: "underline", opacity: 0.85 }}>
                Google Maps →
              </a><br/>
              <a href={S.destino(e.mapa).href} target="_blank" rel="noopener"
                 style={{ color: "inherit", fontSize: 13, opacity: 0.7 }}>Ver avaliações no Google</a>
            </p>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

Object.assign(window, { SectionAgenda, SectionContato });
