import wsAPI from "@/app/[language]/site/lib/wsAPI";
import { useSiteStore } from "@/state/Stores";
import { useTranslations } from "next-intl";
import { useEffect } from "react";
import { useLanguage } from "taehui-lib/language";

export default function useWSAPI() {
  const {
    targetSiteID,
    getSiteView,
    setVisible,
    setEventHandler,
    setEventCloseHandler,
  } = useSiteStore();
  const t = useTranslations();

  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();
    setEventCloseHandler();
  }, [setEventCloseHandler, setEventHandler, setVisible]);

  const language = useLanguage();

  useEffect(() => {
    wsAPI.setLanguage(language);
    wsAPI.connect();

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