// ============================================================
// OBPC — Extra sections (Notícias, Agenda, Contato)
// ============================================================

const { useState: useStateX, useEffect: useEffectX } = React;

// ---------- NOTÍCIAS ----------
const NOTICIAS = [
  { tag: "Conselho",   date: "01 ABR 2026", title: "Reunião Supremo Conselho 2026",
    excerpt: "Líderes e representantes se reuniram em São Paulo para alinhamento, comunhão e planejamento das próximas ações da Obra.",
    tone: "fire",
    img: "https://static.wixstatic.com/media/fab2ef_ae66b882513f4fd0ad5a9f78e101fcc9~mv2.jpg",
    href: "https://www.conselhonacional.org.br/post/reuni%C3%A3o-supremo-conselho-2026" },
  { tag: "Celebração", date: "12 MAR 2026", title: "Comemoração dos 70 anos da OBPC no Mato Grosso do Sul",
    excerpt: "A comunidade do MS se reuniu com gratidão pelas sete décadas de caminhada e pelas vidas transformadas pelo Evangelho.",
    tone: "warm",
    img: "https://static.wixstatic.com/media/fab2ef_ca36d5a626f54419a5a2e46d688a3926~mv2.png",
    href: "https://www.conselhonacional.org.br/post/comemora%C3%A7%C3%A3o-dos-70-anos-da-obpc-no-mato-grosso-do-sul" },
  { tag: "Celebração", date: "08 MAR 2026", title: "70 anos da OBPC: 7 mil pessoas no Grande Templo da Pompeia",
    excerpt: "Marco histórico reuniu cerca de 7 mil pessoas e milhares online. A Câmara de SP entregou a Salva de Prata à denominação.",
    tone: "deep",
    img: "https://static.wixstatic.com/media/fab2ef_ddc1b2de1f504c46a237f96484a346e4~mv2.jpg",
    href: "https://www.conselhonacional.org.br/post/comemora%C3%A7%C3%A3o-dos-70-anos-da-obpc-em-s%C3%A3o-paulo" },
  { tag: "Lançamento", date: "04 FEV 2026", title: "Lançamento: Desperta Brasil",
    excerpt: "Publicação documenta o grande avivamento que transformou o Brasil e inspira as gerações atuais a continuar a obra missionária.",
    tone: "fire",
    img: "https://static.wixstatic.com/media/fab2ef_0c5c3f4743b348b39309b62bc4aed6b6~mv2.png",
    href: "https://www.conselhonacional.org.br/post/lan%C3%A7amento-desperta-brasil" },
];

const SectionNoticias = ({ palette }) => {
  const [hover, setHover] = useStateX(null);
  return (
    <section id="noticias" className="obpc-section obpc-section--news" style={{ background: palette.bg, color: palette.fg }}>
      <div className="obpc-sec-head">
        <span className="obpc-sec-num" style={{ color: palette.accent }}>05 /</span>
        <span className="obpc-sec-kicker" style={{ color: palette.muted }}>Notícias · 2026</span>
      </div>

      <div className="obpc-news-head">
        <Reveal>
          <h2 className="obpc-sec-title" style={{ marginBottom: 0 }}>
            O que acontece <span style={{ color: palette.accent, fontStyle: "italic" }}>hoje</span><br/>
            no Conselho Nacional.
          </h2>
        </Reveal>
        <Reveal delay={120}>
          <a className="obpc-btn obpc-btn--ghost" style={{ borderColor: palette.fg, color: palette.fg, alignSelf: "end" }} href="/noticias">
            Todas as notícias
            <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>

      <div className="obpc-news-grid">
        {NOTICIAS.map((n, i) => (
          <Reveal key={i} delay={i * 80}>
            <a href={n.href || "#"} className="obpc-news-link" target={n.href ? "_blank" : "_self"} rel="noopener noreferrer" style={{ textDecoration: "none", display: "block" }}
              onFocus={() => setHover(i)} onBlur={() => setHover(null)}>
            <article
              className="obpc-news-card"
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
              style={{ borderColor: `${palette.fg}18` }}
            >
              <div className="obpc-news-img">
                {n.img
                  ? <img src={n.img} alt={`Foto da notícia: ${n.title}`} width="800" height="500" loading="lazy" decoding="async" style={{ width: "100%", aspectRatio: "16/10", objectFit: "cover", objectPosition: "center top", display: "block" }}/>
                  : <Placeholder label={`Foto — ${n.title}`} aspect="16/10" tone={n.tone}/>
                }
                <span className="obpc-news-tag" style={{ background: palette.accent, color: palette.bg }}>
                  {n.tag}
                </span>
              </div>
              <div className="obpc-news-body">
                <div className="obpc-news-date" style={{ color: palette.muted }}>{n.date}</div>
                <h3 className="obpc-news-title" style={{ color: hover === i ? palette.accent : palette.fg }}>
                  {n.title}
                </h3>
                <p className="obpc-news-excerpt" style={{ color: palette.muted }}>{n.excerpt}</p>
                <div className="obpc-news-more" style={{ color: hover === i ? palette.accent : palette.muted }}>
                  Leia mais <span style={{ transform: hover === i ? "translateX(4px)" : "none", display: "inline-block", transition: "transform 300ms" }}>→</span>
                </div>
              </div>
            </article>
            </a>
          </Reveal>
        ))}
      </div>
    </section>
  );
};

// ---------- 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 { 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 }}>06 /</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 }}>
              Toda semana,<br/>
              <span style={{ color: palette.accent, fontStyle: "italic" }}>há um lugar</span> para você.
            </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`, boxShadow: `0 24px 60px rgba(0,0,0,0.25)` }}>
            <iframe
              src={GCAL_EMBED_HOME}
              style={{ width: "100%", height: 480, border: "none", display: "block", background: palette.surface }}
              title="Agenda OBPC Jundiaí"
              loading="lazy"
            />
          </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 }) => {
  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>Conselho Nacional · Sede</span>
        </div>
      </Reveal>

      <Reveal delay={80}>
        <h2 className="obpc-contato-title">
          Venha fazer parte<br/>
          da <em>Obra</em>.
        </h2>
      </Reveal>

      <Reveal delay={120}>
        <div style={{ margin: "0 0 48px" }}>
          <a href="/visitantes"
            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"}>
            Quero conhecer a OBPC
            <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>R. Dante Júlio Spina, 62<br/>Vila Arens · Jundiaí — SP<br/>CEP 13201-660</p>
          </div>
        </Reveal>
        <Reveal delay={200}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Pastor</span>
            <p>Pr. Carlos Gomes<br/>
              <a href="https://instagram.com/carlosgomespr" target="_blank" rel="noopener"
                style={{ color: "inherit", opacity: 0.75, fontSize: 13 }}>@carlosgomespr</a>
            </p>
          </div>
        </Reveal>
        <Reveal delay={260}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Redes sociais</span>
            <p>
              <a href="https://instagram.com/obpcjundiai" target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>Instagram @obpcjundiai</a>
              <a href="https://www.facebook.com/obpcjundiaivilaarens/" target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>Facebook</a>
              <a href="https://www.youtube.com/@OBPCJundiai" target="_blank" rel="noopener" style={{ color: "inherit", display: "block", opacity: 0.85 }}>YouTube @OBPCJundiai</a>
            </p>
          </div>
        </Reveal>
        <Reveal delay={320}>
          <div className="obpc-contato-block">
            <span className="obpc-contato-label">Como chegar</span>
            <p>
              <a href="https://share.google/DiN2dyeg36ZU3fvkT" target="_blank" rel="noopener"
                 style={{ color: "inherit", textDecoration: "underline", opacity: 0.85 }}>
                Google Maps →
              </a><br/>
              <span style={{ fontSize: 13, opacity: 0.7 }}>⭐ 5,0 · 42 avaliações</span>
            </p>
          </div>
        </Reveal>
      </div>
    </section>
  );
};

Object.assign(window, { SectionNoticias, SectionAgenda, SectionContato });
