'use client'

/**
 * OrgSwitcher — pick between Companies the current user belongs to. Useful
 * for accounts that ended up multi-company via cross-domain invitations.
 *
 * Native <select> for now. The classNames-slot API stays the same when we
 * upgrade to a dropdown menu. startsim-o7s.
 */

import * as React from 'react'
import type { CompanyLite } from './types'
import {
  ORG_SWITCHER_DEFAULTS,
  type OrgSwitcherClassNames,
} from './org-switcher-default-class-names'

export interface OrgSwitcherProps {
  companies: CompanyLite[]
  currentCompanyId?: string | null
  onSwitch: (companyId: string) => void | Promise<void>
  /** Hide the visible "Organization" label, keep only the SR-only label. */
  hideLabel?: boolean
  label?: string
  classNames?: OrgSwitcherClassNames
}

export function OrgSwitcher({
  companies,
  currentCompanyId,
  onSwitch,
  hideLabel = false,
  label = 'Organization',
  classNames,
}: OrgSwitcherProps) {
  const cls = { ...ORG_SWITCHER_DEFAULTS, ...(classNames ?? {}) }
  // If the caller hasn't pinned currentCompanyId, fall back to the first
  // entry so the <select>'s value matches an option (otherwise React warns).
  const value = currentCompanyId ?? companies[0]?.id ?? ''

  if (companies.length === 0) return null

  return (
    <span className={cls.root}>
      {!hideLabel && (
        <span className={cls.label} aria-hidden="true">
          {label}
        </span>
      )}
      <label className="sr-only" htmlFor="org-switcher-select">
        {label}
      </label>
      <select
        id="org-switcher-select"
        value={value}
        onChange={(e) => onSwitch(e.target.value)}
        className={cls.select}
        aria-label={label}
      >
        {companies.map((c) => (
          <option key={c.id} value={c.id}>
            {c.name}
          </option>
        ))}
      </select>
    </span>
  )
}
