// Home feed (greeting, live, serving, latest message, announcements) + Sunday Live screen.
(function () {
  const { Icon } = window;
  const { Screen, SectionHeader, RoundBtn, SeriesArt, Chip, safeTop } = window.NLUI;
  const { SermonHero } = window.NLCards;
  const D = window.NLData;

  function Greeting() {
    const hr = new Date().getHours();
    const part = hr < 12 ? 'Good morning' : hr < 17 ? 'Good afternoon' : 'Good evening';
    return (
      <div style={{ padding: '4px 20px 18px' }}>
        <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13, fontWeight: 600,
          letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--nl-leaf-700)' }}>
          {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
        </div>
        <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 30,
          letterSpacing: '-0.02em', color: 'var(--nl-navy-900)', margin: '4px 0 0' }}>
          {part}, {D.user.first}.
        </h1>
      </div>
    );
  }

  // Shown only when the livestream is actually on.
  function LiveBanner({ onWatch }) {
    const title = (D.live.upcoming && D.live.upcoming.title) || (D.sermons[0] && D.sermons[0].seriesName) || 'Join the service';
    return (
      <div style={{ margin: '0 20px 24px', borderRadius: 18, overflow: 'hidden', position: 'relative',
        background: 'linear-gradient(135deg, var(--nl-navy-700), var(--nl-navy-900))', padding: 18,
        boxShadow: 'var(--nl-shadow-md)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--nl-clay-500)',
            boxShadow: '0 0 0 4px rgba(216,122,91,0.3)' }} />
          <span style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 11,
            letterSpacing: '0.16em', textTransform: 'uppercase', color: '#fff', whiteSpace: 'nowrap' }}>Live now</span>
        </div>
        <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 21, color: '#fff', lineHeight: 1.1 }}>
          Sunday Worship
        </div>
        <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13, color: 'rgba(255,255,255,0.72)', marginTop: 4 }}>
          {title}
        </div>
        <button onClick={onWatch} className="nl-btn nl-btn--accent nl-btn--sm" style={{ marginTop: 14 }}>
          <Icon name="play" size={15} fill="currentColor" /> Watch live
        </button>
      </div>
    );
  }

  function AnnouncementCard({ a, onClick }) {
    return (
      <button onClick={onClick} style={{ display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
        background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderLeft: '4px solid var(--nl-leaf-600)',
        borderRadius: 12, padding: '14px 16px', marginBottom: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Chip tone={a.theme === 'leaf' ? 'leaf' : a.theme}>{a.tag}</Chip>
          <Icon name="chevronRight" size={16} style={{ color: 'var(--nl-ink-300)' }} />
        </div>
        <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 15, color: 'var(--nl-navy-900)', marginTop: 8 }}>{a.title}</div>
        <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13, color: 'var(--nl-ink-600)', marginTop: 3, lineHeight: 1.4 }}>{a.body}</div>
      </button>
    );
  }

  function Home({ nav, store }) {
    const latest = D.sermons[0];
    const nextServe = (D.serving || []).find(a => a.status === 'confirmed');
    const needs = (D.serving || []).filter(a => a.status === 'unconfirmed').length;
    return (
      <Screen header={{ variant: 'home', right: (
        <React.Fragment>
          <RoundBtn name="search" onClick={() => nav.push('search')} />
          <RoundBtn name="bell" onClick={() => nav.push('notifications')} />
        </React.Fragment>
      ) }}>
        <Greeting />
        {D.live.isLive && <LiveBanner onWatch={() => nav.push('live')} />}

        {(nextServe || needs > 0) && (
          <div style={{ padding: '0 20px', marginBottom: 26 }}>
            <button onClick={() => nav.push('serving')} style={{ width: '100%', textAlign: 'left', cursor: 'pointer',
              background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderLeft: '4px solid var(--nl-leaf-600)',
              borderRadius: 14, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 13, boxShadow: 'var(--nl-shadow-sm)' }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, flexShrink: 0, background: 'var(--nl-navy-50)',
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="users" size={20} style={{ color: 'var(--nl-navy-700)' }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                {nextServe ? (
                  <React.Fragment>
                    <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14.5, color: 'var(--nl-navy-900)' }}>
                      You’re serving {nextServe.date.replace(/^\w+,\s*/, '')}
                    </div>
                    <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-500)', marginTop: 1 }}>
                      {[nextServe.team, nextServe.position].filter(Boolean).join(' · ')}
                    </div>
                  </React.Fragment>
                ) : (
                  <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14.5, color: 'var(--nl-navy-900)' }}>Your serving schedule</div>
                )}
                {needs > 0 && (
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 6, background: 'var(--nl-clay-100)',
                    color: 'var(--nl-clay-900)', borderRadius: 999, padding: '3px 10px', fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 11, whiteSpace: 'nowrap' }}>
                    <Icon name="clock" size={12} /> {needs} {needs > 1 ? 'requests need' : 'request needs'} a response
                  </div>
                )}
              </div>
              <Icon name="chevronRight" size={18} style={{ color: 'var(--nl-ink-300)', flexShrink: 0 }} />
            </button>
          </div>
        )}

        {latest && (
          <div style={{ marginBottom: 30, padding: '0 20px' }}>
            <SectionHeader title="Latest message" action="All sermons" onAction={() => nav.tab('watch')} style={{ padding: 0, marginBottom: 14 }} />
            <SermonHero s={latest} onClick={() => nav.push('sermon', { id: latest.id })} />
          </div>
        )}

        <div style={{ padding: '0 20px' }}>
          <SectionHeader title="Announcements" action="Bulletin" onAction={() => nav.push('bulletin')} style={{ padding: 0, marginBottom: 14 }} />
          {D.announcements.length === 0 && (
            <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>Nothing new this week — check back Sunday.</p>
          )}
          {D.announcements.map(a => (
            <AnnouncementCard key={a.id} a={a} onClick={() => nav.push('bulletin')} />
          ))}
        </div>
      </Screen>
    );
  }

  // ---- Sunday Live: real HLS playback from Cloudflare Stream ----------------
  function Live({ nav }) {
    const videoRef = React.useRef(null);
    const [err, setErr] = React.useState(null);
    const hls = D.live.liveHls;

    React.useEffect(() => {
      const video = videoRef.current;
      if (!video || !hls) return;
      let hlsInstance = null;
      if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = hls; // Safari / iOS native HLS
        video.play().catch(() => {});
      } else {
        window.NLApi.loadHls().then(Hls => {
          if (!Hls.isSupported()) { setErr('Live video isn’t supported in this browser.'); return; }
          hlsInstance = new Hls({ liveSyncDurationCount: 3 });
          hlsInstance.loadSource(hls);
          hlsInstance.attachMedia(video);
          hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => video.play().catch(() => {}));
          hlsInstance.on(Hls.Events.ERROR, (_, data) => { if (data.fatal) setErr('The stream hiccuped — pull down to try again.'); });
        }).catch(() => setErr('Could not load the live player.'));
      }
      return () => { if (hlsInstance) hlsInstance.destroy(); };
    }, [hls]);

    return (
      <div style={{ height: '100%', background: 'var(--nl-navy-900)', display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: `${safeTop(8)} 16px 10px` }}>
          <button onClick={() => nav.pop()} style={{ background: 'rgba(255,255,255,0.12)', border: 0, borderRadius: 999,
            width: 38, height: 38, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#fff' }}>
            <Icon name="chevronLeft" size={20} />
          </button>
          <div style={{ flex: 1, color: '#fff', fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 16 }}>Live</div>
          <div style={{ width: 38 }} />
        </div>

        <div style={{ position: 'relative', width: '100%', aspectRatio: '16/9', background: '#000' }}>
          {D.live.isLive && hls ? (
            <video ref={videoRef} controls playsInline
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} />
          ) : (
            <SeriesArt theme="navy" kicker="New Life Church" title="We’re not live right now"
              sub="Join us Sundays at 10:00 AM" radius={0} style={{ position: 'absolute', inset: 0 }} />
          )}
          {D.live.isLive && (
            <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', alignItems: 'center', gap: 7,
              background: 'rgba(216,122,91,0.92)', borderRadius: 999, padding: '5px 11px', pointerEvents: 'none' }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: '#fff' }} />
              <span style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 10.5, letterSpacing: '0.1em', color: '#fff' }}>LIVE</span>
            </div>
          )}
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '20px 22px calc(env(safe-area-inset-bottom, 0px) + 20px)' }}>
          <div className="nl-eyebrow" style={{ color: 'var(--nl-leaf-500)' }}>Sunday Worship · 10:00 AM</div>
          <h2 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 24, color: '#fff', margin: '8px 0 6px' }}>
            {D.live.isLive ? 'Welcome to church' : 'See you Sunday'}
          </h2>
          {err && <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: '#ECB69E', margin: '8px 0 0' }}>{err}</p>}
          <div style={{ display: 'flex', gap: 10, marginTop: 20 }}>
            <button onClick={() => nav.push('give')} className="nl-btn nl-btn--accent" style={{ flex: 1 }}>
              <Icon name="heart" size={17} /> Give
            </button>
            {D.sermons[0] && (
              <button onClick={() => nav.push('sermon', { id: D.sermons[0].id, tab: 'notes' })} className="nl-btn nl-btn--outline"
                style={{ flex: 1, borderColor: 'rgba(255,255,255,0.4)', color: '#fff' }}>
                <Icon name="note" size={17} /> Notes
              </button>
            )}
          </div>
          <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, lineHeight: 1.6, color: 'rgba(255,255,255,0.55)', marginTop: 22 }}>
            Welcome home. We’re so glad you’re worshiping with us — whether you’re in the room or across the miles.
          </p>
        </div>
      </div>
    );
  }

  window.NLHome = { Home, Live };
})();
