import { useEffect } from "react";

export default function useTaskStatusSync({
  selectedTaskId,
  taskStatus,
  setTaskStatusMap,
  checklistStats,
  setChecklistOpen,
  hasSelectedTask,
  taskForm,
  roleIntersectionCount,
  roleSummary,
  setTaskForm,
  sanitizeTaskForm
}) {
  useEffect(() => {
    if (selectedTaskId == null) return;
    setTaskStatusMap((prev) => ({
      ...prev,
      [selectedTaskId]: taskStatus
    }));
  }, [selectedTaskId, taskStatus]);

  useEffect(() => {
    if (checklistStats.fail > 0) {
      setChecklistOpen(true);
    }
  }, [checklistStats.fail]);

  useEffect(() => {
    if (!hasSelectedTask) return;
    if (taskForm.requireSameBotInBoth) {
      const nextValue = Math.max(1, roleIntersectionCount || 0);
      if (taskForm.maxCompetitorBots !== nextValue || taskForm.maxOurBots !== nextValue) {
        setTaskForm((prev) => sanitizeTaskForm({
          ...prev,
          maxCompetitorBots: nextValue,
          maxOurBots: nextValue
        }));
      }
      return;
    }
    if (taskForm.separateBotRoles) {
      const nextCompetitors = Math.max(1, roleSummary.monitor.length || 0);
      const nextOur = Math.max(1, roleSummary.invite.length || 0);
      const hasConfirmRoles = roleSummary.confirm.length > 0;
      const nextConfirm = taskForm.separateConfirmRoles && hasConfirmRoles
        ? Math.max(1, roleSummary.confirm.length)
        : taskForm.maxConfirmBots;
      if (taskForm.maxCompetitorBots !== nextCompetitors || taskForm.maxOurBots !== nextOur || (taskForm.separateConfirmRoles && hasConfirmRoles && taskForm.maxConfirmBots !== nextConfirm)) {
        setTaskForm((prev) => ({
          ...prev,
          maxCompetitorBots: nextCompetitors,
          maxOurBots: nextOur,
          maxConfirmBots: nextConfirm
        }));
      }
    }
  }, [
    hasSelectedTask,
    roleIntersectionCount,
    roleSummary.monitor.length,
    roleSummary.invite.length,
    roleSummary.confirm.length,
    taskForm.requireSameBotInBoth,
    taskForm.separateBotRoles,
    taskForm.separateConfirmRoles,
    taskForm.maxConfirmBots
  ]);
}
