import { languageStore } from "@shared";
import { Button } from "@mui/material"; // Only Button is needed
import { useEffect, useCallback } from "react";
import { observer } from "mobx-react-lite";

const LANGUAGES = ["ru", "en", "zh"] as const;
type Language = (typeof LANGUAGES)[number];

export const LanguageSwitcher = observer(() => {
  const { language, setLanguage } = languageStore;

  // Memoize getLanguageLabel for consistent rendering
  const getLanguageLabel = useCallback((lang: Language) => {
    switch (lang) {
      case "ru":
        return "RU";
      case "en":
        return "EN";
      case "zh":
        return "ZH";
      default:
        return "";
    }
  }, []);

  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      // Keep Ctrl+S for language cycling
      if (event.key.toLowerCase() === "f3") {
        event.preventDefault(); // Prevent browser save dialog
        const currentIndex = LANGUAGES.indexOf(language as Language);
        const nextIndex = (currentIndex + 1) % LANGUAGES.length;
        setLanguage(LANGUAGES[nextIndex]);
      }
    };

    window.addEventListener("keydown", handleKeyPress);
    return () => {
      window.removeEventListener("keydown", handleKeyPress);
    };
  }, [language, setLanguage]); // Only language is a dependency now

  const handleLanguageChange = (lang: Language) => {
    setLanguage(lang);
  };

  return (
    <div className="fixed top-1/2  -translate-y-1/2 right-0 flex flex-col gap-2 p-4  ">
      {/* Added some styling for better visualization */}
      {LANGUAGES.map((lang) => (
        <Button
          key={lang}
          onClick={() => handleLanguageChange(lang)}
          variant={language === lang ? "contained" : "outlined"} // Highlight the active language
          color="primary"
          sx={{ minWidth: "60px" }} // Give buttons a consistent width
        >
          {getLanguageLabel(lang)}
        </Button>
      ))}
    </div>
  );
});
