"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type {
  Employee,
  Initiative,
  InitiativeStatus,
  InitiativeType,
  MarketingLocation,
  MarketingRole,
  MilestoneStatus,
  OpinionPublica,
  Task,
  TaskStatus,
} from "@/lib/marketing";
import {
  formatCurrency,
  formatDate,
  getStatusPillClass,
  INITIATIVE_STATUS_LABELS,
  INITIATIVE_TYPE_LABELS,
  MILESTONE_STATUS_LABELS,
  OPINION_PUBLICA_LABELS,
  TASK_STATUS_LABELS,
} from "@/lib/marketing/labels";
import { PROJECT_STAGE_LABELS } from "@/lib/projects/labels";

type InitiativeDrawerProps = {
  initiative: Initiative | null;
  tasksById: Record<string, Task>;
  employeesById: Record<string, Employee>;
  locationsById: Record<string, MarketingLocation>;
  role: MarketingRole;
  currentEmployeeId?: string;
  isOpen: boolean;
  onClose: () => void;
  onSaveInitiative: (initiative: Initiative) => void | Promise<boolean>;
  onDeleteInitiative?: (initiativeId: string) => void;
  isDeletingInitiative?: boolean;
  onUpdateTask: (taskId: string, patch: Partial<Pick<Task, "status" | "evidenceLinks">>) => void;
  onCreateTask: (input: { initiativeId: string; title: string; description: string; assigneeId: string; dueDate: string }) => void;
  onCreateMilestone: (input: { initiativeId: string; title: string; description: string; dueDate: string }) => void;
  onUpdateMilestone: (milestoneId: string, patch: { status?: MilestoneStatus }) => void;
  onAddMilestoneCheckpoint: (input: { milestoneId: string; note: string }) => void;
  mode?: "marketing" | "projects";
};

const INITIATIVE_STATUS_OPTIONS: InitiativeStatus[] = ["planning", "in_progress", "completion", "results", "evaluation"];
const INITIATIVE_TYPE_OPTIONS: InitiativeType[] = ["evento", "campania", "cambio", "implementacion", "otro"];
const TASK_STATUS_OPTIONS: TaskStatus[] = ["todo", "in_progress", "blocked", "done"];
const MILESTONE_STATUS_OPTIONS: MilestoneStatus[] = ["pending", "in_progress", "completed"];
const OPINION_OPTIONS: OpinionPublica[] = ["positive", "mixed", "negative"];
type InitiativeDrawerTab = "projection" | "retro" | "planning" | "evidence" | "tasks";

const EXECUTION_TAB_LABELS: Array<{ key: InitiativeDrawerTab; label: string }> = [
  { key: "projection", label: "Proyección" },
  { key: "retro", label: "Retro" },
  { key: "planning", label: "Planeación" },
  { key: "evidence", label: "Evidencia" },
  { key: "tasks", label: "Tareas" },
];

const PLANNING_TAB_LABELS: Array<{ key: InitiativeDrawerTab; label: string }> = [
  { key: "projection", label: "Objetivos" },
  { key: "planning", label: "Planeación" },
  { key: "tasks", label: "Tareas" },
  { key: "evidence", label: "Equipo" },
];

const PROJECT_EXECUTION_TAB_LABELS: Array<{ key: InitiativeDrawerTab; label: string }> = [
  { key: "projection", label: "Definición" },
  { key: "planning", label: "Planeación" },
  { key: "tasks", label: "Event Day" },
  { key: "retro", label: "Resultados" },
  { key: "evidence", label: "Results & Evidence" },
];

const PROJECT_PLANNING_TAB_LABELS: Array<{ key: InitiativeDrawerTab; label: string }> = [
  { key: "projection", label: "Brainstorm" },
  { key: "planning", label: "Planning" },
  { key: "tasks", label: "Event Day" },
  { key: "evidence", label: "Results & Evidence" },
];

type InitiativeWithProjectFinancials = Initiative & {
  plannedCost?: number;
  actualCost?: number;
  targetTicketPrice?: number;
  actualTicketPrice?: number;
  plannedRevenue?: number;
  actualRevenue?: number;
  plannedProfit?: number;
  actualProfit?: number;
  actualMarginPct?: number;
};

function roleCaption(role: MarketingRole): string {
  if (role === "lead" || role === "owner") {
    return "Puedes editar objetivos, resultados, retro, contributors y tareas.";
  }

  if (role === "employee") {
    return "Puedes actualizar avance y evidencia en tus tareas asignadas.";
  }

  return "Vista de solo lectura para dirección.";
}

function toNumber(value: string): number {
  const normalized = value.trim().replace(",", ".");
  if (normalized.length === 0) {
    return Number.NaN;
  }

  const parsed = Number(normalized);
  return Number.isFinite(parsed) ? parsed : Number.NaN;
}

function toFiniteNumber(value: unknown): number {
  const parsed = typeof value === "number" ? value : Number(value);
  return Number.isFinite(parsed) ? parsed : 0;
}

function toNumberInputValue(value: number): string | number {
  return Number.isFinite(value) ? value : "";
}

export default function InitiativeDrawer({
  initiative,
  tasksById,
  employeesById,
  locationsById,
  role,
  currentEmployeeId,
  isOpen,
  onClose,
  onSaveInitiative,
  onDeleteInitiative,
  isDeletingInitiative = false,
  onUpdateTask,
  onCreateTask,
  onCreateMilestone,
  onUpdateMilestone,
  onAddMilestoneCheckpoint,
  mode = "marketing",
}: InitiativeDrawerProps) {
  const isLead = role === "lead" || role === "owner";
  const isEmployee = role === "employee";

  const employees = useMemo(
    () => Object.values(employeesById).sort((a, b) => a.name.localeCompare(b.name, "es-MX")),
    [employeesById]
  );
  const locations = useMemo(
    () => Object.values(locationsById).sort((a, b) => a.name.localeCompare(b.name, "es-MX")),
    [locationsById]
  );

  const [draft, setDraft] = useState<Initiative | null>(initiative);
  const [initiativeEvidenceInput, setInitiativeEvidenceInput] = useState("");
  const [taskEvidenceInputs, setTaskEvidenceInputs] = useState<Record<string, string>>({});
  const [newTaskTitle, setNewTaskTitle] = useState("");
  const [newTaskDescription, setNewTaskDescription] = useState("");
  const [newTaskAssigneeId, setNewTaskAssigneeId] = useState("");
  const [newTaskDueDate, setNewTaskDueDate] = useState("");
  const [newMilestoneTitle, setNewMilestoneTitle] = useState("");
  const [newMilestoneDescription, setNewMilestoneDescription] = useState("");
  const [newMilestoneDueDate, setNewMilestoneDueDate] = useState("");
  const [checkpointInputs, setCheckpointInputs] = useState<Record<string, string>>({});
  const [activeTab, setActiveTab] = useState<InitiativeDrawerTab>("projection");
  const [isSavingInitiative, setIsSavingInitiative] = useState(false);
  const [saveFeedback, setSaveFeedback] = useState<{ kind: "success" | "error"; message: string } | null>(null);
  const [mounted, setMounted] = useState(false);
  const initializedInitiativeIdRef = useRef<string | null>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!initiative) {
      initializedInitiativeIdRef.current = null;
      setDraft(null);
      return;
    }

    if (initializedInitiativeIdRef.current === initiative.id) {
      return;
    }

    initializedInitiativeIdRef.current = initiative.id;
    setDraft(initiative);
    setInitiativeEvidenceInput("");
    setTaskEvidenceInputs({});
    setCheckpointInputs({});
    const defaultAssignee = initiative.contributorIds[0] ?? initiative.ownerId ?? "";
    setNewTaskAssigneeId(defaultAssignee);
    setNewTaskDueDate(initiative.dueDate);
    setNewTaskTitle("");
    setNewTaskDescription("");
    setNewMilestoneTitle("");
    setNewMilestoneDescription("");
    setNewMilestoneDueDate(initiative.dueDate);
    setActiveTab("projection");
    setSaveFeedback(null);
    setIsSavingInitiative(false);
  }, [initiative]);

  useEffect(() => {
    if (!draft) {
      return;
    }

    if (newTaskAssigneeId && employees.some((employee) => employee.id === newTaskAssigneeId)) {
      return;
    }

    const preferredAssignee =
      draft.contributorIds.find((contributorId) => employees.some((employee) => employee.id === contributorId)) ??
      (employees.some((employee) => employee.id === draft.ownerId) ? draft.ownerId : employees[0]?.id ?? "");

    setNewTaskAssigneeId(preferredAssignee);
  }, [draft, employees, newTaskAssigneeId]);

  if (!mounted || !isOpen || !initiative || !draft) {
    return null;
  }

  const ownerName = employeesById[draft.ownerId]?.name ?? "Sin dueño";
  const contributorNames = draft.contributorIds
    .map((contributorId) => employeesById[contributorId]?.name)
    .filter((value): value is string => Boolean(value));

  const scopedLocations = draft.locationIds
    .map((locationId) => locationsById[locationId]?.name)
    .filter((value): value is string => Boolean(value));

  const tasks = draft.taskIds
    .map((taskId) => tasksById[taskId])
    .filter((task): task is Task => Boolean(task));
  const milestones = (draft.milestones ?? []).slice().sort((a, b) => a.sortOrder - b.sortOrder);
  const isPlanningStage = draft.status === "planning";
  const isProjectsPlanPhase = mode === "projects" && (draft.status === "planning" || draft.status === "in_progress");
  const isProjectsActualPhase = mode === "projects" && (draft.status === "completion" || draft.status === "results" || draft.status === "evaluation");
  const drawerTabs =
    mode === "projects"
      ? isProjectsPlanPhase
        ? PROJECT_PLANNING_TAB_LABELS
        : PROJECT_EXECUTION_TAB_LABELS
      : isPlanningStage
        ? PLANNING_TAB_LABELS
        : EXECUTION_TAB_LABELS;
  const wizardSteps = drawerTabs.map((item) => item.key);
  const currentTab = wizardSteps.includes(activeTab) ? activeTab : wizardSteps[0];
  const activeStepIndex = wizardSteps.indexOf(currentTab);
  const safeActiveStepIndex = activeStepIndex < 0 ? 0 : activeStepIndex;
  const selectedMetricCount = Object.values(draft.metricSelection).filter(Boolean).length;
  const projectionTargetsReady =
    (draft.metricSelection.score ? draft.metrics.target > 0 : true) &&
    (draft.metricSelection.tickets ? draft.metrics.ticketsTarget > 0 : true) &&
    (draft.metricSelection.revenue ? draft.metrics.revenueTarget > 0 : true);
  const completedByStep = {
    projection: selectedMetricCount > 0 && projectionTargetsReady && draft.dueDate.length > 0,
    retro:
      draft.retro.queFunciono.trim().length > 0 || draft.retro.queNo.trim().length > 0 || draft.retro.proximoIntento.trim().length > 0,
    planning: milestones.length > 0,
    evidence: mode === "projects" ? draft.evidenceLinks.length > 0 : isPlanningStage ? true : draft.contributorIds.length > 0 || draft.evidenceLinks.length > 0,
    tasks: tasks.length > 0,
  } satisfies Record<InitiativeDrawerTab, boolean>;
  const completedSteps = wizardSteps.filter((step) => completedByStep[step]).length;
  const statusLabels = mode === "projects" ? PROJECT_STAGE_LABELS : INITIATIVE_STATUS_LABELS;
  const projectDraft = draft as InitiativeWithProjectFinancials;
  const isEventProject = mode === "projects" && draft.type === "evento";
  const plannedCost = Math.max(0, toFiniteNumber(projectDraft.plannedCost));
  const actualCost = Math.max(0, toFiniteNumber(projectDraft.actualCost));
  const targetTicketPrice = Math.max(0, toFiniteNumber(projectDraft.targetTicketPrice));
  const actualTicketPrice = Math.max(0, toFiniteNumber(projectDraft.actualTicketPrice));
  const plannedRevenue = isEventProject
    ? Math.max(0, toFiniteNumber(draft.metrics.ticketsTarget)) * targetTicketPrice
    : toFiniteNumber(draft.metrics.revenueTarget);
  const actualRevenue = isEventProject
    ? Math.max(0, toFiniteNumber(draft.metrics.ticketsActual)) * actualTicketPrice
    : toFiniteNumber(draft.metrics.revenueActual);
  const plannedProfit = plannedRevenue - plannedCost;
  const actualProfit = actualRevenue - actualCost;
  const actualMarginPct = actualRevenue > 0 ? (actualProfit / actualRevenue) * 100 : 0;
  const costVariancePct = plannedCost > 0 ? ((actualCost - plannedCost) / plannedCost) * 100 : 0;
  const revenueVariancePct = plannedRevenue > 0 ? ((actualRevenue - plannedRevenue) / plannedRevenue) * 100 : 0;
  const showTicketFields = mode === "projects" ? isEventProject : draft.metricSelection.tickets;
  const showRevenueFields = mode === "projects" ? !isEventProject : draft.metricSelection.revenue;
  const showActualFields = mode === "projects" ? isProjectsActualPhase : !isPlanningStage;

  const buildSaveDraft = (): Initiative => {
    const fallbackLocationId = locations[0]?.id;
    const hasMetric = Object.values(draft.metricSelection).some(Boolean);
    const safeMetrics = {
      target: toFiniteNumber(draft.metrics.target),
      actual: toFiniteNumber(draft.metrics.actual),
      ticketsTarget: toFiniteNumber(draft.metrics.ticketsTarget),
      ticketsActual: toFiniteNumber(draft.metrics.ticketsActual),
      revenueTarget: toFiniteNumber(draft.metrics.revenueTarget),
      revenueActual: toFiniteNumber(draft.metrics.revenueActual),
    };
    const safeDraft = {
      ...draft,
      metrics: safeMetrics,
    } as InitiativeWithProjectFinancials;

    if (mode === "projects") {
      safeDraft.plannedCost = Math.max(0, toFiniteNumber(projectDraft.plannedCost));
      safeDraft.actualCost = Math.max(0, toFiniteNumber(projectDraft.actualCost));
      safeDraft.targetTicketPrice = Math.max(0, toFiniteNumber(projectDraft.targetTicketPrice));
      safeDraft.actualTicketPrice = Math.max(0, toFiniteNumber(projectDraft.actualTicketPrice));
    }

    return {
      ...safeDraft,
      metricSelection: hasMetric ? safeDraft.metricSelection : { score: true, tickets: false, revenue: false },
      locationIds:
        !safeDraft.isGlobal && safeDraft.locationIds.length === 0 && fallbackLocationId ? [fallbackLocationId] : safeDraft.locationIds,
    };
  };

  const handlePrevStep = () => {
    if (safeActiveStepIndex <= 0) {
      return;
    }

    setActiveTab(wizardSteps[safeActiveStepIndex - 1]);
  };

  const handleNextStep = () => {
    if (safeActiveStepIndex >= wizardSteps.length - 1) {
      return;
    }

    setActiveTab(wizardSteps[safeActiveStepIndex + 1]);
  };

  const handleSave = async (): Promise<boolean | void> => {
    setIsSavingInitiative(true);
    setSaveFeedback(null);
    try {
      const result = await onSaveInitiative(buildSaveDraft());
      const ok = result !== false;
      setSaveFeedback({
        kind: ok ? "success" : "error",
        message: ok ? "Guardado correctamente." : "No se pudo guardar.",
      });
      return result;
    } catch {
      setSaveFeedback({
        kind: "error",
        message: "No se pudo guardar.",
      });
      return false;
    } finally {
      setIsSavingInitiative(false);
    }
  };
  const isLastStep = safeActiveStepIndex >= wizardSteps.length - 1;

  return createPortal(
    <div className="fixed inset-0 z-50 overflow-hidden">
      <button
        type="button"
        className="absolute inset-0 m-0 appearance-none border-0 bg-transparent p-0"
        onClick={onClose}
        aria-label="Cerrar detalle"
      />
      <aside className="absolute right-0 top-0 h-[100dvh] w-full max-w-2xl overflow-y-auto overscroll-contain border-l border-benell-stroke bg-benell-sidebar px-5 pb-5 pt-3 shadow-xl">
        <div className="mb-4 mt-0 flex items-start justify-between gap-3">
          <div>
            <p className="text-label font-semibold text-benell-text-soft">Detalle de iniciativa</p>
            {isLead ? (
              <input
                type="text"
                value={draft.name}
                onChange={(event) => setDraft((prev) => (prev ? { ...prev, name: event.target.value } : prev))}
                placeholder="Nombre de iniciativa"
                className="text-h2 mt-1 w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 font-semibold"
              />
            ) : (
              <h3 className="text-h2 mt-1 font-semibold">{draft.name}</h3>
            )}
            <p className="text-label mt-1 text-benell-text-soft">{roleCaption(role)}</p>
            {saveFeedback ? (
              <p className={saveFeedback.kind === "success" ? "text-label mt-1 text-benell-green" : "text-label mt-1 text-benell-red"}>
                {saveFeedback.message}
              </p>
            ) : null}
            {draft.updatedByName ? (
              <p className="text-label mt-1 text-benell-text-soft">
                Editado por {draft.updatedByName}
                {draft.updatedAt ? ` · ${formatDate(draft.updatedAt)}` : ""}
              </p>
            ) : null}
          </div>
          <div className="flex items-center gap-2">
            {isLead ? (
              <button
                type="button"
                onClick={() => {
                  void handleSave();
                }}
                disabled={isSavingInitiative}
                className="rounded-pill bg-benell-brown px-3 py-1.5 text-label font-semibold text-white disabled:opacity-60"
              >
                {isSavingInitiative ? "Guardando..." : "Guardar"}
              </button>
            ) : null}
            {isLead && onDeleteInitiative ? (
              <button
                type="button"
                onClick={() => onDeleteInitiative(draft.id)}
                disabled={isDeletingInitiative}
                className="rounded-pill border border-benell-red/40 bg-white px-3 py-1.5 text-label font-semibold text-benell-red disabled:cursor-not-allowed disabled:opacity-60"
              >
                {isDeletingInitiative ? "Eliminando..." : "Eliminar"}
              </button>
            ) : null}
            <button
              type="button"
              onClick={onClose}
              className="rounded-pill border border-benell-stroke bg-white px-3 py-1.5 text-label font-semibold"
            >
              Cerrar
            </button>
          </div>
        </div>

        <div className="grid gap-3 sm:grid-cols-2">
          <article className="rounded-xl border border-benell-stroke bg-white p-3">
            <p className="text-label font-semibold text-benell-text-soft">Tipo</p>
            {isLead ? (
              <select
                value={draft.type}
                onChange={(event) => setDraft((prev) => (prev ? { ...prev, type: event.target.value as InitiativeType } : prev))}
                className="text-body mt-1 w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
              >
                {INITIATIVE_TYPE_OPTIONS.map((type) => (
                  <option key={type} value={type}>
                    {INITIATIVE_TYPE_LABELS[type]}
                  </option>
                ))}
              </select>
            ) : (
              <p className="text-body mt-1 font-semibold">{INITIATIVE_TYPE_LABELS[draft.type]}</p>
            )}
          </article>
          <article className="rounded-xl border border-benell-stroke bg-white p-3">
            <p className="text-label font-semibold text-benell-text-soft">Status</p>
            {isLead ? (
              <select
                value={draft.status}
                onChange={(event) =>
                  setDraft((prev) => (prev ? { ...prev, status: event.target.value as InitiativeStatus } : prev))
                }
                className="text-body mt-1 w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
              >
                {INITIATIVE_STATUS_OPTIONS.map((status) => (
                  <option key={status} value={status}>
                    {statusLabels[status]}
                  </option>
                ))}
              </select>
            ) : (
              <span className={`mt-1 inline-block rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(draft.status)}`}>
                {statusLabels[draft.status]}
              </span>
            )}
          </article>
          <article className="rounded-xl border border-benell-stroke bg-white p-3 sm:col-span-2">
            <p className="text-label font-semibold text-benell-text-soft">Scope de ubicaciones</p>
            {isLead ? (
              <div className="mt-2 space-y-3">
                <div className="flex flex-wrap gap-2">
                  <button
                    type="button"
                    onClick={() => setDraft((prev) => (prev ? { ...prev, isGlobal: true, locationIds: [] } : prev))}
                    className={`rounded-pill px-3 py-1.5 text-label font-semibold ${
                      draft.isGlobal ? "bg-benell-brown text-white" : "border border-benell-stroke bg-benell-surface text-benell-text"
                    }`}
                  >
                    Global (marca/negocio)
                  </button>
                  <button
                    type="button"
                    onClick={() =>
                      setDraft((prev) => {
                        if (!prev) {
                          return prev;
                        }

                        return {
                          ...prev,
                          isGlobal: false,
                          locationIds: prev.locationIds.length > 0 ? prev.locationIds : locations.slice(0, 1).map((item) => item.id),
                        };
                      })
                    }
                    className={`rounded-pill px-3 py-1.5 text-label font-semibold ${
                      !draft.isGlobal ? "bg-benell-brown text-white" : "border border-benell-stroke bg-benell-surface text-benell-text"
                    }`}
                  >
                    Ubicaciones específicas
                  </button>
                </div>

                {!draft.isGlobal ? (
                  <div className="grid gap-1.5 sm:grid-cols-2">
                    {locations.map((location) => {
                      const isChecked = draft.locationIds.includes(location.id);
                      return (
                        <label key={location.id} className="inline-flex items-center gap-2 rounded-xl border border-benell-stroke bg-benell-surface p-2">
                          <input
                            type="checkbox"
                            checked={isChecked}
                            onChange={(event) => {
                              const checked = event.target.checked;
                              setDraft((prev) => {
                                if (!prev) {
                                  return prev;
                                }

                                const nextLocationIds = checked
                                  ? Array.from(new Set([...prev.locationIds, location.id]))
                                  : prev.locationIds.filter((item) => item !== location.id);

                                return {
                                  ...prev,
                                  locationIds: nextLocationIds,
                                };
                              });
                            }}
                          />
                          <span className="text-label">{location.name}</span>
                        </label>
                      );
                    })}
                  </div>
                ) : null}
              </div>
            ) : (
              <p className="text-body mt-1">{draft.isGlobal ? "Global (marca/negocio)" : scopedLocations.join(" + ") || "Sin ubicaciones"}</p>
            )}
          </article>
        </div>

        <div className="mt-5 rounded-xl border border-benell-stroke bg-white p-3">
          <div className="mb-2 flex items-center justify-between gap-2">
            <p className="text-label font-semibold text-benell-text-soft">
              Paso {safeActiveStepIndex + 1} de {wizardSteps.length}
            </p>
            <p className="text-label text-benell-text-soft">
              {completedSteps}/{wizardSteps.length} completados
            </p>
          </div>
          <div className="h-1.5 w-full overflow-hidden rounded-full bg-benell-surface-muted">
            <div
              className="h-full rounded-full bg-benell-brown transition-all"
              style={{ width: `${((safeActiveStepIndex + 1) / wizardSteps.length) * 100}%` }}
            />
          </div>
        </div>

        <div className="mt-3 flex flex-wrap gap-2">
          {drawerTabs.map((tab) => {
            const isActive = currentTab === tab.key;
            return (
              <button
                key={tab.key}
                type="button"
                onClick={() => setActiveTab(tab.key)}
                className={`inline-flex items-center gap-2 rounded-pill px-3 py-1.5 text-label font-semibold transition ${
                  isActive ? "bg-benell-brown text-white" : "border border-benell-stroke bg-white text-benell-text"
                }`}
              >
                <span className={`inline-block size-2 rounded-full ${completedByStep[tab.key] ? "bg-benell-green" : "bg-benell-text-soft/30"}`} />
                {tab.label}
              </button>
            );
          })}
        </div>

        {currentTab === "projection" ? (
        <section className="mt-5 rounded-xl border border-benell-stroke bg-white p-4">
          <h4 className="text-h3 font-semibold">
            {mode === "projects" ? "Definición financiera y operativa" : isPlanningStage ? "Objetivos y metas" : "Proyección y resultado"}
          </h4>
          {(mode === "projects" ? isProjectsPlanPhase : isPlanningStage) ? (
            <p className="text-label mt-2 text-benell-text-soft">
              {mode === "projects"
                ? "Brainstorm y Planning definen metas y costos; Event Day/Completed/Results concentran ejecución y evidencia."
                : "En planeación se definen objetivos. Resultados, calificación y retro se habilitan fuera de esta etapa."}
            </p>
          ) : null}
          {mode === "projects" ? null : (
            <div className="mt-3 rounded-xl border border-benell-stroke bg-benell-surface p-3">
              <p className="text-label font-semibold text-benell-text-soft">KPIs aplicables (elige 1, 2 o 3)</p>
              <div className="mt-2 grid gap-1.5 sm:grid-cols-3">
                {([
                  ["score", "Score general"],
                  ["tickets", "Tickets"],
                  ["revenue", "Revenue"],
                ] as const).map(([metricKey, label]) => {
                  const isChecked = draft.metricSelection[metricKey];
                  const canUncheck = selectedMetricCount > 1;
                  const disabled = !isLead || (isChecked && !canUncheck);
                  return (
                    <label
                      key={metricKey}
                      className={`inline-flex items-center gap-2 rounded-xl border border-benell-stroke p-2 ${
                        disabled ? "bg-benell-surface-muted" : "bg-white"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={isChecked}
                        disabled={disabled}
                        onChange={(event) =>
                          setDraft((prev) =>
                            prev
                              ? {
                                  ...prev,
                                  metricSelection: {
                                    ...prev.metricSelection,
                                    [metricKey]: event.target.checked,
                                  },
                                }
                              : prev
                          )
                        }
                      />
                      <span className="text-label">{label}</span>
                    </label>
                  );
                })}
              </div>
              {selectedMetricCount === 0 ? (
                <p className="text-label mt-2 text-benell-red">Selecciona al menos un KPI.</p>
              ) : null}
            </div>
          )}
          {mode === "marketing" ? (
            <div className="mt-3 rounded-xl border border-benell-stroke bg-benell-surface p-3">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <p className="text-label font-semibold text-benell-text-soft">Attribution de iniciativas</p>
                {showActualFields && draft.autoUpdatedAt ? (
                  <button
                    type="button"
                    disabled={!isLead}
                    onClick={() =>
                      setDraft((prev) =>
                        prev
                          ? {
                              ...prev,
                              metrics: {
                                ...prev.metrics,
                                actual: prev.autoActual ?? prev.metrics.actual,
                                ticketsActual: prev.autoTicketsActual ?? prev.metrics.ticketsActual,
                                revenueActual: prev.autoRevenueActual ?? prev.metrics.revenueActual,
                              },
                            }
                          : prev
                      )
                    }
                    className="rounded-pill border border-benell-stroke bg-white px-3 py-1 text-label font-semibold text-benell-text disabled:opacity-50"
                  >
                    Usar valores auto
                  </button>
                ) : null}
              </div>
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                <label className="space-y-1">
                  <span className="text-label font-semibold text-benell-text-soft">Canal</span>
                  <select
                    value={draft.attributionChannel ?? ""}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev
                          ? {
                              ...prev,
                              attributionChannel:
                                event.target.value === "facebook" || event.target.value === "instagram"
                                  ? event.target.value
                                  : null,
                            }
                          : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                    disabled={!isLead}
                  >
                    <option value="">Sin attribution</option>
                    <option value="facebook">Facebook</option>
                    <option value="instagram">Instagram</option>
                  </select>
                </label>
                <label className="space-y-1">
                  <span className="text-label font-semibold text-benell-text-soft">Page ID</span>
                  <input
                    type="text"
                    value={draft.attributionPageId ?? ""}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? { ...prev, attributionPageId: event.target.value || null } : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                    disabled={!isLead}
                  />
                </label>
                <label className="space-y-1">
                  <span className="text-label font-semibold text-benell-text-soft">Campaign tag</span>
                  <input
                    type="text"
                    value={draft.attributionCampaign ?? ""}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? { ...prev, attributionCampaign: event.target.value || null } : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                    disabled={!isLead}
                  />
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <label className="space-y-1">
                    <span className="text-label font-semibold text-benell-text-soft">Inicio</span>
                    <input
                      type="date"
                      value={draft.attributionStart ?? ""}
                      onChange={(event) =>
                        setDraft((prev) => (prev ? { ...prev, attributionStart: event.target.value || null } : prev))
                      }
                      className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                      disabled={!isLead}
                    />
                  </label>
                  <label className="space-y-1">
                    <span className="text-label font-semibold text-benell-text-soft">Fin</span>
                    <input
                      type="date"
                      value={draft.attributionEnd ?? ""}
                      onChange={(event) =>
                        setDraft((prev) => (prev ? { ...prev, attributionEnd: event.target.value || null } : prev))
                      }
                      className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                      disabled={!isLead}
                    />
                  </label>
                </div>
              </div>
              {draft.autoUpdatedAt ? (
                <p className="text-caption mt-2 text-benell-text-soft">
                  Último auto-fill: {formatDate(draft.autoUpdatedAt)} · Score {toFiniteNumber(draft.autoActual)} · Tickets{" "}
                  {toFiniteNumber(draft.autoTicketsActual)} · Revenue {formatCurrency(toFiniteNumber(draft.autoRevenueActual))}
                </p>
              ) : null}
            </div>
          ) : null}
          <div className="mt-3 grid gap-3 sm:grid-cols-2">
            {mode !== "projects" && draft.metricSelection.score ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Target score</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(draft.metrics.target)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? { ...prev, metrics: { ...prev.metrics, target: toNumber(event.target.value) } } : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{toFiniteNumber(draft.metrics.target)}</p>
                )}
              </label>
            ) : null}

            {showActualFields && mode !== "projects" && draft.metricSelection.score ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Actual score</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(draft.metrics.actual)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? { ...prev, metrics: { ...prev.metrics, actual: toNumber(event.target.value) } } : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{toFiniteNumber(draft.metrics.actual)}</p>
                )}
              </label>
            ) : null}

            {showTicketFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Tickets target</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="numeric"
                    step="1"
                    value={toNumberInputValue(draft.metrics.ticketsTarget)}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev ? { ...prev, metrics: { ...prev.metrics, ticketsTarget: toNumber(event.target.value) } } : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{toFiniteNumber(draft.metrics.ticketsTarget)}</p>
                )}
              </label>
            ) : null}

            {showActualFields && showTicketFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Tickets actual</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="numeric"
                    step="1"
                    value={toNumberInputValue(draft.metrics.ticketsActual)}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev ? { ...prev, metrics: { ...prev.metrics, ticketsActual: toNumber(event.target.value) } } : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{toFiniteNumber(draft.metrics.ticketsActual)}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" && isEventProject ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Precio ticket planeado</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(projectDraft.targetTicketPrice ?? 0)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? ({ ...prev, targetTicketPrice: toNumber(event.target.value) } as Initiative) : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(targetTicketPrice)}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" && isEventProject && showActualFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Precio ticket actual</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(projectDraft.actualTicketPrice ?? 0)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? ({ ...prev, actualTicketPrice: toNumber(event.target.value) } as Initiative) : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(actualTicketPrice)}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" && isEventProject ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Revenue planeado (auto)</span>
                <p className="text-body text-tabular">{formatCurrency(plannedRevenue)}</p>
              </label>
            ) : null}

            {mode === "projects" && isEventProject && showActualFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Revenue actual (auto)</span>
                <p className="text-body text-tabular">{formatCurrency(actualRevenue)}</p>
              </label>
            ) : null}

            {showRevenueFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">
                  {mode === "projects" ? "Revenue planeado" : "Revenue target"}
                </span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(draft.metrics.revenueTarget)}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev ? { ...prev, metrics: { ...prev.metrics, revenueTarget: toNumber(event.target.value) } } : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(toFiniteNumber(draft.metrics.revenueTarget))}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Costo planeado</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(projectDraft.plannedCost ?? 0)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? ({ ...prev, plannedCost: toNumber(event.target.value) } as Initiative) : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(plannedCost)}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" && showActualFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Costo actual</span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(projectDraft.actualCost ?? 0)}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? ({ ...prev, actualCost: toNumber(event.target.value) } as Initiative) : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(actualCost)}</p>
                )}
              </label>
            ) : null}

            {mode === "projects" ? (
              <div className="rounded-xl border border-benell-stroke bg-benell-surface p-3 sm:col-span-2">
                <p className="text-label font-semibold text-benell-text-soft">Rentabilidad</p>
                <p className="text-body mt-1 text-tabular">Utilidad planeada: {formatCurrency(plannedProfit)}</p>
                <p className="text-body text-tabular">Utilidad actual: {formatCurrency(actualProfit)}</p>
                <p className="text-body text-tabular">Margen actual: {actualMarginPct.toFixed(1)}%</p>
                <p className="text-body text-tabular">Variación costo: {costVariancePct.toFixed(1)}%</p>
                <p className="text-body text-tabular">Variación revenue: {revenueVariancePct.toFixed(1)}%</p>
              </div>
            ) : null}

            {showActualFields && showRevenueFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">
                  {mode === "projects" ? "Revenue actual" : "Revenue actual"}
                </span>
                {isLead ? (
                  <input
                    type="text"
                    inputMode="decimal"
                    step="0.01"
                    value={toNumberInputValue(draft.metrics.revenueActual)}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev ? { ...prev, metrics: { ...prev.metrics, revenueActual: toNumber(event.target.value) } } : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body text-tabular">{formatCurrency(toFiniteNumber(draft.metrics.revenueActual))}</p>
                )}
              </label>
            ) : null}

            <label className="space-y-1">
              <span className="text-label font-semibold text-benell-text-soft">Due date</span>
              {isLead ? (
                <input
                  type="date"
                  value={draft.dueDate}
                  onChange={(event) => setDraft((prev) => (prev ? { ...prev, dueDate: event.target.value } : prev))}
                  className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                />
              ) : (
                <p className="text-body text-tabular">{formatDate(draft.dueDate)}</p>
              )}
            </label>

            {showActualFields ? (
              <label className="space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">Rating ejecución (1-5)</span>
                {isLead ? (
                  <select
                    value={draft.leadRating1to5}
                    onChange={(event) =>
                      setDraft((prev) => (prev ? { ...prev, leadRating1to5: Number(event.target.value) as 1 | 2 | 3 | 4 | 5 } : prev))
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  >
                    {[1, 2, 3, 4, 5].map((rating) => (
                      <option key={rating} value={rating}>
                        {rating}
                      </option>
                    ))}
                  </select>
                ) : (
                  <p className="text-body text-tabular">{draft.leadRating1to5}</p>
                )}
              </label>
            ) : null}
          </div>
        </section>
        ) : null}

        {currentTab === "retro" ? (
        <section className="mt-5 rounded-xl border border-benell-stroke bg-white p-4">
          <h4 className="text-h3 font-semibold">Retro cualitativa</h4>
          <div className="mt-3 space-y-3">
            <label className="block space-y-1">
              <span className="text-label font-semibold text-benell-text-soft">Opinión pública</span>
              {isLead ? (
                <select
                  value={draft.retro.opinionPublica}
                  onChange={(event) =>
                    setDraft((prev) =>
                      prev
                        ? {
                            ...prev,
                            retro: { ...prev.retro, opinionPublica: event.target.value as OpinionPublica },
                          }
                        : prev
                    )
                  }
                  className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                >
                  {OPINION_OPTIONS.map((option) => (
                    <option key={option} value={option}>
                      {OPINION_PUBLICA_LABELS[option]}
                    </option>
                  ))}
                </select>
              ) : (
                <p className="text-body">{OPINION_PUBLICA_LABELS[draft.retro.opinionPublica]}</p>
              )}
            </label>

            {([
              ["queFunciono", "Qué funcionó"],
              ["queNo", "Qué no"],
              ["proximoIntento", "Próximo intento"],
            ] as const).map(([key, label]) => (
              <label key={key} className="block space-y-1">
                <span className="text-label font-semibold text-benell-text-soft">{label}</span>
                {isLead ? (
                  <textarea
                    rows={2}
                    value={draft.retro[key]}
                    onChange={(event) =>
                      setDraft((prev) =>
                        prev
                          ? {
                              ...prev,
                              retro: {
                                ...prev.retro,
                                [key]: event.target.value,
                              },
                            }
                          : prev
                      )
                    }
                    className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                ) : (
                  <p className="text-body">{draft.retro[key]}</p>
                )}
              </label>
            ))}
          </div>
        </section>
        ) : null}

        {currentTab === "planning" ? (
        <section className="mt-5 rounded-xl border border-benell-stroke bg-white p-4">
          <h4 className="text-h3 font-semibold">Planeación: milestones y checkpoints</h4>
          <div className="mt-3 space-y-3">
            {milestones.length > 0 ? (
              milestones.map((milestone) => {
                const checkpointInput = checkpointInputs[milestone.id] ?? "";

                return (
                  <article key={milestone.id} className="rounded-xl border border-benell-stroke bg-benell-surface p-3">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <div>
                        <p className="text-body font-semibold">{milestone.title}</p>
                        <p className="text-label mt-1 text-benell-text-soft">Due: {formatDate(milestone.dueDate)}</p>
                      </div>
                      {isLead ? (
                        <select
                          value={milestone.status}
                          onChange={(event) =>
                            onUpdateMilestone(milestone.id, {
                              status: event.target.value as MilestoneStatus,
                            })
                          }
                          className="text-label rounded-xl border border-benell-stroke bg-white px-2 py-1"
                        >
                          {MILESTONE_STATUS_OPTIONS.map((status) => (
                            <option key={status} value={status}>
                              {MILESTONE_STATUS_LABELS[status]}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <span className={`rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(milestone.status)}`}>
                          {MILESTONE_STATUS_LABELS[milestone.status]}
                        </span>
                      )}
                    </div>

                    <p className="text-label mt-2 text-benell-text-soft">{milestone.description || "Sin descripción"}</p>

                    <div className="mt-2 space-y-1">
                      {milestone.checkpoints.length > 0 ? (
                        milestone.checkpoints.map((checkpoint) => (
                          <div key={checkpoint.id} className="rounded-xl border border-benell-stroke bg-white p-2">
                            <p className="text-label">{checkpoint.note}</p>
                            <p className="text-label mt-1 text-benell-text-soft">
                              {checkpoint.createdByName || "Usuario"} · {formatDate(checkpoint.createdAt)}
                            </p>
                          </div>
                        ))
                      ) : (
                        <p className="text-label text-benell-text-soft">Sin checkpoints todavía.</p>
                      )}
                    </div>

                    {isLead ? (
                      <div className="mt-2 flex flex-wrap gap-2">
                        <input
                          type="text"
                          value={checkpointInput}
                          onChange={(event) =>
                            setCheckpointInputs((prev) => ({
                              ...prev,
                              [milestone.id]: event.target.value,
                            }))
                          }
                          placeholder="Nuevo checkpoint o avance"
                          className="text-body min-w-[240px] flex-1 rounded-xl border border-benell-stroke bg-white px-3 py-2"
                        />
                        <button
                          type="button"
                          onClick={() => {
                            const note = checkpointInput.trim();
                            if (!note) {
                              return;
                            }

                            onAddMilestoneCheckpoint({
                              milestoneId: milestone.id,
                              note,
                            });

                            setCheckpointInputs((prev) => ({
                              ...prev,
                              [milestone.id]: "",
                            }));
                          }}
                          className="rounded-pill border border-benell-stroke bg-white px-3 py-2 text-label font-semibold"
                        >
                          Agregar checkpoint
                        </button>
                      </div>
                    ) : null}
                  </article>
                );
              })
            ) : (
              <p className="text-label text-benell-text-soft">No hay milestones configurados.</p>
            )}
          </div>

          {isLead ? (
            <div className="mt-4 rounded-xl border border-benell-stroke bg-white p-3">
              <p className="text-label font-semibold text-benell-text-soft">Nuevo milestone</p>
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                <input
                  type="text"
                  value={newMilestoneTitle}
                  onChange={(event) => setNewMilestoneTitle(event.target.value)}
                  placeholder="Título"
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                />
                <input
                  type="date"
                  value={newMilestoneDueDate}
                  onChange={(event) => setNewMilestoneDueDate(event.target.value)}
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                />
                <textarea
                  rows={2}
                  value={newMilestoneDescription}
                  onChange={(event) => setNewMilestoneDescription(event.target.value)}
                  placeholder="Descripción"
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2 sm:col-span-2"
                />
                <button
                  type="button"
                  onClick={() => {
                    const title = newMilestoneTitle.trim();
                    const description = newMilestoneDescription.trim();
                    if (!title || !newMilestoneDueDate) {
                      return;
                    }

                    onCreateMilestone({
                      initiativeId: draft.id,
                      title,
                      description,
                      dueDate: newMilestoneDueDate,
                    });

                    setNewMilestoneTitle("");
                    setNewMilestoneDescription("");
                  }}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white sm:col-span-2"
                >
                  Agregar milestone
                </button>
              </div>
            </div>
          ) : null}
        </section>
        ) : null}

        {currentTab === "evidence" ? (
        <section className="mt-5 rounded-xl border border-benell-stroke bg-white p-4">
          <h4 className="text-h3 font-semibold">{isPlanningStage ? "Equipo" : "Equipo y evidencia"}</h4>
          <p className="text-body mt-2">Owner: {ownerName}</p>

          {isLead ? (
            <div className="mt-3">
              <p className="text-label font-semibold text-benell-text-soft">Contributors</p>
              <div className="mt-2 grid gap-1 sm:grid-cols-2">
                {employees
                  .filter((employee) => employee.id !== draft.ownerId)
                  .map((employee) => {
                    const isChecked = draft.contributorIds.includes(employee.id);
                    return (
                      <label key={employee.id} className="inline-flex items-center gap-2 rounded-xl border border-benell-stroke bg-benell-surface p-2">
                        <input
                          type="checkbox"
                          checked={isChecked}
                          onChange={(event) => {
                            const checked = event.target.checked;
                            setDraft((prev) => {
                              if (!prev) {
                                return prev;
                              }

                              const nextContributorIds = checked
                                ? Array.from(new Set([...prev.contributorIds, employee.id]))
                                : prev.contributorIds.filter((id) => id !== employee.id);

                              return {
                                ...prev,
                                contributorIds: nextContributorIds,
                              };
                            });
                          }}
                        />
                        <span className="text-label">{employee.name}</span>
                      </label>
                    );
                  })}
              </div>
            </div>
          ) : (
            <p className="text-body mt-1">Contributors: {contributorNames.join(", ") || "Sin contributors"}</p>
          )}

          {isPlanningStage ? (
            <p className="text-label mt-3 text-benell-text-soft">
              La evidencia se carga en etapa de ejecución/resultados.
            </p>
          ) : (
            <>
              <div className="mt-3 space-y-2">
                {draft.evidenceLinks.length > 0 ? (
                  draft.evidenceLinks.map((link) => (
                    <div key={link} className="flex items-center justify-between gap-2 rounded-xl border border-benell-stroke bg-benell-surface p-2">
                      <a href={link} target="_blank" rel="noreferrer" className="block text-label font-semibold text-benell-brown hover:underline">
                        {link}
                      </a>
                      {isLead ? (
                        <button
                          type="button"
                          onClick={() =>
                            setDraft((prev) =>
                              prev
                                ? {
                                    ...prev,
                                    evidenceLinks: prev.evidenceLinks.filter((item) => item !== link),
                                  }
                                : prev
                            )
                          }
                          className="rounded-pill border border-benell-stroke bg-white px-2 py-1 text-label"
                        >
                          Quitar
                        </button>
                      ) : null}
                    </div>
                  ))
                ) : (
                  <p className="text-label text-benell-text-soft">Sin evidencia cargada.</p>
                )}
              </div>

              {isLead || isEmployee ? (
                <div className="mt-3 flex flex-wrap gap-2">
                  <input
                    type="url"
                    value={initiativeEvidenceInput}
                    onChange={(event) => setInitiativeEvidenceInput(event.target.value)}
                    placeholder="https://evidencia.com"
                    className="text-body min-w-[260px] flex-1 rounded-xl border border-benell-stroke bg-white px-3 py-2"
                  />
                  <button
                    type="button"
                    onClick={() => {
                      const value = initiativeEvidenceInput.trim();
                      if (!value) {
                        return;
                      }

                      setDraft((prev) => {
                        if (!prev || prev.evidenceLinks.includes(value)) {
                          return prev;
                        }

                        return {
                          ...prev,
                          evidenceLinks: [...prev.evidenceLinks, value],
                        };
                      });
                      setInitiativeEvidenceInput("");
                    }}
                    className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                  >
                    Agregar evidencia
                  </button>
                </div>
              ) : null}
            </>
          )}
        </section>
        ) : null}

        {currentTab === "tasks" ? (
        <section className="mt-5 rounded-xl border border-benell-stroke bg-white p-4">
          <h4 className="text-h3 font-semibold">Task list</h4>
          <div className="mt-3 space-y-2">
            {tasks.length > 0 ? (
              tasks.map((task) => {
                const taskCanEdit = isLead || (isEmployee && task.assigneeId === currentEmployeeId);
                const taskEvidenceInput = taskEvidenceInputs[task.id] ?? "";

                return (
                  <article key={task.id} className="rounded-xl border border-benell-stroke bg-benell-surface p-3">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <p className="text-body font-semibold">{task.title}</p>
                      {taskCanEdit ? (
                        <select
                          value={task.status}
                          onChange={(event) => onUpdateTask(task.id, { status: event.target.value as TaskStatus })}
                          className="text-label rounded-xl border border-benell-stroke bg-white px-2 py-1"
                        >
                          {TASK_STATUS_OPTIONS.map((status) => (
                            <option key={status} value={status}>
                              {TASK_STATUS_LABELS[status]}
                            </option>
                          ))}
                        </select>
                      ) : (
                        <span className={`rounded-pill px-2 py-1 text-label font-semibold ${getStatusPillClass(task.status)}`}>
                          {TASK_STATUS_LABELS[task.status]}
                        </span>
                      )}
                    </div>
                    <p className="text-label mt-1 text-benell-text-soft">{task.description}</p>
                    <p className="text-label mt-2 text-benell-text-soft">
                      Asignado: {employeesById[task.assigneeId]?.name ?? "Sin asignado"} · Due: {formatDate(task.dueDate)}
                    </p>

                    <div className="mt-2 space-y-1">
                      {task.evidenceLinks.length > 0 ? (
                        task.evidenceLinks.map((link) => (
                          <a key={link} href={link} target="_blank" rel="noreferrer" className="block text-label text-benell-brown hover:underline">
                            {link}
                          </a>
                        ))
                      ) : (
                        <p className="text-label text-benell-text-soft">Sin evidencia en esta tarea.</p>
                      )}
                    </div>

                    {taskCanEdit ? (
                      <div className="mt-2 flex flex-wrap gap-2">
                        <input
                          type="url"
                          value={taskEvidenceInput}
                          onChange={(event) =>
                            setTaskEvidenceInputs((prev) => ({
                              ...prev,
                              [task.id]: event.target.value,
                            }))
                          }
                          placeholder="https://evidencia-tarea.com"
                          className="text-body min-w-[240px] flex-1 rounded-xl border border-benell-stroke bg-white px-3 py-2"
                        />
                        <button
                          type="button"
                          onClick={() => {
                            const value = taskEvidenceInput.trim();
                            if (!value || task.evidenceLinks.includes(value)) {
                              return;
                            }

                            onUpdateTask(task.id, {
                              evidenceLinks: [...task.evidenceLinks, value],
                            });

                            setTaskEvidenceInputs((prev) => ({
                              ...prev,
                              [task.id]: "",
                            }));
                          }}
                          className="rounded-pill border border-benell-stroke bg-white px-3 py-2 text-label font-semibold"
                        >
                          Agregar evidencia
                        </button>
                      </div>
                    ) : null}
                  </article>
                );
              })
            ) : (
              <p className="text-label text-benell-text-soft">Sin tareas ligadas.</p>
            )}
          </div>

          {isLead ? (
            <div className="mt-4 rounded-xl border border-benell-stroke bg-white p-3">
              <p className="text-label font-semibold text-benell-text-soft">Nueva tarea</p>
              {employees.length === 0 ? (
                <p className="text-label mt-2 text-benell-red">No hay personas de Marketing disponibles para asignar.</p>
              ) : null}
              <div className="mt-2 grid gap-2 sm:grid-cols-2">
                <input
                  type="text"
                  value={newTaskTitle}
                  onChange={(event) => setNewTaskTitle(event.target.value)}
                  placeholder="Título"
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                />
                <input
                  type="date"
                  value={newTaskDueDate}
                  onChange={(event) => setNewTaskDueDate(event.target.value)}
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                />
                <textarea
                  rows={2}
                  value={newTaskDescription}
                  onChange={(event) => setNewTaskDescription(event.target.value)}
                  placeholder="Descripción"
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2 sm:col-span-2"
                />
                <select
                  value={newTaskAssigneeId}
                  onChange={(event) => setNewTaskAssigneeId(event.target.value)}
                  className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
                >
                  {employees.length === 0 ? (
                    <option value="">Sin personas</option>
                  ) : null}
                  {employees.map((employee) => (
                    <option key={employee.id} value={employee.id}>
                      {employee.name} · {employee.roleTitle}
                    </option>
                  ))}
                </select>
                <button
                  type="button"
                  onClick={() => {
                    const title = newTaskTitle.trim();
                    const description = newTaskDescription.trim();

                    if (!title || !newTaskAssigneeId || !newTaskDueDate || employees.length === 0) {
                      return;
                    }

                    onCreateTask({
                      initiativeId: draft.id,
                      title,
                      description,
                      assigneeId: newTaskAssigneeId,
                      dueDate: newTaskDueDate,
                    });

                    setNewTaskTitle("");
                    setNewTaskDescription("");
                  }}
                  disabled={employees.length === 0}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60"
                >
                  Agregar tarea
                </button>
              </div>
            </div>
          ) : null}
        </section>
        ) : null}

        <div className="mt-5 flex items-center justify-between gap-2 rounded-xl border border-benell-stroke bg-white p-3">
          <button
            type="button"
            onClick={handlePrevStep}
            disabled={safeActiveStepIndex <= 0}
            className="rounded-pill border border-benell-stroke bg-white px-3 py-2 text-label font-semibold disabled:opacity-50"
          >
            Anterior
          </button>
          <p className="text-label text-benell-text-soft">
            {drawerTabs[safeActiveStepIndex]?.label}
          </p>
          <button
            type="button"
            onClick={async () => {
              if (isLastStep) {
                if (isLead) {
                  const saveResult = await handleSave();
                  if (mode === "projects" && saveResult !== false) {
                    onClose();
                  }
                  return;
                }

                onClose();
                return;
              }

              handleNextStep();
            }}
            className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
          >
            {isLastStep ? (isLead ? "Guardar" : "Listo") : "Siguiente"}
          </button>
        </div>
      </aside>
    </div>,
    document.body
  );
}
