// §22.10 (M3) — the project switcher in deployment chrome (header). A plain
// <select> of the caller-visible projects; choosing one navigates to its
// `/p/<id>/` home. Rendered only when 2+ projects are visible (a single
// project needs no switcher). The current project is read from the URL.
import { useNavigate, useLocation } from 'react-router-dom'
import { useDeployment } from '../context/DeploymentProvider'

export default function ProjectSwitcher() {
  const { projects } = useDeployment()
  const navigate = useNavigate()
  // The switcher renders in deployment chrome (the header), above the route
  // tree, so it reads the active project from the path rather than useParams.
  const { pathname } = useLocation()
  const match = pathname.match(/^\/p\/([^/]+)/)
  const projectId = match ? match[1] : ''

  if (!projects || projects.length < 2) return null

  return (
    <select
      className="project-switcher"
      aria-label="Switch project"
      value={projectId || ''}
      onChange={e => navigate(`/p/${e.target.value}/`)}
    >
      {/* When not inside a project (e.g. the directory), show a neutral head. */}
      {!projectId && <option value="" disabled>Projects…</option>}
      {projects.map(p => (
        <option key={p.id} value={p.id}>{p.name}</option>
      ))}
    </select>
  )
}
