/* The Upper Room — profile page. Renders the current user OR any member /
   ministry passed in. Reachable via the Me tab (self) or by clicking any
   name/avatar/tile across the app (openProfile in RoomContext). */
const { useContext: useProfileContext, useState: useProfileState } = React;

/* Normalize whatever was clicked (post author, suggestion, circle tile, etc.)
   into a consistent profile shape. */
function normalizeProfile(person) {
  if (!person || person.name === CURRENT_USER.name) {
    return Object.assign({}, CURRENT_USER, { isSelf: true, kind: 'person', posts: MY_POSTS });
  }
  const kind = person.kind || 'person';
  const posts = (typeof FEED_POSTS !== 'undefined' ? FEED_POSTS : []).filter((p) => p.author === person.name);
  if (kind === 'ministry') {
    return { name: person.name, kind: 'ministry', descriptor: person.descriptor || person.role || 'A Prophecy Voices community', followers: person.followers, posts, isSelf: false };
  }
  const church = person.church || person.descriptor || '';
  return {
    name: person.name,
    from: person.from || '',
    church: church,
    kind: 'person',
    headline: person.headline || (church ? 'Believer · ' + church : 'Believer in the Upper Room'),
    bio: person.bio || null,
    communities: person.church ? [{ name: person.church, kind: 'ministry', role: 'Home church' + (person.from ? ' · ' + person.from : '') }] : [],
    posts: posts,
    followers: person.followers,
    isSelf: false,
  };
}

function ProfileActions({ p, room, onNav }) {
  const guard = !room.canEngage;
  const [connected, setConnected] = useProfileState(false);
  if (p.isSelf) {
    return (
      <div className="ur-prof-actions">
        <button className="ur-prof-primary" onClick={() => onNav('home')}><Icon name="feather" size={16} />Share a word</button>
        <button className="ur-prof-ghost" onClick={room.resumeSetup}>Edit profile</button>
        <button className="ur-prof-ghost" onClick={() => room.share('your profile')}><Icon name="send" size={14} />Share profile</button>
      </div>
    );
  }
  const isMin = p.kind === 'ministry';
  return (
    <div className="ur-prof-actions">
      <button className={'ur-prof-primary' + (connected ? ' is-done' : '')} onClick={guard ? room.promptComplete : () => setConnected(!connected)}>
        <Icon name={connected ? 'check' : (isMin ? 'plus' : 'user-plus')} size={16} />
        {connected ? (isMin ? 'Following' : 'Pending') : (isMin ? 'Follow' : 'Connect')}
      </button>
      {!isMin && <button className="ur-prof-ghost" onClick={guard ? room.promptComplete : () => onNav('messages')}><Icon name="message-circle" size={15} />Message</button>}
      <button className="ur-prof-ghost" onClick={() => room.share(p.name + '’s profile')}><Icon name="send" size={14} />Share</button>
    </div>
  );
}

function ProfileHeader({ p, room, onNav }) {
  return (
    <div className="card ur-prof-card">
      <div className="ur-prof-cover"></div>
      <Avatar name={p.name} className={'ur-prof-avatar' + (p.kind === 'ministry' ? ' square' : '')} />
      {p.isSelf && <button className="ur-prof-edit" aria-label="Edit profile" onClick={room.resumeSetup}><Icon name="pencil" size={16} /></button>}
      <div className="ur-prof-body">
        <div className="ur-prof-name">{p.name} {(p.isSelf || p.kind === 'ministry') && <Icon name="badge-check" size={18} />}</div>
        <div className="ur-prof-headline">{p.kind === 'ministry' ? p.descriptor : p.headline}</div>
        {p.kind !== 'ministry' && (
          <div className="ur-prof-meta">
            {p.from && <span><Icon name="map-pin" size={14} />{p.from}</span>}
            {p.church && <span><Icon name="church" size={14} />{p.church}</span>}
          </div>
        )}
        <div className="ur-prof-stats">
          {p.isSelf ? (
            <span><b>{p.circle}</b> in your circle &nbsp;·&nbsp; <b>{p.following}</b> following &nbsp;·&nbsp; Walking with the Lord since {p.since}</span>
          ) : p.followers ? (
            <span><b>{p.followers}</b> {p.kind === 'ministry' ? 'followers' : 'in their circle'}</span>
          ) : (
            <span>In the Upper Room</span>
          )}
        </div>
        <ProfileActions p={p} room={room} onNav={onNav} />
      </div>
    </div>
  );
}

function AboutCard({ p }) {
  if (!p.bio) return null;
  return (
    <div className="card ur-prof-section">
      <div className="ur-section-title">{p.isSelf ? 'My walk' : 'Their walk'}</div>
      <p className="ur-about-text">{p.bio}</p>
    </div>
  );
}

function CommunitiesCard({ p, room }) {
  if (!p.communities || !p.communities.length) return null;
  return (
    <div className="card ur-prof-section">
      <div className="ur-section-title">Fellowships &amp; communities</div>
      {p.communities.map((c) => (
        <div className="ur-community" key={c.name} onClick={() => room.openProfile({ name: c.name, kind: 'ministry', descriptor: c.role })} style={{ cursor: 'pointer' }}>
          <Avatar name={c.name} className="square" style={{ width: 48, height: 48, fontSize: '1rem', borderRadius: 12 }} />
          <div className="ur-community-info">
            <div className="name">{c.name} <Icon name="badge-check" size={13} /></div>
            <div className="role">{c.role}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ActivityPost({ post, isSelf, room }) {
  return (
    <div className="ur-activity-post" onClick={() => room.openPost(post)} style={{ cursor: 'pointer' }}>
      <div className="ur-activity-time">{isSelf ? 'You posted' : 'Posted'} · {post.time}</div>
      <div className="ur-activity-body">{post.body}</div>
      {post.verse && (
        <span className="ur-post-verse">“{post.verse.text}”<span className="ref">{post.verse.ref}</span></span>
      )}
      <div className="ur-activity-counts"><span className="amen-dot">✓</span>{post.amens} amens &nbsp;·&nbsp; {post.comments} comments</div>
    </div>
  );
}

function ActivityCard({ p, room }) {
  return (
    <div className="card ur-prof-section">
      <div className="ur-section-title">Activity</div>
      {p.posts && p.posts.length ? (
        <React.Fragment>
          {p.posts.map((post) => <ActivityPost key={post.id} post={post} isSelf={p.isSelf} room={room} />)}
          <div className="ur-activity-all"><button onClick={() => room.search(p.name)}>Show all activity</button></div>
        </React.Fragment>
      ) : (
        <p className="ur-about-text">{p.isSelf ? 'You haven\u2019t shared a word yet.' : 'No words shared yet \u2014 but every believer has a story.'}</p>
      )}
    </div>
  );
}

function ProfilePage({ person, onNav, onBack }) {
  const room = useProfileContext(window.RoomContext);
  const p = normalizeProfile(person);
  return (
    <div className="ur-shell ur-shell-profile">
      <main className="ur-center">
        {onBack && !p.isSelf && <button className="ur-back" onClick={onBack}><Icon name="arrow-left" size={16} />Back</button>}
        <ProfileHeader p={p} room={room} onNav={onNav} />
        <AboutCard p={p} />
        <CommunitiesCard p={p} room={room} />
        <ActivityCard p={p} room={room} />
      </main>
      <RightRail />
    </div>
  );
}

/* Guest who skipped setup has no profile yet. */
function GuestProfilePrompt() {
  const room = useProfileContext(window.RoomContext);
  return (
    <div className="ur-placeholder">
      <div className="ur-placeholder-cross">✝</div>
      <h2>You don't have a profile yet</h2>
      <p>You're browsing as a guest. Set up your profile to share your walk, find your church family, and connect with believers near you.</p>
      <button className="ur-primary" onClick={room.resumeSetup}>Set up my profile</button>
    </div>
  );
}

Object.assign(window, { ProfilePage, GuestProfilePrompt });
