/* ============================================================
   HOME PAGE
   ============================================================ */

function HeroRotating() {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % HERO_SLIDES.length), 7000);
    return () => clearInterval(t);
  }, []);
  const slide = HERO_SLIDES[idx];
  return (
    <section className="hero">
      <div className="container">
        <div className="hero-rotating">
          <div key={`t-${idx}`} className="anim-in">
            <div className="hero-kicker"><span className="dot"/>{slide.kicker}</div>
            <h1>{slide.title}</h1>
            <p className="hero-lede">{slide.lede}</p>
            <div className="hero-ctas">
              {slide.ctas.map((c, i) => (
                <a key={i} href={c.href} className={`btn btn-${c.kind}`}>
                  {c.label} {c.kind === 'primary' && <Icon.arrow/>}
                </a>
              ))}
            </div>
            <div className="hero-dots">
              {HERO_SLIDES.map((_, i) => (
                <button key={i}
                  className={`hero-dot ${i === idx ? 'active' : ''}`}
                  onClick={() => setIdx(i)}
                  aria-label={`Slide ${i+1}`}/>
              ))}
            </div>
          </div>
          <div key={`i-${idx}`} className="hero-media anim-in">
            <img src={slide.img} alt=""/>
            <div className="hero-caption">
              <strong>{slide.caption.title}</strong>
              {slide.caption.sub}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function HeroBigType() {
  return (
    <section className="hero hero-bigtype">
      <div className="container">
        <div className="hero-kicker" style={{ justifyContent: 'center' }}><span className="dot"/>Est. 1887 · A church for the community</div>
        <h1>A place to <em>belong</em>,<br/>believe, and become.</h1>
        <p className="hero-lede">A family of believers in the heart of the community. Whoever you are, wherever you've come from — you're welcome here.</p>
        <div className="hero-ctas">
          <a href="#/visit" className="btn btn-primary">Plan a visit <Icon.arrow/></a>
          <a href="#/sermons" className="btn btn-outline">Watch a sermon</a>
        </div>
      </div>
    </section>
  );
}

function HeroPhoto() {
  return (
    <section className="hero hero-photo">
      <img src="https://images.unsplash.com/photo-1438032005730-c779502df39b?w=1600&q=80" alt=""/>
      <div className="container hero-inner">
        <div className="hero-kicker"><span className="dot"/>This Sunday · 10:30 AM</div>
        <h1 style={{ maxWidth: '18ch' }}>A place to <em>belong</em>, believe, and become.</h1>
        <p className="hero-lede" style={{ color: 'rgba(255,255,255,0.9)', maxWidth: '48ch' }}>
          Whoever you are, wherever you've come from — you're welcome here.
        </p>
        <div className="hero-ctas">
          <a href="#/visit" className="btn btn-accent">Plan a visit <Icon.arrow/></a>
          <a href="#/sermons" className="btn" style={{ background: 'rgba(255,255,255,0.12)', color: '#fff', backdropFilter: 'blur(8px)' }}>Watch latest sermon</a>
        </div>
      </div>
    </section>
  );
}

function HomePage() {
  const heroMode = document.documentElement.getAttribute('data-hero') || 'rotating';
  const HeroComp = heroMode === 'bigtype' ? HeroBigType : heroMode === 'photo' ? HeroPhoto : HeroRotating;
  return (
    <>
      <HeroComp/>
      <ServicesBar/>

      {/* Ministries preview */}
      <section>
        <div className="container">
          <div className="section-head center">
            <span className="eyebrow">Ministries · Family · Community</span>
            <h2>Find your <em>place</em> to grow.</h2>
            <p style={{ maxWidth: '56ch', margin: '16px auto 0', fontSize: '1.05rem' }}>
              From our toddlers to our seniors, from Sunday worship to midweek pickleball — there's a home for you here.
            </p>
          </div>
          <div className="grid grid-4">
            {MINISTRIES.slice(0,4).map(m => (
              <a key={m.slug} href={`#/ministries/${m.slug}`} className="m-card">
                <div className="m-card-img">
                  <img src={m.img} alt=""/>
                  <span className="m-card-tag">{m.tag}</span>
                </div>
                <div className="m-card-body">
                  <h3>{m.title}</h3>
                  <p>{m.blurb}</p>
                  <div className="m-card-foot">
                    <span className="muted"><Icon.clock/> <span style={{ marginLeft: 4 }}>{m.meta}</span></span>
                    <span style={{ color: 'var(--c-brand)', fontWeight: 600 }}>Explore <Icon.arrow/></span>
                  </div>
                </div>
              </a>
            ))}
          </div>
          <div style={{ textAlign: 'center', marginTop: 40 }}>
            <a href="#/ministries" className="btn btn-outline">View all ministries <Icon.arrow/></a>
          </div>
        </div>
      </section>

      {/* Latest sermon + series */}
      <section style={{ background: 'var(--c-bg-2)', borderTop: '1px solid var(--c-line)', borderBottom: '1px solid var(--c-line)' }}>
        <div className="container">
          <div className="section-head" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 20 }}>
            <div>
              <span className="eyebrow">Sermons</span>
              <h2 style={{ marginTop: 10 }}>Messages <em>worth</em> rewinding.</h2>
            </div>
            <a href="#/sermons" className="btn btn-ghost">Browse all sermons <Icon.arrow/></a>
          </div>

          <HomeLatestSermon/>
        </div>
      </section>

      {/* Upcoming events */}
      <HomeUpcomingEvents/>

      <VerseBlock/>

      {/* New here strip */}
      <section>
        <div className="container">
          <div className="feat-row">
            <div className="feat-img">
              <img src="https://images.unsplash.com/photo-1529634806980-85c3dd6d34ac?w=1000&q=80" alt=""/>
            </div>
            <div>
              <span className="eyebrow">First time?</span>
              <h2 style={{ marginTop: 12 }}>We'd love to <em>meet you</em>.</h2>
              <p style={{ marginTop: 16, fontSize: '1.05rem' }}>
                You don't need to dress up, bring anything, or know what to say. Just come as you are. We'll save you a seat, a cup of coffee, and a warm welcome.
              </p>
              <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0', display: 'grid', gap: 10 }}>
                {['Arrive anytime from 10:00 AM — coffee is on', 'Service is about 75 minutes, family-friendly throughout', 'Children\'s groups run during the sermon', 'There\'s always space for questions afterwards'].map((t,i) => (
                  <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                    <span style={{ width: 20, height: 20, borderRadius: '50%', background: 'var(--c-accent)', color: '#1a1308', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0, marginTop: 2 }}>
                      ✓
                    </span>
                    <span>{t}</span>
                  </li>
                ))}
              </ul>
              <div className="hero-ctas">
                <a href="#/visit" className="btn btn-primary">Plan your visit <Icon.arrow/></a>
                <a href="#/contact" className="btn btn-outline">Get in touch</a>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

Object.assign(window, { HomePage });

/* ============================================================
   Home page — Upcoming events block (live ChurchSuite feed)
   ============================================================ */
function HomeUpcomingEvents() {
  const { events, error } = window.useChurchSuiteEvents();
  // Show everything happening in the next 7 days
  const weekAhead = Date.now() + 7 * 24 * 60 * 60 * 1000;
  const parseStart = s => {
    if (!s) return 0;
    const [d, t] = s.split(' ');
    const [y, mo, da] = d.split('-').map(Number);
    const [h, mi] = (t || '00:00').split(':').map(Number);
    return new Date(y, mo - 1, da, h, mi).getTime();
  };
  const top = (events || []).filter(e => parseStart(e.datetime_start) <= weekAhead);

  // Tiny inline date helpers (mirror events page)
  const MO = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const DY = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  function p(s) {
    if (!s) return null;
    const [d, t] = s.split(' ');
    const [y, mo, da] = d.split('-').map(Number);
    const [h, mi] = (t || '00:00').split(':').map(Number);
    return new Date(y, mo - 1, da, h, mi);
  }
  function fmtT(d) {
    let h = d.getHours(), m = d.getMinutes();
    const ap = h >= 12 ? 'pm' : 'am'; h = h % 12 || 12;
    return m === 0 ? `${h}${ap}` : `${h}:${String(m).padStart(2,'0')}${ap}`;
  }

  return (
    <section>
      <div className="container">
        <div className="section-head" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 20 }}>
          <div>
            <span className="eyebrow">What's on</span>
            <h2 style={{ marginTop: 10 }}>This week at <em>Bethany</em>.</h2>
          </div>
          <a href="#/events" className="btn btn-ghost">Full calendar <Icon.arrow/></a>
        </div>
        {!events && !error && (
          <div className="ev-empty" style={{ padding: '40px 20px' }}>
            <div className="ev-spinner" aria-hidden="true"></div>
          </div>
        )}
        {error && (
          <div className="ev-empty" style={{ padding: '40px 20px' }}>
            <div>Couldn't load events right now. <a href="#/events">View calendar</a></div>
          </div>
        )}
        {events && top.length === 0 && (
          <div className="ev-empty" style={{ padding: '40px 20px' }}>
            <div>Nothing on the calendar in the next seven days. <a href="#/events">See what's coming up</a></div>
          </div>
        )}
        {top.length > 0 && (
          <div className="ev-list-modern">
            {top.map(e => {
              const start = p(e.datetime_start);
              const end = p(e.datetime_end);
              return (
                <a key={e.identifier} className="ev-row" href="#/events"
                   style={{ display: 'grid', textDecoration: 'none' }}>
                  <div className="ev-row-date">
                    <div className="erd-mo">{MO[start.getMonth()]}</div>
                    <div className="erd-d">{start.getDate()}</div>
                  </div>
                  <div className="ev-row-body">
                    <div className="ev-row-title-line">
                      <h4>{e.name}</h4>
                    </div>
                    <div className="ev-row-meta">
                      <span><Icon.calendar/> {DY[start.getDay()]}</span>
                      <span><Icon.clock/> {fmtT(start)}{end ? `–${fmtT(end)}` : ''}</span>
                      {e.category?.name && <span className="ev-row-cat">{e.category.name}</span>}
                    </div>
                  </div>
                  <div className="ev-row-arrow"><Icon.arrow/></div>
                </a>
              );
            })}
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { HomeUpcomingEvents });

/* ============================================================
   Home page — Latest sermon block (live YouTube)
   ============================================================ */
function HomeLatestSermon() {
  const [video, setVideo] = useState(() => {
    try {
      const raw = localStorage.getItem('bb_recent_v2');
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      const items = parsed.v || parsed; // tolerate either shape
      return Array.isArray(items) && items.length ? items[0] : null;
    } catch { return null; }
  });
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    if (video) return; // already have a cached one
    const YT_API_KEY = 'AIzaSyDYsqthvDl1TygsQt0QPD4PDq4-Q5fsxSM';
    const YT_CHANNEL_ID = 'UCvNeLuA60FRBdIHloA1bCpg';
    const uploads = 'UU' + YT_CHANNEL_ID.slice(2);
    const url = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=12&playlistId=${uploads}&key=${YT_API_KEY}`;
    fetch(url)
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(j => {
        const items = (j.items || []).map(it => ({
          id: it.snippet.resourceId?.videoId,
          title: it.snippet.title,
          publishedAt: it.snippet.publishedAt,
          thumb:
            it.snippet.thumbnails?.maxres?.url ||
            it.snippet.thumbnails?.standard?.url ||
            it.snippet.thumbnails?.high?.url ||
            it.snippet.thumbnails?.medium?.url,
          author: it.snippet.videoOwnerChannelTitle || 'Bethany Baptist',
        }));
        if (items.length) {
          setVideo(items[0]);
          try { localStorage.setItem('bb_recent_v2', JSON.stringify({ t: Date.now(), v: items })); } catch {}
        }
      })
      .catch(() => {});
  }, [video]);

  // Fallback while loading: a graceful skeleton
  if (!video) {
    return (
      <div className="yt-hero">
        <div className="yt-player" style={{ background: 'var(--c-bg-2)' }} />
        <div className="yt-player-info">
          <div>
            <div className="yt-live">Latest <span className="dot"/></div>
            <h3 style={{ marginTop: 10, fontSize: '1.8rem', color: 'var(--c-muted)' }}>Loading the latest message…</h3>
          </div>
          <div className="row">
            <a href="#/sermons" className="btn btn-primary">Watch now <Icon.arrow/></a>
            <a href="#/sermons" className="btn btn-outline">Series archive</a>
          </div>
        </div>
      </div>
    );
  }

  // Format date as "12 Apr 2026"
  const d = video.publishedAt ? new Date(video.publishedAt) : null;
  const MO = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const dateStr = d ? `${d.getDate()} ${MO[d.getMonth()]} ${d.getFullYear()}` : '';

  return (
    <div className="yt-hero">
      <div className="yt-player" onClick={() => setPlaying(true)} role="button" tabIndex={0}
           onKeyDown={e => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), setPlaying(true))}
           style={{ cursor: playing ? 'default' : 'pointer' }}>
        {playing ? (
          <iframe
            className="yt-embed"
            src={`https://www.youtube.com/embed/${video.id}?autoplay=1&rel=0&modestbranding=1`}
            title={video.title}
            loading="lazy"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
          />
        ) : (
          <>
            <img className="yt-thumb" src={video.thumb} alt={video.title} loading="lazy"/>
            <div className="yt-play">
              <button className="yt-play-btn" aria-label="Play"><Icon.play/></button>
            </div>
          </>
        )}
      </div>
      <div className="yt-player-info">
        <div>
          <div className="yt-live">Latest <span className="dot"/></div>
          <div className="eyebrow" style={{ color: 'var(--c-muted)' }}>{video.author}</div>
          <h3 style={{ marginTop: 10, fontSize: '1.8rem', lineHeight: 1.2 }}>{video.title}</h3>
          {dateStr && (
            <p style={{ marginTop: 12, color: 'var(--c-muted)', fontSize: 14 }}>
              {dateStr}
            </p>
          )}
        </div>
        <div className="row">
          <a
            href={`https://www.youtube.com/watch?v=${video.id}`}
            target="_blank" rel="noopener"
            className="btn btn-primary"
            onClick={e => { e.preventDefault(); setPlaying(true); }}
          >
            Watch now <Icon.arrow/>
          </a>
          <a href="#/sermons" className="btn btn-outline">Series archive</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeLatestSermon });
