import { useEffect } from "react";
import { Dimensions } from "react-native";

import { useAppDispatch } from "@/store/hooks";
import { setScreenSize } from "@/store/screen/screenSizeSlice";

export const useScreenSizeListener = () => {
  const dispatch = useAppDispatch();

  useEffect(() => {
    const { width, height } = Dimensions.get("window");
    dispatch(setScreenSize({ width, height }));

    const onChange = ({
      window,
    }: {
      window: { width: number; height: number };
    }) => {
      dispatch(setScreenSize({ width: window.width, height: window.height }));
    };

    const subscription = Dimensions.addEventListener("change", onChange);

    return () => subscription.remove();
  }, [dispatch]);
};

export const ScreenSizeListenerWrapper = () => {
  useScreenSizeListener();
  return null;
};
