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;

  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-0 left-1/2 -translate-x-1/2 flex gap-2 p-4 z-100000">
      {/* Added some styling for better visualization */}
      {LANGUAGES.map((lang) => (
        <Button
          key={lang}
          onClick={() => handleLanguageChange(lang)}
          variant={"contained"} // Highlight the active language
          color={language === lang ? "primary" : "inherit"}
          sx={{ minWidth: "60px" }} // Give buttons a consistent width
        >
          {getLanguageLabel(lang)}
        </Button>
      ))}
    </div>
  );
});
