import { e as createComponent, k as renderComponent, r as renderTemplate } from '../chunks/astro/server_CNSJbOTP.mjs';
import 'piccolore';
import { a as api, b as ESTADO_PROCESO_ETIQUETAS, e as ESTADO_PROCESO_BADGE, $ as $$AppLayout } from '../chunks/AppLayout_ClxvESCL.mjs';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { ResponsiveContainer, PieChart, Pie, Cell, Tooltip } from 'recharts';
export { renderers } from '../renderers.mjs';

const COLOR_NIVEL = {
  alto: "#EF4444",
  mediano: "#F59E0B",
  bajo: "#22C55E",
  sin_nivel: "#D1D5DB"
};
const COLOR_ESTADO = {
  no_iniciado: "#6B7280",
  en_proceso: "#3B82F6",
  en_revision: "#F59E0B",
  pendiente_aprobacion: "#8B5CF6",
  completa: "#22C55E",
  anulada: "#EF4444"
};
const ETIQUETA_ESTADO = {
  no_iniciado: "No Iniciada",
  en_proceso: "En Proceso",
  en_revision: "En Revisión",
  pendiente_aprobacion: "Pend. Aprob.",
  completa: "Completada",
  anulada: "Anulada"
};
const COLORES_CP = ["#14B8A6", "#3B82F6", "#F59E0B", "#EF4444", "#8B5CF6", "#22C55E", "#F97316", "#06B6D4"];
function KpiCard({ label, value, colorVal, colorBg, colorIcon, icon }) {
  return /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center gap-4", children: [
    /* @__PURE__ */ jsx("div", { className: `w-12 h-12 ${colorBg} rounded-xl flex items-center justify-center flex-shrink-0`, children: /* @__PURE__ */ jsx("span", { className: colorIcon, children: icon }) }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: label }),
      /* @__PURE__ */ jsx("p", { className: `text-3xl font-bold ${colorVal}`, children: value })
    ] })
  ] });
}
function KpiCardCumplimiento({ pct }) {
  const data = [
    { value: pct },
    { value: 100 - pct }
  ];
  return /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center gap-3", children: [
    /* @__PURE__ */ jsx("div", { className: "flex-shrink-0", style: { width: 72, height: 72 }, children: /* @__PURE__ */ jsxs(PieChart, { width: 72, height: 72, children: [
      /* @__PURE__ */ jsxs(
        Pie,
        {
          data,
          cx: 31,
          cy: 31,
          innerRadius: 22,
          outerRadius: 33,
          startAngle: 90,
          endAngle: -270,
          paddingAngle: 0,
          dataKey: "value",
          stroke: "none",
          children: [
            /* @__PURE__ */ jsx(Cell, { fill: "#14B8A6" }),
            /* @__PURE__ */ jsx(Cell, { fill: "#E5E7EB" })
          ]
        }
      ),
      /* @__PURE__ */ jsxs("text", { x: 36, y: 36, textAnchor: "middle", dominantBaseline: "middle", fontSize: 13, fontWeight: 700, fill: "#0F766E", children: [
        pct,
        "%"
      ] })
    ] }) }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: "Cumplimiento General" }),
      /* @__PURE__ */ jsxs("p", { className: "text-3xl font-bold text-teal-600", children: [
        pct,
        "%"
      ] })
    ] })
  ] });
}
function badgeNivel(nivel) {
  if (!nivel) return /* @__PURE__ */ jsx("span", { className: "badge badge-gray text-xs", children: "—" });
  const mapa = { alto: "badge-danger", mediano: "badge-warning", bajo: "badge-success" };
  const texto = { alto: "AR", mediano: "MR", bajo: "BR" };
  return /* @__PURE__ */ jsx("span", { className: `badge ${mapa[nivel] ?? "badge-gray"} text-xs font-mono`, children: texto[nivel] ?? nivel });
}
function badgeEstado(e) {
  const clave = e;
  return /* @__PURE__ */ jsx("span", { className: `badge ${ESTADO_PROCESO_BADGE[clave] ?? "badge-gray"} text-xs`, children: ESTADO_PROCESO_ETIQUETAS[clave] ?? e });
}
function formatFecha(iso) {
  const d = new Date(iso);
  return d.toLocaleDateString("es-CL", { day: "2-digit", month: "2-digit", year: "numeric" });
}
function formatHora(iso) {
  const d = new Date(iso);
  return d.toLocaleTimeString("es-CL", { hour: "2-digit", minute: "2-digit" });
}
function badgeDias(dias) {
  if (dias <= 7) return /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium px-2 py-0.5 rounded-full bg-red-50 text-red-600", children: [
    "Vence en ",
    dias,
    " días"
  ] });
  if (dias <= 15) return /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium px-2 py-0.5 rounded-full bg-amber-50 text-amber-600", children: [
    "Vence en ",
    dias,
    " días"
  ] });
  return /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium px-2 py-0.5 rounded-full bg-gray-100 text-gray-500", children: [
    "Vence en ",
    dias,
    " días"
  ] });
}
function LabelCentro({ viewBox, valor, subtexto }) {
  const { cx = 0, cy = 0 } = viewBox ?? {};
  return /* @__PURE__ */ jsxs("text", { x: cx, y: cy, textAnchor: "middle", dominantBaseline: "middle", children: [
    /* @__PURE__ */ jsx("tspan", { x: cx, dy: "-6", fontSize: 22, fontWeight: 700, fill: "#111827", children: valor }),
    /* @__PURE__ */ jsx("tspan", { x: cx, dy: 20, fontSize: 11, fill: "#6B7280", children: subtexto })
  ] });
}
function DashboardPanel() {
  const [data, setData] = useState(null);
  const [cargando, setCargando] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    api.get("/dashboard/resumen").then(setData).catch((e) => setError(e instanceof Error ? e.message : "Error al cargar el dashboard")).finally(() => setCargando(false));
  }, []);
  if (cargando) return /* @__PURE__ */ jsx("div", { className: "py-24 text-center text-gray-400", children: "Cargando dashboard…" });
  if (error) return /* @__PURE__ */ jsx("div", { className: "rounded-lg bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700", children: error });
  if (!data) return null;
  const dataNivel = [
    { name: `Alto (AR)`, value: data.por_nivel.alto, key: "alto" },
    { name: `Medio (MR)`, value: data.por_nivel.mediano, key: "mediano" },
    { name: `Bajo (BR)`, value: data.por_nivel.bajo, key: "bajo" },
    { name: `Sin nivel`, value: data.por_nivel.sin_nivel, key: "sin_nivel" }
  ].filter((d) => d.value > 0);
  const dataEstado = Object.entries(data.por_estado).map(([key, value]) => ({
    name: ETIQUETA_ESTADO[key] ?? key,
    value,
    key,
    pct: data.total > 0 ? Math.round(value / data.total * 100) : 0
  })).filter((d) => d.value > 0);
  const dataCp = data.cumplimiento_cp.map((c, i) => ({
    name: c.nombre,
    value: c.total,
    porcentaje: c.porcentaje,
    color: COLORES_CP[i % COLORES_CP.length]
  }));
  const promedioCp = dataCp.length > 0 ? Math.round(dataCp.reduce((s, c) => s + c.porcentaje, 0) / dataCp.length) : 0;
  const cumplimientoGlobal = Math.round(data.cumplimiento_general);
  const pctCumplimientoTareas = data.total > 0 ? Math.round(data.completadas / data.total * 100) : 0;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 xl:grid-cols-5 gap-4", children: [
      /* @__PURE__ */ jsx(
        KpiCard,
        {
          label: "Tareas Totales",
          value: data.total,
          colorVal: "text-blue-600",
          colorBg: "bg-blue-100",
          colorIcon: "text-blue-500",
          icon: /* @__PURE__ */ jsx("svg", { className: "w-6 h-6", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" }) })
        }
      ),
      /* @__PURE__ */ jsx(
        KpiCard,
        {
          label: "Tareas en Proceso",
          value: data.en_proceso,
          colorVal: "text-amber-500",
          colorBg: "bg-amber-100",
          colorIcon: "text-amber-500",
          icon: /* @__PURE__ */ jsx("svg", { className: "w-6 h-6", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" }) })
        }
      ),
      /* @__PURE__ */ jsx(
        KpiCard,
        {
          label: "Tareas Completadas",
          value: data.completadas,
          colorVal: "text-green-600",
          colorBg: "bg-green-100",
          colorIcon: "text-green-500",
          icon: /* @__PURE__ */ jsx("svg", { className: "w-6 h-6", 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" }) })
        }
      ),
      /* @__PURE__ */ jsx(
        KpiCard,
        {
          label: "Tareas Vencidas",
          value: data.vencidas,
          colorVal: "text-red-600",
          colorBg: "bg-red-100",
          colorIcon: "text-red-500",
          icon: /* @__PURE__ */ jsx("svg", { className: "w-6 h-6", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" }) })
        }
      ),
      /* @__PURE__ */ jsx(KpiCardCumplimiento, { pct: pctCumplimientoTareas })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700 mb-3", children: "Tareas por Nivel de Riesgo" }),
        dataNivel.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-center text-gray-400 text-sm py-8", children: "Sin datos" }) : /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: 200, children: /* @__PURE__ */ jsxs(PieChart, { children: [
          /* @__PURE__ */ jsxs(
            Pie,
            {
              data: dataNivel,
              cx: "50%",
              cy: "50%",
              innerRadius: 55,
              outerRadius: 80,
              paddingAngle: 2,
              dataKey: "value",
              labelLine: false,
              children: [
                dataNivel.map((entry) => /* @__PURE__ */ jsx(Cell, { fill: COLOR_NIVEL[entry.key] }, entry.key)),
                /* @__PURE__ */ jsx(LabelCentro, { valor: String(data.total), subtexto: "Total" })
              ]
            }
          ),
          /* @__PURE__ */ jsx(Tooltip, { formatter: (v, name) => [v, name] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1 mt-2", children: dataNivel.map((d) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-gray-600", children: [
          /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx("span", { className: "w-2.5 h-2.5 rounded-full flex-shrink-0", style: { background: COLOR_NIVEL[d.key] } }),
            d.name
          ] }),
          /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
            d.value,
            " ",
            /* @__PURE__ */ jsxs("span", { className: "text-gray-400", children: [
              "(",
              data.total > 0 ? Math.round(d.value / data.total * 100) : 0,
              "%)"
            ] })
          ] })
        ] }, d.key)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700 mb-3", children: "Tareas por Estado" }),
        dataEstado.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-center text-gray-400 text-sm py-8", children: "Sin datos" }) : /* @__PURE__ */ jsx("div", { className: "space-y-2 mt-1", children: dataEstado.map((d) => /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between text-xs text-gray-600 mb-0.5", children: [
            /* @__PURE__ */ jsx("span", { children: d.name }),
            /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
              d.value,
              " ",
              /* @__PURE__ */ jsxs("span", { className: "text-gray-400", children: [
                "(",
                d.pct,
                "%)"
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "h-2 bg-gray-100 rounded-full overflow-hidden", children: /* @__PURE__ */ jsx(
            "div",
            {
              className: "h-full rounded-full transition-all",
              style: { width: `${d.pct}%`, background: COLOR_ESTADO[d.key] }
            }
          ) })
        ] }, d.key)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700 mb-3", children: "Cumplimiento Mensual (CP)" }),
        dataCp.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-center text-gray-400 text-sm py-8", children: "Sin documentos con fecha de vigencia" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(ResponsiveContainer, { width: "100%", height: 130, children: /* @__PURE__ */ jsxs(PieChart, { children: [
            /* @__PURE__ */ jsxs(
              Pie,
              {
                data: dataCp,
                cx: "50%",
                cy: "50%",
                innerRadius: 38,
                outerRadius: 58,
                paddingAngle: 2,
                dataKey: "value",
                labelLine: false,
                children: [
                  dataCp.map((entry, i) => /* @__PURE__ */ jsx(Cell, { fill: entry.color }, i)),
                  /* @__PURE__ */ jsx(LabelCentro, { valor: `${promedioCp}%`, subtexto: "Promedio" })
                ]
              }
            ),
            /* @__PURE__ */ jsx(Tooltip, { formatter: (v, name) => [`${v} docs`, name] })
          ] }) }),
          /* @__PURE__ */ jsx("div", { className: "space-y-1.5 mt-2 max-h-36 overflow-y-auto pr-1", children: dataCp.map((c, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-gray-600", children: [
            /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 truncate", children: [
              /* @__PURE__ */ jsx("span", { className: "w-2.5 h-2.5 rounded-full flex-shrink-0", style: { background: c.color } }),
              /* @__PURE__ */ jsx("span", { className: "truncate", children: c.nombre })
            ] }),
            /* @__PURE__ */ jsxs("span", { className: "font-semibold ml-2 flex-shrink-0", children: [
              Math.round(c.porcentaje),
              "%"
            ] })
          ] }, i)) })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700", children: "Próximos Vencimientos" }),
          /* @__PURE__ */ jsx("a", { href: "/actividades", className: "text-xs text-blue-600 hover:underline", children: "Ver todas →" })
        ] }),
        data.proximos_vencimientos.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-center text-gray-400 text-sm py-6", children: "Sin vencimientos en 30 días" }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: data.proximos_vencimientos.map((pv) => /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
            /* @__PURE__ */ jsx("a", { href: `/actividades/${pv.id}`, className: "text-sm font-medium text-gray-800 hover:text-blue-600 truncate block", children: pv.nombre }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-400 truncate", children: pv.area })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex-shrink-0", children: badgeDias(pv.dias_restantes) })
        ] }, pv.id)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700", children: "Tareas Recientes" }),
          /* @__PURE__ */ jsx("a", { href: "/actividades", className: "text-xs text-blue-600 hover:underline", children: "Ver todas →" })
        ] }),
        data.recientes.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-center text-gray-400 text-sm py-6", children: "Sin actividades" }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: data.recientes.map((r) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          badgeNivel(r.nivel_riesgo),
          /* @__PURE__ */ jsx("div", { className: "min-w-0 flex-1", children: /* @__PURE__ */ jsx("a", { href: `/actividades/${r.id}`, className: "text-sm font-medium text-gray-800 hover:text-blue-600 truncate block", children: r.nombre }) }),
          /* @__PURE__ */ jsxs("div", { className: "flex-shrink-0 text-right", children: [
            badgeEstado(r.estado),
            /* @__PURE__ */ jsxs("p", { className: "text-xs text-gray-400 mt-0.5", children: [
              formatFecha(r.actualizado_en),
              " ",
              formatHora(r.actualizado_en)
            ] })
          ] })
        ] }, r.id)) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl border border-gray-200 shadow-sm p-5", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between mb-3", children: /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-gray-700", children: "Acciones Requeridas" }) }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700", children: [
              /* @__PURE__ */ jsx("span", { className: "text-amber-500", children: "⚠" }),
              "Pendientes de aprobación"
            ] }),
            data.pendientes_aprobacion > 0 ? /* @__PURE__ */ jsx("span", { className: "text-xs font-bold px-2 py-0.5 rounded-full bg-amber-100 text-amber-700", children: data.pendientes_aprobacion }) : /* @__PURE__ */ jsx("span", { className: "text-xs font-bold px-2 py-0.5 rounded-full bg-gray-100 text-gray-400", children: "0" })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700", children: [
              /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "🔴" }),
              "Tareas vencidas"
            ] }),
            data.vencidas > 0 ? /* @__PURE__ */ jsx("span", { className: "text-xs font-bold px-2 py-0.5 rounded-full bg-red-100 text-red-700", children: data.vencidas }) : /* @__PURE__ */ jsx("span", { className: "text-xs font-bold px-2 py-0.5 rounded-full bg-gray-100 text-gray-400", children: "0" })
          ] }),
          cumplimientoGlobal > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700", children: [
              /* @__PURE__ */ jsx("span", { className: "text-teal-500", children: "📄" }),
              "Cumplimiento documental"
            ] }),
            /* @__PURE__ */ jsxs("span", { className: `text-xs font-bold px-2 py-0.5 rounded-full ${cumplimientoGlobal >= 80 ? "bg-green-100 text-green-700" : cumplimientoGlobal >= 60 ? "bg-amber-100 text-amber-700" : "bg-red-100 text-red-700"}`, children: [
              cumplimientoGlobal,
              "%"
            ] })
          ] })
        ] })
      ] })
    ] })
  ] });
}

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

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

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

const page = () => _page;

export { page };
