import { e as createComponent, k as renderComponent, r as renderTemplate } from '../chunks/astro/server_CNSJbOTP.mjs';
import 'piccolore';
import { a as api, o as obtenerUsuario, h as obtenerToken, i as cerrarSesion, $ as $$AppLayout } from '../chunks/AppLayout_DAKNch61.mjs';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { useState, useCallback, useEffect, useRef } from 'react';
export { renderers } from '../renderers.mjs';

function construirArbol(cats) {
  const map = /* @__PURE__ */ new Map();
  cats.forEach((c) => map.set(c.id, { ...c, hijos: [] }));
  const raices = [];
  cats.forEach((c) => {
    const nodo = map.get(c.id);
    if (c.padre_id === null) {
      raices.push(nodo);
    } else {
      const padre = map.get(c.padre_id);
      if (padre) padre.hijos.push(nodo);
    }
  });
  return raices;
}
function formatBytes(bytes) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function formatFecha(fecha) {
  if (!fecha) return "—";
  const d = new Date(fecha);
  if (isNaN(d.getTime())) return fecha;
  return d.toLocaleDateString("es-CL");
}
function icono(mime) {
  if (mime.includes("pdf")) return "📄";
  if (mime.includes("image")) return "🖼️";
  if (mime.includes("sheet") || mime.includes("excel")) return "📊";
  if (mime.includes("presentation") || mime.includes("powerpoint")) return "📑";
  if (mime.includes("word") || mime.includes("document")) return "📝";
  return "📎";
}
function NodoCarpeta({
  cat,
  nivel,
  seleccionadaId,
  expandidas,
  onSelect,
  onToggle
}) {
  const tieneHijos = cat.hijos.length > 0;
  const estaExpandido = expandidas.has(cat.id);
  const esSeleccionada = seleccionadaId === cat.id;
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        style: { paddingLeft: `${nivel * 14 + 8}px` },
        className: `flex items-center gap-1.5 py-1.5 pr-2 rounded-md cursor-pointer text-sm select-none
          ${esSeleccionada ? "bg-blue-600 text-white font-medium" : "text-gray-700 hover:bg-gray-100"}`,
        onClick: () => {
          onSelect(cat);
          if (tieneHijos) onToggle(cat.id);
        },
        children: [
          /* @__PURE__ */ jsx("span", { className: `w-4 text-center text-xs flex-shrink-0 ${esSeleccionada ? "text-blue-200" : "text-gray-400"}`, children: tieneHijos ? estaExpandido ? "▾" : "▸" : "·" }),
          /* @__PURE__ */ jsx("span", { className: `font-mono text-[10px] flex-shrink-0 ${esSeleccionada ? "text-blue-200" : "text-gray-400"}`, children: cat.codigo }),
          /* @__PURE__ */ jsx("span", { className: "truncate text-xs leading-tight", children: cat.nombre })
        ]
      }
    ),
    tieneHijos && estaExpandido && /* @__PURE__ */ jsx("div", { children: cat.hijos.map((hijo) => /* @__PURE__ */ jsx(
      NodoCarpeta,
      {
        cat: hijo,
        nivel: nivel + 1,
        seleccionadaId,
        expandidas,
        onSelect,
        onToggle
      },
      hijo.id
    )) })
  ] });
}
function FormularioSubida({
  categoriaId,
  onSubido,
  onCancelar
}) {
  const [nombre, setNombre] = useState("");
  const [fechaElab, setFechaElab] = useState("");
  const [fechaVig, setFechaVig] = useState("");
  const [archivo, setArchivo] = useState(null);
  const [subiendo, setSubiendo] = useState(false);
  const [error, setError] = useState("");
  const fileRef = useRef(null);
  async function enviar(e) {
    e.preventDefault();
    if (!archivo) {
      setError("Seleccione un archivo");
      return;
    }
    setSubiendo(true);
    setError("");
    try {
      const fd = new FormData();
      fd.append("categoria_id", String(categoriaId));
      fd.append("nombre", nombre.trim());
      fd.append("fecha_elaboracion", fechaElab);
      fd.append("fecha_vigencia", fechaVig);
      fd.append("archivo", archivo);
      const token = obtenerToken();
      const res = await fetch("/api/repositorio/documentos", {
        method: "POST",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        credentials: "include",
        body: fd
      });
      if (res.status === 401) {
        cerrarSesion();
        window.location.href = "/login";
        return;
      }
      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: "Error desconocido" }));
        throw new Error(err.error || `Error ${res.status}`);
      }
      onSubido();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Error al subir el archivo");
    } finally {
      setSubiendo(false);
    }
  }
  return /* @__PURE__ */ jsxs("form", { onSubmit: enviar, className: "border border-blue-200 rounded-lg bg-blue-50 p-4 space-y-3", children: [
    /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-blue-800", children: "Subir documento" }),
    error && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2", children: error }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-gray-700 mb-1", children: "Archivo *" }),
      /* @__PURE__ */ jsx(
        "input",
        {
          ref: fileRef,
          type: "file",
          accept: ".pdf,.png,.jpg,.jpeg,.raw,.dng,.xls,.xlsx,.ppt,.pptx,.doc,.docx",
          onChange: (e) => setArchivo(e.target.files?.[0] ?? null),
          required: true,
          className: "block w-full text-xs text-gray-700 file:mr-3 file:py-1.5 file:px-3 file:rounded file:border-0 file:text-xs file:font-medium file:bg-white file:text-gray-700 hover:file:bg-gray-50 border border-gray-300 rounded"
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "mt-1 text-[10px] text-gray-500", children: "PDF, PNG, JPG, RAW, XLS, XLSX, PPT, PPTX, DOC, DOCX · Máx. 50 MB" })
    ] }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-gray-700 mb-1", children: "Nombre descriptivo" }),
      /* @__PURE__ */ jsx(
        "input",
        {
          type: "text",
          value: nombre,
          onChange: (e) => setNombre(e.target.value),
          placeholder: "Deja en blanco para usar el nombre del archivo",
          maxLength: 400,
          className: "input text-sm w-full"
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-gray-700 mb-1", children: "Fecha de elaboración" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "date",
            value: fechaElab,
            onChange: (e) => setFechaElab(e.target.value),
            className: "input text-sm w-full"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-xs font-medium text-gray-700 mb-1", children: "Fecha de vigencia" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "date",
            value: fechaVig,
            onChange: (e) => setFechaVig(e.target.value),
            className: "input text-sm w-full"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex gap-2 pt-1", children: [
      /* @__PURE__ */ jsx("button", { type: "submit", disabled: subiendo, className: "btn-primary text-sm", children: subiendo ? "Subiendo…" : "Subir documento" }),
      /* @__PURE__ */ jsx("button", { type: "button", onClick: onCancelar, className: "btn-secondary text-sm", children: "Cancelar" })
    ] })
  ] });
}
function RepositorioDocumental() {
  const [usuario, setUsuario] = useState(null);
  const [arbol, setArbol] = useState([]);
  const [expandidas, setExpandidas] = useState(/* @__PURE__ */ new Set());
  const [seleccionada, setSeleccionada] = useState(null);
  const [cargandoCats, setCargandoCats] = useState(true);
  const [documentos, setDocumentos] = useState([]);
  const [totalDocs, setTotalDocs] = useState(0);
  const [cargandoDocs, setCargandoDocs] = useState(false);
  const [mostrarSubida, setMostrarSubida] = useState(false);
  const [eliminando, setEliminando] = useState(null);
  const [error, setError] = useState("");
  const [faseFiltro, setFaseFiltro] = useState(null);
  const [resumen, setResumen] = useState(null);
  const [documentoViendo, setDocumentoViendo] = useState(null);
  const [blobUrlViendo, setBlobUrlViendo] = useState(null);
  const cargarResumen = useCallback(async () => {
    try {
      const data = await api.get("/repositorio/resumen-vigencia");
      setResumen(data);
    } catch {
    }
  }, []);
  useEffect(() => {
    setUsuario(obtenerUsuario());
  }, []);
  const puedeSubir = usuario && usuario.rol !== "consultor";
  const esLiderOAdmin = usuario && (usuario.rol === "admin" || usuario.rol === "lider");
  useEffect(() => {
    async function cargarCats() {
      try {
        const cats = await api.get("/repositorio/categorias");
        setArbol(construirArbol(cats));
      } catch (e) {
        setError(`No se pudo cargar la estructura de carpetas${e instanceof Error ? ` (${e.message})` : ""}`);
      } finally {
        setCargandoCats(false);
      }
    }
    cargarCats();
    cargarResumen();
  }, [cargarResumen]);
  const cargarDocumentos = useCallback(async (catId, fase = null) => {
    setCargandoDocs(true);
    setDocumentos([]);
    try {
      let url = `/repositorio/documentos?`;
      if (catId) url += `categoria_id=${catId}&`;
      if (fase) url += `fase_vigencia=${fase}&`;
      const data = await api.get(url);
      setDocumentos(data.datos ?? []);
      setTotalDocs(data.total ?? 0);
    } catch {
      setError("No se pudieron cargar los documentos");
    } finally {
      setCargandoDocs(false);
    }
  }, []);
  function seleccionarCategoria(cat) {
    setSeleccionada(cat);
    setFaseFiltro(null);
    setMostrarSubida(false);
    cargarDocumentos(cat.id, null);
  }
  function seleccionarFase(fase) {
    setFaseFiltro(fase);
    setSeleccionada(null);
    setMostrarSubida(false);
    cargarDocumentos(null, fase);
  }
  function toggleExpandir(id) {
    setExpandidas((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }
  async function verDocumento(doc) {
    try {
      const token = obtenerToken();
      const res = await fetch(`/api/repositorio/documentos/${doc.id}/descargar`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {}
      });
      if (res.status === 401) {
        cerrarSesion();
        window.location.href = "/login";
        return;
      }
      if (!res.ok) throw new Error();
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      setDocumentoViendo(doc);
      setBlobUrlViendo(url);
    } catch {
      alert("Error al abrir el archivo");
    }
  }
  function cerrarVisor() {
    if (blobUrlViendo) {
      URL.revokeObjectURL(blobUrlViendo);
    }
    setDocumentoViendo(null);
    setBlobUrlViendo(null);
  }
  async function descargar(doc) {
    try {
      const token = obtenerToken();
      const res = await fetch(`/api/repositorio/documentos/${doc.id}/descargar`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        credentials: "include"
      });
      if (res.status === 401) {
        cerrarSesion();
        window.location.href = "/login";
        return;
      }
      if (!res.ok) throw new Error();
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = doc.nombre_original;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      alert("Error al descargar el archivo");
    }
  }
  async function eliminar(docId) {
    if (!confirm("¿Eliminar este documento? Esta acción no se puede deshacer.")) return;
    setEliminando(docId);
    try {
      await api.delete(`/repositorio/documentos/${docId}`);
      if (seleccionada) cargarDocumentos(seleccionada.id);
    } catch {
      alert("Error al eliminar el documento");
    } finally {
      setEliminando(null);
    }
  }
  function breadcrumb(cat) {
    if (!cat) return "";
    const partes = [cat.nombre];
    let padreId = cat.padre_id;
    while (padreId !== null) {
      const encontrado = buscarEnArbol(arbol, padreId);
      if (!encontrado) break;
      partes.unshift(encontrado.nombre);
      padreId = encontrado.padre_id;
    }
    return partes.join(" › ");
  }
  function buscarEnArbol(nodos, id) {
    for (const n of nodos) {
      if (n.id === id) return n;
      const found = buscarEnArbol(n.hijos, id);
      if (found) return found;
    }
    return null;
  }
  const vigenciaBadge = (fecha) => {
    if (!fecha) return null;
    const hoy = /* @__PURE__ */ new Date();
    const venc = new Date(fecha);
    const diasRestantes = Math.floor((venc.getTime() - hoy.getTime()) / (1e3 * 60 * 60 * 24));
    if (diasRestantes <= 30) return /* @__PURE__ */ jsx("span", { className: "badge badge-danger text-[10px] whitespace-nowrap", children: "0 a 1 mes" });
    if (diasRestantes <= 90) return /* @__PURE__ */ jsx("span", { className: "badge badge-warning text-[10px] whitespace-nowrap", children: "1 a 3 meses" });
    return /* @__PURE__ */ jsx("span", { className: "badge badge-success text-[10px] whitespace-nowrap", children: "> 3 meses" });
  };
  return /* @__PURE__ */ jsxs("div", { className: "h-full flex flex-col space-y-0", children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-4 flex flex-col sm:flex-row sm:items-end justify-between gap-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h1", { className: "text-xl font-semibold text-gray-900", children: "Repositorio Documental" }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: "Archivo Maestro de Gestión Preventiva" })
      ] }),
      resumen && /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => seleccionarFase("rojo"),
            className: `px-3 py-1.5 rounded-md border text-sm flex items-center gap-2 transition-colors ${faseFiltro === "rojo" ? "bg-red-50 border-red-200 text-red-700 font-medium" : "bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,
            children: [
              /* @__PURE__ */ jsx("span", { className: "w-2.5 h-2.5 rounded-full bg-red-500" }),
              "0 a 1 mes (",
              resumen.rojo,
              ")"
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => seleccionarFase("amarillo"),
            className: `px-3 py-1.5 rounded-md border text-sm flex items-center gap-2 transition-colors ${faseFiltro === "amarillo" ? "bg-yellow-50 border-yellow-200 text-yellow-700 font-medium" : "bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,
            children: [
              /* @__PURE__ */ jsx("span", { className: "w-2.5 h-2.5 rounded-full bg-yellow-400" }),
              "1 a 3 meses (",
              resumen.amarillo,
              ")"
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => seleccionarFase("verde"),
            className: `px-3 py-1.5 rounded-md border text-sm flex items-center gap-2 transition-colors ${faseFiltro === "verde" ? "bg-green-50 border-green-200 text-green-700 font-medium" : "bg-white border-gray-200 text-gray-600 hover:bg-gray-50"}`,
            children: [
              /* @__PURE__ */ jsx("span", { className: "w-2.5 h-2.5 rounded-full bg-green-500" }),
              "> 3 meses (",
              resumen.verde,
              ")"
            ]
          }
        )
      ] })
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "mb-4 bg-red-50 border border-red-200 rounded-lg px-4 py-3", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-red-700", children: error }) }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col md:flex-row gap-4 flex-1 min-h-0 md:[height:calc(100vh-200px)]", children: [
      /* @__PURE__ */ jsxs("div", { className: "w-full md:w-72 flex-shrink-0 bg-white border border-gray-200 rounded-lg overflow-y-auto max-h-64 md:max-h-none", children: [
        /* @__PURE__ */ jsx("div", { className: "px-3 py-3 border-b border-gray-100", children: /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold text-gray-500 uppercase tracking-wide", children: "Carpetas" }) }),
        /* @__PURE__ */ jsx("div", { className: "py-2 px-1", children: cargandoCats ? /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400 text-center py-8", children: "Cargando…" }) : arbol.map((cat) => /* @__PURE__ */ jsx(
          NodoCarpeta,
          {
            cat,
            nivel: 0,
            seleccionadaId: seleccionada?.id ?? null,
            expandidas,
            onSelect: seleccionarCategoria,
            onToggle: toggleExpandir
          },
          cat.id
        )) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-64 bg-white border border-gray-200 rounded-lg overflow-y-auto flex flex-col", children: seleccionada === null && faseFiltro === null ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center h-full text-gray-400 space-y-2", children: [
        /* @__PURE__ */ jsx("svg", { className: "w-12 h-12", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx(
          "path",
          {
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: 1.5,
            d: "M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
          }
        ) }),
        /* @__PURE__ */ jsx("p", { className: "text-sm", children: "Seleccione una carpeta o filtro para ver sus documentos" })
      ] }) : /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
        /* @__PURE__ */ jsxs("div", { className: "px-4 py-3 border-b border-gray-100 flex items-start justify-between gap-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            faseFiltro ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx("p", { className: "text-[10px] text-gray-400 uppercase tracking-wide mb-0.5", children: "Filtro Global" }),
              /* @__PURE__ */ jsxs("h2", { className: "text-base font-semibold text-gray-900 truncate", children: [
                faseFiltro === "rojo" && "0 a 1 mes (Requiere Atención)",
                faseFiltro === "amarillo" && "1 a 3 meses (Próximos)",
                faseFiltro === "verde" && "Más de 3 meses (Vigentes)"
              ] })
            ] }) : seleccionada && /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx("p", { className: "text-[10px] text-gray-400 uppercase tracking-wide mb-0.5", children: breadcrumb(seleccionada) }),
              /* @__PURE__ */ jsxs("h2", { className: "text-base font-semibold text-gray-900 truncate", children: [
                /* @__PURE__ */ jsx("span", { className: "font-mono text-sm text-gray-500 mr-2", children: seleccionada.codigo }),
                seleccionada.nombre
              ] })
            ] }),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-gray-500 mt-0.5", children: [
              totalDocs,
              " ",
              totalDocs === 1 ? "documento" : "documentos"
            ] })
          ] }),
          puedeSubir && !mostrarSubida && !faseFiltro && /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => setMostrarSubida(true),
              className: "btn-primary text-sm flex-shrink-0",
              children: "+ Subir documento"
            }
          )
        ] }),
        mostrarSubida && /* @__PURE__ */ jsx("div", { className: "px-4 py-3 border-b border-gray-100", children: /* @__PURE__ */ jsx(
          FormularioSubida,
          {
            categoriaId: seleccionada?.id || 0,
            onSubido: () => {
              setMostrarSubida(false);
              if (seleccionada) cargarDocumentos(seleccionada.id, null);
              cargarResumen();
            },
            onCancelar: () => setMostrarSubida(false)
          }
        ) }),
        /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-y-auto", children: cargandoDocs ? /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-400 text-center py-12", children: "Cargando documentos…" }) : documentos.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-gray-400 space-y-2", children: [
          /* @__PURE__ */ jsx("svg", { className: "w-10 h-10", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx(
            "path",
            {
              strokeLinecap: "round",
              strokeLinejoin: "round",
              strokeWidth: 1.5,
              d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
            }
          ) }),
          /* @__PURE__ */ jsx("p", { className: "text-sm", children: "No hay documentos en esta carpeta" }),
          puedeSubir && /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => setMostrarSubida(true),
              className: "text-blue-600 hover:text-blue-800 text-sm underline",
              children: "Subir el primer documento"
            }
          )
        ] }) : /* @__PURE__ */ jsx("div", { className: "divide-y divide-gray-100", children: documentos.map((doc) => /* @__PURE__ */ jsx("div", { className: "px-4 py-3 hover:bg-gray-50 transition-colors", children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2.5 min-w-0", children: [
            /* @__PURE__ */ jsx("span", { className: "text-xl flex-shrink-0 mt-0.5", children: icono(doc.tipo_mime) }),
            /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
              /* @__PURE__ */ jsx("p", { className: "text-sm font-medium text-gray-900 truncate", children: doc.nombre }),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500 truncate", children: doc.nombre_original }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 mt-1 flex-wrap", children: [
                /* @__PURE__ */ jsx("span", { className: "text-[10px] text-gray-400", children: formatBytes(doc.tamano) }),
                doc.fecha_elaboracion && /* @__PURE__ */ jsxs("span", { className: "text-[10px] text-gray-500", children: [
                  "Elaboración: ",
                  formatFecha(doc.fecha_elaboracion)
                ] }),
                doc.fecha_vigencia && /* @__PURE__ */ jsxs("span", { className: "text-[10px] text-gray-500 flex items-center gap-1", children: [
                  "Vigencia: ",
                  formatFecha(doc.fecha_vigencia),
                  vigenciaBadge(doc.fecha_vigencia)
                ] }),
                /* @__PURE__ */ jsxs("span", { className: "text-[10px] text-gray-400", children: [
                  doc.usuario_nombre,
                  " · ",
                  formatFecha(doc.creado_en)
                ] })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => verDocumento(doc),
                className: "text-blue-600 hover:text-blue-800 text-xs font-medium px-2 py-1 rounded hover:bg-blue-50 transition-colors",
                title: "Visualizar",
                children: "Ver"
              }
            ),
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => descargar(doc),
                className: "text-blue-500 hover:text-blue-700 text-xs font-medium px-2 py-1 rounded hover:bg-blue-50 transition-colors",
                title: "Descargar",
                children: "Descargar"
              }
            ),
            (esLiderOAdmin || doc.subido_por === usuario?.id) && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: async () => {
                  await eliminar(doc.id);
                  cargarResumen();
                },
                disabled: eliminando === doc.id,
                className: "text-red-500 hover:text-red-700 text-xs font-medium px-2 py-1 rounded hover:bg-red-50 transition-colors disabled:opacity-50",
                title: "Eliminar",
                children: eliminando === doc.id ? "…" : "Eliminar"
              }
            )
          ] })
        ] }) }, doc.id)) }) })
      ] }) })
    ] }),
    documentoViendo && blobUrlViendo && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 z-[100] flex items-center justify-center bg-black/70 p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-2xl w-full max-w-5xl h-[90vh] flex flex-col overflow-hidden relative", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-3 border-b border-gray-200", children: [
        /* @__PURE__ */ jsx("h3", { className: "font-semibold text-gray-900 truncate pr-4", children: documentoViendo.nombre_original }),
        /* @__PURE__ */ jsx("button", { onClick: cerrarVisor, className: "text-gray-500 hover:text-gray-700 bg-gray-100 hover:bg-gray-200 p-1.5 rounded-full transition-colors", children: /* @__PURE__ */ jsx("svg", { className: "w-5 h-5", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) }) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex-1 bg-gray-100 overflow-auto flex items-center justify-center p-2", children: documentoViendo.tipo_mime.startsWith("image/") ? /* @__PURE__ */ jsx("img", { src: blobUrlViendo, alt: documentoViendo.nombre_original, className: "max-w-full max-h-full object-contain shadow-sm bg-white" }) : documentoViendo.tipo_mime === "application/pdf" ? /* @__PURE__ */ jsx("iframe", { src: blobUrlViendo, className: "w-full h-full border-0 bg-white shadow-sm" }) : /* @__PURE__ */ jsxs("div", { className: "text-center p-8 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200 max-w-md w-full", children: [
        /* @__PURE__ */ jsx("svg", { className: "w-16 h-16 mx-auto mb-4 text-gray-300", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.5, d: "M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" }) }),
        /* @__PURE__ */ jsx("p", { className: "mb-4 text-gray-600", children: "Este tipo de archivo no se puede visualizar directamente en el navegador." }),
        /* @__PURE__ */ jsx("button", { onClick: () => descargar(documentoViendo), className: "btn-primary", children: "Descargar archivo" })
      ] }) })
    ] }) })
  ] });
}

const $$Index = createComponent(($$result, $$props, $$slots) => {
  return renderTemplate`${renderComponent($$result, "AppLayout", $$AppLayout, { "titulo": "Repositorio Documental", "seccionActiva": "repositorio" }, { "default": ($$result2) => renderTemplate` ${renderComponent($$result2, "RepositorioDocumental", RepositorioDocumental, { "client:load": true, "client:component-hydration": "load", "client:component-path": "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/components/repositorio/RepositorioDocumental", "client:component-export": "default" })} ` })}`;
}, "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/pages/repositorio/index.astro", void 0);

const $$file = "C:/Proyectos IA/Sistema de Control y Gestión Crew Consultores/frontend/src/pages/repositorio/index.astro";
const $$url = "/repositorio";

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  default: $$Index,
  file: $$file,
  url: $$url
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
