// Community screens: Events (PCO Calendar) + Event detail, Prayer request, Bulletin.
(function () {
  const { Icon } = window;
  const { useState } = React;
  const { Screen, RoundBtn, Chip, SeriesArt, art } = window.NLUI;
  const { EventCard } = window.NLCards;
  const D = window.NLData;

  // ---- Events (live from Planning Center Calendar) --------------------------
  function Events({ nav }) {
    const month = D.events[0] && D.events[0].startsAt
      ? new Date(D.events[0].startsAt).toLocaleDateString('en-US', { month: 'long', year: 'numeric' }) : '';
    return (
      <Screen header={{ variant: 'detail', title: 'Events', 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 }}>What’s on</h1>
          {month && <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: 'var(--nl-ink-500)', marginTop: 4 }}>{month}</div>}
        </div>
        <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {D.events.length === 0 && (
            <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', padding: '30px 10px' }}>
              No upcoming events posted yet — check back soon.
            </p>
          )}
          {D.events.map(e => <EventCard key={e.id} e={e} onClick={() => nav.push('event', { id: e.id })} />)}
        </div>
      </Screen>
    );
  }

  function icsLink(e) {
    if (!e.startsAt) return null;
    const dt = (iso) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
    const end = e.endsAt || new Date(new Date(e.startsAt).getTime() + 60 * 60 * 1000).toISOString();
    const ics = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//New Life Church//App//EN', 'BEGIN:VEVENT',
      `UID:${e.id}@newlifepetersburg.com`, `DTSTART:${dt(e.startsAt)}`, `DTEND:${dt(end)}`,
      `SUMMARY:${e.title.replace(/[,;]/g, ' ')}`, `LOCATION:${(e.loc || '').replace(/[,;]/g, ' ')}`,
      'END:VEVENT', 'END:VCALENDAR'].join('\r\n');
    return 'data:text/calendar;charset=utf-8,' + encodeURIComponent(ics);
  }

  function EventDetail({ nav, params }) {
    const e = D.events.find(x => x.id === params.id) || D.events[0];
    if (!e) return null;
    const cal = icsLink(e);
    return (
      <Screen header={{ variant: 'detail', title: e.title, onBack: () => nav.pop() }} pad>
        <div style={{ padding: '0 20px' }}>
          <div style={{ width: '100%', aspectRatio: '16/9', borderRadius: 18, overflow: 'hidden', marginBottom: 20, position: 'relative' }}>
            {e.imageUrl
              ? <img src={e.imageUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              : <SeriesArt theme={e.theme} kicker="New Life Church" title={e.title} sub={e.when} radius={18} />}
          </div>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 26, color: 'var(--nl-navy-900)', margin: '0 0 16px' }}>{e.title}</h1>
          {[['calendar', e.startsAt ? new Date(e.startsAt).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' }) + (e.when.includes('·') ? ' ·' + e.when.split('·')[1] : '') : e.when],
            ['mapPin', e.loc]].map(([ic, tx]) => tx && (
            <div key={ic} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0',
              fontFamily: 'var(--nl-font-sans)', fontSize: 15, color: 'var(--nl-navy-900)' }}>
              <Icon name={ic} size={20} style={{ color: 'var(--nl-leaf-700)' }} /> {tx}
            </div>
          ))}
          {(e.summary || e.description) && (
            <p className="nl-body" style={{ marginTop: 16 }}>{e.summary || e.description}</p>
          )}
          <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
            {e.churchCenterUrl && (
              <a href={e.churchCenterUrl} target="_blank" rel="noopener" className="nl-btn nl-btn--primary"
                style={{ flex: 1, textDecoration: 'none', boxSizing: 'border-box' }}>
                Details & registration
              </a>
            )}
            {cal && (
              <a href={cal} download={`${e.title}.ics`} className="nl-btn nl-btn--outline"
                style={{ width: 54, padding: 0, boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none' }}
                title="Add to calendar">
                <Icon name="calendar" size={19} />
              </a>
            )}
          </div>
        </div>
      </Screen>
    );
  }

  // ---- Prayer request (private — goes to the church office) -----------------
  function Prayer({ nav }) {
    const [text, setText] = useState('');
    const [anon, setAnon] = useState(false);
    const [phase, setPhase] = useState('compose'); // compose | sending | sent | error
    const submit = async () => {
      if (!text.trim()) return;
      setPhase('sending');
      try {
        if (D.mode === 'live') await window.NLApi.prayer(text.trim(), anon);
        setPhase('sent');
      } catch (e) { setPhase('error'); }
    };
    return (
      <Screen header={{ variant: 'detail', title: 'Prayer', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 18px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>We’d love to pray with you</h1>
          <p style={{ fontFamily: 'var(--nl-font-serif)', fontStyle: 'italic', fontSize: 15.5, color: 'var(--nl-ink-600)', margin: '6px 0 0', lineHeight: 1.5 }}>
            “Carry each other’s burdens.” — Galatians 6:2
          </p>
        </div>

        {phase === 'sent' ? (
          <div style={{ padding: '20px 20px', textAlign: 'center' }}>
            <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--nl-leaf-600)', margin: '20px auto 18px',
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="check" size={32} strokeWidth={2.4} style={{ color: 'var(--nl-navy-900)' }} />
            </div>
            <h2 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 24, color: 'var(--nl-navy-900)', margin: '0 0 8px' }}>We’ve got it</h2>
            <p className="nl-body" style={{ color: 'var(--nl-ink-600)' }}>
              Your request went straight to our prayer team. You are not walking through this alone.
            </p>
            <button onClick={() => { setText(''); setPhase('compose'); }} className="nl-btn nl-btn--outline" style={{ marginTop: 18 }}>
              Share another request
            </button>
          </div>
        ) : (
          <div style={{ padding: '0 20px' }}>
            <div style={{ background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 16, padding: 18, boxShadow: 'var(--nl-shadow-sm)' }}>
              <textarea value={text} onChange={e => setText(e.target.value)}
                placeholder="What can we pray with you about?" className="nl-textarea"
                style={{ minHeight: 140, resize: 'vertical', fontSize: 15, lineHeight: 1.6, marginBottom: 14 }} />
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, cursor: 'pointer' }}>
                <input type="checkbox" checked={anon} onChange={e => setAnon(e.target.checked)}
                  style={{ width: 18, height: 18, accentColor: 'var(--nl-leaf-600)' }} />
                <span style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 14, color: 'var(--nl-ink-700)' }}>Share anonymously</span>
              </label>
              <button onClick={submit} disabled={phase === 'sending' || !text.trim()}
                className="nl-btn nl-btn--accent" style={{ width: '100%', opacity: text.trim() ? 1 : 0.5 }}>
                <Icon name="send" size={17} /> {phase === 'sending' ? 'Sending…' : 'Send to the prayer team'}
              </button>
              {phase === 'error' && (
                <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13, color: 'var(--nl-danger)', marginTop: 10, textAlign: 'center' }}>
                  Couldn’t send just now — please try again.
                </p>
              )}
            </div>
            <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-400)', textAlign: 'center', lineHeight: 1.5, padding: '14px 20px 0' }}>
              Requests are private — only the pastoral team sees them.
            </p>
          </div>
        )}
      </Screen>
    );
  }

  // ---- Bulletin (announcements) ---------------------------------------------
  function Bulletin({ nav }) {
    return (
      <Screen header={{ variant: 'detail', title: 'Bulletin', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 18px' }}>
          <div className="nl-eyebrow">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</div>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: '6px 0 0' }}>This week at New Life</h1>
        </div>
        <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {D.announcements.length === 0 && (
            <p className="nl-body" style={{ color: 'var(--nl-ink-500)', textAlign: 'center', padding: '30px 10px' }}>
              Nothing posted this week — enjoy the quiet.
            </p>
          )}
          {D.announcements.map(a => (
            <div key={a.id} style={{ background: 'var(--nl-white)', border: '1px solid var(--nl-border)',
              borderLeft: '4px solid var(--nl-leaf-600)', borderRadius: 12, padding: 18 }}>
              <Chip tone={a.theme === 'leaf' ? 'leaf' : a.theme}>{a.tag}</Chip>
              <h3 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 19, color: 'var(--nl-navy-900)', margin: '10px 0 6px' }}>{a.title}</h3>
              <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 14.5, lineHeight: 1.55, color: 'var(--nl-ink-700)', margin: 0 }}>{a.body}</p>
              {a.url && (
                <a href={a.url} target="_blank" rel="noopener" className="nl-btn nl-btn--ghost nl-btn--sm"
                  style={{ marginTop: 12, paddingLeft: 0, textDecoration: 'none' }}>
                  Learn more <Icon name="arrowRight" size={16} />
                </a>
              )}
            </div>
          ))}
        </div>
      </Screen>
    );
  }

  window.NLCommunity = { Events, EventDetail, Prayer, Bulletin };
})();
