/* The Upper Room — secondary screens that close the dead-ends:
   Search, Saved words, Prayer wall, Settings, and the legal pages
   (Community Covenant / Privacy / Terms). Plus the Share sheet modal.
   Each is reachable through RoomContext (goView / search / share / signOut). */
const { useState: useExtraState, useContext: useExtraContext } = React;

/* Resolve a post id (from SAVED_WORDS / alerts) back to the full post. */
function findPost(id) {
  const all = (typeof FEED_POSTS !== 'undefined' ? FEED_POSTS : []).concat(typeof MY_POSTS !== 'undefined' ? MY_POSTS : []);
  return all.filter((p) => p.id === id)[0] || null;
}

/* ── Share sheet ── a lightweight share modal used everywhere a Share /
   Share profile button lives. Copy-link gives real feedback in the demo. */
function ShareSheet({ subject, onClose }) {
  const [copied, setCopied] = useExtraState(false);
  const channels = [
    { icon: 'message-circle', label: 'Send in a message' },
    { icon: 'users', label: 'Share to your circle' },
    { icon: 'hand-heart', label: 'Add to the prayer wall' },
  ];
  return (
    <div className="ur-modal-scrim ur-sheet-scrim" onClick={onClose}>
      <div className="ur-sheet" onClick={(e) => e.stopPropagation()}>
        <div className="ur-sheet-grip"></div>
        <div className="ur-sheet-title">Share {subject || 'this'}</div>
        <div className="ur-sheet-list">
          {channels.map((c) => (
            <button key={c.label} className="ur-sheet-row" onClick={onClose}>
              <span className="ur-sheet-ic"><Icon name={c.icon} size={18} /></span>{c.label}
            </button>
          ))}
          <button className="ur-sheet-row" onClick={() => { setCopied(true); }}>
            <span className="ur-sheet-ic"><Icon name={copied ? 'check' : 'link'} size={18} /></span>
            {copied ? 'Link copied' : 'Copy link'}
          </button>
        </div>
        <button className="ur-sheet-cancel" onClick={onClose}>Cancel</button>
      </div>
    </div>
  );
}

/* ── Search results ── matches one query across people, ministries,
   churches, and shared words. */
function SearchPage({ query }) {
  const room = useExtraContext(window.RoomContext);
  const idx = React.useMemo(() => buildSearchIndex(), []);
  const q = (query || '').trim().toLowerCase();
  const has = (s) => (s || '').toLowerCase().indexOf(q) !== -1;

  if (!q) {
    return (
      <div className="ur-shell ur-shell-solo">
        <main className="ur-center">
          <div className="ur-search-empty">
            <Icon name="search" size={32} />
            <h2>Search the Upper Room</h2>
            <p>Find believers, ministries, churches near you, and words shared in the room.</p>
          </div>
        </main>
      </div>
    );
  }

  const people = idx.people.filter((p) => has(p.name) || has(p.from) || has(p.church));
  const ministries = idx.ministries.filter((m) => has(m.name) || has(m.descriptor));
  const churches = idx.churches.filter((c) => has(c.name) || has(c.from));
  const words = idx.words.filter((w) => has(w.body) || has(w.author) || (w.verse && (has(w.verse.text) || has(w.verse.ref))));
  const total = people.length + ministries.length + churches.length + words.length;

  return (
    <div className="ur-shell ur-shell-solo">
      <main className="ur-center">
        <div className="ur-results-head">
          <b>{total}</b> {total === 1 ? 'result' : 'results'} for “{query}”
        </div>

        {!total && (
          <div className="card ur-search-empty small">
            <p>No matches yet. Try a name, a city, or a church.</p>
          </div>
        )}

        {!!people.length && (
          <div className="card ur-result-group">
            <div className="ur-section-title">Believers</div>
            {people.map((p) => (
              <div className="ur-result-row" key={'p' + p.name} onClick={() => room.openProfile(p)}>
                <Avatar name={p.name} />
                <div className="ur-result-info"><div className="name">{p.name}</div><div className="meta">{[p.from, p.church].filter(Boolean).join(' · ')}</div></div>
                <Icon name="chevron-right" size={16} />
              </div>
            ))}
          </div>
        )}

        {!!ministries.length && (
          <div className="card ur-result-group">
            <div className="ur-section-title">Voices &amp; ministries</div>
            {ministries.map((m) => (
              <div className="ur-result-row" key={'m' + m.name} onClick={() => room.openProfile({ name: m.name, kind: 'ministry', descriptor: m.descriptor, followers: m.followers })}>
                <Avatar name={m.name} className="square" />
                <div className="ur-result-info"><div className="name">{m.name} <Icon name="badge-check" size={13} /></div><div className="meta">{m.descriptor}</div></div>
                <Icon name="chevron-right" size={16} />
              </div>
            ))}
          </div>
        )}

        {!!churches.length && (
          <div className="card ur-result-group">
            <div className="ur-section-title">Churches near you</div>
            {churches.map((c) => (
              <div className="ur-result-row" key={'c' + c.name} onClick={() => room.goView('gatherings')}>
                <Avatar name={c.name} className="square" />
                <div className="ur-result-info"><div className="name">{c.name}</div><div className="meta">{c.from}</div></div>
                <Icon name="chevron-right" size={16} />
              </div>
            ))}
          </div>
        )}

        {!!words.length && (
          <div className="card ur-result-group">
            <div className="ur-section-title">Words shared</div>
            {words.map((w) => (
              <div className="ur-result-word" key={'w' + w.id} onClick={() => room.openPost(w)}>
                <div className="meta">{w.author} · {w.time}</div>
                <div className="ur-result-snippet">{w.body.slice(0, 140)}{w.body.length > 140 ? '…' : ''}</div>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}

/* ── Saved words ── the member's bookmarked posts, each with their note. */
function SavedWordsPage() {
  const room = useExtraContext(window.RoomContext);
  const saved = (typeof SAVED_WORDS !== 'undefined' ? SAVED_WORDS : []).map((s) => ({ note: s.note, post: findPost(s.id) })).filter((s) => s.post);
  return (
    <div className="ur-shell ur-shell-solo">
      <main className="ur-center">
        <div className="ur-page-head"><Icon name="bookmark" size={20} /><h2>Saved words</h2></div>
        <p className="ur-page-sub">Words you’ve set aside to come back to, pray over, or weigh against Scripture.</p>
        {saved.length ? saved.map((s, i) => (
          <article className="card ur-saved" key={i}>
            {s.note && <div className="ur-saved-note"><Icon name="bookmark" size={13} />{s.note}</div>}
            <div className="ur-saved-author" onClick={() => room.openProfile({ name: s.post.author, from: s.post.from, church: s.post.church })}>
              <Avatar name={s.post.author} style={{ width: 36, height: 36, fontSize: '0.8rem' }} />
              <div><div className="name">{s.post.author}</div><div className="meta">{s.post.time}</div></div>
            </div>
            <div className="ur-saved-body" onClick={() => room.openPost(s.post)}>{s.post.body}</div>
            {s.post.verse && <span className="ur-post-verse">“{s.post.verse.text}”<span className="ref">{s.post.verse.ref}</span></span>}
          </article>
        )) : (
          <div className="card ur-search-empty small"><p>You haven’t saved any words yet. Tap the bookmark on a word to keep it here.</p></div>
        )}
      </main>
    </div>
  );
}

/* ── Prayer wall ── requests laid down for the room to carry. */
function PrayerRow({ pr }) {
  const room = useExtraContext(window.RoomContext);
  const guard = !room.canEngage;
  const [praying, setPraying] = useExtraState(false);
  const count = pr.praying + (praying ? 1 : 0);
  return (
    <article className={'card ur-prayer' + (pr.urgent ? ' urgent' : '') + (pr.answered ? ' answered' : '')}>
      {pr.urgent && !pr.answered && <div className="ur-prayer-flag">Urgent</div>}
      {pr.answered && <div className="ur-prayer-flag answered"><Icon name="check" size={12} />Answered · Praise</div>}
      <div className="ur-prayer-head" onClick={() => room.openProfile({ name: pr.name, from: pr.from, church: pr.church })}>
        <Avatar name={pr.name} />
        <div><div className="name">{pr.name}</div><div className="meta">{pr.from} · {pr.time}</div></div>
      </div>
      <div className="ur-prayer-text">{pr.text}</div>
      <div className="ur-prayer-bar">
        <button className={'ur-pray-btn' + (praying ? ' active' : '')} onClick={guard ? room.promptComplete : () => setPraying(!praying)}>
          <Icon name="hand-heart" size={16} fill={praying ? 'currentColor' : undefined} />{praying ? 'Praying' : 'I’m praying'}
        </button>
        <span className="ur-pray-count">{count} praying</span>
      </div>
    </article>
  );
}

function PrayerWallPage() {
  const room = useExtraContext(window.RoomContext);
  const guard = !room.canEngage;
  const list = (typeof PRAYER_WALL !== 'undefined' ? PRAYER_WALL : []);
  return (
    <div className="ur-shell ur-shell-solo">
      <main className="ur-center">
        <div className="ur-page-head"><Icon name="hand-heart" size={20} /><h2>Prayer wall</h2></div>
        <p className="ur-page-sub">Requests the room is carrying together. Tap to stand with a believer in prayer.</p>
        <button className="card ur-prayer-compose" onClick={guard ? room.promptComplete : room.openCompose}>
          <Avatar name={CURRENT_USER.name} style={{ width: 38, height: 38, fontSize: '0.82rem' }} />
          <span>{guard ? 'Complete your profile to ask for prayer…' : 'Ask the room to pray with you…'}</span>
        </button>
        {list.map((pr) => <PrayerRow key={pr.id} pr={pr} />)}
        <div className="ur-foot-note">“Carry each other’s burdens.” · Galatians 6:2</div>
      </main>
    </div>
  );
}

/* ── Settings ── reachable from the Me menu. Toggles are local-only for the
   demo; Sign out returns to the welcome screen. */
function ToggleRow({ label, sub, on, onToggle }) {
  return (
    <button className="ur-set-row" onClick={onToggle}>
      <div className="ur-set-text"><div className="label">{label}</div>{sub && <div className="sub">{sub}</div>}</div>
      <span className={'ur-switch' + (on ? ' on' : '')}><span className="knob"></span></span>
    </button>
  );
}

function SettingsPage() {
  const room = useExtraContext(window.RoomContext);
  const [notif, setNotif] = useExtraState(true);
  const [email, setEmail] = useExtraState(false);
  const [discover, setDiscover] = useExtraState(true);
  return (
    <div className="ur-shell ur-shell-solo">
      <main className="ur-center">
        <div className="ur-page-head"><Icon name="settings" size={20} /><h2>Settings</h2></div>

        <div className="card ur-prof-section">
          <div className="ur-section-title">Account</div>
          <button className="ur-set-link" onClick={room.resumeSetup}><Icon name="user" size={16} />Edit profile<Icon name="chevron-right" size={15} /></button>
          <button className="ur-set-link" onClick={() => room.goView('saved')}><Icon name="bookmark" size={16} />Saved words<Icon name="chevron-right" size={15} /></button>
        </div>

        <div className="card ur-prof-section">
          <div className="ur-section-title">Notifications</div>
          <ToggleRow label="Push notifications" sub="Amens, comments, prayers, and invites" on={notif} onToggle={() => setNotif(!notif)} />
          <ToggleRow label="Weekly word email" sub="The prophetic word from Prophecy Voices" on={email} onToggle={() => setEmail(!email)} />
        </div>

        <div className="card ur-prof-section">
          <div className="ur-section-title">Privacy</div>
          <ToggleRow label="Let believers near me find me" sub="Used for “believers near you” suggestions" on={discover} onToggle={() => setDiscover(!discover)} />
        </div>

        <div className="card ur-prof-section">
          <div className="ur-section-title">About</div>
          <button className="ur-set-link" onClick={() => room.goView('legal-covenant')}><Icon name="scroll" size={16} />Community Covenant<Icon name="chevron-right" size={15} /></button>
          <button className="ur-set-link" onClick={() => room.goView('legal-privacy')}><Icon name="lock" size={16} />Privacy Policy<Icon name="chevron-right" size={15} /></button>
          <button className="ur-set-link" onClick={() => room.goView('legal-terms')}><Icon name="file-text" size={16} />Terms of Use<Icon name="chevron-right" size={15} /></button>
        </div>

        <div className="card ur-prof-section">
          <div className="ur-section-title">Danger zone</div>
          <button className="ur-set-link ur-danger" onClick={() => {
            if (!window.confirm('Delete your account?\n\nThis erases everything you have shared — posts, prayers, messages, connections, and your profile. It cannot be undone.')) return;
            fetch('/api/account', { method: 'DELETE', credentials: 'same-origin' })
              .catch(() => {})
              .finally(() => { room.signOut(); });
          }}><Icon name="trash-2" size={16} />Delete my account<Icon name="chevron-right" size={15} /></button>
        </div>

        <button className="ur-signout" onClick={room.signOut}><Icon name="log-out" size={16} />Sign out</button>
        <div className="ur-foot-note">The Upper Room · A Prophecy Voices community</div>
      </main>
    </div>
  );
}

/* ── Legal pages ── Community Covenant / Privacy / Terms. Real, readable
   copy so the auth-screen and settings links no longer dead-end at "#". */
const LEGAL = {
  'legal-covenant': {
    icon: 'scroll', title: 'Community Covenant',
    intro: 'The Upper Room is a gathering place, not a stage. By joining, you agree to keep it a safe space where believers can share, weigh, and grow together.',
    sections: [
      ['Gather in good faith', 'Speak honestly and humbly. Share what you sense the Lord is saying, and hold it loosely enough to be weighed by Scripture and by the room.'],
      ['Weigh everything', 'Prophetic words are tested, not blindly received. “Do not treat prophecies with contempt but test them all; hold on to what is good.” (1 Thess. 5:20–21)'],
      ['Honor one another', 'No harassment, slander, or tearing down. Disagree with grace. Every person here bears the image of God.'],
      ['Guard the vulnerable', 'No predatory behavior, solicitation, or exploitation. Protect newcomers and those who are hurting.'],
      ['Keep it the Word', 'This is not a marketplace for fear, manipulation, or financial schemes dressed as faith. Point people to Christ.'],
    ],
    foot: 'Breaking this covenant may lead to a word of correction, a temporary pause, or removal from the room.',
  },
  'legal-privacy': {
    icon: 'lock', title: 'Privacy Policy',
    intro: 'We collect only what we need to help believers find and encourage one another, and we never sell your information.',
    sections: [
      ['What we collect', 'Your name, where you’re from, the church you attend, your “walk” bio, and the words, prayers, and reactions you choose to share.'],
      ['How we use it', 'To build your profile, suggest believers near you, group you with your church community, and surface gatherings you might join.'],
      ['What we never do', 'We never sell your data, and we never spam you. You control your notification and discovery settings at any time.'],
      ['Your church field', 'The church you enter helps us connect you to a local community and its gatherings. You can edit or remove it whenever you like.'],
      ['Your control', 'You can edit your profile, turn off discovery, or sign out at any time. Contact us to request deletion of your account and data.'],
    ],
    foot: 'Questions about your privacy? Reach the Prophecy Voices team any time.',
  },
  'legal-terms': {
    icon: 'file-text', title: 'Terms of Use',
    intro: 'By using The Upper Room you agree to these terms and to the Community Covenant.',
    sections: [
      ['Who can join', 'You must be old enough to consent under your local law and provide accurate information about yourself.'],
      ['Your content', 'You keep ownership of the words you share. By posting, you give us permission to display them within the community.'],
      ['Acceptable use', 'Use the room for its purpose — fellowship, encouragement, and weighing the Word. Don’t abuse, impersonate, or disrupt it.'],
      ['No spiritual guarantee', 'The Upper Room is a community tool. Words shared here are to be tested by Scripture and trusted counsel, not treated as infallible.'],
      ['Changes', 'We may update these terms as the community grows. We’ll let you know when something material changes.'],
    ],
    foot: 'Continued use of The Upper Room means you accept the current terms.',
  },
};

function LegalPage({ view, onBack }) {
  const doc = LEGAL[view] || LEGAL['legal-covenant'];
  return (
    <div className="ur-shell ur-shell-solo">
      <main className="ur-center">
        {onBack && <button className="ur-back" onClick={onBack}><Icon name="arrow-left" size={16} />Back</button>}
        <div className="card ur-legal">
          <div className="ur-legal-head"><Icon name={doc.icon} size={22} /><h2>{doc.title}</h2></div>
          <p className="ur-legal-intro">{doc.intro}</p>
          {doc.sections.map((s, i) => (
            <div className="ur-legal-section" key={i}>
              <h3>{s[0]}</h3>
              <p>{s[1]}</p>
            </div>
          ))}
          <p className="ur-legal-foot">{doc.foot}</p>
          <div className="ur-legal-links">
            <button onClick={() => onBack && onBack()}>Back to the room</button>
          </div>
        </div>
        <div className="ur-foot-note">The Upper Room · A Prophecy Voices community</div>
      </main>
    </div>
  );
}

Object.assign(window, { ShareSheet, SearchPage, SavedWordsPage, PrayerWallPage, SettingsPage, LegalPage });
