import { useEffect, useState } from 'react';
import { EventTimeline, Room, RoomStateEvent } from 'matrix-js-sdk';

// Reactive «invited + joined member count» — stays current when members
// join, leave, or are invited so the room header «N participants» line and
// any member-count-driven chrome flips immediately. Without the subscription
// the number freezes at mount-time and only refreshes on navigation.
//
// The captured `state` makes the cleanup detach from the same emitter we
// attached to (no orphan listeners). We don't try to follow re-subscription
// if matrix-js-sdk swaps the live-timeline state container while `room`
// identity is unchanged — that's a rare /sync corner case (room upgrade
// catch-up) and the count would simply go stale until the next mount.
export const useRoomMemberCount = (room: Room): number => {
  const [count, setCount] = useState<number>(() => room.getInvitedAndJoinedMemberCount());

  useEffect(() => {
    const state = room.getLiveTimeline().getState(EventTimeline.FORWARDS);
    setCount(room.getInvitedAndJoinedMemberCount());
    if (!state) return undefined;
    const handler = () => setCount(room.getInvitedAndJoinedMemberCount());
    state.on(RoomStateEvent.Members, handler);
    return () => {
      state.removeListener(RoomStateEvent.Members, handler);
    };
  }, [room]);

  return count;
};
