/* ============================================================
   BridgeOS — Friends tab  (in-depth friend browsing)
   ============================================================ */
function FriendCard({ profile, today, onClick }) {
  const P = window.PP;
  const stats = profileStats(profile, today);
  return (
    <button className="friend-card" onClick={onClick}>
      <Avatar profile={profile} size={52} />
      <div className="fc-body">
        <div className="fc-name">
          {profile.meta.name}
          {profile._isRealUser && (
            <span className="me-tag" style={{ marginLeft: 6, fontSize: 9, background: "color-mix(in oklch,oklch(0.82 0.13 200) 14%,transparent)", color: "oklch(0.82 0.13 200)", borderColor: "color-mix(in oklch,oklch(0.82 0.13 200) 35%,transparent)" }}>REAL</span>
          )}
        </div>
        <div className="fc-sub mono dim">Lv {stats.level} · ⚡{stats.power}{stats.streak > 0 ? ` · 🔥${stats.streak}d` : ""}</div>
        <div className="fc-bars">
          {P.CAT_ORDER.map(c => {
            const cl = P.catLevel((stats.scores && stats.scores[c]) || 0);
            return (
              <div key={c} className="fc-bar-item" style={{ "--ch": `oklch(0.82 0.15 ${P.CATS[c].hue})` }}>
                <span className="fc-bar-key mono">{c}</span>
                <div className="fc-bar-track"><div className="fc-bar-fill" style={{ width: `${cl.pct * 100}%` }} /></div>
              </div>
            );
          })}
        </div>
      </div>
      <span className="fc-arrow dim">›</span>
    </button>
  );
}

function FriendsView({ state, today, authUser, onMessage, onRefreshFriends }) {
  const [detail, setDetail] = useState(null);
  const [showAddFriend, setShowAddFriend] = useState(false);

  const seen = new Set();
  const friends = [
    ...(state.realFriends || []),
    ...state.friends.filter(f => !f._isRealUser),
  ].filter(f => { if (seen.has(f.id)) return false; seen.add(f.id); return true; });

  function handleRemove(id) {
    if (!window.Bridge || !authUser) return;
    setDetail(null);
    Bridge.removeFriend(authUser.id, id).then(function(res) {
      if (res && res.error) { console.error("[removeFriend]", res.error); return; }
      if (onRefreshFriends) onRefreshFriends(id);
    });
  }

  return (
    <div className="friends-view">
      <div className="ql-head">
        <div>
          <div className="ql-date">Friends</div>
          <div className="ql-quote">
            {friends.length} friend{friends.length !== 1 ? "s" : ""} · tap to see their full profile
          </div>
        </div>
        {authUser && (
          <button className="btn btn-sm btn-accent" onClick={() => setShowAddFriend(true)}>+ Add friend</button>
        )}
      </div>

      {friends.length === 0 ? (
        <div className="empty">
          {authUser
            ? "No friends yet — add friends to see their progress here."
            : "Sign in to connect with real friends and see their full profiles."}
        </div>
      ) : (
        <div className="friend-list">
          {friends.map(f => (
            <FriendCard key={f.id} profile={f} today={today} onClick={() => setDetail(f)} />
          ))}
        </div>
      )}

      {detail && (
        <FriendDetail
          profile={detail}
          today={today}
          mode="week"
          onClose={() => setDetail(null)}
          onMessage={onMessage}
          authUser={authUser}
          onRemoveFriend={authUser ? handleRemove : null}
        />
      )}

      {showAddFriend && authUser && (
        <AddFriendModal
          myId={authUser.id}
          onClose={() => setShowAddFriend(false)}
          onAdded={onRefreshFriends}
        />
      )}
    </div>
  );
}

Object.assign(window, { FriendsView, FriendCard });
