// Rôle : surveille globalement les comptes à rebours actifs et déclenche les alertes internes autorisées.
import { useEffect, useRef } from "react";
import { getCountdownTargetMs } from "../features/toolboxes/modules/timerUtils.js";
import { moduleStorageKey } from "../features/toolboxes/storage/toolboxStorage.js";

function getVisibleToolboxIds(route, drawerGameId, links) {
  const visibleIds = new Set();
  const toolboxMatch = route.match(/^\/toolbox\/([^/]+)/);
  if (toolboxMatch?.[1]) visibleIds.add(toolboxMatch[1]);
  const drawerToolboxId = drawerGameId ? links[drawerGameId] : "";
  if (drawerToolboxId) visibleIds.add(drawerToolboxId);
  return visibleIds;
}

function getAlertMessage(template, toolbox, countdown) {
  return template
    .replaceAll("{label}", countdown.label)
    .replaceAll("{toolbox}", toolbox.name);
}

export function useTimerAlerts({ toolboxes, moduleData, links, route, drawerGameId, normalizeTimerData, textContent, notify }) {
  const previousTargetsRef = useRef(new Map());
  const lastTickRef = useRef(Date.now());

  useEffect(() => {
    const visibleToolboxIds = getVisibleToolboxIds(route, drawerGameId, links);
    const alertMessageTemplate = textContent?.alertMessage || "Compte à rebours terminé : {label}";

    function tick() {
      const nowMs = Date.now();
      const lastTickMs = lastTickRef.current;
      const nextTargets = new Map();

      toolboxes.forEach((toolbox) => {
        toolbox.modules.forEach((module) => {
          if (module.type !== "timer") return;

          const data = normalizeTimerData(moduleData[moduleStorageKey(toolbox.id, module.id)]);

          data.countdowns.forEach((countdown) => {
            if (countdown.alertMode === "off") return;
            if (countdown.alertMode === "visible" && !visibleToolboxIds.has(toolbox.id)) return;

            const key = `${toolbox.id}:${module.id}:${countdown.id}`;
            const targetMs = getCountdownTargetMs(countdown, nowMs);
            const previousTargetMs = previousTargetsRef.current.get(key) || targetMs;
            nextTargets.set(key, targetMs);

            if (!targetMs || previousTargetMs <= lastTickMs || previousTargetMs > nowMs) return;
            notify(getAlertMessage(alertMessageTemplate, toolbox, countdown));
          });
        });
      });

      previousTargetsRef.current = nextTargets;
      lastTickRef.current = nowMs;
    }

    tick();
    const intervalId = window.setInterval(tick, 500);
    return () => window.clearInterval(intervalId);
  }, [drawerGameId, links, moduleData, normalizeTimerData, notify, route, textContent, toolboxes]);
}
