import "../../styles/SideMenu.css";
import AppealWidget from "../widgets/AppealWidget";
import { useEffect, useState, useCallback, useRef } from "react";
import { observer } from "mobx-react-lite";
import sideMenuPhoto from "/side-menu-photo.png";
import RouteWidget from "../widgets/RouteWidget";
import ContentAPI from "../../api/content/content.api";
import { useGeolocationStore, useColorStore } from "../../stores";
import "../../styles/LeftWidget.css";
import SightsList from "./SightsList";
import StationsList from "./StationsList";
import LeftWidget from "./LeftWidget";
import { apiStore } from "../../api/ApiStore/store";
import { getMediaUrl } from "../../api/apiConfig";
import defaultCrest from "../../assets/images/Герб.png";

const SideMenu = observer(({ onMenuToggle }) => {
  const {
    carrier,
    city,
    route,
    getArticle,
    sightArticles,
    sightArticlesEn,
    sightArticlesZh,
    routeSights,
    routeSightsEn,
    routeSightsZh,
  } = apiStore;
  const [isMenuOpen, openMenu] = useState(false);
  const [isSightsOpen, openSights] = useState(false);
  const [isStationOpen, openStation] = useState(false);
  const [isWidgetOpen, openWidget] = useState(false);
  const [isWeatherVisible, setIsWeatherVisible] = useState(true);
  const [isLeftWidgetVisible, setIsLeftWidgetVisible] = useState(false);
  const [localSelectedSightId, setLocalSelectedSightId] = useState(null);
  const [isSightsAnimating, setIsSightsAnimating] = useState(false);
  const [isStationAnimating, setIsStationAnimating] = useState(false);
  const [shouldRenderSights, setShouldRenderSights] = useState(false);
  const [shouldRenderStation, setShouldRenderStation] = useState(false);
  const [sightTop, setSightTop] = useState(null);
  const isSortingChangingRef = useRef(false);

  const store = useGeolocationStore();
  const { setIsGovernorWidgetOpen, sortingBy, setSortingBy } = store;
  const colorStore = useColorStore();
  const { currentColor, startColorAnimation } = colorStore;
  const {
    contextData,
    isGovernorWidgetOpen,
    isLoading: isGeolocationLoading,
    selectedLanguage,
    setSelectedLanguage,
    setIsLeftWidgetOpen,
    nearestSightId,
    selectedSightId,
    isManualSelection,
    setSelectedSightId,
    setIsManualSelection,
    setIsRightWidgetSelectorOpen,
    isLeftWidgetOpen,
  } = store;

  const sideMenuRef = useRef(null);
  const sightsListRef = useRef(null);
  const stationsListRef = useRef(null);
  const activeTouches = useRef(new Map());

  // Запуск анимации цвета при монтировании компонента
  useEffect(() => {
    startColorAnimation();
  }, [startColorAnimation]);

  useEffect(() => {
    const menuContainer = sideMenuRef.current;
    if (!menuContainer) return;

    const SCROLL_THRESHOLD = 10;

    const handleTouchStart = (e) => {
      const sightsContainer = sightsListRef.current;
      const stationsContainer = stationsListRef.current;

      for (const touch of e.changedTouches) {
        let scrollTarget = null;
        const targetElement = document.elementFromPoint(
          touch.clientX,
          touch.clientY
        );

        // Определяем, над каким из скролл-контейнеров находится палец
        if (sightsContainer && sightsContainer.contains(targetElement)) {
          scrollTarget = sightsContainer;
        } else if (
          stationsContainer &&
          stationsContainer.contains(targetElement)
        ) {
          scrollTarget = stationsContainer;
        }

        if (scrollTarget) {
          activeTouches.current.set(touch.identifier, {
            target: scrollTarget,
            startY: touch.clientY,
            lastY: touch.clientY,
            isScrolling: false, // Флаг, что скролл еще не начался
          });
        }
      }
    };

    const handleTouchMove = (e) => {
      for (const touch of e.changedTouches) {
        const activeTouch = activeTouches.current.get(touch.identifier);
        if (activeTouch) {
          const deltaY = touch.clientY - activeTouch.startY;

          if (!activeTouch.isScrolling && Math.abs(deltaY) > SCROLL_THRESHOLD) {
            activeTouch.isScrolling = true;
          }

          if (activeTouch.isScrolling) {
            e.preventDefault(); // Предотвращаем стандартное поведение только при скролле
            const moveDelta = touch.clientY - activeTouch.lastY;
            activeTouch.target.scrollTop -= moveDelta;
            activeTouch.lastY = touch.clientY;
          }
        }
      }
    };

    const handleTouchEnd = (e) => {
      for (const touch of e.changedTouches) {
        activeTouches.current.delete(touch.identifier);
      }
    };

    menuContainer.addEventListener("touchstart", handleTouchStart, {
      passive: true,
    });
    menuContainer.addEventListener("touchmove", handleTouchMove, {
      passive: false,
    });
    menuContainer.addEventListener("touchend", handleTouchEnd, {
      passive: true,
    });
    menuContainer.addEventListener("touchcancel", handleTouchEnd, {
      passive: true,
    });

    return () => {
      menuContainer.removeEventListener("touchstart", handleTouchStart);
      menuContainer.removeEventListener("touchmove", handleTouchMove);
      menuContainer.removeEventListener("touchend", handleTouchEnd);
      menuContainer.removeEventListener("touchcancel", handleTouchEnd);
    };
  }, [isSightsOpen, isStationOpen]); // Перезапускаем эффект, когда списки появляются/исчезают
  // --- КОНЕЦ: Улучшенная логика ---

  useEffect(() => {
    if (isGovernorWidgetOpen) {
      openWidget(true);
    } else {
      openWidget(false);
    }
  }, [isGovernorWidgetOpen]);

  useEffect(() => {
    setIsLeftWidgetVisible(isMenuOpen && isLeftWidgetOpen);
  }, [isMenuOpen, isLeftWidgetOpen]);

  useEffect(() => {}, [
    localSelectedSightId,
    sightTop,
    isLeftWidgetVisible,
    isLeftWidgetOpen,
    isMenuOpen,
  ]);

  useEffect(() => {
    if (isLeftWidgetVisible) {
      setIsWeatherVisible(false);
    } else {
      setIsWeatherVisible(true);
    }
  }, [isLeftWidgetVisible]);

  const [designData, setDesignData] = useState(null);
  const [routeData, setRouteData] = useState(null);
  const [isLangMenuOpen, setIsLangMenuOpen] = useState(false);

  useEffect(() => {
    async function fetchCarrierAndCrest() {
      try {
        const carrierPath = carrier.logo ? getMediaUrl(carrier.logo) : null;
        const cityPath = city.arms ? getMediaUrl(city.arms) : null;

        const response = {
          carrierPath: carrierPath,
          creastPath: cityPath,
        };
        setDesignData(response);
      } catch (err) {
        console.error("Ошибка в получении данных герба и перевозчика:", err);
      }
    }
    fetchCarrierAndCrest();
  }, [contextData?.routeId, isGeolocationLoading, selectedLanguage]);

  useEffect(() => {
    if (isGeolocationLoading || !contextData?.routeId) {
      return;
    }
    async function fetchRoutePathData() {
      try {
        setRouteData(route);
      } catch (err) {
        console.error("Ошибка в получении данных маршрута:", err);
      }
    }
    fetchRoutePathData();
  }, [contextData?.routeId, isGeolocationLoading, selectedLanguage]);

  useEffect(() => {
    const fetchArticles = async () => {
      if (route && route?.governor_appeal > 0) {
        await getArticle(route?.governor_appeal, "ru");
        await getArticle(route?.governor_appeal, "en");
        await getArticle(route?.governor_appeal, "zh");
      }
    };
    fetchArticles();
  }, [route, route?.governor_appeal]);

  const handleLanguageChange = (langCode) => {
    setSelectedLanguage(langCode);
    setIsLangMenuOpen(false);
  };

  const handleMenuToggle = (newMenuState) => {
    openWidget(false);
    store.closeGovernorModal();
    if (onMenuToggle) onMenuToggle(newMenuState);
    if (newMenuState) {
      openMenu(newMenuState);
    } else {
      setIsLeftWidgetVisible(false);
      // Закрываем списки мгновенно
      if (isSightsOpen) {
        openSights(false);
        setLocalSelectedSightId(null);
        setSightTop(null);
        setIsSightsAnimating(false);
        setShouldRenderSights(false);
      }
      if (isStationOpen) {
        openStation(false);
        setIsStationAnimating(false);
        setShouldRenderStation(false);
      }
      openMenu(newMenuState);
      setIsLeftWidgetOpen(false);
    }
  };

  const isMenuOpenRef = useRef(isMenuOpen);
  const handleMenuToggleRef = useRef(handleMenuToggle);
  useEffect(() => { isMenuOpenRef.current = isMenuOpen; }, [isMenuOpen]);
  useEffect(() => { handleMenuToggleRef.current = handleMenuToggle; });

  useEffect(() => {
    // Автоматическое закрытие сайд-меню после 60 секунд бездействия
    let idleSeconds = 0;

    const checkIdle = () => {
      idleSeconds += 1;

      if (idleSeconds >= 60 && isMenuOpenRef.current) {
        handleMenuToggleRef.current(false);
      }
    };

    const intervalId = setInterval(checkIdle, 1000);

    const resetIdle = () => {
      idleSeconds = 0;
    };

    const events = [
      "mousedown",
      "mousemove",
      "keypress",
      "scroll",
      "touchstart",
      "click",
    ];

    events.forEach((event) => {
      window.addEventListener(event, resetIdle, { passive: true });
    });

    return () => {
      clearInterval(intervalId);
      events.forEach((event) => {
        window.removeEventListener(event, resetIdle);
      });
    };
  }, []);

  // Закрываем и открываем список достопримечательностей при изменении сортировки
  const prevSortingByRef = useRef(sortingBy);
  const isFirstRenderRef = useRef(true);
  useEffect(() => {
    // Пропускаем первый рендер
    if (isFirstRenderRef.current) {
      isFirstRenderRef.current = false;
      prevSortingByRef.current = sortingBy;
      return;
    }

    // Если список достопримечательностей открыт и сортировка изменилась, закрываем и открываем заново
    if (isSightsOpen && prevSortingByRef.current !== sortingBy) {
      // Блокируем обновление позиции виджета во время процесса
      isSortingChangingRef.current = true;

      setIsSightsAnimating(true);
      openSights(false);

      setTimeout(() => {
        setIsSightsAnimating(false);
        setShouldRenderSights(false);

        // Открываем список заново
        setShouldRenderSights(true);
        setTimeout(() => {
          openSights(true);
          // Разблокируем обновление позиции после полного открытия
          setTimeout(() => {
            isSortingChangingRef.current = false;
          }, 350);
        }, 10);
      }, 300);
    }

    prevSortingByRef.current = sortingBy;
  }, [sortingBy, isSightsOpen]);

  return (
    <div
      className="widget-layer"
      style={{
        zIndex: 10000000,
        transition: "transform 0.3s ease",
        transform: isMenuOpen ? "translateX(0)" : "translateX(-300px)",
      }}
    >
      <div
        className="side-menu"
        ref={sideMenuRef}
        style={{
          zIndex: 1000,
          pointerEvents: "auto",
          background:
            isSightsOpen || isStationOpen
              ? `linear-gradient(to bottom right, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 100%), rgba(var(--carrier-left-rgb, 76, 175, 75), 0.4)`
              : undefined,
          backdropFilter:
            isSightsOpen || isStationOpen ? "blur(10px)" : undefined,
          boxShadow:
            isSightsOpen || isStationOpen
              ? "0 0 0 1px rgba(255, 255, 255, 0.3) inset, 4px 4px 12px 0 rgba(255, 255, 255, 0.12) inset"
              : undefined,
          transition:
            "background 0.3s ease, backdrop-filter 0.3s ease, box-shadow 0.3s ease",
        }}
      >
        <img
          className="side-menu-crest"
          src={designData?.creastPath || defaultCrest}
          alt="Герб"
        />
        {carrier?.slogan && (
          <div className="side-menu-label">{carrier.slogan}</div>
        )}
        {shouldRenderSights && (
          <SightsList
            ref={sightsListRef}
            className={isSightsOpen ? "slide-in" : "slide-out"}
            onCloseSights={() => {
              setIsSightsAnimating(true);
              openSights(false);
              setIsLeftWidgetVisible(false);
              setTimeout(() => {
                setIsLeftWidgetOpen(false);
                setIsSightsAnimating(false);
                setShouldRenderSights(false);
              }, 300);
            }}
            setWeatherVisible={setIsWeatherVisible}
            setLocalSelectedSightId={setLocalSelectedSightId}
            localSelectedSightId={localSelectedSightId}
            onSightTopChange={(top) => {
              // Не обновляем позицию виджета во время смены сортировки
              if (isSortingChangingRef.current) {
                return;
              }
              setSightTop(top);
            }}
            onSightSelected={(sightId) => {
              // Обработка выбора достопримечательности уже в компоненте
            }}
          />
        )}
        {shouldRenderStation && (
          <StationsList
            ref={stationsListRef}
            className={isStationOpen ? "slide-in" : "slide-out"}
            setWeatherVisible={setIsWeatherVisible}
            onCloseStation={() => {
              setIsStationAnimating(true);
              openStation(false);
              setIsLeftWidgetVisible(false);
              setTimeout(() => {
                setIsLeftWidgetOpen(false);
                setIsStationAnimating(false);
                setShouldRenderStation(false);
                setIsWeatherVisible(true);
              }, 300);
            }}
            onStationSelected={(stationId) => {
              // Обработка выбора остановки уже в компоненте
            }}
            onSightClick={(sightId, top) => {
              setLocalSelectedSightId(sightId);
              if (top !== undefined) {
                setSightTop(top);
              }
              setIsLeftWidgetOpen(true);
            }}
          />
        )}
        {route?.governor_appeal > 0 && (
          <div
            onPointerUp={() => {
              openWidget(!isWidgetOpen);
              store.setIsGovernorWidgetOpen(!isWidgetOpen);
            }}
            className="appeal-button"
          >
            {selectedLanguage == "ru"
              ? "Обращение губернатора"
              : selectedLanguage == "zh"
              ? "州长致辞"
              : "Governor's appeal"}
          </div>
        )}
        <div className="side-menu-buttons" style={{ marginTop: route?.governor_appeal > 0 ? '40px' : '260px' }}>
          <div
            onPointerUp={() => {
              if (!isSightsOpen) {
                if (isStationOpen) {
                  setIsStationAnimating(true);
                  openStation(false);
                  setTimeout(() => {
                    setIsStationAnimating(false);
                    setShouldRenderStation(false);

                    setLocalSelectedSightId(null);
                    setSightTop(null);
                    setShouldRenderSights(true);
                    setTimeout(() => {
                      openSights(true);
                    }, 10);
                  }, 300);
                } else {
                  setLocalSelectedSightId(null);
                  setSightTop(null);
                  setShouldRenderSights(true);
                  setTimeout(() => {
                    openSights(true);
                  }, 10);
                }
                openWidget(false);
                store.closeGovernorModal();
                setIsLeftWidgetOpen(false);
              } else {
                setIsSightsAnimating(true);
                openSights(false);
                setIsLeftWidgetVisible(false);
                setLocalSelectedSightId(null);
                setSightTop(null);
                setTimeout(() => {
                  setIsLeftWidgetOpen(false);
                  setIsSightsAnimating(false);
                  setShouldRenderSights(false);
                }, 300);
              }
            }}
            className={`side-menu-button ${
              isSightsOpen ? "side-menu-button--active" : ""
            }`}
          >
            {selectedLanguage == "ru"
              ? "Достопримечательности"
              : selectedLanguage == "zh"
              ? "景点"
              : "Attractions"}
</div>
          <div
            onPointerUp={() => {
              if (!isStationOpen) {
                if (isSightsOpen) {
                  setIsSightsAnimating(true);
                  openSights(false);
                  setIsLeftWidgetVisible(false);
                  setLocalSelectedSightId(null);
                  setSightTop(null);
                  setTimeout(() => {
                    setIsLeftWidgetOpen(false);
                    setIsSightsAnimating(false);
                    setShouldRenderSights(false);
                    setShouldRenderStation(true);
                    setTimeout(() => {
                      openStation(true);
                    }, 10);
                  }, 300);
                } else {
                  setLocalSelectedSightId(null);
                  setSightTop(null);
                  setShouldRenderStation(true);
                  setTimeout(() => {
                    openStation(true);
                  }, 10);
                }
                openWidget(false);
                store.closeGovernorModal();
                setIsLeftWidgetOpen(false);
              } else {
                setIsStationAnimating(true);
                openStation(false);
                setTimeout(() => {
                  setIsStationAnimating(false);
                  setShouldRenderStation(false);
                }, 300);
              }
            }}
            className={`side-menu-button ${
              isStationOpen ? "side-menu-button--active" : ""
            }`}
          >
            {selectedLanguage == "ru"
              ? "Остановки"
              : selectedLanguage == "zh"
              ? "车站"
              : "Stations"}
</div>
        </div>
        <div className="side-menu-tag">
          {/* {selectedLanguage == "ru"
            ? "#ВсемПоПути"
            : selectedLanguage == "zh"
            ? "#每个人都在路上"
            : "#EveryoneOnTheWay"} */}
        </div>
        <div className="side-menu-bottom-section">
          <div className="side-menu-carrier-block">
            {designData?.carrierPath && (
              <img
                className="carrier-logo"
                src={designData?.carrierPath}
                alt="ГЭТ - Электротранспорт Санкт-Петербурга"
              />
            )}
            {carrier?.full_name && (
              <div className="side-menu-slogan">{carrier.short_name}</div>
            )}
          </div>
          <img className="side-menu-bottom-photo" src={sideMenuPhoto} alt="" />
        </div>
      </div>
      <div className="side-menu-control-panel">
        <RouteWidget />

        <AppealWidget
          widgetImgPath={(() => {
            const m = sightArticles.get(route?.governor_appeal + "_ru")?.media;
            const mediaId = Array.isArray(m) ? m[0]?.id : m?.id;
            return mediaId ? getMediaUrl(mediaId) : undefined;
          })()}
          isOpen={isWidgetOpen}
          style={{
            transform: isWidgetOpen ? "translateX(0)" : "translateX(-200%)",
            transition: "transform 0.5s ease",
            zIndex: -1,
            pointerEvents: isWidgetOpen ? "auto" : "none",
          }}
          widgetLabel={
            selectedLanguage == "ru"
              ? sightArticles.get(route?.governor_appeal + "_ru")?.heading
              : selectedLanguage == "zh"
              ? sightArticlesZh.get(route?.governor_appeal + "_zh")?.heading
              : sightArticlesEn.get(route?.governor_appeal + "_en")?.heading
          }
          widgetText={
            selectedLanguage == "ru"
              ? sightArticles.get(route?.governor_appeal + "_ru")?.body
              : selectedLanguage == "zh"
              ? sightArticlesZh.get(route?.governor_appeal + "_zh")?.body
              : sightArticlesEn.get(route?.governor_appeal + "_en")?.body
          }
        />

        <div
          className="side-menu-control-buttons"
          style={{ pointerEvents: "auto" }}
        >
          <svg
            className="side-menu-open icon-color-animated"
            style={{
              transform: !isMenuOpen ? "rotate(180deg)" : "rotate(0deg)",
              transition: "transform 0.15s ease",
              "--animated-color": currentColor,
            }}
            onPointerUp={() => {
              handleMenuToggle(!isMenuOpen);
            }}
            width="48"
            height="48"
            viewBox="0 0 48 48"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <rect x="8" y="7" width="31" height="33" fill="black" />
            <path
              d="M24.0001 0C10.7501 0 0.00012207 10.75 0.00012207 24C0.00012207 37.25 10.7501 48 24.0001 48C37.2501 48 48.0001 37.25 48.0001 24C48.0001 10.75 37.2501 0 24.0001 0ZM37.5401 25.84C37.5401 26.4 37.0901 26.85 36.5301 26.85H20.5901C20.1401 26.85 19.9201 27.39 20.2301 27.71L27.6801 35.16C28.0801 35.56 28.0801 36.2 27.6801 36.59L25.0801 39.19C24.6801 39.59 24.0401 39.59 23.6501 39.19L12.4901 28.03L9.17012 24.71C8.77012 24.31 8.77012 23.67 9.17012 23.28L12.4901 19.96L23.6501 8.8C24.0501 8.4 24.6901 8.4 25.0801 8.8L27.6801 11.4C28.0801 11.8 28.0801 12.44 27.6801 12.83L20.2301 20.28C19.9101 20.6 20.1401 21.14 20.5901 21.14H36.5301C37.0901 21.14 37.5401 21.59 37.5401 22.15V25.82V25.84Z"
              fill="white"
            />
          </svg>

          {isLangMenuOpen ? (
            <div className="side-menu-control-lang-open">
              <svg
                onPointerUp={() => handleLanguageChange("ru")}
                className={`side-menu-control-lang icon-color-animated ${
                  selectedLanguage === "ru" ? "active" : ""
                }`}
                width="48"
                height="48"
                viewBox="0 0 48 48"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                style={{ "--animated-color": currentColor }}
              >
                <rect x="3" y="3" width="42" height="42" rx="21" fill="black" />
                <path
                  className={`${selectedLanguage == "ru" ? "active" : ""}`}
                  d="M24 0C10.75 0 0 10.75 0 24C0 37.25 10.75 48 24 48C37.25 48 48 37.25 48 24C48 10.75 37.25 0 24 0ZM24.2 33.55H19.92L16.29 26.46H13.11V33.55H9.12V14.18H16.32C18.61 14.18 20.37 14.69 21.62 15.71C22.87 16.73 23.48 18.17 23.48 20.03C23.48 21.35 23.19 22.45 22.62 23.34C22.05 24.22 21.18 24.93 20.02 25.45L24.21 33.37V33.56L24.2 33.55ZM40.3 26.94C40.3 29.06 39.64 30.74 38.31 31.97C36.98 33.2 35.17 33.82 32.87 33.82C30.57 33.82 28.81 33.22 27.48 32.02C26.15 30.82 25.47 29.18 25.44 27.08V14.18H29.43V26.97C29.43 28.24 29.73 29.16 30.34 29.74C30.95 30.32 31.79 30.61 32.86 30.61C35.1 30.61 36.24 29.43 36.28 27.07V14.18H40.28V26.94H40.3Z"
                />
                <path
                  className={`${selectedLanguage == "ru" ? "active" : ""}`}
                  d="M16.3086 17.4099H13.0986V23.2199H16.3186C17.3186 23.2199 18.0986 22.9599 18.6486 22.4499C19.1986 21.9399 19.4686 21.2399 19.4686 20.3399C19.4686 19.4399 19.2086 18.7099 18.6886 18.1799C18.1686 17.6499 17.3686 17.3899 16.2986 17.3899L16.3086 17.4099Z"
                />
              </svg>
              <svg
                onPointerUp={() => handleLanguageChange("zh")}
                className={`side-menu-control-lang icon-color-animated ${
                  selectedLanguage === "zh" ? "active" : ""
                }`}
                width="48"
                height="48"
                viewBox="0 0 48 48"
                style={{ "--animated-color": currentColor }}
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <rect x="3" y="3" width="42" height="42" rx="21" fill="black" />
                <path
                  className={`${selectedLanguage == "zh" ? "active" : ""}`}
                  d="M10.287 20.382H6.291V24.147H10.287V20.382Z"
                />
                <path
                  className={`${selectedLanguage == "zh" ? "active" : ""}`}
                  d="M13.704 24.147H17.721V20.382H13.704V24.147Z"
                />
                <path
                  className={`${selectedLanguage == "zh" ? "active" : ""}`}
                  d="M36.1254 20.046H29.8575C30.6606 21.9406 31.7187 23.6442 33.0513 25.1217C34.3105 23.6927 35.3315 22.0126 36.1254 20.046Z"
                />
                <path
                  className={`${selectedLanguage == "zh" ? "active" : ""}`}
                  fillRule="evenodd"
                  clipRule="evenodd"
                  d="M24 48C37.2548 48 48 37.2548 48 24C48 10.7452 37.2548 0 24 0C10.7452 0 0 10.7452 0 24C0 37.2548 10.7452 48 24 48ZM10.287 13.5H13.704V17.1541H21.117V28.446H17.721V27.375H13.704V33.969H10.287V27.375H6.291V28.5511H3V17.1541H10.287V13.5ZM31.35 13.5H34.704V16.8181H43.083V20.046H39.8887C38.804 22.9506 37.3746 25.3834 35.581 27.4065C37.6488 28.9237 40.1651 30.0542 43.1682 30.7291L43.8469 30.8817L43.3465 31.3649C42.7753 31.9162 41.9777 33.0771 41.5886 33.7939L41.4484 34.0521L41.1642 33.9778C37.8385 33.1088 35.1249 31.7521 32.8974 29.9253C30.6296 31.6954 27.9389 33.0335 24.802 34.015L24.4889 34.1129L24.3502 33.8156C24.0724 33.2203 23.2933 32.029 22.8051 31.439L22.4307 30.9868L22.9986 30.8373C25.936 30.0648 28.4025 28.9702 30.4373 27.4935C28.6775 25.4061 27.319 22.9142 26.2412 20.046H23.097V16.8181H31.35V13.5Z"
                />
              </svg>
              <svg
                onPointerUp={() => handleLanguageChange("en")}
                className={`side-menu-control-lang icon-color-animated ${
                  selectedLanguage === "en" ? "active" : ""
                }`}
                width="48"
                height="48"
                viewBox="0 0 48 48"
                style={{ "--animated-color": currentColor }}
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <rect x="3" y="3" width="42" height="42" rx="21" fill="black" />
                <path
                  className={`${selectedLanguage == "en" ? "active" : ""}`}
                  d="M24 0C10.75 0 0 10.75 0 24C0 37.25 10.75 48 24 48C37.25 48 48 37.25 48 24C48 10.75 37.25 0 24 0ZM21.57 33.79H8.41V14.15H21.55V17.43H12.45V22.11H20.22V25.28H12.45V30.54H21.57V33.79ZM39.54 33.79H35.49L27.61 20.87V33.79H23.56V14.15H27.61L35.5 27.1V14.15H39.53V33.79H39.54Z"
                />
              </svg>
            </div>
          ) : (
            <svg
              className="icon-color-animated"
              onPointerUp={() => {
                setIsLangMenuOpen(true);
              }}
              width="48"
              height="48"
              style={{ "--animated-color": currentColor }}
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <rect x="4" y="3" width="39" height="42" rx="19.5" fill="black" />
              <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M0 24C0 10.75 10.75 0 24 0C37.25 0 48 10.75 48 24C48 37.25 37.25 48 24 48C10.75 48 0 37.25 0 24ZM36.05 19.41L38.27 25.47L40.47 19.39L39.17 19.77C39.16 19.75 39.16 19.35 39.16 19.32C38.58 12.41 32.99 7.15 25.94 7.15C25.42 7.15 24.99 7.58 24.99 8.1C24.99 8.62 25.42 9.05 25.94 9.05C31.92 9.05 36.68 13.47 37.26 19.31C37.26 19.325 37.2625 19.435 37.265 19.545C37.2675 19.655 37.27 19.765 37.27 19.78L36.05 19.41ZM8.90375 27.5369C11.3535 26.9568 13.6332 25.8438 15.5701 24.2838L15.5709 24.2846C17.2124 25.8526 19.2497 26.9784 21.4812 27.5521C21.5875 27.5649 21.6945 27.5649 21.8007 27.5521C22.3194 27.6074 22.8298 27.3911 23.1385 26.9848C23.448 26.5786 23.5086 26.0441 23.2986 25.5826C23.0879 25.1211 22.6389 24.803 22.1202 24.7477C20.4804 24.3182 18.9808 23.4937 17.7634 22.3495C20.2489 20.0131 22.1036 17.1245 23.1659 13.9363C23.2729 13.5077 23.165 13.0566 22.8754 12.716C22.6016 12.3627 22.1709 12.1552 21.7136 12.1552H16.6307V10.402C16.6307 9.90121 16.3535 9.43889 15.9045 9.1881C15.4556 8.9373 14.9012 8.9373 14.4522 9.1881C14.0033 9.43809 13.7261 9.90121 13.7261 10.402V12.1824H8.64317C8.12367 12.1824 7.64484 12.45 7.38509 12.8835C7.12534 13.317 7.12534 13.8522 7.38509 14.2857C7.64484 14.7192 8.1245 14.9868 8.64317 14.9868H19.6655C18.6804 16.9971 17.3443 18.828 15.7153 20.3993C14.8373 19.3977 14.0688 18.3128 13.4207 17.1598C13.2747 16.7896 12.9734 16.4972 12.5909 16.3529C12.2083 16.2087 11.7809 16.2279 11.4141 16.405C11.0473 16.5821 10.7751 16.901 10.6647 17.2824C10.5544 17.6638 10.6166 18.0724 10.8357 18.4074C11.6058 19.7423 12.5153 20.997 13.551 22.1516C12.0207 23.3728 10.2307 24.2533 8.30873 24.7317C7.92284 24.7709 7.56932 24.956 7.32617 25.2469C7.08219 25.5369 6.96767 25.9095 7.00833 26.2813C7.04899 26.6539 7.24069 26.9952 7.54193 27.23C7.84235 27.4656 8.22824 27.5761 8.61329 27.5369C8.70956 27.5513 8.80748 27.5513 8.90375 27.5369ZM34.9002 38.8803C35.2512 39.0301 35.6487 39.0397 36.0072 38.9067C36.3815 38.7865 36.6886 38.5237 36.8587 38.18C37.0288 37.8362 37.0462 37.4404 36.9077 37.0839L30.3434 20.7767C30.238 20.5131 30.0529 20.2863 29.8115 20.1261C29.57 19.9658 29.2845 19.8793 28.9924 19.8785C28.7019 19.8785 28.4173 19.9626 28.1766 20.1196C27.9359 20.2775 27.7501 20.501 27.6422 20.7623L21.136 36.523C20.9443 36.9885 21.024 37.5181 21.346 37.9116C21.668 38.305 22.1825 38.5029 22.6962 38.4308C23.2107 38.3579 23.6455 38.0269 23.8372 37.5606L25.4057 33.6489H32.3185L34.1342 38.1079C34.2737 38.4524 34.5492 38.7304 34.9002 38.8803ZM28.9052 25.1652L31.1857 30.8445H31.1849H26.5667L28.9052 25.1652Z"
                fill="white"
              />
            </svg>
          )}

          {isSightsOpen && (
            <svg
              width="48"
              height="48"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              className="icon-color-animated"
              style={{
                marginLeft: "10px",
                transition: "transform 0.3s ease-out",
                transform:
                  sortingBy === "asc" ? "rotate(0deg)" : "rotate(180deg)",
                "--animated-color": currentColor,
              }}
              onPointerUp={() => {
                setSortingBy(sortingBy === "asc" ? "desc" : "asc");
              }}
            >
              <g clipPath="url(#clip0_580_81492)">
                <path
                  d="M24 0C10.75 0 0 10.75 0 24C0 37.25 10.75 48 24 48C37.25 48 48 37.25 48 24C48 10.75 37.25 0 24 0ZM26.18 33.63H13.27C12.44 33.63 11.77 32.96 11.77 32.13C11.77 31.3 12.44 30.63 13.27 30.63H26.19C27.02 30.63 27.69 31.3 27.69 32.13C27.69 32.96 27.01 33.63 26.18 33.63ZM30.46 25.62H13.26C12.43 25.62 11.76 24.95 11.76 24.12C11.76 23.29 12.43 22.62 13.26 22.62H30.46C31.29 22.62 31.96 23.29 31.96 24.12C31.96 24.95 31.29 25.62 30.46 25.62ZM34.73 17.37H13.27C12.44 17.37 11.77 16.7 11.77 15.87C11.77 15.04 12.44 14.37 13.27 14.37H34.73C35.56 14.37 36.23 15.04 36.23 15.87C36.23 16.7 35.56 17.37 34.73 17.37Z"
                  fill="white"
                />
              </g>
              <defs>
                <clipPath id="clip0_580_81492">
                  <rect width="48" height="48" fill="white" />
                </clipPath>
              </defs>
            </svg>
          )}
        </div>
      </div>
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          transform: isLeftWidgetVisible
            ? "translateX(0)"
            : "translateX(-200%)",
          transition: "transform 1s ease",
          zIndex: -1,
          pointerEvents: isLeftWidgetVisible ? "auto" : "none",
        }}
      >
        <LeftWidget
          selectedSightId={localSelectedSightId}
          onClose={() => {
            setIsLeftWidgetVisible(false);
            setTimeout(() => {
              setIsLeftWidgetOpen(false);
            }, 1000);
          }}
          isVisible={isLeftWidgetVisible}
          sightTop={sightTop}
        />
      </div>
    </div>
  );
});

export default SideMenu;
