import { cn } from '@/lib/utils'

/**
 * LanguageSwitch — segmented control для смены i18next language.
 * Замена @nstart/ui LanguageSwitch (тот же value/options/onChange API).
 *
 * <p>Compact: 3-letter codes (RU/EN/ZH...) в Tektur uppercase. Tab-like
 * underline indicator под active. На narrow screens сворачивается в icon
 * только (TODO mobile responsive).
 */

/** nstart-compat: {id, label}. `value` accepted as alias. */
export type LanguageOption = {
  id: string
  label: string
  /** Alias of `id`. */
  value?: string
  /** Short 2-3 char code (RU/EN/ZH). Default — id.toUpperCase(). */
  short?: string
}

export type LanguageSwitchProps = {
  value: string
  options: LanguageOption[]
  onChange: (id: string) => void
  className?: string
  'aria-label'?: string
}

export function LanguageSwitch({
  value,
  options,
  onChange,
  className,
  'aria-label': ariaLabel,
}: LanguageSwitchProps) {
  return (
    <div
      role="radiogroup"
      aria-label={ariaLabel ?? 'Language'}
      className={cn(
        // h-8 box to match TopBar toolbar height. Buttons fill 100% height
        // через inline-flex + items-center — никакого vertical jitter
        // от text baseline vs icon baseline.
        'inline-flex items-stretch rounded-md border border-line bg-surface h-7 overflow-hidden',
        className,
      )}
    >
      {options.map((opt) => {
        const v = opt.id ?? opt.value!
        const active = v === value
        return (
          <button
            key={v}
            type="button"
            role="radio"
            aria-checked={active}
            onClick={() => onChange(v)}
            title={opt.label}
            className={cn(
              'inline-flex items-center justify-center px-2.5 text-cap leading-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
              active
                ? 'bg-accent-bg text-accent'
                : 'text-mute hover:text-ink hover:bg-surface-2',
            )}
          >
            {/* Display priority: short → label (if compact like "RU"/"EN") →
              * uppercase id. Label predominates когда caller передал human
              * label типа "RU"/"EN" в options. */}
            {opt.short ?? opt.label ?? v.toUpperCase()}
          </button>
        )
      })}
    </div>
  )
}
