// More hub + Profile, Notifications, Search, Downloads.
(function () {
  const { Icon } = window;
  const { useState } = React;
  const { Screen, RoundBtn, Chip, safeTop } = window.NLUI;
  const { SermonRow } = window.NLCards;
  const D = window.NLData;

  const GRID = [
    { id: 'events', label: 'Events', icon: 'calendar', tone: 'navy' },
    { id: 'galleries', label: 'Photos', icon: 'image', tone: 'leaf' },
    { id: 'serving', label: 'Serving', icon: 'users', tone: 'navy' },
    { id: 'prayer', label: 'Prayer', icon: 'heart', tone: 'clay' },
    { id: 'bulletin', label: 'Bulletin', icon: 'note', tone: 'wheat' },
    { id: 'give', label: 'Give', icon: 'gift', tone: 'leaf' },
    { id: 'downloads', label: 'Downloads', icon: 'download', tone: 'navy' },
    { id: 'highlights', label: 'My Bible', icon: 'bookmark', tone: 'clay' },
  ];
  const TONE_BG = { navy: 'var(--nl-navy-800)', leaf: 'var(--nl-leaf-600)', clay: 'var(--nl-clay-500)', wheat: 'var(--nl-wheat-500)' };
  const TONE_FG = { navy: '#fff', leaf: 'var(--nl-navy-900)', clay: '#fff', wheat: 'var(--nl-navy-900)' };

  function Avatar({ size = 52, fontSize = 22 }) {
    if (D.user.avatar) {
      return <img src={D.user.avatar} alt="" style={{ width: size, height: size, borderRadius: 999, objectFit: 'cover', flexShrink: 0 }} />;
    }
    return (
      <div style={{ width: size, height: size, borderRadius: 999, background: 'var(--nl-navy-800)', color: '#fff', flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize }}>
        {(D.user.first || '?')[0]}
      </div>
    );
  }

  function More({ nav, store }) {
    return (
      <Screen header={{ variant: 'large', title: 'More', right: <RoundBtn name="user" onClick={() => nav.push('profile')} /> }}>
        {/* member card */}
        <div style={{ padding: '0 20px 22px' }}>
          <button onClick={() => nav.push('profile')} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
            background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 16, padding: 16, boxShadow: 'var(--nl-shadow-sm)' }}>
            <Avatar />
            <div style={{ flex: 1, textAlign: 'left' }}>
              <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 19, color: 'var(--nl-navy-900)' }}>{D.user.name}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                <Chip>{D.user.membership || 'Member'}</Chip>
                <span style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12, color: 'var(--nl-ink-500)' }}>via Planning Center</span>
              </div>
            </div>
            <Icon name="chevronRight" size={20} style={{ color: 'var(--nl-ink-300)' }} />
          </button>
        </div>

        <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {GRID.map(g => (
            <button key={g.id} onClick={() => nav.push(g.id)} style={{ cursor: 'pointer', textAlign: 'left',
              background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 16, padding: 18 }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: TONE_BG[g.tone], color: TONE_FG[g.tone],
                display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
                <Icon name={g.icon} size={22} />
              </div>
              <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 15.5, color: 'var(--nl-navy-900)' }}>{g.label}</div>
            </button>
          ))}
        </div>

        <div style={{ padding: '26px 20px 0' }}>
          <button onClick={() => store.signOut()} className="nl-btn nl-btn--ghost" style={{ width: '100%', justifyContent: 'center', color: 'var(--nl-danger)' }}>
            <Icon name="logout" size={18} /> Sign out
          </button>
          <div style={{ textAlign: 'center', fontFamily: 'var(--nl-font-sans)', fontSize: 12, color: 'var(--nl-ink-400)', marginTop: 14 }}>
            New Life Church · Petersburg, MI · v1.0
          </div>
        </div>
      </Screen>
    );
  }

  function Profile({ nav, store }) {
    const dls = D.sermons.filter(s => store.isDownloaded(s.id)).length;
    const rows = [
      { label: 'Downloads', icon: 'download', detail: dls ? `${dls}` : '', to: 'downloads' },
      { label: 'My Bible', icon: 'bookmark', to: 'highlights' },
      { label: 'Serving schedule', icon: 'users', to: 'serving' },
    ];
    return (
      <Screen header={{ variant: 'detail', title: 'Profile', onBack: () => nav.pop() }}>
        <div style={{ textAlign: 'center', padding: '0 20px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}><Avatar size={84} fontSize={36} /></div>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 26, color: 'var(--nl-navy-900)', margin: 0 }}>{D.user.name}</h1>
          {D.user.email && <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: 'var(--nl-ink-500)', marginTop: 4 }}>{D.user.email}</div>}
          <div style={{ marginTop: 10 }}><Chip>{D.user.membership || 'Member'}</Chip></div>
          <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-400)', marginTop: 12, lineHeight: 1.5 }}>
            Your profile comes from Planning Center. To update your info, ask the church office.
          </p>
        </div>

        <div style={{ padding: '0 20px' }}>
          <div style={{ background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 14, overflow: 'hidden' }}>
            {rows.map((r, i) => (
              <button key={r.label} onClick={() => nav.push(r.to)} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%',
                textAlign: 'left', cursor: 'pointer', background: 'none', border: 0, padding: '14px 16px',
                borderBottom: i < rows.length - 1 ? '1px solid var(--nl-divider)' : 0 }}>
                <Icon name={r.icon} size={20} style={{ color: 'var(--nl-navy-700)' }} />
                <span style={{ flex: 1, fontFamily: 'var(--nl-font-sans)', fontSize: 15, color: 'var(--nl-navy-900)' }}>{r.label}</span>
                {r.detail && <span style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 14, color: 'var(--nl-ink-400)' }}>{r.detail}</span>}
                <Icon name="chevronRight" size={18} style={{ color: 'var(--nl-ink-300)' }} />
              </button>
            ))}
          </div>

          <button onClick={() => store.signOut()} className="nl-btn nl-btn--outline" style={{ width: '100%', marginTop: 20, color: 'var(--nl-danger)', borderColor: 'var(--nl-danger)' }}>
            <Icon name="logout" size={18} /> Sign out
          </button>
        </div>
      </Screen>
    );
  }

  function Notifications({ nav }) {
    return (
      <Screen header={{ variant: 'detail', title: 'Notifications', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 16px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>Notifications</h1>
        </div>
        <div style={{ textAlign: 'center', padding: '40px 30px' }}>
          <Icon name="bell" size={40} style={{ color: 'var(--nl-ink-300)', margin: '0 auto 12px' }} />
          <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>
            You’re all caught up. When something new happens — a message posts or the livestream starts — it’ll show here.
          </p>
        </div>
      </Screen>
    );
  }

  function Downloads({ nav, store }) {
    const dls = D.sermons.filter(s => store.isDownloaded(s.id));
    return (
      <Screen header={{ variant: 'detail', title: 'Downloads', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 8px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>Downloads</h1>
          <p className="nl-body" style={{ marginTop: 4, color: 'var(--nl-ink-500)' }}>Watch anywhere — even without signal.</p>
        </div>
        <div style={{ padding: '8px 20px 0' }}>
          {dls.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '50px 20px' }}>
              <Icon name="download" size={40} style={{ color: 'var(--nl-ink-300)', margin: '0 auto 12px' }} />
              <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>No downloads yet. Open any sermon and tap “Save offline.”</p>
              <button onClick={() => nav.tab('watch')} className="nl-btn nl-btn--outline" style={{ marginTop: 14 }}>Browse sermons</button>
            </div>
          ) : dls.map((s, i) => (
            <div key={s.id} style={{ borderBottom: i < dls.length - 1 ? '1px solid var(--nl-divider)' : 0, display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <SermonRow s={s} onClick={() => nav.push('sermon', { id: s.id })} />
              </div>
              <button onClick={() => store.removeDownload(s)} title="Remove download" style={{ flexShrink: 0, width: 36, height: 36,
                borderRadius: 999, border: '1px solid var(--nl-border)', background: 'var(--nl-white)', cursor: 'pointer',
                color: 'var(--nl-ink-500)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="x" size={17} />
              </button>
            </div>
          ))}
        </div>
      </Screen>
    );
  }

  function Search({ nav }) {
    const [q, setQ] = useState('');
    const ql = q.toLowerCase();
    const res = q ? D.sermons.filter(s =>
      (s.title + ' ' + s.topic + ' ' + s.speaker + ' ' + s.seriesName + ' ' + s.scripture + ' ' + s.book)
        .toLowerCase().includes(ql)) : [];
    const topics = [...new Set(D.sermons.map(s => s.seriesName).filter(Boolean))].slice(0, 8);
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--nl-bg)' }}>
        <div style={{ paddingTop: safeTop(8), background: 'var(--nl-bg)', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 16px 12px' }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8, background: 'var(--nl-white)',
              border: '1px solid var(--nl-border)', borderRadius: 12, padding: '10px 14px' }}>
              <Icon name="search" size={19} style={{ color: 'var(--nl-ink-400)' }} />
              <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Search messages, series, scripture"
                style={{ flex: 1, border: 0, outline: 'none', background: 'transparent', fontFamily: 'var(--nl-font-sans)', fontSize: 15, color: 'var(--nl-navy-900)', minWidth: 0 }} />
            </div>
            <button onClick={() => nav.pop()} style={{ background: 'none', border: 0, cursor: 'pointer', fontFamily: 'var(--nl-font-sans)',
              fontSize: 15, fontWeight: 600, color: 'var(--nl-navy-800)' }}>Cancel</button>
          </div>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '6px 20px calc(env(safe-area-inset-bottom, 0px) + 20px)' }}>
          {!q && topics.length > 0 && (
            <div>
              <div className="nl-eyebrow" style={{ marginBottom: 12 }}>Browse series</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {topics.map(t => (
                  <button key={t} onClick={() => setQ(t)} style={{ cursor: 'pointer', border: '1px solid var(--nl-border)', background: 'var(--nl-white)',
                    borderRadius: 999, padding: '9px 16px', fontFamily: 'var(--nl-font-sans)', fontSize: 14, color: 'var(--nl-navy-900)' }}>{t}</button>
                ))}
              </div>
            </div>
          )}
          {q && res.length === 0 && <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', marginTop: 30 }}>No results for “{q}”.</p>}
          {res.slice(0, 50).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>
          ))}
        </div>
      </div>
    );
  }

  window.NLMore = { More, Profile, Notifications, Downloads, Search };
})();
