"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { useSession } from "next-auth/react";
import DepartmentKpiTracker from "@/components/kpis/DepartmentKpiTracker";
import type {
  HumanCapitalComplianceObligationDTO,
  HumanCapitalDashboardResponse,
  HumanCapitalFilesListItemDTO,
  HumanCapitalOrgTargetDTO,
  HumanCapitalPayrollSummaryDTO,
  HumanCapitalPersonFilesDTO,
  HumanCapitalVacancyDTO,
  HumanCapitalCareerContentDTO,
  HumanCapitalWorkspaceTabConfig,
} from "@/lib/human-capital/types";

const DEFAULT_TABS: HumanCapitalWorkspaceTabConfig[] = [
  { key: "resumen", label: "Resumen", order: 0, visible: true, widgets: ["summary_metrics"] },
  { key: "expedientes", label: "Expedientes", order: 1, visible: true, widgets: ["people_files_table"] },
  { key: "nomina", label: "Nomina", order: 2, visible: true, widgets: ["payroll_summary"] },
  {
    key: "reclutamiento",
    label: "Reclutamiento",
    order: 3,
    visible: true,
    widgets: ["recruitment_headcount", "recruitment_vacancies", "recruitment_org_target"],
  },
  { key: "desarrollo", label: "Desarrollo", order: 4, visible: true, widgets: ["career_feed"] },
  { key: "cumplimiento", label: "Cumplimiento", order: 5, visible: true, widgets: ["compliance_overview"] },
];

type HumanCapitalPayrollRunDTO = {
  id: string;
  periodStart: string;
  periodEnd: string;
  frequency: string;
  locationCode: string | null;
  status: string;
  source: string | null;
  externalRef: string | null;
  importedAt: string;
};

type HumanCapitalCompliancePaymentDTO = {
  id: string;
  obligationId: string;
  paymentDate: string;
  amount: number;
  status: string;
  referencePeriod: string | null;
  receiptUrl: string | null;
  note: string | null;
};

type HumanCapitalFileEditorItem = HumanCapitalPersonFilesDTO["items"][number];

function normalizeTab(value: string | string[] | undefined) {
  if (!value || Array.isArray(value)) {
    return "resumen";
  }
  return value;
}

export default function HumanCapitalWorkspaceTabPage() {
  const params = useParams<{ tab: string }>();
  const activeTab = normalizeTab(params?.tab);
  const { data: session } = useSession();
  const canManage =
    session?.user?.role === "owner" ||
    (session?.user?.role === "leader" &&
      (session?.user?.department === "capital_humano" || session?.user?.department === "administracion"));

  const [dashboard, setDashboard] = useState<HumanCapitalDashboardResponse | null>(null);
  const [workspaceTabs, setWorkspaceTabs] = useState<HumanCapitalWorkspaceTabConfig[]>(DEFAULT_TABS);
  const [peopleFiles, setPeopleFiles] = useState<HumanCapitalFilesListItemDTO[]>([]);
  const [vacancies, setVacancies] = useState<HumanCapitalVacancyDTO[]>([]);
  const [orgTargets, setOrgTargets] = useState<HumanCapitalOrgTargetDTO[]>([]);
  const [headcount, setHeadcount] = useState<{ total: number; breakdown: Array<{ locationCode: string; roleKey: string; count: number }> } | null>(null);
  const [payrollSummary, setPayrollSummary] = useState<HumanCapitalPayrollSummaryDTO | null>(null);
  const [payrollRuns, setPayrollRuns] = useState<HumanCapitalPayrollRunDTO[]>([]);
  const [announcements, setAnnouncements] = useState<HumanCapitalCareerContentDTO[]>([]);
  const [courses, setCourses] = useState<HumanCapitalCareerContentDTO[]>([]);
  const [compliance, setCompliance] = useState<HumanCapitalComplianceObligationDTO[]>([]);
  const [payments, setPayments] = useState<HumanCapitalCompliancePaymentDTO[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const [payrollDraft, setPayrollDraft] = useState({
    periodStart: "",
    periodEnd: "",
    frequency: "weekly" as "weekly" | "biweekly",
    locationCode: "",
    externalRef: "",
    csvText: "",
  });

  const [vacancyDraft, setVacancyDraft] = useState({ locationCode: "", roleKey: "", title: "" });
  const [orgDraft, setOrgDraft] = useState({ locationCode: "", roleKey: "", targetCount: "" });
  const [announcementDraft, setAnnouncementDraft] = useState({ title: "", body: "" });
  const [courseDraft, setCourseDraft] = useState({ title: "", body: "" });
  const [complianceDraft, setComplianceDraft] = useState({ body: "imss", title: "", dueDate: "" });
  const [paymentDraft, setPaymentDraft] = useState({ obligationId: "", paymentDate: "", amount: 0 });
  const [selectedFileUserId, setSelectedFileUserId] = useState<string | null>(null);
  const [selectedPersonFile, setSelectedPersonFile] = useState<HumanCapitalPersonFilesDTO | null>(null);
  const [loadingPersonFile, setLoadingPersonFile] = useState(false);
  const [savingPersonFile, setSavingPersonFile] = useState(false);
  const [uploadingByRequirement, setUploadingByRequirement] = useState<Record<string, boolean>>({});

  const activeTabConfig = useMemo(
    () => workspaceTabs.find((tab) => tab.key === activeTab),
    [workspaceTabs, activeTab]
  );

  const activeWidgets = useMemo(() => activeTabConfig?.widgets ?? [], [activeTabConfig]);

  const showSummary = activeWidgets.includes("summary_metrics");
  const showFiles = activeWidgets.includes("people_files_table");
  const showPayroll = activeWidgets.includes("payroll_summary");
  const showRecruitmentHeadcount = activeWidgets.includes("recruitment_headcount");
  const showRecruitmentVacancies = activeWidgets.includes("recruitment_vacancies");
  const showRecruitmentOrg = activeWidgets.includes("recruitment_org_target");
  const showCareer = activeWidgets.includes("career_feed");
  const showCompliance = activeWidgets.includes("compliance_overview");

  const loadResumen = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/human-capital/dashboard", { method: "GET", cache: "no-store" });
      const payload = (await response.json()) as HumanCapitalDashboardResponse & { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo cargar Capital Humano.");
      }
      setDashboard(payload);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar Capital Humano.");
    } finally {
      setLoading(false);
    }
  }, []);

  const loadFiles = useCallback(async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/human-capital/files", { method: "GET", cache: "no-store" });
      const payload = (await response.json().catch(() => ({}))) as { files?: HumanCapitalFilesListItemDTO[]; error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudieron cargar expedientes.");
      }
      setPeopleFiles(payload.files ?? []);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudieron cargar expedientes.");
    } finally {
      setLoading(false);
    }
  }, []);

  const loadRecruitment = useCallback(async (includeHeadcount = false) => {
    if (!canManage) {
      return;
    }
    setLoading(true);
    try {
      const requests = [
        fetch("/api/human-capital/recruitment/vacancies", { method: "GET", cache: "no-store" }),
        fetch("/api/human-capital/recruitment/org-targets", { method: "GET", cache: "no-store" }),
      ];
      if (includeHeadcount) {
        requests.push(fetch("/api/human-capital/recruitment/headcount", { method: "GET", cache: "no-store" }));
      }

      const [vacanciesResponse, orgResponse, headcountResponse] = await Promise.all(requests);
      const vacanciesPayload = (await vacanciesResponse.json()) as { vacancies?: HumanCapitalVacancyDTO[]; error?: string };
      if (!vacanciesResponse.ok) {
        throw new Error(vacanciesPayload.error ?? "No se pudieron cargar vacantes.");
      }
      const orgPayload = (await orgResponse.json()) as { targets?: HumanCapitalOrgTargetDTO[]; error?: string };
      if (!orgResponse.ok) {
        throw new Error(orgPayload.error ?? "No se pudieron cargar organigramas.");
      }
      if (includeHeadcount && headcountResponse) {
        const headcountPayload = (await headcountResponse.json()) as { total?: number; breakdown?: Array<{ locationCode: string; roleKey: string; count: number }>; error?: string };
        if (!headcountResponse.ok) {
          throw new Error(headcountPayload.error ?? "No se pudo cargar headcount.");
        }
        setHeadcount({ total: headcountPayload.total ?? 0, breakdown: headcountPayload.breakdown ?? [] });
      }
      setVacancies(vacanciesPayload.vacancies ?? []);
      setOrgTargets(orgPayload.targets ?? []);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar reclutamiento.");
    } finally {
      setLoading(false);
    }
  }, [canManage]);

  const loadPayroll = useCallback(async () => {
    setLoading(true);
    try {
      const [summaryResponse, runsResponse] = await Promise.all([
        fetch("/api/human-capital/payroll/summary", { method: "GET", cache: "no-store" }),
        fetch("/api/human-capital/payroll/runs", { method: "GET", cache: "no-store" }),
      ]);

      const summaryPayload = (await summaryResponse.json()) as { summary?: HumanCapitalPayrollSummaryDTO | null; error?: string };
      if (!summaryResponse.ok) {
        throw new Error(summaryPayload.error ?? "No se pudo cargar nomina.");
      }
      const runsPayload = (await runsResponse.json()) as { runs?: HumanCapitalPayrollRunDTO[]; error?: string };
      if (!runsResponse.ok) {
        throw new Error(runsPayload.error ?? "No se pudieron cargar corridas.");
      }
      setPayrollSummary(summaryPayload.summary ?? null);
      setPayrollRuns(runsPayload.runs ?? []);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar nomina.");
    } finally {
      setLoading(false);
    }
  }, []);

  const loadDevelopment = useCallback(async () => {
    setLoading(true);
    try {
      const [annResponse, courseResponse] = await Promise.all([
        fetch("/api/human-capital/career/announcements", { method: "GET", cache: "no-store" }),
        fetch("/api/human-capital/career/courses", { method: "GET", cache: "no-store" }),
      ]);

      const annPayload = (await annResponse.json()) as { announcements?: HumanCapitalCareerContentDTO[]; error?: string };
      if (!annResponse.ok) {
        throw new Error(annPayload.error ?? "No se pudieron cargar anuncios.");
      }
      const coursePayload = (await courseResponse.json()) as { courses?: HumanCapitalCareerContentDTO[]; error?: string };
      if (!courseResponse.ok) {
        throw new Error(coursePayload.error ?? "No se pudieron cargar cursos.");
      }
      setAnnouncements(annPayload.announcements ?? []);
      setCourses(coursePayload.courses ?? []);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar desarrollo.");
    } finally {
      setLoading(false);
    }
  }, []);

  const loadCompliance = useCallback(async () => {
    setLoading(true);
    try {
      const [obligationResponse, paymentResponse] = await Promise.all([
        fetch("/api/human-capital/compliance/obligations", { method: "GET", cache: "no-store" }),
        fetch("/api/human-capital/compliance/payments", { method: "GET", cache: "no-store" }),
      ]);

      const obligationPayload = (await obligationResponse.json()) as { obligations?: HumanCapitalComplianceObligationDTO[]; error?: string };
      if (!obligationResponse.ok) {
        throw new Error(obligationPayload.error ?? "No se pudo cargar cumplimiento.");
      }
      const paymentPayload = (await paymentResponse.json()) as { payments?: HumanCapitalCompliancePaymentDTO[]; error?: string };
      if (!paymentResponse.ok) {
        throw new Error(paymentPayload.error ?? "No se pudo cargar pagos.");
      }
      setCompliance(obligationPayload.obligations ?? []);
      setPayments(paymentPayload.payments ?? []);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar cumplimiento.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    setError(null);
    if (showSummary) {
      void loadResumen();
    }
    if (showFiles && canManage) {
      void loadFiles();
    }
    if ((showRecruitmentHeadcount || showRecruitmentVacancies || showRecruitmentOrg) && canManage) {
      void loadRecruitment(showRecruitmentHeadcount);
    }
    if (showPayroll && canManage) {
      void loadPayroll();
    }
    if (showCareer) {
      void loadDevelopment();
    }
    if (showCompliance && canManage) {
      void loadCompliance();
    }
  }, [canManage, loadCompliance, loadDevelopment, loadFiles, loadPayroll, loadRecruitment, loadResumen, showCareer, showCompliance, showFiles, showPayroll, showRecruitmentHeadcount, showRecruitmentOrg, showRecruitmentVacancies, showSummary]);

  useEffect(() => {
    let cancelled = false;

    async function loadConfig() {
      try {
        const response = await fetch("/api/human-capital/workspace/config", { method: "GET", cache: "no-store" });
        const payload = (await response.json()) as { config?: { tabs?: HumanCapitalWorkspaceTabConfig[] } };
        if (!cancelled && response.ok && payload.config?.tabs) {
          setWorkspaceTabs(payload.config.tabs);
        }
      } catch {
        if (!cancelled) {
          setWorkspaceTabs(DEFAULT_TABS);
        }
      }
    }

    void loadConfig();
    return () => {
      cancelled = true;
    };
  }, []);

  const topPeople = useMemo(() => peopleFiles.slice(0, 8), [peopleFiles]);

  const locationOptions = useMemo(() => {
    const values = new Set<string>();
    for (const person of peopleFiles) {
      if (person.locationId) {
        values.add(person.locationId);
      }
    }
    for (const vacancy of vacancies) {
      values.add(vacancy.locationCode);
    }
    for (const target of orgTargets) {
      values.add(target.locationCode);
    }
    for (const row of headcount?.breakdown ?? []) {
      values.add(row.locationCode);
    }
    return Array.from(values).sort((a, b) => a.localeCompare(b));
  }, [headcount, orgTargets, peopleFiles, vacancies]);

  const roleOptions = useMemo(() => {
    const values = new Set<string>();
    for (const person of peopleFiles) {
      if (person.departmentRole) {
        values.add(person.departmentRole);
      }
    }
    for (const vacancy of vacancies) {
      values.add(vacancy.roleKey);
    }
    for (const target of orgTargets) {
      values.add(target.roleKey);
    }
    for (const row of headcount?.breakdown ?? []) {
      values.add(row.roleKey);
    }
    return Array.from(values).sort((a, b) => a.localeCompare(b));
  }, [headcount, orgTargets, peopleFiles, vacancies]);

  const loadPersonFile = useCallback(async (userId: string) => {
    setSelectedFileUserId(userId);
    setLoadingPersonFile(true);
    setError(null);
    try {
      const response = await fetch(`/api/human-capital/files/${userId}`, { method: "GET", cache: "no-store" });
      const payload = (await response.json().catch(() => ({}))) as { file?: HumanCapitalPersonFilesDTO; error?: string };
      if (!response.ok || !payload.file) {
        throw new Error(payload.error ?? "No se pudo cargar el expediente.");
      }
      setSelectedPersonFile(payload.file);
    } catch (loadError) {
      setSelectedPersonFile(null);
      setError(loadError instanceof Error ? loadError.message : "No se pudo cargar el expediente.");
    } finally {
      setLoadingPersonFile(false);
    }
  }, []);

  const updatePersonFileItem = useCallback(
    (
      requirementId: string,
      patch: Partial<Pick<HumanCapitalFileEditorItem, "status" | "valueText" | "evidenceUrl" | "note">>
    ) => {
      setSelectedPersonFile((previous) => {
        if (!previous) {
          return previous;
        }
        return {
          ...previous,
          items: previous.items.map((item) => (item.requirementId === requirementId ? { ...item, ...patch } : item)),
        };
      });
    },
    []
  );

  const uploadPersonFileEvidence = useCallback(
    async (requirementId: string, file: File) => {
      if (!selectedPersonFile) {
        return;
      }

      setUploadingByRequirement((previous) => ({ ...previous, [requirementId]: true }));
      setError(null);

      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await fetch("/api/human-capital/files/upload", {
          method: "POST",
          body: formData,
        });
        const payload = (await response.json().catch(() => ({}))) as { fileUrl?: string; error?: string };

        if (!response.ok || !payload.fileUrl) {
          throw new Error(payload.error ?? "No se pudo subir el archivo.");
        }

        const currentItem = selectedPersonFile.items.find((item) => item.requirementId === requirementId);
        updatePersonFileItem(requirementId, {
          evidenceUrl: payload.fileUrl,
          status: currentItem?.status === "missing" ? "submitted" : currentItem?.status,
        });
      } catch (uploadError) {
        setError(uploadError instanceof Error ? uploadError.message : "No se pudo subir el archivo.");
      } finally {
        setUploadingByRequirement((previous) => ({ ...previous, [requirementId]: false }));
      }
    },
    [selectedPersonFile, updatePersonFileItem]
  );

  const savePersonFile = useCallback(async () => {
    if (!selectedPersonFile) {
      return;
    }

    setSavingPersonFile(true);
    setError(null);

    try {
      const response = await fetch(`/api/human-capital/files/${selectedPersonFile.userId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          items: selectedPersonFile.items.map((item) => ({
            requirementId: item.requirementId,
            status: item.status,
            valueText: item.valueText?.trim() || null,
            evidenceUrl: item.evidenceUrl?.trim() || null,
            note: item.note?.trim() || null,
          })),
        }),
      });
      const payload = (await response.json().catch(() => ({}))) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo guardar el expediente.");
      }

      await loadFiles();
      await loadPersonFile(selectedPersonFile.userId);
    } catch (saveError) {
      setError(saveError instanceof Error ? saveError.message : "No se pudo guardar el expediente.");
    } finally {
      setSavingPersonFile(false);
    }
  }, [loadFiles, loadPersonFile, selectedPersonFile]);

  const publishPayroll = async () => {
    setError(null);
    try {
      const response = await fetch("/api/human-capital/payroll/import", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          periodStart: payrollDraft.periodStart,
          periodEnd: payrollDraft.periodEnd,
          frequency: payrollDraft.frequency,
          locationCode: payrollDraft.locationCode || null,
          externalRef: payrollDraft.externalRef || null,
          csvText: payrollDraft.csvText,
        }),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo importar nomina.");
      }
      setPayrollDraft({ periodStart: "", periodEnd: "", frequency: "weekly", locationCode: "", externalRef: "", csvText: "" });
      await loadPayroll();
    } catch (publishError) {
      setError(publishError instanceof Error ? publishError.message : "No se pudo importar nomina.");
    }
  };

  const createVacancy = async () => {
    if (!vacancyDraft.locationCode || !vacancyDraft.roleKey || !vacancyDraft.title) {
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/recruitment/vacancies", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(vacancyDraft),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear vacante.");
      }
      setVacancyDraft({ locationCode: "", roleKey: "", title: "" });
      await loadRecruitment(showRecruitmentHeadcount);
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo crear vacante.");
    }
  };

  const createOrgTarget = async () => {
    const targetCount = Number(orgDraft.targetCount);
    if (!orgDraft.locationCode || !orgDraft.roleKey || orgDraft.targetCount.trim() === "" || !Number.isFinite(targetCount)) {
      setError("Completa ubicacion, rol y objetivo numerico.");
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/recruitment/org-targets", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          locationCode: orgDraft.locationCode,
          roleKey: orgDraft.roleKey,
          targetCount,
        }),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear objetivo.");
      }
      setOrgDraft({ locationCode: "", roleKey: "", targetCount: "" });
      await loadRecruitment(showRecruitmentHeadcount);
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo crear objetivo.");
    }
  };

  const publishAnnouncement = async () => {
    if (!announcementDraft.title.trim() || !announcementDraft.body.trim()) {
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/career/announcements", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(announcementDraft),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo publicar anuncio.");
      }
      setAnnouncementDraft({ title: "", body: "" });
      await loadDevelopment();
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo publicar anuncio.");
    }
  };

  const publishCourse = async () => {
    if (!courseDraft.title.trim() || !courseDraft.body.trim()) {
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/career/courses", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(courseDraft),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo publicar curso.");
      }
      setCourseDraft({ title: "", body: "" });
      await loadDevelopment();
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo publicar curso.");
    }
  };

  const createObligation = async () => {
    if (!complianceDraft.title.trim()) {
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/compliance/obligations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(complianceDraft),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo crear obligacion.");
      }
      setComplianceDraft({ body: "imss", title: "", dueDate: "" });
      await loadCompliance();
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo crear obligacion.");
    }
  };

  const createPayment = async () => {
    if (!paymentDraft.obligationId || !paymentDraft.paymentDate || !paymentDraft.amount) {
      return;
    }
    setError(null);
    try {
      const response = await fetch("/api/human-capital/compliance/payments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(paymentDraft),
      });
      const payload = (await response.json()) as { error?: string };
      if (!response.ok) {
        throw new Error(payload.error ?? "No se pudo registrar pago.");
      }
      setPaymentDraft({ obligationId: "", paymentDate: "", amount: 0 });
      await loadCompliance();
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo registrar pago.");
    }
  };

  return (
    <div className="space-y-6">
      <header className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
        <h1 className="text-display">Capital Humano</h1>
        <p className="text-body-lg text-benell-text-soft">Workspace dinamico por tab.</p>
      </header>

      {error ? <p className="text-label text-benell-red">{error}</p> : null}
      {loading ? <p className="text-label text-benell-text-soft">Cargando...</p> : null}

      {!activeTabConfig ? (
        <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Tab no configurado</h2>
          <p className="text-body text-benell-text-soft">
            Este tab no esta habilitado en el workspace. Ajusta la configuracion para activarlo.
          </p>
          {canManage ? (
            <Link
              href="/departments/human-capital/configuracion"
              className="mt-3 inline-flex text-label font-semibold text-benell-brown hover:text-black"
            >
              Ir a configuracion →
            </Link>
          ) : null}
        </section>
      ) : null}

      {showSummary ? (
        <>
          <DepartmentKpiTracker
            department="capital_humano"
            title="KPIs del area: Capital Humano + Administracion"
            description="Define como medir, evidencia, score y actualizacion semanal para cada KPI de esta area."
          />

          <section className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <p className="text-label text-benell-text-soft">People KPI</p>
              <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.aggregateScore.totalScore.toFixed(1) ?? "0.0"}%</p>
            </article>
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <p className="text-label text-benell-text-soft">Headcount activo</p>
              <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.activeHeadcount ?? 0}</p>
              <p className="text-caption text-benell-text-soft">Δ {dashboard?.summary.netHeadcountChange ?? 0} vs previo</p>
            </article>
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <p className="text-label text-benell-text-soft">Rotacion mensual</p>
              <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.monthlyChurnPct.toFixed(1) ?? "0.0"}%</p>
            </article>
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <p className="text-label text-benell-text-soft">Tenure mediano</p>
              <p className="text-h2 mt-1 font-semibold text-benell-text">{dashboard?.summary.medianTenureMonths.toFixed(1) ?? "0.0"}m</p>
            </article>
          </section>

          <section className="grid grid-cols-1 gap-4 xl:grid-cols-2">
            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Tendencia de rotacion (6 meses)</h2>
              <div className="mt-3 h-64">
                <ResponsiveContainer width="100%" height="100%">
                  <LineChart data={dashboard?.churnTrend ?? []}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Line type="monotone" dataKey="churnPct" stroke="#8a6a3d" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </article>

            <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Distribucion de tenure</h2>
              <div className="mt-3 h-64">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={dashboard?.tenureBands ?? []}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="label" />
                    <YAxis allowDecimals={false} />
                    <Tooltip />
                    <Bar dataKey="count" fill="#8a6a3d" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </article>
          </section>
        </>
      ) : null}

      {showFiles ? (
        <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <div className="mb-3 flex items-center justify-between gap-3">
            <h2 className="text-h2 font-semibold">Expedientes por persona</h2>
            <Link href="/people" className="text-label font-semibold text-benell-brown hover:text-black">
              Ver directorio completo →
            </Link>
          </div>
          {!canManage ? (
            <p className="text-body text-benell-text-soft">Solo lideres pueden ver expedientes detallados.</p>
          ) : null}
          <div className="overflow-x-auto">
            <table className="w-full min-w-[860px] text-sm">
              <thead>
                <tr className="border-b border-benell-stroke text-left text-label text-benell-text-soft">
                  <th className="px-2 py-2">Persona</th>
                  <th className="px-2 py-2">Departamento</th>
                  <th className="px-2 py-2">Ubicacion</th>
                  <th className="px-2 py-2">Completitud</th>
                  <th className="px-2 py-2">Faltantes</th>
                  <th className="px-2 py-2">Acciones</th>
                </tr>
              </thead>
              <tbody>
                {canManage ? (
                  topPeople.length > 0 ? (
                    topPeople.map((person) => (
                      <tr key={person.userId} className="border-b border-benell-stroke/70">
                        <td className="px-2 py-2">
                          <p className="font-semibold text-benell-text">{person.name}</p>
                          <p className="text-caption text-benell-text-soft">{person.email}</p>
                        </td>
                        <td className="px-2 py-2 text-benell-text-soft">{person.department ?? "-"} · {person.departmentRole ?? "-"}</td>
                        <td className="px-2 py-2 text-benell-text-soft">{person.locationId ?? "-"}</td>
                        <td className="px-2 py-2 text-benell-text-soft">{person.completionPct}%</td>
                        <td className="px-2 py-2 text-benell-text-soft">{person.requiredMissing}</td>
                        <td className="px-2 py-2">
                          <button
                            type="button"
                            onClick={() => void loadPersonFile(person.userId)}
                            className={`rounded-pill border border-benell-stroke px-3 py-1 text-caption font-semibold text-benell-brown hover:bg-benell-surface-alt ${
                              selectedFileUserId === person.userId ? "bg-benell-surface-alt" : ""
                            }`}
                          >
                            {selectedFileUserId === person.userId ? "Editando..." : "Editar expediente"}
                          </button>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={6} className="px-2 py-4 text-center text-sm text-benell-text-soft">
                        No hay personas disponibles.
                      </td>
                    </tr>
                  )
                ) : (
                  <tr>
                    <td colSpan={6} className="px-2 py-4 text-center text-sm text-benell-text-soft">
                      Sin permiso para ver expedientes.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {canManage ? (
            <section className="mt-4 rounded-benell border border-benell-stroke bg-white p-4">
              <div className="mb-3 flex items-center justify-between gap-2">
                <h3 className="text-h3 font-semibold text-benell-text">Edicion de expediente</h3>
                {selectedPersonFile ? (
                  <p className="text-caption text-benell-text-soft">
                    {selectedPersonFile.name} · {selectedPersonFile.completionPct}% completo
                  </p>
                ) : null}
              </div>

              {loadingPersonFile ? <p className="text-body text-benell-text-soft">Cargando expediente...</p> : null}

              {!loadingPersonFile && !selectedPersonFile ? (
                <p className="text-body text-benell-text-soft">Selecciona una persona en la tabla para cargar y actualizar su expediente.</p>
              ) : null}

              {selectedPersonFile ? (
                <div className="space-y-3">
                  {selectedPersonFile.items.map((item) => (
                    <article key={item.requirementId} className="rounded-lg border border-benell-stroke bg-benell-surface px-3 py-3">
                      <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
                        <p className="text-sm font-semibold text-benell-text">
                          {item.requirementLabel}
                          {item.isRequired ? " *" : ""}
                        </p>
                        <select
                          value={item.status}
                          onChange={(event) =>
                            updatePersonFileItem(item.requirementId, {
                              status: event.target.value as HumanCapitalFileEditorItem["status"],
                            })
                          }
                          className="rounded-lg border border-benell-stroke bg-white px-2 py-1 text-caption"
                          disabled={savingPersonFile}
                        >
                          <option value="missing">missing</option>
                          <option value="submitted">submitted</option>
                          <option value="verified">verified</option>
                          <option value="rejected">rejected</option>
                        </select>
                      </div>
                      <div className="grid grid-cols-1 gap-2 md:grid-cols-3">
                        <input
                          value={item.valueText ?? ""}
                          onChange={(event) => updatePersonFileItem(item.requirementId, { valueText: event.target.value })}
                          placeholder="Dato / folio / texto"
                          className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                          disabled={savingPersonFile}
                        />
                        <input
                          value={item.evidenceUrl ?? ""}
                          onChange={(event) => updatePersonFileItem(item.requirementId, { evidenceUrl: event.target.value })}
                          placeholder="Archivo o URL de evidencia"
                          className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                          disabled={savingPersonFile}
                        />
                        <input
                          value={item.note ?? ""}
                          onChange={(event) => updatePersonFileItem(item.requirementId, { note: event.target.value })}
                          placeholder="Nota"
                          className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                          disabled={savingPersonFile}
                        />
                      </div>
                      <div
                        className="mt-2 rounded-lg border border-dashed border-benell-stroke bg-white px-3 py-3"
                        onDragOver={(event) => {
                          event.preventDefault();
                        }}
                        onDrop={(event) => {
                          event.preventDefault();
                          const file = event.dataTransfer.files?.[0];
                          if (file) {
                            void uploadPersonFileEvidence(item.requirementId, file);
                          }
                        }}
                      >
                        <p className="text-caption text-benell-text-soft">Arrastra y suelta archivo aqui, o selecciona uno.</p>
                        <div className="mt-2 flex items-center gap-2">
                          <label className="cursor-pointer rounded-pill border border-benell-stroke px-3 py-1 text-caption font-semibold text-benell-brown hover:bg-benell-surface-alt">
                            Seleccionar archivo
                            <input
                              type="file"
                              className="hidden"
                              disabled={savingPersonFile || uploadingByRequirement[item.requirementId]}
                              onChange={(event) => {
                                const file = event.target.files?.[0];
                                if (file) {
                                  void uploadPersonFileEvidence(item.requirementId, file);
                                }
                                event.currentTarget.value = "";
                              }}
                            />
                          </label>
                          {uploadingByRequirement[item.requirementId] ? (
                            <p className="text-caption text-benell-text-soft">Subiendo...</p>
                          ) : null}
                          {item.evidenceUrl ? (
                            <a
                              href={item.evidenceUrl}
                              target="_blank"
                              rel="noreferrer"
                              className="text-caption font-semibold text-benell-brown hover:text-black"
                            >
                              Abrir archivo
                            </a>
                          ) : null}
                        </div>
                      </div>
                    </article>
                  ))}
                  <div className="flex flex-wrap gap-2">
                    <button
                      type="button"
                      onClick={() => void savePersonFile()}
                      disabled={savingPersonFile}
                      className="rounded-pill bg-benell-brown px-4 py-2 text-label font-semibold text-white disabled:opacity-50"
                    >
                      {savingPersonFile ? "Guardando..." : "Guardar expediente"}
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setSelectedFileUserId(null);
                        setSelectedPersonFile(null);
                      }}
                      disabled={savingPersonFile}
                      className="rounded-pill border border-benell-stroke px-4 py-2 text-label font-semibold text-benell-text disabled:opacity-50"
                    >
                      Cerrar editor
                    </button>
                  </div>
                </div>
              ) : null}
            </section>
          ) : null}
        </section>
      ) : null}

      {showPayroll ? (
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Resumen de nomina</h2>
            {!canManage ? (
              <p className="text-body text-benell-text-soft">Solo lideres pueden ver nomina.</p>
            ) : null}
            {payrollSummary ? (
              <div className="mt-3 space-y-2 text-body text-benell-text-soft">
                <p>Periodo: {payrollSummary.periodStart} → {payrollSummary.periodEnd}</p>
                <p>Frecuencia: {payrollSummary.frequency}</p>
                <p>Ubicacion: {payrollSummary.locationCode ?? "todas"}</p>
                <p>Percepciones: {payrollSummary.percepciones.toFixed(2)}</p>
                <p>Deducciones: {payrollSummary.deducciones.toFixed(2)}</p>
                <p>Aportaciones: {payrollSummary.aportaciones.toFixed(2)}</p>
                <p>Neto: {payrollSummary.neto.toFixed(2)}</p>
                <p>Personas: {payrollSummary.peopleCount}</p>
              </div>
            ) : (
              <p className="text-body text-benell-text-soft">No hay corridas.</p>
            )}
          </section>

          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Importar CSV</h2>
            <div className="mt-3 grid grid-cols-1 gap-2">
              <input
                value={payrollDraft.periodStart}
                onChange={(event) => setPayrollDraft((prev) => ({ ...prev, periodStart: event.target.value }))}
                placeholder="Periodo inicio (YYYY-MM-DD)"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                disabled={!canManage}
              />
              <input
                value={payrollDraft.periodEnd}
                onChange={(event) => setPayrollDraft((prev) => ({ ...prev, periodEnd: event.target.value }))}
                placeholder="Periodo fin (YYYY-MM-DD)"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                disabled={!canManage}
              />
              <select
                value={payrollDraft.frequency}
                onChange={(event) => setPayrollDraft((prev) => ({ ...prev, frequency: event.target.value as "weekly" | "biweekly" }))}
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                disabled={!canManage}
              >
                <option value="weekly">Semanal</option>
                <option value="biweekly">Quincenal</option>
              </select>
              <input
                value={payrollDraft.locationCode}
                onChange={(event) => setPayrollDraft((prev) => ({ ...prev, locationCode: event.target.value }))}
                placeholder="Ubicacion (opcional)"
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                disabled={!canManage}
              />
              <textarea
                value={payrollDraft.csvText}
                onChange={(event) => setPayrollDraft((prev) => ({ ...prev, csvText: event.target.value }))}
                placeholder="Pega CSV de CONTPAQi"
                rows={6}
                className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                disabled={!canManage}
              />
              <button
                type="button"
                onClick={() => void publishPayroll()}
                disabled={!canManage}
                className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white disabled:opacity-50"
              >
                Importar nomina
              </button>
            </div>
          </section>
        </div>
      ) : null}

      {showRecruitmentHeadcount || showRecruitmentVacancies || showRecruitmentOrg ? (
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
          {showRecruitmentHeadcount ? (
            <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
              <h2 className="text-h2 font-semibold">Headcount actual</h2>
              {!canManage ? (
                <p className="text-body text-benell-text-soft">Solo lideres pueden ver headcount detallado.</p>
              ) : null}
              {canManage ? (
                <div className="mt-3 space-y-2 text-body text-benell-text-soft">
                  <p>Total activo: {headcount?.total ?? 0}</p>
                  <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
                    {(headcount?.breakdown ?? []).map((row) => (
                      <div key={`${row.locationCode}-${row.roleKey}`} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                        <p className="text-sm font-semibold text-benell-text">{row.locationCode}</p>
                        <p className="text-caption text-benell-text-soft">{row.roleKey} · {row.count}</p>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}
            </section>
          ) : null}
          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Vacantes</h2>
            {!canManage ? (
              <p className="text-body text-benell-text-soft">Solo lideres pueden ver vacantes.</p>
            ) : null}
            <ul className="mt-3 space-y-2">
              {canManage
                ? vacancies.map((vacancy) => (
                    <li key={vacancy.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                      <p className="text-sm font-semibold text-benell-text">{vacancy.title}</p>
                      <p className="text-caption text-benell-text-soft">
                        {vacancy.locationCode} · {vacancy.roleKey} · {vacancy.status}
                      </p>
                    </li>
                  ))
                : null}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <input
                  value={vacancyDraft.locationCode}
                  onChange={(event) => setVacancyDraft((prev) => ({ ...prev, locationCode: event.target.value }))}
                  placeholder="Ubicacion"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <input
                  value={vacancyDraft.roleKey}
                  onChange={(event) => setVacancyDraft((prev) => ({ ...prev, roleKey: event.target.value }))}
                  placeholder="Rol"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <input
                  value={vacancyDraft.title}
                  onChange={(event) => setVacancyDraft((prev) => ({ ...prev, title: event.target.value }))}
                  placeholder="Titulo"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <button
                  type="button"
                  onClick={() => void createVacancy()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Crear vacante
                </button>
              </div>
            ) : null}
          </section>

          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Organizacion ideal</h2>
            {!canManage ? (
              <p className="text-body text-benell-text-soft">Solo lideres pueden ver objetivos.</p>
            ) : null}
            <ul className="mt-3 space-y-2">
              {canManage
                ? orgTargets.map((target) => (
                    <li key={target.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                      <p className="text-sm font-semibold text-benell-text">{target.locationCode} · {target.roleKey}</p>
                      <p className="text-caption text-benell-text-soft">
                        Objetivo: {target.targetCount} | Actual: {target.actualCount} | Gap: {target.gap}
                      </p>
                    </li>
                  ))
                : null}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <select
                  value={orgDraft.locationCode}
                  onChange={(event) => setOrgDraft((prev) => ({ ...prev, locationCode: event.target.value }))}
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                >
                  <option value="">Ubicacion</option>
                  {locationOptions.map((location) => (
                    <option key={location} value={location}>
                      {location}
                    </option>
                  ))}
                </select>
                <select
                  value={orgDraft.roleKey}
                  onChange={(event) => setOrgDraft((prev) => ({ ...prev, roleKey: event.target.value }))}
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                >
                  <option value="">Rol</option>
                  {roleOptions.map((role) => (
                    <option key={role} value={role}>
                      {role}
                    </option>
                  ))}
                </select>
                <input
                  type="text"
                  inputMode="numeric"
                  value={orgDraft.targetCount}
                  onChange={(event) => {
                    const value = event.target.value;
                    if (/^\d*$/.test(value)) {
                      setOrgDraft((prev) => ({ ...prev, targetCount: value }));
                    }
                  }}
                  placeholder="Objetivo"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm [appearance:textfield]"
                />
                <button
                  type="button"
                  onClick={() => void createOrgTarget()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Guardar objetivo
                </button>
              </div>
            ) : null}
          </section>
        </div>
      ) : null}

      {showCareer ? (
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Anuncios internos</h2>
            <ul className="mt-3 space-y-2">
              {announcements.map((item) => (
                <li key={item.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                  <p className="text-sm font-semibold text-benell-text">{item.title}</p>
                  <p className="text-caption text-benell-text-soft">{item.body}</p>
                </li>
              ))}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <input
                  value={announcementDraft.title}
                  onChange={(event) => setAnnouncementDraft((prev) => ({ ...prev, title: event.target.value }))}
                  placeholder="Titulo"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <textarea
                  value={announcementDraft.body}
                  onChange={(event) => setAnnouncementDraft((prev) => ({ ...prev, body: event.target.value }))}
                  placeholder="Detalle"
                  rows={3}
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <button
                  type="button"
                  onClick={() => void publishAnnouncement()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Publicar anuncio
                </button>
              </div>
            ) : null}
          </section>

          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Cursos</h2>
            <ul className="mt-3 space-y-2">
              {courses.map((item) => (
                <li key={item.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                  <p className="text-sm font-semibold text-benell-text">{item.title}</p>
                  <p className="text-caption text-benell-text-soft">{item.body}</p>
                </li>
              ))}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <input
                  value={courseDraft.title}
                  onChange={(event) => setCourseDraft((prev) => ({ ...prev, title: event.target.value }))}
                  placeholder="Titulo"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <textarea
                  value={courseDraft.body}
                  onChange={(event) => setCourseDraft((prev) => ({ ...prev, body: event.target.value }))}
                  placeholder="Detalle"
                  rows={3}
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <button
                  type="button"
                  onClick={() => void publishCourse()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Publicar curso
                </button>
              </div>
            ) : null}
          </section>
        </div>
      ) : null}

      {showCompliance ? (
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Obligaciones</h2>
            {!canManage ? (
              <p className="text-body text-benell-text-soft">Solo lideres pueden ver cumplimiento.</p>
            ) : null}
            <ul className="mt-3 space-y-2">
              {canManage
                ? compliance.map((item) => (
                    <li key={item.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                      <p className="text-sm font-semibold text-benell-text">{item.title}</p>
                      <p className="text-caption text-benell-text-soft">
                        {item.body} · {item.status} · {item.dueDate ?? "-"}
                      </p>
                    </li>
                  ))
                : null}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <select
                  value={complianceDraft.body}
                  onChange={(event) => setComplianceDraft((prev) => ({ ...prev, body: event.target.value }))}
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                >
                  <option value="imss">IMSS</option>
                  <option value="infonavit">Infonavit</option>
                  <option value="fonacot">Fonacot</option>
                  <option value="other">Otro</option>
                </select>
                <input
                  value={complianceDraft.title}
                  onChange={(event) => setComplianceDraft((prev) => ({ ...prev, title: event.target.value }))}
                  placeholder="Titulo"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <input
                  value={complianceDraft.dueDate}
                  onChange={(event) => setComplianceDraft((prev) => ({ ...prev, dueDate: event.target.value }))}
                  placeholder="Fecha vencimiento (YYYY-MM-DD)"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <button
                  type="button"
                  onClick={() => void createObligation()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Crear obligacion
                </button>
              </div>
            ) : null}
          </section>

          <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
            <h2 className="text-h2 font-semibold">Pagos</h2>
            {!canManage ? (
              <p className="text-body text-benell-text-soft">Solo lideres pueden ver pagos.</p>
            ) : null}
            <ul className="mt-3 space-y-2">
              {canManage
                ? payments.map((item) => (
                    <li key={item.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                      <p className="text-sm font-semibold text-benell-text">Pago {item.amount}</p>
                      <p className="text-caption text-benell-text-soft">{item.obligationId} · {item.paymentDate}</p>
                    </li>
                  ))
                : null}
            </ul>
            {canManage ? (
              <div className="mt-4 grid grid-cols-1 gap-2">
                <input
                  value={paymentDraft.obligationId}
                  onChange={(event) => setPaymentDraft((prev) => ({ ...prev, obligationId: event.target.value }))}
                  placeholder="Obligacion ID"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <input
                  value={paymentDraft.paymentDate}
                  onChange={(event) => setPaymentDraft((prev) => ({ ...prev, paymentDate: event.target.value }))}
                  placeholder="Fecha pago (YYYY-MM-DD)"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <input
                  type="number"
                  value={paymentDraft.amount}
                  onChange={(event) => setPaymentDraft((prev) => ({ ...prev, amount: Number(event.target.value) }))}
                  placeholder="Monto"
                  className="rounded-lg border border-benell-stroke bg-white px-3 py-2 text-sm"
                />
                <button
                  type="button"
                  onClick={() => void createPayment()}
                  className="rounded-pill bg-benell-brown px-3 py-2 text-label font-semibold text-white"
                >
                  Registrar pago
                </button>
              </div>
            ) : null}
          </section>
        </div>
      ) : null}

      {showPayroll && payrollRuns.length > 0 ? (
        <section className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell">
          <h2 className="text-h2 font-semibold">Corridas recientes</h2>
          <ul className="mt-3 space-y-2">
            {payrollRuns.map((run) => (
              <li key={run.id} className="rounded-lg border border-benell-stroke bg-white px-3 py-2">
                <p className="text-sm font-semibold text-benell-text">{run.periodStart} → {run.periodEnd}</p>
                <p className="text-caption text-benell-text-soft">{run.frequency} · {run.locationCode ?? "todas"}</p>
              </li>
            ))}
          </ul>
        </section>
      ) : null}
    </div>
  );
}
