// Watch library + Sermon detail (real video player, notes, scripture) + Gallery detail.
(function () {
  const { Icon } = window;
  const { useState, useRef, useEffect } = React;
  const { Screen, RoundBtn, SeriesArt, Chip, art, safeTop } = window.NLUI;
  const { SermonArt, SermonHero, SermonRow, GalleryCover } = window.NLCards;
  const D = window.NLData;

  // Segmented control --------------------------------------------------------
  function Segmented({ options, value, onChange, style }) {
    return (
      <div style={{ display: 'flex', background: 'var(--nl-ink-100)', borderRadius: 999, padding: 3, ...style }}>
        {options.map(o => {
          const on = o.id === value;
          return (
            <button key={o.id} onClick={() => onChange(o.id)} style={{ flex: 1, border: 0, cursor: 'pointer',
              borderRadius: 999, padding: '8px 0', fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 13.5,
              background: on ? 'var(--nl-white)' : 'transparent', color: on ? 'var(--nl-navy-900)' : 'var(--nl-ink-500)',
              boxShadow: on ? 'var(--nl-shadow-sm)' : 'none', transition: 'all .15s' }}>{o.label}</button>
          );
        })}
      </div>
    );
  }

  function Watch({ nav }) {
    const [tab, setTab] = useState('sermons');
    const [shown, setShown] = useState(20);
    const latest = D.sermons[0];
    return (
      <Screen header={{ variant: 'large', title: 'Watch', right: <RoundBtn name="search" onClick={() => nav.push('search')} /> }}>
        <div style={{ padding: '0 20px 18px' }}>
          <Segmented value={tab} onChange={setTab}
            options={[{ id: 'sermons', label: 'Sermons' }, { id: 'galleries', label: 'Galleries' }]} />
        </div>

        {tab === 'sermons' ? (
          <React.Fragment>
            {latest && (
              <div style={{ padding: '0 20px 8px' }}>
                {latest.seriesName && <div className="nl-eyebrow" style={{ marginBottom: 10 }}>Current series · {latest.seriesName}</div>}
                <SermonHero s={latest} label={null} onClick={() => nav.push('sermon', { id: latest.id })} />
              </div>
            )}
            <div style={{ padding: '18px 20px 0' }}>
              <h3 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 19, color: 'var(--nl-navy-900)', margin: '0 0 4px' }}>
                Recent messages
              </h3>
              {D.sermons.slice(0, shown).map((s, i, arr) => (
                <div key={s.id} style={{ borderBottom: i < arr.length - 1 ? '1px solid var(--nl-divider)' : 0 }}>
                  <SermonRow s={s} onClick={() => nav.push('sermon', { id: s.id })} />
                </div>
              ))}
              {shown < D.sermons.length && (
                <button onClick={() => setShown(n => n + 30)} className="nl-btn nl-btn--ghost" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }}>
                  Show more · {D.sermons.length - shown} older messages
                </button>
              )}
            </div>
          </React.Fragment>
        ) : (
          <div style={{ padding: '0 20px' }}>
            {D.galleries.length === 0 && (
              <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', padding: '30px 10px' }}>
                No photo galleries yet — they’ll appear here after the next event.
              </p>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              {D.galleries.map(g => <GalleryCover key={g.id} g={g} onClick={() => nav.push('gallery', { id: g.id })} />)}
            </div>
          </div>
        )}
      </Screen>
    );
  }

  // ---- Real sermon player ---------------------------------------------------
  function Player({ s, store }) {
    const videoRef = useRef(null);
    const [started, setStarted] = useState(false);
    const lastSaved = useRef(0);

    const begin = () => {
      const v = videoRef.current;
      if (!v) return;
      const resume = store.resumeTime(s.id);
      if (resume > 10 && (!v.duration || resume < v.duration * 0.95)) v.currentTime = resume;
      v.play().catch(() => {});
      setStarted(true);
    };

    const onTime = (e) => {
      const v = e.target;
      const now = Date.now();
      if (now - lastSaved.current > 5000 && v.duration) {
        lastSaved.current = now;
        store.setProgress(s.id, v.currentTime, v.duration);
      }
    };

    if (!s.videoUrl) {
      return (
        <div style={{ position: 'relative', width: '100%', aspectRatio: '16/9', background: '#000' }}>
          <SermonArt s={s} radius={0} />
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '10px 14px',
            background: 'rgba(5,31,46,0.72)', color: '#fff', fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, textAlign: 'center' }}>
            {s.archivedLocally ? 'This message is in our archive — contact the church office for a copy.' : 'Video coming soon.'}
          </div>
        </div>
      );
    }

    return (
      <div style={{ position: 'relative', width: '100%', aspectRatio: '16/9', background: '#000', overflow: 'hidden' }}>
        <video ref={videoRef} controls={started} playsInline preload="metadata"
          poster={s.thumbnail || undefined} src={s.videoUrl} onTimeUpdate={onTime}
          onPlay={() => setStarted(true)}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', background: '#000' }} />
        {!started && (
          <button onClick={begin} aria-label="Play" style={{ position: 'absolute', inset: 0, border: 0, cursor: 'pointer',
            background: s.thumbnail ? 'rgba(5,31,46,0.25)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {!s.thumbnail && <SermonArt s={s} radius={0} />}
            <div style={{ position: s.thumbnail ? 'static' : 'absolute', width: 62, height: 62, borderRadius: 999,
              background: 'rgba(251,250,246,0.94)', display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: 'var(--nl-shadow-lg)' }}>
              <Icon name="play" size={26} fill="currentColor" style={{ color: 'var(--nl-navy-800)', marginLeft: 3 }} />
            </div>
          </button>
        )}
      </div>
    );
  }

  function SermonDetail({ nav, store, params }) {
    const s = D.sermons.find(x => x.id === params.id) || D.sermons[0];
    const [tab, setTab] = useState(params.tab || 'about');
    const downloaded = store.isDownloaded(s.id);
    const dlState = store.downloadState(s.id);
    const note = store.notes[s.id] || '';
    const ref = D.parseRef(s.scripture);
    const [verses, setVerses] = useState(ref ? D.bibleText[ref.key] || null : null);

    useEffect(() => {
      if (tab === 'scripture' && ref && !verses) {
        window.NLApi.bible(ref.book, ref.chapter)
          .then(d => setVerses(d.verses))
          .catch(() => {});
      }
    }, [tab]);

    const share = () => {
      const url = `${window.location.origin}/?sermon=${s.id}`;
      if (navigator.share) navigator.share({ title: s.title, text: `${s.title} — New Life Church`, url }).catch(() => {});
      else { navigator.clipboard && navigator.clipboard.writeText(url); alert('Link copied'); }
    };

    return (
      <div style={{ height: '100%', overflowY: 'auto', background: 'var(--nl-bg)' }}>
        <div style={{ position: 'sticky', top: 0, zIndex: 20, background: '#000' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: `${safeTop(8)} 14px 8px`, position: 'absolute', top: 0, left: 0, right: 0, zIndex: 2, pointerEvents: 'none' }}>
            <button onClick={() => nav.pop()} style={{ width: 38, height: 38, borderRadius: 999, border: 0, cursor: 'pointer', pointerEvents: 'auto',
              background: 'rgba(5,31,46,0.4)', backdropFilter: 'blur(6px)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="chevronLeft" size={20} />
            </button>
          </div>
          <Player s={s} store={store} />
        </div>

        <div style={{ padding: '20px 20px 40px' }}>
          {s.seriesName && <Chip>{s.seriesName}{s.part ? ` · ${s.part}` : ''}</Chip>}
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 26, lineHeight: 1.1,
            letterSpacing: '-0.01em', color: 'var(--nl-navy-900)', margin: '12px 0 6px' }}>{s.title}</h1>
          <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: 'var(--nl-ink-500)' }}>
            {[s.speaker, s.date, s.length].filter(Boolean).join(' · ')}
          </div>

          {/* actions */}
          <div style={{ display: 'flex', gap: 10, margin: '18px 0 22px' }}>
            <button onClick={() => downloaded ? store.removeDownload(s) : store.startDownload(s)}
              disabled={dlState === 'downloading' || !s.videoUrl}
              title={downloaded ? 'Remove download' : 'Save for offline'}
              style={{ flex: 1, height: 46, borderRadius: 8,
                border: '1.5px solid ' + (downloaded ? 'var(--nl-leaf-600)' : 'var(--nl-navy-800)'),
                cursor: s.videoUrl ? 'pointer' : 'default', opacity: s.videoUrl ? 1 : 0.4,
                background: downloaded ? 'var(--nl-leaf-100)' : 'transparent',
                color: downloaded ? 'var(--nl-leaf-800)' : 'var(--nl-navy-800)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14, whiteSpace: 'nowrap' }}>
              <Icon name={downloaded ? 'check' : 'download'} size={19} strokeWidth={downloaded ? 2.2 : 1.7} />
              {dlState === 'downloading' ? 'Saving…' : downloaded ? 'Saved offline' : 'Save offline'}
            </button>
            <button onClick={share} title="Share" style={{ width: 50, height: 46, borderRadius: 8, border: '1.5px solid var(--nl-navy-800)', cursor: 'pointer',
              background: 'transparent', color: 'var(--nl-navy-800)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="share" size={19} />
            </button>
          </div>

          <Segmented value={tab} onChange={setTab} style={{ marginBottom: 20 }}
            options={[{ id: 'about', label: 'About' }, { id: 'notes', label: 'Notes' }, { id: 'scripture', label: 'Scripture' }]} />

          {tab === 'about' && (
            <div>
              <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 15.5, lineHeight: 1.65, color: 'var(--nl-ink-700)', margin: 0 }}>
                {s.blurb || `${s.title}${s.speaker ? ' — ' + s.speaker : ''}${s.date ? ', ' + s.date : ''}.`}
              </p>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 16 }}>
                {s.topic && <Chip tone="navy">{s.topic}</Chip>}
                {s.scripture && <Chip tone="wheat">{s.scripture}</Chip>}
              </div>
            </div>
          )}

          {tab === 'notes' && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 10,
                fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-500)' }}>
                <Icon name="note" size={15} style={{ color: 'var(--nl-leaf-700)' }} />
                Your notes save automatically and sync to your account
              </div>
              <textarea value={note} onChange={e => store.setNote(s.id, e.target.value)}
                placeholder="Type what God is speaking to you…"
                className="nl-textarea" style={{ minHeight: 200, resize: 'vertical', lineHeight: 1.6, fontSize: 15 }} />
              {ref && (
                <button onClick={() => nav.push('reader', { chapter: ref.key })} style={{ marginTop: 14, width: '100%',
                  background: 'var(--nl-navy-50)', border: '1px solid var(--nl-navy-200)', borderRadius: 12, padding: '14px 16px',
                  cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left' }}>
                  <Icon name="bookOpen" size={22} style={{ color: 'var(--nl-navy-700)' }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14, color: 'var(--nl-navy-900)' }}>Open {s.scripture} in the Bible</div>
                    <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-500)' }}>Read along, highlight & save verses</div>
                  </div>
                  <Icon name="chevronRight" size={18} style={{ color: 'var(--nl-ink-300)' }} />
                </button>
              )}
            </div>
          )}

          {tab === 'scripture' && (
            <div>
              <div className="nl-eyebrow" style={{ marginBottom: 4 }}>This week’s passage</div>
              <h3 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 22, color: 'var(--nl-navy-900)', margin: '0 0 16px' }}>
                {ref ? ref.key : s.scripture || 'Scripture'}
              </h3>
              {verses ? (
                <div style={{ fontFamily: 'var(--nl-font-serif)', fontSize: 17, lineHeight: 1.7, color: 'var(--nl-navy-900)' }}>
                  {verses.map(([n, t]) => (
                    <span key={n}>
                      <sup style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 10, fontWeight: 700,
                        color: 'var(--nl-leaf-700)', marginRight: 4, verticalAlign: 'super' }}>{n}</sup>
                      {t}{' '}
                    </span>
                  ))}
                </div>
              ) : (
                <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>
                  {ref ? 'Loading passage…' : 'No passage listed for this message.'}
                </p>
              )}
              {ref && (
                <button onClick={() => nav.push('reader', { chapter: ref.key })} className="nl-btn nl-btn--outline" style={{ width: '100%', marginTop: 20 }}>
                  <Icon name="bookOpen" size={18} /> Open in Bible reader
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    );
  }

  // ---- Gallery detail (real photos) -----------------------------------------
  function GalleryDetail({ nav, params }) {
    const g = D.galleries.find(x => x.id === params.id) || D.galleries[0] || { id: '', title: 'Gallery', count: 0 };
    const [photos, setPhotos] = useState(null);
    const [light, setLight] = useState(null);

    useEffect(() => {
      if (D.mode !== 'live') { setPhotos([]); return; }
      fetch(`/api/galleries/${g.id}/photos`)
        .then(r => r.json())
        .then(d => setPhotos(d.photos || []))
        .catch(() => setPhotos([]));
    }, [g.id]);

    const photoUrl = (p) => `/api/photo/${g.id}/${p.id}`;

    return (
      <Screen header={{ variant: 'detail', title: g.title, onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 10px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>{g.title}</h1>
          <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: 'var(--nl-ink-500)', marginTop: 4 }}>
            {[g.date, g.count ? `${g.count} photos` : ''].filter(Boolean).join(' · ')}
          </div>
        </div>

        {photos === null && (
          <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', padding: 30 }}>Loading photos…</p>
        )}
        {photos && photos.length === 0 && (
          <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', padding: 30 }}>
            {D.mode === 'live' ? 'No photos in this gallery yet.' : 'Photos appear here once the app is connected to the church backend.'}
          </p>
        )}
        {photos && photos.length > 0 && (
          <div style={{ padding: '12px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
            {photos.map((p, i) => (
              <button key={p.id} onClick={() => setLight(i)} style={{ aspectRatio: '1/1', border: 0, cursor: 'pointer', padding: 0,
                borderRadius: 8, overflow: 'hidden', background: 'var(--nl-ink-100)' }}>
                <img src={photoUrl(p)} alt={p.caption || ''} loading="lazy"
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              </button>
            ))}
          </div>
        )}

        {light !== null && photos && photos[light] && (
          <div onClick={() => setLight(null)} style={{ position: 'fixed', inset: 0, zIndex: 90, background: 'rgba(5,31,46,0.96)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
            <button onClick={() => setLight(null)} style={{ position: 'absolute', top: safeTop(8), right: 18, background: 'rgba(255,255,255,0.14)',
              border: 0, borderRadius: 999, width: 40, height: 40, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="x" size={22} />
            </button>
            <img src={photoUrl(photos[light])} alt="" onClick={e => e.stopPropagation()}
              style={{ maxWidth: '94%', maxHeight: '74%', borderRadius: 12, objectFit: 'contain' }} />
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 18 }} onClick={e => e.stopPropagation()}>
              <button disabled={light <= 0} onClick={() => setLight(l => l - 1)} style={{ background: 'rgba(255,255,255,0.14)', opacity: light <= 0 ? 0.4 : 1,
                border: 0, borderRadius: 999, width: 40, height: 40, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="chevronLeft" size={20} />
              </button>
              <a href={`${photoUrl(photos[light])}?download=1`} download style={{ display: 'flex', alignItems: 'center', gap: 8,
                background: 'var(--nl-leaf-600)', color: 'var(--nl-navy-900)', borderRadius: 999, padding: '10px 18px',
                fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 13, textDecoration: 'none' }}>
                <Icon name="download" size={16} /> Save
              </a>
              <button disabled={light >= photos.length - 1} onClick={() => setLight(l => l + 1)} style={{ background: 'rgba(255,255,255,0.14)', opacity: light >= photos.length - 1 ? 0.4 : 1,
                border: 0, borderRadius: 999, width: 40, height: 40, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="chevronRight" size={20} />
              </button>
            </div>
            <div style={{ color: 'rgba(255,255,255,0.7)', fontFamily: 'var(--nl-font-sans)', fontSize: 13, marginTop: 12 }}>
              {light + 1} of {photos.length}
            </div>
          </div>
        )}
      </Screen>
    );
  }

  function Galleries({ nav }) {
    return (
      <Screen header={{ variant: 'detail', title: 'Galleries', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 10px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>Photos</h1>
        </div>
        <div style={{ padding: '12px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {D.galleries.map(g => <GalleryCover key={g.id} g={g} onClick={() => nav.push('gallery', { id: g.id })} />)}
        </div>
      </Screen>
    );
  }

  window.NLWatch = { Watch, SermonDetail, GalleryDetail, Galleries, Segmented };
})();
