import { e as createComponent, k as renderComponent, r as renderTemplate, m as maybeRenderHead } from '../../chunks/astro/server_CNSJbOTP.mjs';
import 'piccolore';
import { R as ROL_ETIQUETAS, a as api, $ as $$AppLayout } from '../../chunks/AppLayout_DAKNch61.mjs';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useCallback, useEffect } from 'react';
export { renderers } from '../../renderers.mjs';

const ROLES = ["admin", "lider", "colaborador", "consultor"];
function FormularioUsuario({ usuario, empresas, onCerrar, onGuardado }) {
  const esEdicion = !!usuario;
  const perfilesIniciales = usuario?.perfiles && usuario.perfiles.length > 0 ? usuario.perfiles.map((p) => ({ empresa_id: p.empresa_id, rol: p.rol })) : empresas[0] ? [{ empresa_id: empresas[0].id, rol: "colaborador" }] : [];
  const [form, setForm] = useState({
    perfiles: perfilesIniciales,
    correo: usuario?.correo || "",
    nombre_usuario: usuario?.nombre_usuario || "",
    contrasena: "",
    nombre: usuario?.nombre || "",
    apellido: usuario?.apellido || "",
    activo: usuario?.activo ?? true,
    es_prevencionista: usuario?.es_prevencionista ?? false
  });
  const [errores, setErrores] = useState({});
  const [guardando, setGuardando] = useState(false);
  const [errorGlobal, setErrorGlobal] = useState("");
  function actualizar(campo, valor) {
    setForm((f) => ({ ...f, [campo]: valor }));
    setErrores((e) => ({ ...e, [campo]: "" }));
  }
  function agregarPerfil() {
    const empresasUsadas = new Set(form.perfiles.map((p) => p.empresa_id));
    const disponible = empresas.find((e) => !empresasUsadas.has(e.id));
    if (!disponible) return;
    setForm((f) => ({ ...f, perfiles: [...f.perfiles, { empresa_id: disponible.id, rol: "colaborador" }] }));
  }
  function actualizarPerfil(index, campo, valor) {
    setForm((f) => {
      const nuevos = [...f.perfiles];
      nuevos[index] = { ...nuevos[index], [campo]: valor };
      return { ...f, perfiles: nuevos };
    });
    setErrores((e) => ({ ...e, perfiles: "" }));
  }
  function eliminarPerfil(index) {
    setForm((f) => ({ ...f, perfiles: f.perfiles.filter((_, i) => i !== index) }));
  }
  function validar() {
    const nuevosErrores = {};
    if (!form.nombre.trim()) nuevosErrores.nombre = "El nombre es requerido";
    if (!form.apellido.trim()) nuevosErrores.apellido = "El apellido es requerido";
    if (form.perfiles.length === 0) {
      nuevosErrores.perfiles = "Debe asignar al menos un perfil";
    } else {
      const empresasIds = form.perfiles.map((p) => p.empresa_id);
      if (new Set(empresasIds).size !== empresasIds.length) {
        nuevosErrores.perfiles = "No puede repetir la misma empresa en dos perfiles";
      }
    }
    if (!form.correo.trim()) nuevosErrores.correo = "El correo es requerido";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.correo)) nuevosErrores.correo = "Correo inválido";
    if (!esEdicion) {
      if (!form.contrasena) nuevosErrores.contrasena = "La contraseña es requerida";
      else if (form.contrasena.length < 8) nuevosErrores.contrasena = "Mínimo 8 caracteres";
    }
    setErrores(nuevosErrores);
    return Object.keys(nuevosErrores).length === 0;
  }
  async function guardar(e) {
    e.preventDefault();
    if (!validar()) return;
    setGuardando(true);
    setErrorGlobal("");
    try {
      if (esEdicion) {
        await api.put(`/usuarios/${usuario.id}`, {
          nombre: form.nombre,
          apellido: form.apellido,
          correo: form.correo,
          nombre_usuario: form.nombre_usuario || null,
          activo: form.activo,
          es_prevencionista: form.es_prevencionista,
          perfiles: form.perfiles
        });
      } else {
        await api.post("/usuarios", {
          perfiles: form.perfiles,
          correo: form.correo,
          nombre_usuario: form.nombre_usuario || null,
          contrasena: form.contrasena,
          nombre: form.nombre,
          apellido: form.apellido
        });
      }
      onGuardado();
    } catch (e2) {
      setErrorGlobal(e2 instanceof Error ? e2.message : "Error al guardar");
    } finally {
      setGuardando(false);
    }
  }
  const empresasDisponibles = (currentEmpresaId) => empresas.filter(
    (e) => e.id === currentEmpresaId || !form.perfiles.some((p) => p.empresa_id === e.id)
  );
  return /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl w-full max-w-lg my-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-100", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900", children: esEdicion ? "Editar Usuario" : "Nuevo Usuario" }),
      /* @__PURE__ */ jsx("button", { onClick: onCerrar, className: "p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg 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__ */ jsxs("form", { onSubmit: guardar, className: "p-6 space-y-4", children: [
      errorGlobal && /* @__PURE__ */ jsx("div", { className: "p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: errorGlobal }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Nombre *" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "text",
              value: form.nombre,
              onChange: (e) => {
                const v = e.target.value;
                actualizar("nombre", v);
              },
              className: `input ${errores.nombre ? "border-red-400" : ""}`,
              placeholder: "Juan"
            }
          ),
          errores.nombre && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 mt-1", children: errores.nombre })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Apellido *" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "text",
              value: form.apellido,
              onChange: (e) => {
                const v = e.target.value;
                actualizar("apellido", v);
              },
              className: `input ${errores.apellido ? "border-red-400" : ""}`,
              placeholder: "Pérez"
            }
          ),
          errores.apellido && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 mt-1", children: errores.apellido })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Correo electrónico *" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "email",
            value: form.correo,
            onChange: (e) => {
              const v = e.target.value;
              actualizar("correo", v);
            },
            className: `input ${errores.correo ? "border-red-400" : ""}`,
            placeholder: "usuario@empresa.cl"
          }
        ),
        errores.correo && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 mt-1", children: errores.correo })
      ] }),
      !esEdicion && /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Contraseña *" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "password",
            value: form.contrasena,
            onChange: (e) => {
              const v = e.target.value;
              actualizar("contrasena", v);
            },
            className: `input ${errores.contrasena ? "border-red-400" : ""}`,
            placeholder: "Mínimo 8 caracteres"
          }
        ),
        errores.contrasena && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 mt-1", children: errores.contrasena })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: [
          "Nombre de usuario ",
          /* @__PURE__ */ jsx("span", { className: "text-gray-400 font-normal", children: "(opcional)" })
        ] }),
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "text",
            value: form.nombre_usuario,
            onChange: (e) => {
              const v = e.target.value.toLowerCase().replace(/\s/g, "");
              actualizar("nombre_usuario", v);
            },
            className: "input",
            placeholder: "ej: jperez",
            autoComplete: "off"
          }
        ),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400 mt-1", children: "Permite iniciar sesión sin usar el correo." })
      ] }),
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-1.5", children: [
          /* @__PURE__ */ jsxs("label", { className: "block text-sm font-medium text-gray-700", children: [
            "Perfiles *",
            " ",
            /* @__PURE__ */ jsx("span", { className: "text-gray-400 font-normal", children: "(empresa + rol)" })
          ] }),
          form.perfiles.length < empresas.length && /* @__PURE__ */ jsxs(
            "button",
            {
              type: "button",
              onClick: agregarPerfil,
              className: "text-xs text-blue-600 hover:text-blue-700 font-medium flex items-center gap-1",
              children: [
                /* @__PURE__ */ jsx("svg", { className: "w-3.5 h-3.5", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 4v16m8-8H4" }) }),
                "Agregar empresa"
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsx("div", { className: `border rounded-lg overflow-hidden ${errores.perfiles ? "border-red-400" : "border-gray-200"}`, children: form.perfiles.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400 p-3", children: "No hay perfiles asignados" }) : form.perfiles.map((perfil, idx) => /* @__PURE__ */ jsxs("div", { className: `flex items-center gap-2 p-2.5 ${idx > 0 ? "border-t border-gray-100" : ""}`, children: [
          idx === 0 && /* @__PURE__ */ jsx("span", { className: "badge badge-info text-xs flex-shrink-0", children: "Principal" }),
          /* @__PURE__ */ jsx(
            "select",
            {
              value: perfil.empresa_id,
              onChange: (e) => actualizarPerfil(idx, "empresa_id", Number(e.target.value)),
              className: "input text-sm flex-1 min-w-0",
              children: empresasDisponibles(perfil.empresa_id).map((emp) => /* @__PURE__ */ jsx("option", { value: emp.id, children: emp.nombre }, emp.id))
            }
          ),
          /* @__PURE__ */ jsx(
            "select",
            {
              value: perfil.rol,
              onChange: (e) => actualizarPerfil(idx, "rol", e.target.value),
              className: "input text-sm w-36 flex-shrink-0",
              children: ROLES.map((r) => /* @__PURE__ */ jsx("option", { value: r, children: ROL_ETIQUETAS[r] }, r))
            }
          ),
          form.perfiles.length > 1 && /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              onClick: () => eliminarPerfil(idx),
              className: "p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded transition-colors flex-shrink-0",
              title: "Eliminar perfil",
              children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", 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" }) })
            }
          )
        ] }, idx)) }),
        errores.perfiles && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500 mt-1", children: errores.perfiles })
      ] }),
      esEdicion && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-3 cursor-pointer", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: form.activo,
              onChange: (e) => {
                const v = e.target.checked;
                actualizar("activo", v);
              },
              className: "w-4 h-4 rounded border-gray-300"
            }
          ),
          /* @__PURE__ */ jsx("span", { className: "text-sm text-gray-700", children: "Usuario activo" })
        ] }),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-3 cursor-pointer", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: form.es_prevencionista,
              onChange: (e) => {
                const v = e.target.checked;
                actualizar("es_prevencionista", v);
              },
              className: "w-4 h-4 rounded border-gray-300"
            }
          ),
          /* @__PURE__ */ jsx("span", { className: "text-sm text-gray-700", children: "APR / Prevencionista" })
        ] })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end pt-2", children: [
        /* @__PURE__ */ jsx("button", { type: "button", onClick: onCerrar, className: "btn-secondary text-sm", disabled: guardando, children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { type: "submit", className: "btn-primary text-sm", disabled: guardando, children: guardando ? "Guardando..." : esEdicion ? "Guardar cambios" : "Crear usuario" })
      ] })
    ] })
  ] }) });
}

const BADGES_ROL = {
  admin: "badge badge-info",
  lider: "badge badge-warning",
  colaborador: "badge badge-success",
  consultor: "badge badge-gray"
};
function TablaUsuarios() {
  const [usuarios, setUsuarios] = useState([]);
  const [empresas, setEmpresas] = useState([]);
  const [total, setTotal] = useState(0);
  const [pagina, setPagina] = useState(1);
  const [cargando, setCargando] = useState(true);
  const [error, setError] = useState("");
  const [filtroRol, setFiltroRol] = useState("");
  const [filtroActivo, setFiltroActivo] = useState(true);
  const [modalAbierto, setModalAbierto] = useState(false);
  const [usuarioEditar, setUsuarioEditar] = useState(null);
  const [confirmDesactivar, setConfirmDesactivar] = useState(null);
  const [confirmEliminar, setConfirmEliminar] = useState(null);
  const [modalResetPass, setModalResetPass] = useState(null);
  const [tempPass, setTempPass] = useState("");
  const [tempPassError, setTempPassError] = useState("");
  const [tempPassOk, setTempPassOk] = useState(false);
  const [tempPassGuardando, setTempPassGuardando] = useState(false);
  const porPagina = 20;
  const cargarEmpresas = useCallback(async () => {
    try {
      const data = await api.get("/empresas?activo=true&por_pagina=100");
      setEmpresas(data.datos);
    } catch {
    }
  }, []);
  const cargarUsuarios = useCallback(async () => {
    setCargando(true);
    setError("");
    try {
      const params = new URLSearchParams({
        pagina: String(pagina),
        por_pagina: String(porPagina),
        activo: String(filtroActivo),
        ...filtroRol ? { rol: filtroRol } : {}
      });
      const data = await api.get(`/usuarios?${params}`);
      setUsuarios(data.datos);
      setTotal(data.total);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Error al cargar usuarios");
    } finally {
      setCargando(false);
    }
  }, [pagina, filtroRol, filtroActivo]);
  useEffect(() => {
    cargarEmpresas();
  }, [cargarEmpresas]);
  useEffect(() => {
    cargarUsuarios();
  }, [cargarUsuarios]);
  async function desactivarUsuario(usuario) {
    try {
      await api.delete(`/usuarios/${usuario.id}`);
      setConfirmDesactivar(null);
      cargarUsuarios();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Error al desactivar usuario");
    }
  }
  function abrirResetPass(u) {
    setModalResetPass(u);
    setTempPass("");
    setTempPassError("");
    setTempPassOk(false);
  }
  async function guardarResetPass() {
    if (tempPass.length < 8) {
      setTempPassError("La contraseña debe tener al menos 8 caracteres");
      return;
    }
    setTempPassGuardando(true);
    setTempPassError("");
    try {
      await api.post(`/usuarios/${modalResetPass.id}/resetear-contrasena`, {
        nueva_contrasena: tempPass
      });
      setTempPassOk(true);
    } catch (e) {
      setTempPassError(e instanceof Error ? e.message : "Error al cambiar la contraseña");
    } finally {
      setTempPassGuardando(false);
    }
  }
  async function eliminarUsuario(usuario) {
    try {
      await api.delete(`/usuarios/${usuario.id}/eliminar`);
      setConfirmEliminar(null);
      cargarUsuarios();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Error al eliminar usuario");
    }
  }
  async function activarUsuario(usuario) {
    try {
      await api.put(`/usuarios/${usuario.id}`, { activo: true });
      cargarUsuarios();
    } catch (e) {
      alert(e instanceof Error ? e.message : "Error al activar usuario");
    }
  }
  const totalPaginas = Math.ceil(total / porPagina);
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", children: [
        /* @__PURE__ */ jsxs(
          "select",
          {
            value: filtroRol,
            onChange: (e) => {
              setFiltroRol(e.currentTarget.value);
              setPagina(1);
            },
            className: "input w-auto text-sm",
            children: [
              /* @__PURE__ */ jsx("option", { value: "", children: "Todos los roles" }),
              /* @__PURE__ */ jsx("option", { value: "admin", children: "Administrador" }),
              /* @__PURE__ */ jsx("option", { value: "lider", children: "Líder" }),
              /* @__PURE__ */ jsx("option", { value: "colaborador", children: "Colaborador" }),
              /* @__PURE__ */ jsx("option", { value: "consultor", children: "Consultor" })
            ]
          }
        ),
        /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm text-gray-600 cursor-pointer", children: [
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "checkbox",
              checked: filtroActivo,
              onChange: (e) => {
                setFiltroActivo(e.currentTarget.checked);
                setPagina(1);
              },
              className: "rounded border-gray-300"
            }
          ),
          "Solo activos"
        ] })
      ] }),
      /* @__PURE__ */ jsxs(
        "button",
        {
          onClick: () => {
            setUsuarioEditar(null);
            setModalAbierto(true);
          },
          className: "btn-primary text-sm flex items-center gap-2",
          children: [
            /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 4v16m8-8H4" }) }),
            "Nuevo Usuario"
          ]
        }
      )
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: error }),
    /* @__PURE__ */ jsx("div", { className: "table-container", children: /* @__PURE__ */ jsxs("table", { className: "table", children: [
      /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsx("th", { children: "Nombre" }),
        /* @__PURE__ */ jsx("th", { className: "hidden md:table-cell", children: "Correo" }),
        /* @__PURE__ */ jsx("th", { children: "Rol" }),
        /* @__PURE__ */ jsx("th", { className: "hidden lg:table-cell", children: "Empresa" }),
        /* @__PURE__ */ jsx("th", { children: "Estado" }),
        /* @__PURE__ */ jsx("th", { children: "Acciones" })
      ] }) }),
      /* @__PURE__ */ jsx("tbody", { children: cargando ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 6, className: "text-center py-10 text-gray-400", children: "Cargando usuarios..." }) }) : usuarios.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 6, className: "text-center py-10 text-gray-400", children: "No se encontraron usuarios" }) }) : usuarios.map((u) => /* @__PURE__ */ jsxs("tr", { children: [
        /* @__PURE__ */ jsxs("td", { children: [
          /* @__PURE__ */ jsxs("div", { className: "font-medium text-gray-900", children: [
            u.nombre,
            " ",
            u.apellido
          ] }),
          /* @__PURE__ */ jsx("div", { className: "text-xs text-gray-500 md:hidden", children: u.correo }),
          u.nombre_usuario && /* @__PURE__ */ jsxs("div", { className: "text-xs text-gray-400 font-mono", children: [
            "@",
            u.nombre_usuario
          ] })
        ] }),
        /* @__PURE__ */ jsx("td", { className: "hidden md:table-cell text-gray-600", children: u.correo }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsx("span", { className: BADGES_ROL[u.rol], children: ROL_ETIQUETAS[u.rol] }) }),
        /* @__PURE__ */ jsx("td", { className: "hidden lg:table-cell text-gray-600", children: u.perfiles && u.perfiles.length > 0 ? u.perfiles.map((p, i) => {
          const nombre = empresas.find((e) => e.id === p.empresa_id)?.nombre ?? `#${p.empresa_id}`;
          return /* @__PURE__ */ jsx("span", { className: "inline-flex items-center gap-1", children: i === 0 ? /* @__PURE__ */ jsx("span", { className: "font-medium", children: nombre }) : /* @__PURE__ */ jsxs("span", { className: "text-gray-400 text-xs", children: [
            " · ",
            nombre
          ] }) }, p.id);
        }) : /* @__PURE__ */ jsx("span", { className: "text-gray-400", children: "—" }) }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsx("span", { className: u.activo ? "badge badge-success" : "badge badge-gray", children: u.activo ? "Activo" : "Inactivo" }) }),
        /* @__PURE__ */ jsx("td", { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => {
                setUsuarioEditar(u);
                setModalAbierto(true);
              },
              title: "Editar",
              className: "p-1.5 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors",
              children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" }) })
            }
          ),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => abrirResetPass(u),
              title: "Establecer contraseña temporal",
              className: "p-1.5 text-gray-500 hover:text-amber-600 hover:bg-amber-50 rounded-lg transition-colors",
              children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" }) })
            }
          ),
          u.activo ? u.nombre_usuario !== "admin" && /* @__PURE__ */ jsx(
            "button",
            {
              onClick: () => setConfirmDesactivar(u),
              title: "Desactivar",
              className: "p-1.5 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors",
              children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" }) })
            }
          ) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => activarUsuario(u),
                title: "Activar",
                className: "p-1.5 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors",
                children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" }) })
              }
            ),
            u.nombre_usuario !== "admin" && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: () => setConfirmEliminar(u),
                title: "Eliminar permanentemente",
                className: "p-1.5 text-gray-500 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors",
                children: /* @__PURE__ */ jsx("svg", { className: "w-4 h-4", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" }) })
              }
            )
          ] })
        ] }) })
      ] }, u.id)) })
    ] }) }),
    totalPaginas > 1 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-4 text-sm text-gray-600", children: [
      /* @__PURE__ */ jsxs("span", { children: [
        "Mostrando ",
        (pagina - 1) * porPagina + 1,
        "–",
        Math.min(pagina * porPagina, total),
        " de ",
        total
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx("button", { disabled: pagina === 1, onClick: () => setPagina((p) => p - 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "← Anterior" }),
        /* @__PURE__ */ jsx("button", { disabled: pagina === totalPaginas, onClick: () => setPagina((p) => p + 1), className: "btn-secondary py-1 px-3 text-xs disabled:opacity-50", children: "Siguiente →" })
      ] })
    ] }),
    modalAbierto && /* @__PURE__ */ jsx(
      FormularioUsuario,
      {
        usuario: usuarioEditar,
        empresas,
        onCerrar: () => setModalAbierto(false),
        onGuardado: () => {
          setModalAbierto(false);
          cargarUsuarios();
        }
      }
    ),
    confirmDesactivar && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl max-w-sm w-full p-6", children: [
      /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900 mb-2", children: "¿Desactivar usuario?" }),
      /* @__PURE__ */ jsxs("p", { className: "text-gray-600 text-sm mb-5", children: [
        "Se desactivará ",
        /* @__PURE__ */ jsxs("strong", { children: [
          confirmDesactivar.nombre,
          " ",
          confirmDesactivar.apellido
        ] }),
        ". El usuario no podrá iniciar sesión."
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end", children: [
        /* @__PURE__ */ jsx("button", { onClick: () => setConfirmDesactivar(null), className: "btn-secondary text-sm", children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { onClick: () => desactivarUsuario(confirmDesactivar), className: "btn-danger text-sm", children: "Desactivar" })
      ] })
    ] }) }),
    modalResetPass && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl w-full max-w-sm", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-6 border-b border-gray-100", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900", children: "Contraseña temporal" }),
          /* @__PURE__ */ jsxs("p", { className: "text-sm text-gray-500 mt-0.5", children: [
            modalResetPass.nombre,
            " ",
            modalResetPass.apellido
          ] })
        ] }),
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: () => setModalResetPass(null),
            className: "p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg 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: "p-6 space-y-4", children: tempPassOk ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsx("div", { className: "p-3 bg-green-50 border border-green-200 rounded-lg text-sm text-green-700", children: "Contraseña temporal establecida. Comunícala al usuario para que pueda ingresar." }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 p-3 bg-gray-50 rounded-lg border border-gray-200", children: [
          /* @__PURE__ */ jsx("svg", { className: "w-4 h-4 text-amber-500 flex-shrink-0", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" }) }),
          /* @__PURE__ */ jsx("span", { className: "text-sm font-mono font-medium text-gray-800 tracking-wide", children: tempPass })
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400", children: "El usuario deberá cambiarla desde su perfil al iniciar sesión." }),
        /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx("button", { onClick: () => setModalResetPass(null), className: "btn-primary text-sm", children: "Cerrar" }) })
      ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
        tempPassError && /* @__PURE__ */ jsx("div", { className: "p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700", children: tempPassError }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("label", { className: "block text-sm font-medium text-gray-700 mb-1.5", children: "Nueva contraseña temporal" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "text",
              value: tempPass,
              onChange: (e) => {
                setTempPass(e.target.value);
                setTempPassError("");
              },
              className: "input font-mono",
              placeholder: "Mínimo 8 caracteres",
              autoComplete: "off"
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400 mt-1", children: "El usuario usará esta contraseña para ingresar y luego podrá cambiarla desde su perfil." })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end pt-1", children: [
          /* @__PURE__ */ jsx("button", { onClick: () => setModalResetPass(null), className: "btn-secondary text-sm", disabled: tempPassGuardando, children: "Cancelar" }),
          /* @__PURE__ */ jsx("button", { onClick: guardarResetPass, className: "btn-primary text-sm", disabled: tempPassGuardando, children: tempPassGuardando ? "Guardando..." : "Establecer contraseña" })
        ] })
      ] }) })
    ] }) }),
    confirmEliminar && /* @__PURE__ */ jsx("div", { className: "fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-xl max-w-sm w-full p-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 mb-3", children: [
        /* @__PURE__ */ jsx("div", { className: "w-10 h-10 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0", children: /* @__PURE__ */ jsx("svg", { className: "w-5 h-5 text-red-600", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" }) }) }),
        /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold text-gray-900", children: "¿Eliminar usuario permanentemente?" })
      ] }),
      /* @__PURE__ */ jsxs("p", { className: "text-gray-600 text-sm mb-2", children: [
        "Se eliminará ",
        /* @__PURE__ */ jsxs("strong", { children: [
          confirmEliminar.nombre,
          " ",
          confirmEliminar.apellido
        ] }),
        " de forma permanente."
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-red-600 text-xs mb-5 bg-red-50 rounded-lg px-3 py-2", children: "Esta acción no se puede deshacer. Se perderán todos sus datos, perfiles y sesiones." }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-3 justify-end", children: [
        /* @__PURE__ */ jsx("button", { onClick: () => setConfirmEliminar(null), className: "btn-secondary text-sm", children: "Cancelar" }),
        /* @__PURE__ */ jsx("button", { onClick: () => eliminarUsuario(confirmEliminar), className: "btn-danger text-sm", children: "Eliminar permanentemente" })
      ] })
    ] }) })
  ] });
}

const $$Usuarios = createComponent(($$result, $$props, $$slots) => {
  return renderTemplate`${renderComponent($$result, "AppLayout", $$AppLayout, { "titulo": "Gesti\xF3n de Usuarios", "seccionActiva": "usuarios" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}<div class="mb-4"> <a href="/dashboard" class="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-[#1B2B4B] transition-colors"> <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path> </svg>
Volver al Dashboard
</a> </div> ${renderComponent($$result2, "TablaUsuarios", TablaUsuarios, { "client:load": true, "client:component-hydration": "load", "client:component-path": "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/components/admin/TablaUsuarios", "client:component-export": "default" })} ` })}`;
}, "C:/Proyectos IA/Sistema de Control y Gesti\xF3n Crew Consultores/frontend/src/pages/admin/usuarios.astro", void 0);

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

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

const page = () => _page;

export { page };
