import { ACTIVE_CLUB_STORAGE_KEY } from './api'

/** Nur Mitgliedschaften mit aktivem Vereinszugang (Backend: club_members.status). */
export function activeClubMemberships(clubs) {
  return (clubs || []).filter(
    (c) => (c.membership_status || 'active').toString().trim().toLowerCase() === 'active'
  )
}

/**
 * Einheitliche Anzeige des aktiven Vereins: Abgleich mit effective_club_id, active_club_id,
 * LocalStorage (Request-Header-Quelle), sonst erster **aktiver** Verein der Liste.
 */
export function getResolvedActiveClubIdForUi(user) {
  const clubs = activeClubMemberships(user?.clubs)
  if (!clubs.length) return null

  const idInClubs = (id) =>
    id != null &&
    id !== '' &&
    clubs.some((c) => Number(c.id) === Number(id))

  const eff = user?.effective_club_id
  if (idInClubs(eff)) return Number(eff)

  const ac = user?.active_club_id
  if (idInClubs(ac)) return Number(ac)

  try {
    const ls = localStorage.getItem(ACTIVE_CLUB_STORAGE_KEY)
    if (ls && /^\d+$/.test(ls.trim()) && clubs.some((c) => String(c.id) === ls.trim())) {
      return Number(ls.trim())
    }
  } catch {
    /* ignore */
  }

  return Number(clubs[0].id)
}
