// Lightweight cross-component auth/user state notifications.
// Pages call `notifyAuthChange()` after they update auth-related
// localStorage (login, signup, register, profile photo, logout) so
// that the persistent Header can immediately re-sync without a reload.

export const AUTH_CHANGE_EVENT = "auth-change";

export function notifyAuthChange() {
  if (typeof window !== "undefined") {
    window.dispatchEvent(new Event(AUTH_CHANGE_EVENT));
  }
}

// Notifies listeners (e.g. the floating chat button) whether the mobile
// header menu is currently open, so they can hide themselves behind it.
export const MOBILE_MENU_EVENT = "mobile-menu-toggle";

export function notifyMobileMenu(open: boolean) {
  if (typeof window !== "undefined") {
    window.dispatchEvent(
      new CustomEvent(MOBILE_MENU_EVENT, { detail: { open } }),
    );
  }
}

/**
 * Resolve the best available user photo URL from a user object,
 * tolerating the different field names used across the app/API.
 */
export function getUserPhoto(user: any): string {
  return (
    user?.profile_picture ||
    user?.avatar ||
    user?.profile_image ||
    user?.image ||
    ""
  );
}
