/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useState } from "react";
import Button from "./Button";
import FullscreenExitIcon from "../icons/FullscreenExitIcon";
import FullscreenIcon from "../icons/FullscreenIcon";
import clsx from "clsx";

function FullscreenButton({ className }: { className?: string }) {
  const [isFullScreen, setIsFullScreen] = useState(false);

  async function handleFullScreenClick() {
    try {
      if (isFullScreen) {
        await document.exitFullscreen();
      } else {
        // Проверяем поддержку полноэкранного режима
        if (!document.body.requestFullscreen) {
          console.warn("Полноэкранный режим не поддерживается");
          return;
        }
        await document.body.requestFullscreen();
      }
    } catch (error) {
      console.error("Ошибка при переключении полноэкранного режима:", error);
    }
  }

  useEffect(() => {
    const handleFullScreenChange = () => {
      setIsFullScreen(!!document.fullscreenElement);
    };

    document.addEventListener("fullscreenchange", handleFullScreenChange);

    return () => {
      document.removeEventListener("fullscreenchange", handleFullScreenChange);
    };
  }, [handleFullScreenClick]);

  return (
    <Button
      variant="primary"
      onClick={handleFullScreenClick}
      className={clsx(
        "fixed 2xl:bottom-[1.111vw] bottom-4 2xl:right-[1.111vw] right-4",
        className
      )}
    >
      <div className="2xl:size-[1.111vw] size-4">
        {isFullScreen ? <FullscreenExitIcon /> : <FullscreenIcon />}
      </div>
    </Button>
  );
}

export default FullscreenButton;
