import { useEffect } from "react";
import Taro from "@tarojs/taro";

const VERSION_CHECK_INTERVAL = 5 * 60 * 1000; // 每5分钟检查一次
const VERSION_KEY = "app_version_identifier";
const VersionChecker = () => {
  useEffect(() => {
    let timer: NodeJS.Timeout;
    const checkVersion = async () => {
      try {
        const response = await fetch("/", {
          method: "HEAD",
          headers: {
            "Cache-Control": "no-cache",
            "If-None-Match": localStorage.getItem(`${VERSION_KEY}-etag`) || "",
            "If-Modified-Since":
              localStorage.getItem(`${VERSION_KEY}-last-modified`) || "",
          },
        });
        if (response.status === 200) {
          const newEtag = response.headers.get("ETag");
          const newLastModified = response.headers.get("Last-Modified");
          console.log("New version:", newEtag, newLastModified);
          if (newEtag || newLastModified) {
            clearTimeout(timer);
            Taro.showModal({
              title: "新版本可用",
              content: "新版本已经准备好，是否立即刷新？",
              success: function () {
                // 更新本地存储版本信息
                if (newEtag) {
                  localStorage.setItem(`${VERSION_KEY}-etag`, newEtag);
                }

                if (newLastModified) {
                  localStorage.setItem(
                    `${VERSION_KEY}-last-modified`,
                    newLastModified,
                  );
                }

                window.location.reload();
              },
            });
          }
        }
        // 更新检查计时器
        timer = setTimeout(checkVersion, VERSION_CHECK_INTERVAL);
      } catch (error) {
        console.error("版本检查失败:", error);
        timer = setTimeout(checkVersion, VERSION_CHECK_INTERVAL);
      }
    };
    // 首次检查
    checkVersion();
    return () => clearTimeout(timer);
  }, []);
  return null;
};
export default VersionChecker;
