// Rôle : fournit l'outil task planner avec tâches récurrentes, parents, pré requis et échange texte.
import { useEffect, useMemo, useRef, useState } from "react";
import { Icon } from "../../../components/Icon.jsx";
import { InlineNotice } from "../../../components/AppOverlays.jsx";
import { Tooltip } from "../../../components/Tooltip.jsx";
import { useDraftForm } from "../../../hooks/useDraftForm.js";
import { applyGroupedReorderOperation, useGroupedReorder } from "../../../hooks/useGroupedReorder.js";
import { useInlineEdit } from "../../../hooks/useInlineEdit.js";
import { TextExchangeActions } from "./TextExchangeActions.jsx";

const TASK_TYPES = ["daily", "weekly", "unique"];
const WEEK_DAYS = [
  { value: 1, label: "Lundi" },
  { value: 2, label: "Mardi" },
  { value: 3, label: "Mercredi" },
  { value: 4, label: "Jeudi" },
  { value: 5, label: "Vendredi" },
  { value: 6, label: "Samedi" },
  { value: 0, label: "Dimanche" }
];

function getTaskTypeLabel(type, textContent) {
  if (type === "daily") return textContent.dailyType || "Quotidienne";
  if (type === "weekly") return textContent.weeklyType || "Hebdomadaire";
  return textContent.uniqueType || "Ponctuelle";
}

function parseResetTime(value) {
  const [hours, minutes] = String(value || "00:00").split(":").map((part) => Number.parseInt(part, 10));
  return {
    hours: Number.isInteger(hours) ? Math.min(23, Math.max(0, hours)) : 0,
    minutes: Number.isInteger(minutes) ? Math.min(59, Math.max(0, minutes)) : 0
  };
}

function getLatestDailyReset(now, resetTime) {
  const { hours, minutes } = parseResetTime(resetTime);
  const reset = new Date(now);
  reset.setHours(hours, minutes, 0, 0);
  if (reset.getTime() > now) reset.setDate(reset.getDate() - 1);
  return reset.getTime();
}

function getLatestWeeklyReset(now, resetTime, weekDay) {
  const { hours, minutes } = parseResetTime(resetTime);
  const reset = new Date(now);
  reset.setHours(hours, minutes, 0, 0);
  const dayDiff = (reset.getDay() - weekDay + 7) % 7;
  reset.setDate(reset.getDate() - dayDiff);
  if (reset.getTime() > now) reset.setDate(reset.getDate() - 7);
  return reset.getTime();
}

function applyDueResets(data, now = Date.now()) {
  let latestResetAt = data.lastResetAt;
  let changed = false;
  const tasks = data.tasks.map((task) => {
    if (task.type === "unique") return task;
    const resetAt = task.type === "daily"
      ? getLatestDailyReset(now, task.dailyResetTime || data.resetTime)
      : getLatestWeeklyReset(now, data.resetTime, task.weeklyResetDay ?? data.weeklyResetDay);
    latestResetAt = Math.max(latestResetAt, resetAt);
    if (!task.checked || resetAt <= (task.checkedAt || data.lastResetAt)) return task;
    changed = true;
    return { ...task, checked: false, checkedAt: 0 };
  });

  if (latestResetAt > data.lastResetAt) changed = true;
  return changed ? { ...data, lastResetAt: latestResetAt, tasks } : data;
}

function moveTask(tasks, fromTaskId, toTaskId, placement = "before") {
  const nextTasks = [...tasks];
  const fromIndex = nextTasks.findIndex((task) => task.id === fromTaskId);
  const toIndex = nextTasks.findIndex((task) => task.id === toTaskId);
  if (fromIndex < 0 || toIndex < 0) return tasks;
  const [moved] = nextTasks.splice(fromIndex, 1);
  const targetIndex = nextTasks.findIndex((task) => task.id === toTaskId);
  nextTasks.splice(placement === "after" ? targetIndex + 1 : targetIndex, 0, moved);
  return nextTasks;
}

function getBoundaryTaskId(tasks, taskIds, placement) {
  const ids = new Set(taskIds);
  const orderedTasks = tasks.filter((task) => ids.has(task.id));
  return placement === "after" ? orderedTasks.at(-1)?.id || "" : orderedTasks[0]?.id || "";
}

function getTaskTitle(tasks, taskId) {
  return tasks.find((task) => task.id === taskId)?.title || "Tâche supprimée";
}

function getTaskParentId(taskId, relations, taskIds) {
  return relations.find((relation) => relation.fromTaskId === taskId && taskIds.has(relation.toTaskId))?.toTaskId || "";
}

function getTaskParentMap(tasks, relations) {
  const taskIds = new Set(tasks.map((task) => task.id));
  const parentMap = new Map(tasks.map((task) => [task.id, getTaskParentId(task.id, relations, taskIds)]));
  tasks.forEach((task) => {
    const visited = new Set([task.id]);
    let parentId = parentMap.get(task.id);
    while (parentId) {
      if (visited.has(parentId)) {
        parentMap.set(task.id, "");
        return;
      }
      visited.add(parentId);
      parentId = parentMap.get(parentId);
    }
  });
  return parentMap;
}

function getTasksForParent(tasks, parentMap, parentId) {
  return tasks.filter((task) => (parentMap.get(task.id) || "") === parentId);
}

function getTaskCategory(task) {
  return String(task?.category || "").trim();
}

function getTaskById(tasks, taskId) {
  return tasks.find((task) => task.id === taskId) || null;
}

function getEffectiveTaskCategory(task, tasks, parentMap) {
  const parentId = parentMap.get(task?.id) || "";
  const parentTask = parentId ? getTaskById(tasks, parentId) : null;
  return parentTask ? getEffectiveTaskCategory(parentTask, tasks, parentMap) : getTaskCategory(task);
}

function getTaskCategoryForParent(task, tasks, parentMap, parentId) {
  return parentId ? getEffectiveTaskCategory(task, tasks, parentMap) : getTaskCategory(task);
}

function getTaskCategoryDataset(task, tasks, parentMap) {
  return getEffectiveTaskCategory(task, tasks, parentMap);
}

function countTaskTree(taskIds, tasks, parentMap) {
  let count = 0;
  const visited = new Set();
  function visit(taskId) {
    if (visited.has(taskId)) return;
    visited.add(taskId);
    count += 1;
    tasks
      .filter((task) => (parentMap.get(task.id) || "") === taskId)
      .forEach((child) => visit(child.id));
  }
  taskIds.forEach(visit);
  return count;
}

function getTaskTreeIds(taskIds, tasks, parentMap) {
  const ids = [];
  const visited = new Set();
  function visit(taskId) {
    if (visited.has(taskId)) return;
    visited.add(taskId);
    ids.push(taskId);
    tasks
      .filter((task) => (parentMap.get(task.id) || "") === taskId)
      .forEach((child) => visit(child.id));
  }
  taskIds.forEach(visit);
  return ids;
}

function countCompletedTaskTree(taskIds, tasks, parentMap) {
  const taskIdsSet = new Set(getTaskTreeIds(taskIds, tasks, parentMap));
  return tasks.filter((task) => taskIdsSet.has(task.id) && task.checked).length;
}

function isTaskTreeComplete(taskIds, tasks, parentMap) {
  const treeIds = getTaskTreeIds(taskIds, tasks, parentMap);
  return treeIds.length > 0 && treeIds.every((taskId) => getTaskById(tasks, taskId)?.checked);
}

function getTaskCategoryGroups(tasks, parentMap, parentId, categoryOrder) {
  const siblings = getTasksForParent(tasks, parentMap, parentId);
  if (parentId) {
    return {
      entries: siblings.map((task) => ({ type: "task", task })),
      uncategorized: siblings,
      categories: []
    };
  }
  const categories = [];
  siblings.forEach((task) => {
    const category = getTaskCategoryForParent(task, tasks, parentMap, parentId);
    if (category && !categories.includes(category)) categories.push(category);
  });
  const orderedCategories = [
    ...categoryOrder.filter((category) => categories.includes(category)),
    ...categories.filter((category) => !categoryOrder.includes(category))
  ];
  const uncategorized = siblings.filter((task) => !getTaskCategoryForParent(task, tasks, parentMap, parentId));
  const categoryGroups = orderedCategories.map((category) => ({
      category,
      tasks: siblings.filter((task) => getTaskCategoryForParent(task, tasks, parentMap, parentId) === category)
    })).filter((group) => group.tasks.length);
  const renderedCategories = new Set();
  const entries = siblings.map((task) => {
    const category = getTaskCategoryForParent(task, tasks, parentMap, parentId);
    if (!category) return { type: "task", task };
    if (renderedCategories.has(category)) return null;
    renderedCategories.add(category);
    return { type: "category", group: categoryGroups.find((group) => group.category === category) };
  }).filter(Boolean);
  return {
    entries,
    uncategorized,
    categories: categoryGroups
  };
}

function getRootTaskIdsForCategory(tasks, parentMap, category) {
  return tasks
    .filter((task) => !parentMap.get(task.id) && getTaskCategory(task) === category)
    .map((task) => task.id);
}

export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
  const data = context.normalizeTaskPlannerData(context.getModuleData(toolboxId, moduleId, { tasks: [] }));
  const textContent = context.moduleText?.taskPlanner || {};
  const taskDraft = useDraftForm({ title: "", type: "daily" });
  const [nowMs, setNowMs] = useState(() => Date.now());
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [openDescriptions, setOpenDescriptions] = useState(() => new Set());
  const [openTaskSettings, setOpenTaskSettings] = useState(() => new Set());
  const [prerequisiteNoticeTaskIds, setPrerequisiteNoticeTaskIds] = useState(() => new Set());
  const prerequisiteNoticeTimeouts = useRef(new Map());
  const parentMap = useMemo(() => getTaskParentMap(data.tasks, data.relations), [data.tasks, data.relations]);
  const {
    itemReorder,
    groupReorder,
    getItemProps,
    getGroupProps,
    getGroupBoundaryProps,
    isItemDragging,
    isItemDropTarget,
    isGroupDragging,
    isGroupDropTarget,
    isBoundaryDropTarget,
    getDropPlacement,
    shouldShowGroupBoundaries
  } = useGroupedReorder({
    namespace: "task-planner",
    items: data.tasks,
    getItemId: (task) => task.id,
    getParentId: (task) => parentMap.get(task.id) || "",
    getItemGroup: (task) => getTaskCategoryDataset(task, data.tasks, parentMap),
    getEffectiveGroup: (task) => getTaskCategoryDataset(task, data.tasks, parentMap),
    reorderFeatures: {
      item: {
        groupChange: true,
        boundaryDrop: true,
        rootOnly: true
      },
      group: {
        reorder: true,
        boundaryDrop: true,
        itemDrop: true,
        rootOnly: true
      }
    },
    onItemMove: (operation) => {
      const fromTaskId = operation.sourceId;
      const fromTask = data.tasks.find((task) => task.id === fromTaskId);
      if (!fromTask) return;
      function setRootTaskCategory(tasks, category) {
        return tasks.map((task) => {
          if (task.id !== fromTaskId) return task;
          const nextTask = { ...task };
          if (category) nextTask.category = category;
          else delete nextTask.category;
          return nextTask;
        });
      }
      function moveToCategory(category, placement = operation.placement) {
        const nextTasks = setRootTaskCategory(data.tasks, category);
        const targetIds = category
          ? getRootTaskIdsForCategory(data.tasks, parentMap, category).filter((taskId) => taskId !== fromTaskId)
          : data.tasks.filter((task) => !parentMap.get(task.id) && !getTaskCategory(task) && task.id !== fromTaskId).map((task) => task.id);
        const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, placement);
        save({ ...data, tasks: boundaryTaskId ? moveTask(nextTasks, fromTaskId, boundaryTaskId, placement) : nextTasks });
      }
      if (operation.targetType === "boundary") {
        const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, operation.targetGroup);
        const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement);
        if (!boundaryTaskId) return;
        const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap);
        const tasks = sourceCategory ? setRootTaskCategory(data.tasks, "") : data.tasks;
        save({ ...data, tasks: moveTask(tasks, fromTaskId, boundaryTaskId, operation.placement) });
        return;
      }
      if (operation.targetType === "group") {
        const targetCategory = operation.targetGroup;
        const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap);
        if (!sourceCategory) {
          const targetIds = getRootTaskIdsForCategory(data.tasks, parentMap, targetCategory);
          const boundaryTaskId = getBoundaryTaskId(data.tasks, targetIds, operation.placement);
          if (boundaryTaskId) save({ ...data, tasks: moveTask(data.tasks, fromTaskId, boundaryTaskId, operation.placement) });
          return;
        }
        moveToCategory(targetCategory);
        return;
      }
      const targetTask = data.tasks.find((task) => task.id === operation.targetId);
      const targetCategory = targetTask ? getTaskCategoryDataset(targetTask, data.tasks, parentMap) : "";
      const sourceCategory = getTaskCategoryDataset(fromTask, data.tasks, parentMap);
      const shouldChangeRootCategory = !parentMap.get(fromTaskId) && targetTask && !parentMap.get(operation.targetId) && targetCategory !== sourceCategory;
      const tasks = shouldChangeRootCategory ? setRootTaskCategory(data.tasks, targetCategory) : data.tasks;
      save({ ...data, tasks: moveTask(tasks, fromTaskId, operation.targetId, operation.placement) });
    },
    onGroupMove: (operation) => {
      save(applyGroupedReorderOperation(data, {
        operation,
        itemsKey: "tasks",
        groupOrderKey: "categoryOrder",
        getItemGroup: (task) => parentMap.get(task.id) ? "" : getTaskCategory(task),
        setItemGroup: (task) => task
      }));
    },
    hierarchy: { enabled: true, stickyParents: true }
  });
  const reorder = {
    itemReorder,
    groupReorder,
    getItemProps,
    getGroupProps,
    getGroupBoundaryProps,
    isItemDragging,
    isItemDropTarget,
    isGroupDragging,
    isGroupDropTarget,
    isBoundaryDropTarget,
    getDropPlacement,
    shouldShowGroupBoundaries
  };

  function save(nextData) {
    context.setModuleData(toolboxId, moduleId, nextData, "taskPlanner");
  }

  useEffect(() => {
    const intervalId = window.setInterval(() => setNowMs(Date.now()), 60000);
    return () => window.clearInterval(intervalId);
  }, []);

  useEffect(() => () => {
    prerequisiteNoticeTimeouts.current.forEach((timeoutId) => window.clearTimeout(timeoutId));
  }, []);

  useEffect(() => {
    const resetData = applyDueResets(data, nowMs);
    if (resetData !== data) save(resetData);
  });

  function addTask(event) {
    taskDraft.handleSubmit(event, (draft, { reset }) => {
      const cleanTitle = draft.title.trim();
      if (!cleanTitle) return;
      save({
        ...data,
        tasks: [
          ...data.tasks,
          {
            id: context.uid("task"),
            title: cleanTitle,
            description: "",
            type: draft.type,
            checked: false,
            checkedAt: 0
          }
        ]
      });
      reset();
    });
  }

  function updateTask(taskId, updater) {
    save({ ...data, tasks: data.tasks.map((task) => task.id === taskId ? updater(task) : task) });
  }

  function deleteTask(taskId) {
    save({
      ...data,
      tasks: data.tasks.filter((task) => task.id !== taskId),
      relations: data.relations.filter((relation) => relation.fromTaskId !== taskId && relation.toTaskId !== taskId)
    });
  }

  function addLinkTarget(fromTaskId, toTaskId) {
    if (!toTaskId || fromTaskId === toTaskId || data.relations.some((relation) => relation.fromTaskId === fromTaskId && relation.toTaskId === toTaskId)) return;
    save({
      ...data,
      tasks: data.tasks.map((task) => {
        if (task.id !== fromTaskId || !task.category) return task;
        const nextTask = { ...task };
        delete nextTask.category;
        return nextTask;
      }),
      relations: [
        ...data.relations.filter((relation) => relation.fromTaskId !== fromTaskId),
        { id: context.uid("relation"), fromTaskId, toTaskId, prerequisite: false }
      ]
    });
  }

  function removeLinkTarget(fromTaskId, toTaskId) {
    save({
      ...data,
      relations: data.relations.filter((relation) => relation.fromTaskId !== fromTaskId || relation.toTaskId !== toTaskId)
    });
  }

  function setPrerequisite(fromTaskId, toTaskId, prerequisite) {
    const hasRelation = data.relations.some((relation) => relation.fromTaskId === fromTaskId && relation.toTaskId === toTaskId);
    save({
      ...data,
      relations: hasRelation
        ? data.relations.map((relation) => relation.fromTaskId === fromTaskId && relation.toTaskId === toTaskId ? { ...relation, prerequisite } : relation)
        : [...data.relations, { id: context.uid("relation"), fromTaskId, toTaskId, prerequisite }]
    });
  }

  function setTaskCategory(taskId, category) {
    const normalizedCategory = String(category || "").trim();
    const tasks = data.tasks.map((task) => {
      if (task.id !== taskId) return task;
      const nextTask = { ...task };
      if (normalizedCategory) nextTask.category = normalizedCategory;
      else delete nextTask.category;
      return nextTask;
    });
    const categoryOrder = [
      ...data.categoryOrder.filter((categoryName) => tasks.some((task) => task.category === categoryName)),
      ...tasks.map((task) => task.category).filter(Boolean).filter((categoryName) => !data.categoryOrder.includes(categoryName))
    ];
    save({ ...data, tasks, categoryOrder });
  }

  function toggleCategoryCollapsed(category) {
    const collapsedCategories = data.collapsedCategories.includes(category)
      ? data.collapsedCategories.filter((item) => item !== category)
      : [...data.collapsedCategories, category];
    save({ ...data, collapsedCategories });
  }

  function clearCompletedUniqueTasks() {
    const removedTaskIds = new Set(data.tasks.filter((task) => task.type === "unique" && task.checked).map((task) => task.id));
    if (!removedTaskIds.size) return;
    const tasks = data.tasks.filter((task) => !removedTaskIds.has(task.id));
    const relations = data.relations.filter((relation) => !removedTaskIds.has(relation.fromTaskId) && !removedTaskIds.has(relation.toTaskId));
    save({ ...data, tasks, relations });
  }

  function toggleSet(setter, taskId) {
    setter((current) => {
      const next = new Set(current);
      if (next.has(taskId)) next.delete(taskId);
      else next.add(taskId);
      return next;
    });
  }

  function showPrerequisiteNotice(taskId) {
    const currentTimeoutId = prerequisiteNoticeTimeouts.current.get(taskId);
    if (currentTimeoutId) window.clearTimeout(currentTimeoutId);
    setPrerequisiteNoticeTaskIds((current) => new Set(current).add(taskId));
    const timeoutId = window.setTimeout(() => {
      prerequisiteNoticeTimeouts.current.delete(taskId);
      setPrerequisiteNoticeTaskIds((current) => {
        const next = new Set(current);
        next.delete(taskId);
        return next;
      });
    }, 2600);
    prerequisiteNoticeTimeouts.current.set(taskId, timeoutId);
  }

  return (
    <div className="task-planner-module">
      <div className="task-planner-topbar">
        <div className="task-planner-global-controls">
          <button
            className={`tool-split-scroll-toggle task-planner-hide-completed-toggle ${data.hideCompleted ? "active" : ""}`}
            type="button"
            onClick={() => save({ ...data, hideCompleted: !data.hideCompleted })}
            aria-pressed={data.hideCompleted}
            aria-label={textContent.hideCompletedTitle || "Masquer les tâches effectuées"}
            title={textContent.hideCompletedTitle || "Masquer les tâches effectuées"}
          >
            <Icon name={data.hideCompleted ? "eye-closed" : "eye-open"} />
            <i aria-hidden="true" />
          </button>
          <button
            className={`task-planner-settings-toggle ${settingsOpen ? "active" : ""}`}
            type="button"
            onClick={() => setSettingsOpen((value) => !value)}
            aria-expanded={settingsOpen}
            aria-label={textContent.settingsTitle || "Réglages du planificateur"}
            title={textContent.settingsTitle || "Réglages du planificateur"}
          >
            <Icon name="settings" />
            <span>{textContent.settingsButtonLabel || "Paramètres des réinitialisations"}</span>
          </button>
        </div>
        {editing && (
          <div className="task-planner-add-stack">
            <form className="inline-form task-planner-add-form" onSubmit={addTask}>
              <input {...taskDraft.getFieldProps("title", { placeholder: textContent.titlePlaceholder || "Nouvelle tâche" })} />
              <select {...taskDraft.getFieldProps("type", { "aria-label": textContent.typeLabel || "Type" })}>
                {TASK_TYPES.map((taskType) => <option key={taskType} value={taskType}>{getTaskTypeLabel(taskType, textContent)}</option>)}
              </select>
              <button className="primary">{textContent.addButton || "Ajouter"}</button>
            </form>
            <TextExchangeActions type="taskPlanner" data={data} context={context} textContent={textContent} onImport={(nextData) => save(nextData)} />
          </div>
        )}
      </div>

      {settingsOpen && (
        <section className="task-planner-settings" aria-label={textContent.settingsTitle || "Réglages du planificateur"}>
          <label>
            <span>{textContent.globalWeeklyResetDayLabel || "Reset hebdo"}</span>
            <select value={data.weeklyResetDay} onChange={(event) => save({ ...data, weeklyResetDay: Number(event.target.value) })}>
              {WEEK_DAYS.map((day) => <option key={day.value} value={day.value}>{day.label}</option>)}
            </select>
          </label>
          <label>
            <span>{textContent.resetTimeLabel || "Heure de reset"}</span>
            <input type="time" value={data.resetTime} onChange={(event) => save({ ...data, resetTime: event.target.value || "00:00" })} />
          </label>
          <div className="task-planner-settings-actions">
            <button
              className="task-planner-clear-completed-button danger"
              type="button"
              onClick={clearCompletedUniqueTasks}
              disabled={!data.tasks.some((task) => task.type === "unique" && task.checked)}
              title={textContent.clearCompletedUniqueTitle || "Nettoyer les tâches ponctuelles terminées"}
              aria-label={textContent.clearCompletedUniqueTitle || "Nettoyer les tâches ponctuelles terminées"}
            >
              <Icon name="trash" />
              <span>{textContent.clearCompletedUniqueButton || "Nettoyer les tâches ponctuelles terminées"}</span>
            </button>
          </div>
        </section>
      )}

      <ul className="task-planner-list">
        {data.tasks.length ? (
          <TaskPlannerBranch
            parentId=""
            parentMap={parentMap}
            tasks={data.tasks}
            data={data}
            reorder={reorder}
            textContent={textContent}
            openDescriptions={openDescriptions}
            openTaskSettings={openTaskSettings}
            prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds}
            onToggleDescription={(taskId) => toggleSet(setOpenDescriptions, taskId)}
            onToggleSettings={(taskId) => toggleSet(setOpenTaskSettings, taskId)}
            onPrerequisiteNotice={showPrerequisiteNotice}
            onUpdateTask={updateTask}
            onDeleteTask={deleteTask}
            onAddLinkTarget={addLinkTarget}
            onRemoveLinkTarget={removeLinkTarget}
            onSetPrerequisite={setPrerequisite}
            onSetTaskCategory={setTaskCategory}
            onToggleCategoryCollapsed={toggleCategoryCollapsed}
          />
        ) : (
          <li className="task-planner-empty">{textContent.emptyTasks || "Aucune tâche planifiée."}</li>
        )}
      </ul>
    </div>
  );
}

function TaskPlannerBranch({
  parentId,
  parentMap,
  tasks,
  data,
  reorder,
  textContent,
  openDescriptions,
  openTaskSettings,
  prerequisiteNoticeTaskIds,
  onToggleDescription,
  onToggleSettings,
  onPrerequisiteNotice,
  onUpdateTask,
  onDeleteTask,
  onAddLinkTarget,
  onRemoveLinkTarget,
  onSetPrerequisite,
  onSetTaskCategory,
  onToggleCategoryCollapsed,
  visited = new Set()
}) {
  const groupedTasks = getTaskCategoryGroups(tasks, parentMap, parentId, data.categoryOrder);
  const children = [...groupedTasks.uncategorized, ...groupedTasks.categories.flatMap((group) => group.tasks)].filter((task) => !visited.has(task.id));
  if (!children.length) return null;
  const nextVisited = new Set([...visited, ...children.map((task) => task.id)]);
  const showCategoryBoundaryDropZones = !parentId && reorder.shouldShowGroupBoundaries({ parentId });

  function hasVisibleDescendants(taskId, seen = new Set()) {
    if (seen.has(taskId)) return false;
    seen.add(taskId);
    return getTasksForParent(tasks, parentMap, taskId).some((child) => !child.checked || hasVisibleDescendants(child.id, seen));
  }

  function renderTask(task) {
    const nestedChildren = getTasksForParent(tasks, parentMap, task.id).filter((child) => !nextVisited.has(child.id));
    const nestedBranch = nestedChildren.length ? (
      <TaskPlannerBranch
        parentId={task.id}
        parentMap={parentMap}
        tasks={tasks}
        data={data}
        reorder={reorder}
        textContent={textContent}
        openDescriptions={openDescriptions}
        openTaskSettings={openTaskSettings}
        prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds}
        onToggleDescription={onToggleDescription}
        onToggleSettings={onToggleSettings}
        onPrerequisiteNotice={onPrerequisiteNotice}
        onUpdateTask={onUpdateTask}
        onDeleteTask={onDeleteTask}
        onAddLinkTarget={onAddLinkTarget}
        onRemoveLinkTarget={onRemoveLinkTarget}
        onSetPrerequisite={onSetPrerequisite}
        onSetTaskCategory={onSetTaskCategory}
        onToggleCategoryCollapsed={onToggleCategoryCollapsed}
        visited={nextVisited}
      />
    ) : null;
    if (data.hideCompleted && task.checked) {
      if (!hasVisibleDescendants(task.id)) return null;
      return (
        <li className="task-planner-hidden-parent" key={`${task.id}:visible-children`}>
          <div className="task-planner-hidden-parent-line">
            <input
              type="checkbox"
              checked={task.checked}
              onChange={(event) => onUpdateTask(task.id, (current) => ({
                ...current,
                checked: event.target.checked,
                checkedAt: event.target.checked ? Date.now() : 0
              }))}
              aria-label={`${textContent.uncheckTitle || "Marquer non effectué"} ${task.title}`}
            />
            <span title={task.title}>{task.title}</span>
            <small>{getTaskTypeLabel(task.type, textContent)}</small>
          </div>
          <ul className="task-planner-list task-planner-child-list">{nestedBranch}</ul>
        </li>
      );
    }
    return (
      <TaskPlannerItem
        key={task.id}
        task={task}
        tasks={tasks}
        data={data}
        parentMap={parentMap}
        parentId={parentId}
        reorder={reorder}
        textContent={textContent}
        descriptionOpen={openDescriptions.has(task.id)}
        settingsOpen={openTaskSettings.has(task.id)}
        prerequisiteNoticeVisible={prerequisiteNoticeTaskIds.has(task.id)}
        onToggleDescription={() => onToggleDescription(task.id)}
        onToggleSettings={() => onToggleSettings(task.id)}
        onPrerequisiteNotice={onPrerequisiteNotice}
        onUpdateTask={onUpdateTask}
        onDeleteTask={onDeleteTask}
        onAddLinkTarget={onAddLinkTarget}
        onRemoveLinkTarget={onRemoveLinkTarget}
        onSetPrerequisite={onSetPrerequisite}
        onSetTaskCategory={onSetTaskCategory}
      >
        {nestedBranch}
      </TaskPlannerItem>
    );
  }

  function renderCategory(group) {
      const groupTasks = group.tasks.filter((task) => !visited.has(task.id));
      if (!groupTasks.length) return null;
      if (data.hideCompleted && isTaskTreeComplete(groupTasks.map((task) => task.id), tasks, parentMap)) return null;
      const groupCount = countTaskTree(groupTasks.map((task) => task.id), tasks, parentMap);
      const groupCompletedCount = countCompletedTaskTree(groupTasks.map((task) => task.id), tasks, parentMap);
      const isCollapsed = data.collapsedCategories.includes(group.category);
      const sectionClassName = [
        "task-planner-category-section",
        groupCompletedCount === groupCount ? "is-complete" : "",
        isCollapsed ? "is-collapsed" : "",
        reorder.isGroupDragging(group.category, parentId) ? "is-dragging" : "",
        reorder.isGroupDropTarget(group.category, parentId) ? "is-drop-target" : "",
        reorder.getDropPlacement("group", group.category, parentId) === "after" ? "drop-after" : ""
      ].filter(Boolean).join(" ");
      const beforeDropZone = showCategoryBoundaryDropZones ? (
        <li
          className={`task-planner-category-boundary-drop-zone ${reorder.isBoundaryDropTarget({ groupId: group.category, parentId, placement: "before" }) ? "is-drop-target" : ""}`}
          key={`${parentId || "root"}:${group.category}:before-drop`}
          {...reorder.getGroupBoundaryProps({ groupId: group.category, parentId, placement: "before" })}
        />
      ) : null;
      const afterDropZone = showCategoryBoundaryDropZones ? (
        <li
          className={`task-planner-category-boundary-drop-zone ${reorder.isBoundaryDropTarget({ groupId: group.category, parentId, placement: "after" }) ? "is-drop-target" : ""}`}
          key={`${parentId || "root"}:${group.category}:after-drop`}
          {...reorder.getGroupBoundaryProps({ groupId: group.category, parentId, placement: "after" })}
        />
      ) : null;
      return [
        beforeDropZone,
        <li className={sectionClassName} key={`${parentId || "root"}:${group.category}`} {...reorder.getGroupProps({ groupId: group.category, parentId })}>
          <div className="checklist-section-header task-planner-category-header">
            <div className="task-planner-category-title">
              <button
                className="task-planner-category-drag-handle"
                type="button"
                onPointerDown={(event) => reorder.groupReorder.startDrag(event, { groupId: group.category, parentId })}
                aria-label={`${textContent.categoryReorderTitle || "Déplacer la catégorie"} ${group.category}`}
                title={textContent.categoryReorderTitle || "Déplacer la catégorie"}
              >
                <Icon name="drag" />
              </button>
              <h3>{group.category}</h3>
            </div>
            <div className="task-planner-category-actions">
              <span>{groupCompletedCount} / {groupCount}</span>
              <button
                className="checklist-section-collapse-button"
                type="button"
                onClick={() => onToggleCategoryCollapsed(group.category)}
                aria-expanded={!isCollapsed}
                title={isCollapsed ? textContent.showCategoryTitle || "Afficher cette catégorie" : textContent.hideCategoryTitle || "Réduire cette catégorie"}
                aria-label={isCollapsed ? textContent.showCategoryTitle || "Afficher cette catégorie" : textContent.hideCategoryTitle || "Réduire cette catégorie"}
              >
                <Icon name={isCollapsed ? "chevron-down" : "chevron-up"} />
              </button>
            </div>
          </div>
          {!isCollapsed && (
            <ul className="task-planner-list">
              {groupTasks.map(renderTask).filter(Boolean)}
            </ul>
          )}
        </li>,
        afterDropZone
      ];
  }

  const entries = groupedTasks.entries.map((entry) => {
    if (entry.type === "task") return visited.has(entry.task.id) ? null : renderTask(entry.task);
    return renderCategory(entry.group);
  }).filter(Boolean);
  return entries;
}

function TaskPlannerItem({
  task,
  tasks,
  data,
  parentMap,
  parentId,
  reorder,
  textContent,
  descriptionOpen,
  settingsOpen,
  prerequisiteNoticeVisible,
  onToggleDescription,
  onToggleSettings,
  onPrerequisiteNotice,
  onUpdateTask,
  onDeleteTask,
  onAddLinkTarget,
  onRemoveLinkTarget,
  onSetPrerequisite,
  onSetTaskCategory,
  children
}) {
  const parentTask = parentId ? getTaskById(tasks, parentId) : null;
  const inheritedCategory = parentTask ? getEffectiveTaskCategory(parentTask, tasks, parentMap) : "";
  const categoryValue = parentTask ? inheritedCategory : task.category || "";
  const categoryEditable = !parentTask;
  const relations = data.relations.filter((relation) => relation.fromTaskId === task.id);
  const missingPrerequisites = relations.filter((relation) => relation.prerequisite && !tasks.find((item) => item.id === relation.toTaskId)?.checked);
  const relationTargets = tasks.filter((item) => item.id !== task.id && !relations.some((relation) => relation.toTaskId === item.id));
  const noticeMessage = prerequisiteNoticeVisible && missingPrerequisites.length > 0 ? textContent.missingPrerequisiteNotice || "Pré requis parent non effectué" : "";
  const className = [
    "task-planner-item",
    task.checked ? "is-complete" : "",
    missingPrerequisites.length ? "has-missing-prerequisite" : "",
    reorder.isItemDragging(task.id) ? "is-dragging" : "",
    reorder.isItemDropTarget(task.id) ? "is-drop-target" : "",
    reorder.getDropPlacement("item", task.id) === "after" ? "drop-after" : ""
  ].filter(Boolean).join(" ");
  const titleEdit = useInlineEdit({
    value: task.title,
    transform: (draft) => String(draft || "").trim() || task.title,
    onCommit: (title) => onUpdateTask(task.id, (current) => ({ ...current, title }))
  });
  const categoryEdit = useInlineEdit({
    value: categoryValue,
    onCommit: (category) => {
      if (categoryEditable) onSetTaskCategory(task.id, category);
    }
  });
  const descriptionEdit = useInlineEdit({
    value: task.description,
    onCommit: (description) => onUpdateTask(task.id, (current) => ({ ...current, description })),
    commitOnEnter: false
  });

  function updateChecked(event) {
    const checked = event.target.checked;
    if (checked && missingPrerequisites.length > 0) onPrerequisiteNotice(task.id);
    onUpdateTask(task.id, (current) => ({
      ...current,
      checked,
      checkedAt: checked ? Date.now() : 0
    }));
  }

  return (
    <li className={className} {...reorder.getItemProps({ itemId: task.id, groupId: getTaskCategoryDataset(task, tasks, parentMap), parentId })}>
      <div className="task-planner-line">
        <button
          className="task-planner-drag-handle"
          type="button"
          onPointerDown={(event) => reorder.itemReorder.startDrag(event, task.id)}
          aria-label={`${textContent.reorderTitle || "Déplacer"} ${task.title}`}
          title={textContent.reorderTitle || "Déplacer"}
        >
          <Icon name="drag" />
        </button>
        <input
          type="checkbox"
          checked={task.checked}
          onChange={updateChecked}
          aria-label={`${task.checked ? textContent.uncheckTitle || "Marquer non effectué" : textContent.checkTitle || "Marquer effectué"} ${task.title}`}
        />
        <input
          {...titleEdit.getInputProps({
            className: "tool-split-entry-label task-planner-title-input",
            "aria-label": textContent.titleLabel || "Titre"
          })}
        />
        <select
          className="task-planner-type-select"
          value={task.type}
          onChange={(event) => onUpdateTask(task.id, (current) => {
            const nextType = event.target.value;
            const nextTask = { ...current, type: nextType };
            if (nextType !== "weekly") delete nextTask.weeklyResetDay;
            if (nextType !== "daily") delete nextTask.dailyResetTime;
            return nextTask;
          })}
          aria-label={textContent.typeLabel || "Type"}
        >
          {TASK_TYPES.map((taskType) => <option key={taskType} value={taskType}>{getTaskTypeLabel(taskType, textContent)}</option>)}
        </select>
        {missingPrerequisites.length > 0 && (
          <Tooltip
            className="task-planner-warning"
            content={<MissingPrerequisitesTooltip missingPrerequisites={missingPrerequisites} tasks={tasks} textContent={textContent} />}
            position="top-start"
          >
            {textContent.missingPrerequisiteBadge || "Pré requis"}
          </Tooltip>
        )}
        <div className="task-planner-actions">
          <button
            className={`task-planner-dropdown-button ${descriptionOpen ? "active" : ""}`}
            type="button"
            onClick={onToggleDescription}
            aria-expanded={descriptionOpen}
            aria-label={`${descriptionOpen ? textContent.hideDescriptionTitle || "Masquer la description" : textContent.showDescriptionTitle || "Afficher la description"} ${task.title}`}
            title={descriptionOpen ? textContent.hideDescriptionTitle || "Masquer la description" : textContent.showDescriptionTitle || "Afficher la description"}
          >
            <Icon name={descriptionOpen ? "chevron-up" : "chevron-down"} />
          </button>
          <button
            className={`task-planner-settings-button ${settingsOpen ? "active" : ""}`}
            type="button"
            onClick={onToggleSettings}
            aria-expanded={settingsOpen}
            aria-label={`${textContent.taskSettingsTitle || "Réglages de la tâche"} ${task.title}`}
            title={textContent.taskSettingsTitle || "Réglages de la tâche"}
          >
            <Icon name="settings" />
          </button>
          <button className="task-planner-delete-button danger" type="button" onClick={() => onDeleteTask(task.id)} aria-label={`${textContent.deleteTitle || "Supprimer"} ${task.title}`} title={textContent.deleteTitle || "Supprimer"}>
            <Icon name="trash" />
          </button>
        </div>
      </div>
      <InlineNotice className="task-planner-notice" message={noticeMessage} />
      {descriptionOpen && (
        <div className="task-planner-description-panel">
          <label className={`task-planner-category-field ${categoryEditable ? "" : "is-disabled"}`}>
            <span>{textContent.categoryLabel || "Catégorie"}</span>
            <input
              {...categoryEdit.getInputProps({
                disabled: !categoryEditable,
                placeholder: textContent.categoryPlaceholder || "Nom de catégorie",
                "aria-label": `${textContent.categoryLabel || "Catégorie"} ${task.title}`
              })}
            />
          </label>
          <label className="task-planner-description-field">
            <span>{textContent.descriptionLabel || "Description"}</span>
            <textarea
              {...descriptionEdit.getInputProps({
                className: "task-planner-description",
                placeholder: textContent.descriptionPlaceholder || "Description",
                "aria-label": `${textContent.descriptionLabel || "Description"} ${task.title}`
              })}
            />
          </label>
        </div>
      )}
      {settingsOpen && (
        <div className="task-planner-task-settings">
          <TaskResetSettings task={task} data={data} textContent={textContent} onUpdateTask={onUpdateTask} />
          <LinksEditor
            label={textContent.linksLabel || "Parent"}
            relations={relations}
            task={task}
            tasks={tasks}
            parentMap={parentMap}
            relationTargets={relationTargets}
            emptyLabel={textContent.emptyLinks || "Aucun parent"}
            addLabel={textContent.addLinkLabel || "Définir un parent"}
            removeLabel={textContent.removeRelationTitle || "Retirer"}
            prerequisiteLabel={textContent.prerequisiteCheckboxLabel || "Pré requis"}
            onAddLinkTarget={onAddLinkTarget}
            onRemoveLinkTarget={onRemoveLinkTarget}
            onSetPrerequisite={onSetPrerequisite}
          />
        </div>
      )}
      {children && <ul className="task-planner-list task-planner-child-list">{children}</ul>}
    </li>
  );
}

function MissingPrerequisitesTooltip({ missingPrerequisites, tasks, textContent }) {
  return (
    <span className="task-planner-prerequisite-tooltip">
      <strong>{textContent.missingPrerequisiteTitle || "Pré requis non effectué"}</strong>
      <span>
        {missingPrerequisites.map((relation) => (
          <span key={relation.id}>{getTaskTitle(tasks, relation.toTaskId)}</span>
        ))}
      </span>
    </span>
  );
}

function TaskResetSettings({ task, data, textContent, onUpdateTask }) {
  if (task.type === "daily") {
    const hasOverride = Boolean(task.dailyResetTime);
    return (
      <div className="task-planner-reset-override">
        <span>{textContent.taskDailyResetTimeLabel || "Heure quotidienne"}</span>
        <div className="task-planner-reset-control">
          <input
            type="time"
            value={task.dailyResetTime || data.resetTime}
            onChange={(event) => onUpdateTask(task.id, (current) => {
              const nextTask = { ...current };
              if (event.target.value && event.target.value !== data.resetTime) nextTask.dailyResetTime = event.target.value;
              else delete nextTask.dailyResetTime;
              return nextTask;
            })}
            aria-label={`${textContent.taskDailyResetTimeLabel || "Heure quotidienne"} ${task.title}`}
          />
          <button
            type="button"
            onClick={() => onUpdateTask(task.id, (current) => {
              const nextTask = { ...current };
              delete nextTask.dailyResetTime;
              return nextTask;
            })}
            disabled={!hasOverride}
            title={textContent.inheritResetTime || "Utiliser l'heure globale"}
            aria-label={`${textContent.inheritResetTime || "Utiliser l'heure globale"} ${task.title}`}
          >
            <Icon name="rubber" />
          </button>
        </div>
      </div>
    );
  }

  if (task.type === "weekly") {
    return (
      <label className="task-planner-reset-override">
        <span>{textContent.taskWeeklyResetDayLabel || "Jour hebdo"}</span>
        <select
          value={task.weeklyResetDay ?? ""}
          onChange={(event) => onUpdateTask(task.id, (current) => {
            const nextTask = { ...current };
            if (event.target.value === "") {
              delete nextTask.weeklyResetDay;
            } else {
              nextTask.weeklyResetDay = Number(event.target.value);
            }
            return nextTask;
          })}
        >
          <option value="">{textContent.inheritWeeklyResetDay || "Global"}</option>
          {WEEK_DAYS.map((day) => <option key={day.value} value={day.value}>{day.label}</option>)}
        </select>
      </label>
    );
  }

  return (
    <div className="task-planner-reset-override is-empty">
      <span>{textContent.taskResetLabel || "Réinitialisation"}</span>
      <p>{textContent.noTaskResetLabel || "Aucun reset"}</p>
    </div>
  );
}

function LinksEditor({ label, relations, task, tasks, parentMap, relationTargets, emptyLabel, addLabel, removeLabel, prerequisiteLabel, onAddLinkTarget, onRemoveLinkTarget, onSetPrerequisite }) {
  const descendantIds = new Set();
  function collectDescendants(taskId) {
    tasks.filter((item) => parentMap.get(item.id) === taskId).forEach((child) => {
      descendantIds.add(child.id);
      collectDescendants(child.id);
    });
  }
  collectDescendants(task.id);
  const availableTargets = relationTargets.filter((target) => !descendantIds.has(target.id));

  return (
    <div className="task-planner-relations">
      <span>{label}</span>
      <select
        value=""
        onChange={(event) => {
          onAddLinkTarget(task.id, event.target.value);
          event.target.value = "";
        }}
        aria-label={addLabel}
      >
        <option value="">{addLabel}</option>
        {availableTargets.map((target) => <option key={target.id} value={target.id}>{target.title}</option>)}
      </select>
      <div>
        {relations.length ? relations.map((relation) => (
          <div className="task-planner-relation-chip" key={relation.id}>
            <span>{getTaskTitle(tasks, relation.toTaskId)}</span>
            <label title={prerequisiteLabel}>
              <input
                type="checkbox"
                checked={relation.prerequisite}
                onChange={(event) => onSetPrerequisite(task.id, relation.toTaskId, event.target.checked)}
                aria-label={`${prerequisiteLabel} ${getTaskTitle(tasks, relation.toTaskId)}`}
              />
              <span>{prerequisiteLabel}</span>
            </label>
            <button type="button" onClick={() => onRemoveLinkTarget(task.id, relation.toTaskId)} title={removeLabel} aria-label={`${removeLabel} ${getTaskTitle(tasks, relation.toTaskId)}`}>
              <Icon name="close" />
            </button>
          </div>
        )) : <em>{emptyLabel}</em>}
      </div>
    </div>
  );
}
