import { useAuth } from '../context/AuthContext'

/**
 * 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 = user?.clubs || []
  if (clubs.length <= 1) return null

  const selectClubId =
    user?.active_club_id != null && clubs.some((c) => c.id === user.active_club_id)
      ? user.active_club_id
      : clubs[0]?.id

  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>
  )
}
