// @design-system: i18n/LanguageToggle
/**
 * LanguageToggle - segmented control for locale switching.
 *
 * Shows every registered locale as a button; active locale is highlighted.
 * Updates every locale subscriber synchronously without navigating.
 *
 * @example
 * <LanguageToggle />
 */

'use client';

import { cn } from '@/lib/cn';
import { useLocale, useT } from '@/lib/i18n/react';
import { LOCALES, type Locale } from '@/lib/i18n';
import { Icon } from '@/components/ui/icons/Icon';

export interface LanguageToggleProps {
  className?: string;
  /**
   * When true, renders the locale code instead of the full language
   * name. Used in the desktop navbar where horizontal space is tight.
   * aria-label still resolves to the full localized name for screen readers.
   */
  compact?: boolean;
}

export function LanguageToggle({ className, compact = false }: LanguageToggleProps) {
  const { locale, setLocale } = useLocale();
  const t = useT('i18n');

  function handleSelect(loc: Locale) {
    if (loc !== locale) setLocale(loc);
  }

  return (
    <div className={cn('language-toggle inline-flex items-center gap-1.5', className)}>
      <Icon name="Globe" size="sm" color="muted" aria-hidden />
      <div
        role="group"
        aria-label={t('language')}
        data-testid="language-toggle"
        className={cn(
          'inline-flex overflow-hidden',
          'rounded-md',
          'border-border-default border',
          'bg-surface-base',
        )}
      >
        {LOCALES.map((loc) => {
          const isActive = locale === loc;
          return (
            <button
              key={loc}
              type="button"
              aria-current={isActive ? 'true' : undefined}
              aria-label={loc === 'he' ? t('hebrew') : t('english')}
              data-locale={loc}
              data-user-content
              onClick={() => handleSelect(loc)}
              className={cn(
                compact ? 'px-2 py-1 text-xs' : 'px-3 py-1.5 text-sm',
                'font-medium',
                'transition-colors duration-[var(--duration-fast)] ease-[var(--ease-out)]',
                'focus-visible:z-[var(--z-raised)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
                isActive
                  ? 'bg-brand-primary-600 text-brand-on-primary'
                  : 'text-text-secondary hover:bg-surface-inset hover:text-text-primary bg-transparent',
              )}
            >
              {compact
                ? loc === 'he'
                  ? t('he_label')
                  : t('en_label')
                : loc === 'he'
                  ? t('hebrew')
                  : t('english')}
            </button>
          );
        })}
      </div>
    </div>
  );
}
