import {
  ViewModeContextProps,
  ViewModeProviderProps,
} from "@app/models/components";
import React, { createContext, useContext, useState, useEffect } from "react";

const ViewModeContext = createContext<ViewModeContextProps>({
  isMobileView: false,
  isRTL: false,
});

export const useViewMode = () => {
  return useContext(ViewModeContext);
};

export const ViewModeProvider: React.FC<ViewModeProviderProps> = ({
  children,
}) => {
  const [isMobileView, setIsMobileView] = useState(false);
  const [isRTL, setIsRTL] = useState(false);

  useEffect(() => {
    const checkWindowWidth = () => {
      const settingsPage = document.getElementById("sfsync-settings-page");

      setIsMobileView(
        (settingsPage && settingsPage.offsetWidth <= 782) ?? false
      );
    };

    checkWindowWidth();

    window.addEventListener("resize", checkWindowWidth);

    return () => {
      window.removeEventListener("resize", checkWindowWidth);
    };
  }, []);

  useEffect(() => {
    const htmlDir = document.documentElement.getAttribute("dir");
    if (htmlDir === "rtl") {
      setIsRTL(true);
    } else {
      setIsRTL(false);
    }
  }, []);

  return (
    <ViewModeContext.Provider value={{ isMobileView, isRTL }}>
      {children}
    </ViewModeContext.Provider>
  );
};
