import { useAuth } from '../context/AuthContext'
import { activeClubMemberships, getResolvedActiveClubIdForUi } from '../utils/activeClub'

/**
 * Zeigt einen Vereins-Umschalter, wenn der Nutzer mehreren Vereinen zugeordnet ist.
 * Steuert den Mandanten-Kontext (Header X-Active-Club-Id + Profilfeld active_club_id).
 */
export default function ActiveClubSwitcher({ variant = 'sidebar' }) {
  const { user, setActiveClub } = useAuth()
  const clubs = activeClubMemberships(user?.clubs)
  if (clubs.length <= 1) return null

  const selectClubId = getResolvedActiveClubIdForUi(user)

  const isMobile = variant === 'mobile'

  return (
    <label
      className={
        'active-club-switch' +
        (isMobile ? ' active-club-switch--mobile' : ' active-club-switch--sidebar')
      }
    >
      <span className="active-club-switch__label">Aktiver Verein</span>
      <select
        className="form-input active-club-switch__select"
        aria-label="Aktiven Verein wählen"
        value={selectClubId ?? ''}
        onChange={(e) => {
          const v = e.target.value
          if (v) setActiveClub(Number(v))
        }}
      >
        {clubs.map((c) => (
          <option key={c.id} value={c.id}>
            {c.name || `Verein #${c.id}`}
          </option>
        ))}
      </select>
    </label>
  )
}
