"use client";
// 回响星核 / Echo Nexus — 主循环 hook
import { useEffect, useRef } from "react";
import { useGameStore } from "@/store/gameStore";

/** 250ms tick：产能 + 自动产晶体 + 自动解码 + 成就检测 */
export function useGameLoop() {
  const tick = useGameStore((s) => s.tick);
  const autoDecodeTick = useGameStore((s) => s.autoDecodeTick);
  const checkAchievements = useGameStore((s) => s.checkAchievements);
  const init = useGameStore((s) => s.init);
  const inited = useRef(false);

  useEffect(() => {
    if (!inited.current) {
      init();
      inited.current = true;
    }
    let achCounter = 0;
    const id = setInterval(() => {
      const now = Date.now();
      tick(now);
      autoDecodeTick();
      // 成就检测每秒执行一次（降低开销）
      achCounter++;
      if (achCounter % 4 === 0) {
        checkAchievements();
      }
    }, 250);
    return () => clearInterval(id);
  }, [tick, autoDecodeTick, checkAchievements, init]);

  // 页面可见性：切回时补 tick + 立即检测成就
  useEffect(() => {
    const onVis = () => {
      if (document.visibilityState === "visible") {
        tick(Date.now());
        checkAchievements();
      }
    };
    document.addEventListener("visibilitychange", onVis);
    return () => document.removeEventListener("visibilitychange", onVis);
  }, [tick, checkAchievements]);
}

