/**
 * @file LanguageSwitcher.tsx - Dropdown component allowing users to switch between supported i18next languages (e.g., English, Ukranian).
 * Displays a flag emoji alongside each language's localized display name.
 * Rendered inside the Navbar user settings dropdown and on the login page.
 */

import { type ChangeEvent, useState } from 'react';
import i18next from 'i18next';
import { fallbackLanguage, supportedLanguages } from '../i18next/config.ts';
import { FloatingLabel, Form } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';

/**
 * Language switcher dropdown that allows the user to change the application locale.
 * Reads the currently resolved language from i18next on mount and updates it when the user selects a different option.
 */
export const LanguageSwitcher = () => {
  // Store selected language in state
  const [selectedLanguage, setSelectedLanguage] = useState<string>(
    i18next.resolvedLanguage || fallbackLanguage
  );
  // Update selected language on select change
  const updateSelectedLanguage = (event: ChangeEvent<HTMLSelectElement>) => {
    const newSelectedLanguage = event.target.value;

    i18next.changeLanguage(newSelectedLanguage);
    setSelectedLanguage(newSelectedLanguage);
  };

  const { i18n, t } = useTranslation(undefined, {
    keyPrefix: 'components.language_switcher',
  });

  return (
    <FloatingLabel controlId={'language-switcher-select'} label={t('label')}>
      <Form.Select
        value={selectedLanguage}
        onChange={updateSelectedLanguage}
        className={'no-focus-transformation'}
        style={{ minWidth: '10rem' }}
      >
        {supportedLanguages.map((language) => (
          <option key={language.code} value={language.code}>
            {language.flagEmoji}{' '}
            {language.displayName(i18n.resolvedLanguage as string)}
          </option>
        ))}
      </Form.Select>
    </FloatingLabel>
  );
};
