import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSwitcher = () => {
  const { i18n } = useTranslation();

  const namespaces = useMemo(() => {
    return Array.isArray(i18n.options.ns)
      ? (i18n.options.ns as string[])
      : typeof i18n.options.ns === 'string'
        ? [i18n.options.ns]
        : ['common'];
  }, [i18n]);

  const didPreloadRef = useRef(false);

  const [selected, setSelected] = useState((i18n.language || 'de').slice(0, 2));

  useEffect(() => {
    setSelected((i18n.language || 'de').slice(0, 2));
  }, [i18n.language]);

  useEffect(() => {
    void i18n.loadLanguages(['de', 'pl']);
  }, [i18n]);

  useEffect(() => {
    if (didPreloadRef.current) return;
    didPreloadRef.current = true;

    void i18n.loadNamespaces(namespaces);
    void i18n.reloadResources(['de', 'pl'], namespaces);
  }, [i18n, namespaces]);

  const changeLanguage = (lng: string) => {
    setSelected(lng);
    localStorage.setItem('i18nextLng', lng);
    void i18n.changeLanguage(lng);
  };

  const current = selected;

  const baseBtn =
    'inline-flex items-center gap-2 h-9 px-3 rounded-full border border-gray-200 bg-white text-sm font-semibold';

  const activeBtn = 'text-gray-900 border-gray-400 ring-1 ring-gray-300';
  const inactiveBtn = 'text-gray-700 hover:bg-gray-50 hover:text-gray-900';

  return (
    <div className="flex items-center gap-2">
      <button
        type="button"
        onClick={() => changeLanguage('de')}
        className={`${baseBtn} ${current === 'de' ? activeBtn : inactiveBtn}`}
        aria-pressed={current === 'de'}
      >
        <span aria-hidden="true">🇩🇪</span>
        <span>DE</span>
      </button>

      <button
        type="button"
        onClick={() => changeLanguage('pl')}
        className={`${baseBtn} ${current === 'pl' ? activeBtn : inactiveBtn}`}
        aria-pressed={current === 'pl'}
      >
        <span aria-hidden="true">🇵🇱</span>
        <span>PL</span>
      </button>
    </div>
  );
};

export default LanguageSwitcher;
