'use client'

/**
 * RoleSelector — headless role picker honoring the OWNER/ADMIN/MEMBER/VIEWER
 * hierarchy from @startsimpli/api.
 *
 * Native <select> for now. A Radix Select upgrade is a follow-up — the
 * classNames-slot API stays the same. startsim-o7s.
 */

import * as React from 'react'
import type { TeamRole } from './types'
import {
  ROLE_SELECTOR_DEFAULTS,
  type RoleSelectorClassNames,
} from './role-selector-default-class-names'

const ALL_ROLES: TeamRole[] = ['owner', 'admin', 'member', 'viewer']

export interface RoleSelectorProps {
  value: TeamRole
  onChange: (role: TeamRole) => void
  disabled?: boolean
  /**
   * Restrict the list of options. Defaults to OWNER/ADMIN/MEMBER/VIEWER.
   * The InviteMemberDialog hides 'owner' from this list by default since you
   * promote owners via update-role, not the invite flow.
   */
  availableRoles?: TeamRole[]
  /** Label fallback for screen readers when no <label> wraps the component. */
  ariaLabel?: string
  classNames?: RoleSelectorClassNames
}

const LABELS: Record<TeamRole, string> = {
  owner: 'Owner',
  admin: 'Admin',
  member: 'Member',
  viewer: 'Viewer',
}

export function RoleSelector({
  value,
  onChange,
  disabled,
  availableRoles = ALL_ROLES,
  ariaLabel = 'Role',
  classNames,
}: RoleSelectorProps) {
  const cls = { ...ROLE_SELECTOR_DEFAULTS, ...(classNames ?? {}) }
  return (
    <span className={cls.root}>
      <select
        aria-label={ariaLabel}
        value={value}
        disabled={disabled}
        onChange={(e) => onChange(e.target.value as TeamRole)}
        className={cls.select}
      >
        {availableRoles.map((r) => (
          <option key={r} value={r}>
            {LABELS[r]}
          </option>
        ))}
      </select>
    </span>
  )
}
