import { useEffect, useState } from "react";
import { useSatExam } from "../stores/useSatExam";

export const useSatTimer = () => {
  const phase = useSatExam((s) => s.phase);
  const getRemainingTime = useSatExam((s) => s.getRemainingTime);
  const startBreak = useSatExam((s) => s.startBreak);
  const skipBreak = useSatExam((s) => s.skipBreak);
  const finishExam = useSatExam((s) => s.finishExam);

  const currentModule = useSatExam((s) => s.currentModuleQuestions);

  const [time, setTime] = useState(0);

  // ✅ reset timer when phase or module changes
  useEffect(() => {
    setTime(getRemainingTime());
  }, [phase, currentModule?.module_id]);

  useEffect(() => {
    if (phase === "IDLE" || phase === "FINISHED") return;

    const interval = setInterval(() => {
      const remaining = getRemainingTime();
      setTime(remaining);

      if (remaining === 0) {
        clearInterval(interval);

        if (phase === "BREAK") {
          // ✅ break ended → go back to module
          skipBreak();
          return;
        }

        if (phase === "MODULE") {
          // ⚠️ IMPORTANT:
          // Timer should NOT load next module automatically.
          // Instead, finish exam UI or let backend decide.

          finishExam();
          return;
        }
      }
    }, 1000);

    return () => clearInterval(interval);
  }, [phase, getRemainingTime, skipBreak, finishExam]);

  return time;
};
