import { MutableRefObject, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useSiteStore } from "src/Stores";
import SiteComponent from "src/site/SiteComponent";

export default function useSiteComponent(
  siteYellsView: MutableRefObject<HTMLDivElement | null>,
) {
  const {
    targetSiteID,
    getSiteView,
    setVisible,
    setEventHandler,
    setEventCloseHandler,
  } = useSiteStore();
  const { t } = useTranslation();

  useEffect(() => {
    const onVisibilityModified = () => {
      if (setVisible()) {
        const siteView = getSiteView(targetSiteID);
        if (siteView) {
          siteView.wasNotify = false;
        }
      }
    };

    document.addEventListener("visibilitychange", onVisibilityModified);

    return () => {
      document.removeEventListener("visibilitychange", onVisibilityModified);
    };
  }, [getSiteView, setVisible, targetSiteID]);

  useEffect(() => {
    setVisible();
    setEventHandler(siteYellsView, t);
    setEventCloseHandler(siteYellsView);
  }, [setEventCloseHandler, setEventHandler, setVisible, siteYellsView, t]);

  useEffect(() => {
    SiteComponent.connect();

    return () => {
      SiteComponent.disconnect();
    };
  }, []);
}
