import { useNavigate, useLocation } from 'react-router-dom';
import { useLanguage } from '../contexts/LanguageContext';
import type { Language } from '../data/types';
import '../scss/language-toggle.scss';
import { useScreenReaderAnnouncements } from '../hooks/useScreenReaderAnnouncements';

/** Swap /de/ ↔ /en/ prefix (or /de/technical ↔ /en/technical) in the pathname. */
function getEquivalentPath(pathname: string, targetLang: Language): string {
  if (pathname.startsWith('/de')) return pathname.replace(/^\/de/, `/${targetLang}`);
  if (pathname.startsWith('/en')) return pathname.replace(/^\/en/, `/${targetLang}`);
  return `/${targetLang}/`;
}

export default function LanguageToggle() {
  const { language } = useLanguage();
  const { announce } = useScreenReaderAnnouncements();
  const navigate = useNavigate();
  const location = useLocation();

  const handleLanguageChange = (newLang: Language) => {
    if (newLang !== language) {
      const targetPath = getEquivalentPath(location.pathname, newLang);
      navigate(targetPath);
      announce(`Language changed to ${newLang === 'en' ? 'English' : 'Deutsch'}`);
    }
  };

  return (
    <div className="language-toggle" role="group" aria-label="Language selection">
      <button
        className={`language-toggle__button ${language === 'en' ? 'language-toggle__button--active' : ''}`}
        onClick={() => handleLanguageChange('en')}
        aria-label="Switch to English"
        aria-pressed={language === 'en'}
        type="button"
      >
        EN
      </button>
      <button
        className={`language-toggle__button ${language === 'de' ? 'language-toggle__button--active' : ''}`}
        onClick={() => handleLanguageChange('de')}
        aria-label="Zu Deutsch wechseln"
        aria-pressed={language === 'de'}
        type="button"
      >
        DE
      </button>
    </div>
  );
}
