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

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, 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 moveCategory(categoryOrder, fromCategory, toCategory, placement = "before") {
  const index = categoryOrder.indexOf(fromCategory);
  const targetIndex = categoryOrder.indexOf(toCategory);
  if (index < 0 || targetIndex < 0 || fromCategory === toCategory) return categoryOrder;
  const nextOrder = [...categoryOrder];
  const [moved] = nextOrder.splice(index, 1);
  const nextTargetIndex = nextOrder.indexOf(toCategory);
  nextOrder.splice(placement === "after" ? nextTargetIndex + 1 : nextTargetIndex, 0, moved);
  return nextOrder;
}

function sortTasks(tasks, sortMode) {
  if (sortMode !== "type") return tasks;
  const order = new Map(TASK_TYPES.map((type, index) => [type, index]));
  return [...tasks].sort((a, b) => (order.get(a.type) ?? 99) - (order.get(b.type) ?? 99));
}

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, sortMode) {
  return sortTasks(tasks.filter((task) => (parentMap.get(task.id) || "") === parentId), sortMode);
}

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 getTaskCategoryGroups(tasks, parentMap, parentId, sortMode, categoryOrder) {
  const siblings = getTasksForParent(tasks, parentMap, parentId, sortMode);
  if (parentId) {
    return {
      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))
  ];
  return {
    uncategorized: siblings.filter((task) => !getTaskCategoryForParent(task, tasks, parentMap, parentId)),
    categories: orderedCategories.map((category) => ({
      category,
      tasks: siblings.filter((task) => getTaskCategoryForParent(task, tasks, parentMap, parentId) === category)
    })).filter((group) => group.tasks.length)
  };
}

function getCategorySectionId(parentId, category) {
  return `${parentId || ""}\n${category}`;
}

function parseCategorySectionId(id) {
  const separatorIndex = id.indexOf("\n");
  if (separatorIndex < 0) return { parentId: "", category: id };
  return {
    parentId: id.slice(0, separatorIndex),
    category: id.slice(separatorIndex + 1)
  };
}

export function TaskPlannerModule({ toolboxId, moduleId, context, editing }) {
  const data = context.normalizeTaskPlannerData(context.getModuleData(toolboxId, moduleId, { tasks: [] }));
  const textContent = context.moduleText?.taskPlanner || {};
  const [title, setTitle] = useState("");
  const [type, setType] = useState("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 {
    draggingId,
    dropTarget,
    startDrag
  } = usePointerReorder({
    targetSelector: ".task-planner-item",
    getTargetId: (target) => target.dataset.taskId,
    canDropOn: (target, draggingTaskId) => {
      const draggingTask = data.tasks.find((task) => task.id === draggingTaskId);
      return data.sortMode === "manual"
        && target.dataset.parentId === (parentMap.get(draggingTaskId) || "")
        && target.dataset.category === getTaskCategoryDataset(draggingTask, data.tasks, parentMap);
    },
    onMove: (fromTaskId, toTaskId, placement) => save({ ...data, tasks: moveTask(data.tasks, fromTaskId, toTaskId, placement) })
  });
  const {
    draggingId: draggingCategoryId,
    dropTarget: categoryDropTarget,
    startDrag: startCategoryDrag
  } = usePointerReorder({
    targetSelector: ".task-planner-category-section",
    getTargetId: (target) => getCategorySectionId(target.dataset.parentId || "", target.dataset.category || ""),
    canDropOn: (target, draggingIdValue) => {
      const draggingCategory = parseCategorySectionId(draggingIdValue);
      return target.dataset.parentId === draggingCategory.parentId && Boolean(target.dataset.category);
    },
    onMove: (fromId, toId, placement) => {
      const fromCategory = parseCategorySectionId(fromId).category;
      const toCategory = parseCategorySectionId(toId).category;
      save({ ...data, categoryOrder: moveCategory(data.categoryOrder, fromCategory, toCategory, placement) });
    }
  });

  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) {
    event.preventDefault();
    const cleanTitle = title.trim();
    if (!cleanTitle) return;
    save({
      ...data,
      tasks: [
        ...data.tasks,
        {
          id: context.uid("task"),
          title: cleanTitle,
          description: "",
          type,
          checked: false,
          checkedAt: 0
        }
      ]
    });
    setTitle("");
    setType("daily");
  }

  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 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-sort-toggle ${data.sortMode === "type" ? "active" : ""}`}
            type="button"
            onClick={() => save({ ...data, sortMode: data.sortMode === "type" ? "manual" : "type" })}
            aria-pressed={data.sortMode === "type"}
            aria-label={textContent.sortModeLabel || "Tri automatique"}
            title={textContent.sortModeLabel || "Tri automatique"}
          >
            <Icon name="sort-time" />
            <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 && (
          <form className="inline-form task-planner-add-form" onSubmit={addTask}>
            <input name="title" placeholder={textContent.titlePlaceholder || "Nouvelle tâche"} value={title} onChange={(event) => setTitle(event.target.value)} />
            <select value={type} onChange={(event) => setType(event.target.value)} 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>
        )}
      </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>
        </section>
      )}

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

function TaskPlannerBranch({
  parentId,
  parentMap,
  tasks,
  data,
  draggingId,
  dropTarget,
  draggingCategoryId,
  categoryDropTarget,
  textContent,
  openDescriptions,
  openTaskSettings,
  prerequisiteNoticeTaskIds,
  onDragStart,
  onCategoryDragStart,
  onToggleDescription,
  onToggleSettings,
  onPrerequisiteNotice,
  onUpdateTask,
  onDeleteTask,
  onAddLinkTarget,
  onRemoveLinkTarget,
  onSetPrerequisite,
  onSetTaskCategory,
  visited = new Set()
}) {
  const groupedTasks = getTaskCategoryGroups(tasks, parentMap, parentId, data.sortMode, 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)]);

  function renderTask(task) {
    const nestedChildren = getTasksForParent(tasks, parentMap, task.id, data.sortMode).filter((child) => !nextVisited.has(child.id));
    return (
      <TaskPlannerItem
        key={task.id}
        task={task}
        tasks={tasks}
        data={data}
        parentMap={parentMap}
        parentId={parentId}
        draggingId={draggingId}
        dropTarget={dropTarget}
        textContent={textContent}
        descriptionOpen={openDescriptions.has(task.id)}
        settingsOpen={openTaskSettings.has(task.id)}
        prerequisiteNoticeVisible={prerequisiteNoticeTaskIds.has(task.id)}
        onDragStart={onDragStart}
        onToggleDescription={() => onToggleDescription(task.id)}
        onToggleSettings={() => onToggleSettings(task.id)}
        onPrerequisiteNotice={onPrerequisiteNotice}
        onUpdateTask={onUpdateTask}
        onDeleteTask={onDeleteTask}
        onAddLinkTarget={onAddLinkTarget}
        onRemoveLinkTarget={onRemoveLinkTarget}
        onSetPrerequisite={onSetPrerequisite}
        onSetTaskCategory={onSetTaskCategory}
      >
        {nestedChildren.length ? (
          <TaskPlannerBranch
            parentId={task.id}
            parentMap={parentMap}
            tasks={tasks}
            data={data}
            draggingId={draggingId}
            dropTarget={dropTarget}
            draggingCategoryId={draggingCategoryId}
            categoryDropTarget={categoryDropTarget}
            textContent={textContent}
            openDescriptions={openDescriptions}
            openTaskSettings={openTaskSettings}
            prerequisiteNoticeTaskIds={prerequisiteNoticeTaskIds}
            onDragStart={onDragStart}
            onCategoryDragStart={onCategoryDragStart}
            onToggleDescription={onToggleDescription}
            onToggleSettings={onToggleSettings}
            onPrerequisiteNotice={onPrerequisiteNotice}
            onUpdateTask={onUpdateTask}
            onDeleteTask={onDeleteTask}
            onAddLinkTarget={onAddLinkTarget}
            onRemoveLinkTarget={onRemoveLinkTarget}
            onSetPrerequisite={onSetPrerequisite}
            onSetTaskCategory={onSetTaskCategory}
            visited={nextVisited}
          />
        ) : null}
      </TaskPlannerItem>
    );
  }

  return [
    ...groupedTasks.uncategorized.filter((task) => !visited.has(task.id)).map(renderTask),
    ...groupedTasks.categories.map((group) => {
      const groupTasks = group.tasks.filter((task) => !visited.has(task.id));
      if (!groupTasks.length) return null;
      const groupCount = countTaskTree(groupTasks.map((task) => task.id), tasks, parentMap);
      const categoryId = getCategorySectionId(parentId, group.category);
      const sectionClassName = [
        "task-planner-category-section",
        draggingCategoryId === categoryId ? "is-dragging" : "",
        categoryDropTarget.id === categoryId ? "is-drop-target" : "",
        categoryDropTarget.id === categoryId && categoryDropTarget.placement === "after" ? "drop-after" : ""
      ].filter(Boolean).join(" ");
      return (
        <li className={sectionClassName} key={`${parentId || "root"}:${group.category}`} data-parent-id={parentId} data-category={group.category}>
          <div className="checklist-section-header task-planner-category-header">
            <div>
              <button
                className="task-planner-category-drag-handle"
                type="button"
                onPointerDown={(event) => onCategoryDragStart(event, categoryId)}
                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>
            <span>{groupCount}</span>
          </div>
          <ul className="task-planner-list">
            {groupTasks.map(renderTask)}
          </ul>
        </li>
      );
    })
  ].filter(Boolean);
}

function TaskPlannerItem({
  task,
  tasks,
  data,
  parentMap,
  parentId,
  draggingId,
  dropTarget,
  textContent,
  descriptionOpen,
  settingsOpen,
  prerequisiteNoticeVisible,
  onDragStart,
  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 [categoryDraft, setCategoryDraft] = useState(categoryValue);
  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" : "",
    draggingId === task.id ? "is-dragging" : "",
    dropTarget.id === task.id ? "is-drop-target" : "",
    dropTarget.id === task.id && dropTarget.placement === "after" ? "drop-after" : ""
  ].filter(Boolean).join(" ");

  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
    }));
  }

  useEffect(() => {
    setCategoryDraft(categoryValue);
  }, [categoryValue, task.id]);

  function commitCategoryDraft() {
    if (categoryEditable && categoryDraft.trim() !== (task.category || "")) onSetTaskCategory(task.id, categoryDraft);
  }

  return (
    <li className={className} data-task-id={task.id} data-parent-id={parentId} data-category={getTaskCategoryDataset(task, tasks, parentMap)}>
      <div className="task-planner-line">
        <button
          className="task-planner-drag-handle"
          type="button"
          onPointerDown={(event) => onDragStart(event, task.id)}
          disabled={data.sortMode !== "manual"}
          aria-label={`${textContent.reorderTitle || "Déplacer"} ${task.title}`}
          title={data.sortMode === "manual" ? textContent.reorderTitle || "Déplacer" : textContent.reorderDisabledTitle || "Tri manuel désactivé"}
        >
          <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
          className="tool-split-entry-label task-planner-title-input"
          value={task.title}
          onChange={(event) => onUpdateTask(task.id, (current) => ({ ...current, title: event.target.value }))}
          onBlur={(event) => onUpdateTask(task.id, (current) => ({ ...current, title: event.target.value.trim() || current.title }))}
          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;
            return nextTask;
          })}
          aria-label={textContent.typeLabel || "Type"}
        >
          {TASK_TYPES.map((taskType) => <option key={taskType} value={taskType}>{getTaskTypeLabel(taskType, textContent)}</option>)}
        </select>
        {missingPrerequisites.length > 0 && (
          <span className="task-planner-warning" title={textContent.missingPrerequisiteTitle || "Pré requis non effectué"}>
            {textContent.missingPrerequisiteBadge || "Pré requis"}
          </span>
        )}
        <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
              value={categoryDraft}
              onChange={(event) => setCategoryDraft(event.target.value)}
              onBlur={commitCategoryDraft}
              onKeyDown={(event) => {
                if (event.key === "Enter") event.currentTarget.blur();
              }}
              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
              className="task-planner-description"
              value={task.description}
              onChange={(event) => onUpdateTask(task.id, (current) => ({ ...current, description: event.target.value }))}
              placeholder={textContent.descriptionPlaceholder || "Description"}
              aria-label={`${textContent.descriptionLabel || "Description"} ${task.title}`}
            />
          </label>
        </div>
      )}
      {settingsOpen && (
        <div className="task-planner-task-settings">
        {task.type === "weekly" && (
          <label className="task-planner-weekly-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>
        )}
        <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 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>
      <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>
      <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>
  );
}
