(function initCurationReview(global) {
  "use strict";

  const ledger = document.querySelector("[data-curation-ledger]");
  if (!ledger) return;

  const feedback = ledger.querySelector("[data-curation-feedback]");
  const sheet = ledger.querySelector("#audit_review_sheet");
  const sheetBody = sheet?.querySelector("[data-audit-sheet-body]");
  const sheetTitle = sheet?.querySelector("[data-audit-sheet-title]");
  const sheetKicker = sheet?.querySelector("[data-audit-sheet-kicker]");
  const sheetActions = sheet?.querySelector("[data-audit-sheet-actions]");
  let opener = null;
  let version = ledger.dataset.curationVersion || global.EPICRISIS_PDF_DATA?.curationVersion || "";

  global.EpicrisisApp?.tabs?.create({
    root: ledger.querySelector("[data-audit-tabs]"),
    tabSelector: "[data-audit-tab]",
    panelSelector: "[data-audit-panel]",
    tabDataKey: "auditTab",
    panelDataKey: "auditPanel",
    defaultTab: "todos",
    storageKey: "epicrisis:auditoria-active-tab",
  });

  ledger.querySelectorAll("[data-audit-list]").forEach((list) => {
    Array.from(list.querySelectorAll("[data-audit-row]"))
      .sort((left, right) => Number(left.dataset.auditRisk) - Number(right.dataset.auditRisk))
      .forEach((row) => list.append(row));
  });

  function setFeedback(message, isError = false) {
    if (!feedback) return;
    feedback.textContent = message;
    feedback.classList.toggle("is-error", isError);
  }

  function setItemError(container, message, field = null) {
    const error = container?.querySelector("[data-audit-item-error]");
    if (error) {
      error.textContent = message;
      error.hidden = !message;
    }
    if (field) {
      field.setAttribute("aria-invalid", "true");
      field.focus();
    }
  }

  function setBusy(container, busy) {
    container.querySelectorAll("button, input, select, textarea").forEach((element) => {
      element.disabled = busy;
    });
    sheet?.setAttribute("aria-busy", String(busy));
  }

  function hasChanges(container) {
    const code = container.querySelector("[data-curation-code]");
    const description = container.querySelector("[data-curation-description]");
    return (
      (code && code.value.trim() !== container.dataset.originalCode) ||
      (description && description.value.trim() !== container.dataset.originalDescription) ||
      Boolean(container.querySelector("[data-curation-soat-candidate]")?.value) ||
      Boolean(container.querySelector("[data-curation-reference-toggle]")?.checked) ||
      Boolean(container.querySelector("[data-curation-manual-soat]")?.value.trim()) ||
      Boolean(container.querySelector("[data-curation-manual-group]")?.value.trim()) ||
      Boolean(container.querySelector("[data-curation-component]:checked"))
    );
  }

  function openSheet(button) {
    if (!sheet || !sheetBody) return;
    const template = document.getElementById(button.dataset.auditOpen || "");
    if (!(template instanceof HTMLTemplateElement)) return;
    opener = button;
    sheetBody.replaceChildren(template.content.cloneNode(true));
    sheetTitle.textContent = button.dataset.auditTitle || "Detalle";
    const readonly = Boolean(sheetBody.querySelector("[data-audit-readonly]"));
    sheetKicker.textContent = readonly ? "Trazabilidad de la decisión" : "Revisión de hallazgo";
    sheetActions.hidden = readonly;
    sheet.showModal();
    const date = sheetBody.querySelector("[data-audit-date]");
    if (date?.dateTime) {
      const parsed = new Date(date.dateTime);
      if (!Number.isNaN(parsed.valueOf())) {
        date.textContent = new Intl.DateTimeFormat("es-CO", {
          dateStyle: "medium",
          timeStyle: "short",
          timeZone: "America/Bogota",
        }).format(parsed);
      }
    }
    sheet.querySelector(".pdf-sheet__close")?.focus();
  }

  async function submitDecision(container, requestedAction) {
    const caseKey = String(global.EPICRISIS_PDF_DATA?.caseKey || "").trim();
    const itemId = String(container.dataset.curationItem || "").trim();
    if (!caseKey || !itemId || !version) {
      setItemError(container, "No se encontró la versión trazable del caso.");
      return;
    }

    container.querySelectorAll('[aria-invalid="true"]').forEach((field) => field.removeAttribute("aria-invalid"));
    setItemError(container, "");
    const changed = hasChanges(container);
    const action = requestedAction === "reject" ? "reject" : changed ? "correct" : "approve";
    const codeField = container.querySelector("[data-curation-code]");
    const descriptionField = container.querySelector("[data-curation-description]");
    const reasonField = container.querySelector("[data-curation-reason]");
    const code = codeField?.value.trim() || "";
    const description = descriptionField?.value.trim() || "";
    const selectedSoatCode = container.querySelector("[data-curation-soat-candidate]")?.value.trim() || "";
    const reason = reasonField?.value.trim() || "";
    const calculateReference = container.querySelector("[data-curation-reference-toggle]")?.checked === true;
    const manualSoatCode = container.querySelector("[data-curation-manual-soat]")?.value.trim() || "";
    const manualSurgicalGroup = container.querySelector("[data-curation-manual-group]")?.value.trim() || "";
    const selectedComponents = Array.from(
      container.querySelectorAll("[data-curation-component]:checked"),
      (element) => element.value,
    );

    if (action === "correct" && ((!code || !description) && !selectedSoatCode)) {
      const field = !code ? codeField : descriptionField;
      setItemError(container, "Para corregir indica código y descripción o selecciona un SOAT.", field);
      return;
    }
    if (!reason && (action !== "approve" || container.dataset.requiresReason === "true")) {
      setItemError(container, "Escribe el motivo de la decisión para conservar la trazabilidad.", reasonField);
      return;
    }
    if (calculateReference && (!selectedComponents.length || (!manualSoatCode && !manualSurgicalGroup && !selectedSoatCode))) {
      setItemError(container, "Selecciona componentes y un SOAT exacto o grupo oficial para calcular la referencia.", container.querySelector("[data-curation-manual-soat]"));
      return;
    }
    if (action === "reject" && !global.confirm("¿Confirmas el rechazo de este hallazgo? Esta decisión quedará registrada.")) return;

    setBusy(container, true);
    setFeedback("Guardando decisión…");
    try {
      const response = await fetch(
        `/api/epicrisis/cases/${encodeURIComponent(caseKey)}/curation/items/${encodeURIComponent(itemId)}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            decision: action,
            expected_version: version,
            corrected_code: action === "correct" ? code : "",
            corrected_description: action === "correct" ? description : "",
            selected_soat_code: action === "correct" ? selectedSoatCode : "",
            reason,
            calculate_reference: calculateReference,
            manual_soat_code: manualSoatCode,
            manual_surgical_group: manualSurgicalGroup || null,
            selected_components: selectedComponents,
            reference_year: 2026,
          }),
        },
      );
      const result = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (response.status === 409) {
          setItemError(container, "El caso cambió en otra sesión. Recargando la versión vigente…");
          global.setTimeout(() => global.location.reload(), 900);
          return;
        }
        throw new Error(result.detail || `No fue posible guardar la decisión (${response.status}).`);
      }
      version = result.curation?.version || result.version || result.curation_version || version;
      setFeedback("Decisión registrada. Actualizando la conciliación…");
      global.setTimeout(() => global.location.reload(), 450);
    } catch (error) {
      setBusy(container, false);
      setItemError(container, error.message || "No fue posible guardar la decisión.");
      setFeedback(error.message || "No fue posible guardar la decisión.", true);
    }
  }

  ledger.addEventListener("click", (event) => {
    const openButton = event.target.closest("[data-audit-open]");
    if (openButton) return openSheet(openButton);
    const editButton = event.target.closest("[data-audit-edit]");
    if (editButton) {
      const form = editButton.closest("[data-audit-sheet-content]")?.querySelector("[data-audit-edit-form]");
      if (form) {
        form.hidden = false;
        editButton.hidden = true;
        form.querySelector("input, select")?.focus();
      }
      return;
    }
    const actionButton = event.target.closest("[data-curation-action]");
    if (!actionButton || !sheetBody) return;
    const container = sheetBody.querySelector("[data-curation-item]");
    if (container) submitDecision(container, actionButton.dataset.curationAction);
  });

  sheet?.addEventListener("close", () => {
    sheetBody?.replaceChildren();
    opener?.focus();
    opener = null;
  });
})(window);
