import { T as reactExports, K as jsxRuntimeExports } from "./server-ChzsfjB9.js";
import { a as AppLayout, w as ShoppingCart, x as Skeleton, U as Users, P as Package, C as Card, f as CardContent } from "./card-HyNxoILF.js";
import { I as Input, B as Button, C as ChartColumn } from "./input-muzHTpl5.js";
import { L as Label } from "./label-2bHC70jG.js";
import { S as Select, c as SelectTrigger, d as SelectValue, a as SelectContent, b as SelectItem } from "./select-YkkkCruU.js";
import { u as useCurrentCliente, l as useCurrentClienteId, g as formatDateBR, t as toNum, h as formatDateBRShort, L as LoadingOverlay, C as ClienteDbStatus, f as formatBRL, j as formatNumber, d as formatBRLCompact, i as formatDateToSQL, a as executeClienteQuery, e as executeClienteBatchQuery, c as exportChartToPDF, b as exportChartToExcel } from "./exporters-Br36eL2f.js";
import { C as ChartCard } from "./ChartCard-C25D4EJU.js";
import { C as CalendarDays } from "./calendar-days-HMPXAKu8.js";
import { T as TrendingUp } from "./trending-up-fVcv4n6f.js";
import { R as Receipt, a as AreaChart, A as Area } from "./AreaChart-BUqNOUUz.js";
import { R as ResponsiveContainer, C as CartesianGrid, X as XAxis, Y as YAxis, g as Tooltip, a as BarChart, B as Bar } from "./BarChart-BhbIu8Yo.js";
import { S as SquareUserRound } from "./square-user-round-DET6Zr_F.js";
import "node:async_hooks";
import "node:stream/web";
import "node:stream";
import "./router-uu4vGjiO.js";
import "./index-BxBx9O65.js";
import "./index-CZazwQDH.js";
import "./lock-0me_4kb9.js";
import "./sheet-CpXgBl29.js";
const today = () => formatDateToSQL(/* @__PURE__ */ new Date());
const daysAgo = (n) => {
  const d = /* @__PURE__ */ new Date();
  d.setDate(d.getDate() - n);
  return formatDateToSQL(d);
};
const COLOR_PRIMARY = "var(--primary)";
const COLOR_SUCCESS = "var(--success)";
const COLOR_WARNING = "var(--warning)";
const COLOR_INFO = "var(--info)";
const PIE_PALETTE = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)", "var(--primary)", "var(--success)", "var(--warning)"];
const tooltipStyle = {
  backgroundColor: "var(--popover)",
  border: "1px solid var(--border)",
  borderRadius: "10px",
  fontSize: "12px",
  boxShadow: "0 8px 24px -8px rgb(0 0 0 / 0.18)",
  padding: "8px 12px"
};
const tooltipLabelStyle = {
  color: "var(--muted-foreground)",
  fontSize: 11,
  marginBottom: 4
};
function Page() {
  const cliente = useCurrentCliente();
  const clienteId = useCurrentClienteId();
  const [dataIni, setDataIni] = reactExports.useState(daysAgo(30));
  const [dataFim, setDataFim] = reactExports.useState(today());
  const [loja, setLoja] = reactExports.useState("__all__");
  const [lojas, setLojas] = reactExports.useState([]);
  const [cards, setCards] = reactExports.useState(null);
  const [serie, setSerie] = reactExports.useState([]);
  const [mes, setMes] = reactExports.useState([]);
  const [vend, setVend] = reactExports.useState([]);
  const [cli, setCli] = reactExports.useState([]);
  const [prod, setProd] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [erro, setErro] = reactExports.useState(null);
  const lastLoadKeyRef = reactExports.useRef("");
  const params = reactExports.useMemo(() => ({
    data_ini: dataIni,
    data_fim: dataFim,
    loja: loja === "__all__" ? null : Number(loja) || loja,
    limit: 20
  }), [dataIni, dataFim, loja]);
  const lojaNome = reactExports.useMemo(() => {
    if (loja === "__all__") return "Todas as lojas";
    return lojas.find((l) => String(l.id) === String(loja))?.nome ?? `Loja ${loja}`;
  }, [loja, lojas]);
  const reportSubtitle = reactExports.useMemo(() => `Período: ${formatDateBR(dataIni)} a ${formatDateBR(dataFim)}  •  Loja: ${lojaNome}${cliente ? `  •  Cliente: ${cliente.fantasyName}` : ""}`, [dataIni, dataFim, lojaNome, cliente]);
  async function buscarGraficos() {
    if (!clienteId) {
      setErro({
        code: "NO_ACTIVE_CLIENT",
        message: "Nenhum cliente ativo selecionado."
      });
      return;
    }
    setLoading(true);
    setErro(null);
    setCards(null);
    setSerie([]);
    setMes([]);
    setVend([]);
    setCli([]);
    setProd([]);
    try {
      const falhas = [];
      if (lojas.length === 0) {
        const r = await executeClienteQuery("ranking.lojas", {}, clienteId);
        if (r.code === "OK") setLojas(r.rows);
        else falhas.push(`ranking.lojas: ${r.code} - ${r.message}`);
      }
      const steps = [["ranking.cards", params, (rows) => setCards(rows[0] ? {
        total_periodo: toNum(rows[0].total_periodo),
        qtd_vendas_periodo: toNum(rows[0].qtd_vendas_periodo),
        total_hoje: toNum(rows[0].total_hoje)
      } : null)], ["ranking.vendas_dia", params, (rows) => setSerie(rows.map((r) => ({
        ...r,
        total: toNum(r.total),
        qtd_vendas: toNum(r.qtd_vendas)
      })))], ["ranking.faturamento_mensal", {
        loja: params.loja
      }, (rows) => setMes(rows.map((r) => ({
        ...r,
        total: toNum(r.total)
      })))], ["ranking.top_vendedores", params, (rows) => setVend(rows.map((r) => ({
        ...r,
        total: toNum(r.total),
        qtd: toNum(r.qtd)
      })))], ["ranking.top_clientes", params, (rows) => setCli(rows.map((r) => ({
        ...r,
        total: toNum(r.total),
        qtd: toNum(r.qtd)
      })))], ["ranking.top_produtos", params, (rows) => setProd(rows.map((r) => ({
        ...r,
        total: toNum(r.total),
        qtd: toNum(r.qtd)
      })))]];
      const batch = await executeClienteBatchQuery(steps.map(([key, p]) => ({
        key,
        params: p
      })), clienteId);
      for (const [key, , apply] of steps) {
        const r = batch.results[key];
        if (!r || r.code !== "OK") {
          falhas.push(`${key}: ${r?.code ?? "ERR"} - ${r?.message || "Falha na consulta."}`);
          continue;
        }
        if ((r.rows ?? []).length === 0) falhas.push(`${key}: retornou 0 linhas para o período selecionado.`);
        apply(r.rows);
      }
      if (falhas.length > 0) setErro({
        code: "QUERY_FAIL",
        message: falhas.join("\n")
      });
    } catch (e) {
      setErro({
        code: "INTERNAL",
        message: e instanceof Error ? e.message : "Erro inesperado"
      });
    } finally {
      setLoading(false);
    }
  }
  reactExports.useEffect(() => {
    if (!clienteId) {
      lastLoadKeyRef.current = "";
      setErro({
        code: "NO_ACTIVE_CLIENT",
        message: "Nenhum cliente ativo selecionado."
      });
      return;
    }
    const loadKey = JSON.stringify({
      clienteId,
      dataIni,
      dataFim,
      loja
    });
    if (lastLoadKeyRef.current === loadKey) return;
    const t = setTimeout(() => {
      lastLoadKeyRef.current = loadKey;
      buscarGraficos();
    }, 300);
    return () => clearTimeout(t);
  }, [clienteId, dataIni, dataFim, loja]);
  reactExports.useEffect(() => {
    if (lojas.length === 1 && loja === "__all__") {
      setLoja(String(lojas[0].id));
    }
  }, [lojas, loja]);
  const serieData = reactExports.useMemo(() => serie.map((s) => ({
    dia: s.dia,
    diaLabel: formatDateBRShort(s.dia),
    total: toNum(s.total),
    qtd_vendas: toNum(s.qtd_vendas)
  })), [serie]);
  const mesData = reactExports.useMemo(() => mes.map((m) => ({
    mes: m.mes,
    total: toNum(m.total)
  })), [mes]);
  const exportSerie = (fmt) => {
    const columns = [{
      header: "Data",
      key: "dia",
      format: "text"
    }, {
      header: "Total (R$)",
      key: "total",
      format: "brl"
    }, {
      header: "Qtd. Vendas",
      key: "qtd_vendas",
      format: "int"
    }];
    const rows = serieData.map((r) => ({
      dia: formatDateBR(r.dia),
      total: r.total,
      qtd_vendas: r.qtd_vendas
    }));
    const totals = {
      total: rows.reduce((a, r) => a + r.total, 0),
      qtd_vendas: rows.reduce((a, r) => a + r.qtd_vendas, 0)
    };
    if (fmt === "pdf") exportChartToPDF({
      title: "Vendas por dia",
      subtitle: reportSubtitle,
      columns,
      rows,
      totals,
      filename: "ranking-vendas-por-dia.pdf"
    });
    else exportChartToExcel({
      sheetName: "Vendas por dia",
      columns,
      rows,
      filename: "ranking-vendas-por-dia.xlsx"
    });
  };
  const exportMes = (fmt) => {
    const columns = [{
      header: "Mês",
      key: "mes",
      format: "text"
    }, {
      header: "Faturamento (R$)",
      key: "total",
      format: "brl"
    }];
    const rows = mesData;
    const totals = {
      total: rows.reduce((a, r) => a + r.total, 0)
    };
    if (fmt === "pdf") exportChartToPDF({
      title: "Faturamento últimos 12 meses",
      subtitle: reportSubtitle,
      columns,
      rows,
      totals,
      filename: "ranking-faturamento-mensal.pdf"
    });
    else exportChartToExcel({
      sheetName: "Faturamento mensal",
      columns,
      rows,
      filename: "ranking-faturamento-mensal.xlsx"
    });
  };
  const exportRank = (title, file, rowsIn, fmt, labelHeader) => {
    const columns = [{
      header: "#",
      key: "pos",
      format: "int"
    }, {
      header: labelHeader,
      key: "label",
      format: "text"
    }, {
      header: "Total (R$)",
      key: "total",
      format: "brl"
    }, {
      header: "Qtd.",
      key: "qtd",
      format: "int"
    }];
    const rows = rowsIn.map((r, i) => ({
      pos: i + 1,
      label: r.label,
      total: toNum(r.total),
      qtd: toNum(r.qtd)
    }));
    const totals = {
      total: rows.reduce((a, r) => a + r.total, 0),
      qtd: rows.reduce((a, r) => a + r.qtd, 0)
    };
    if (fmt === "pdf") exportChartToPDF({
      title,
      subtitle: reportSubtitle,
      columns,
      rows,
      totals,
      filename: `${file}.pdf`
    });
    else exportChartToExcel({
      sheetName: title.slice(0, 31),
      columns,
      rows,
      filename: `${file}.xlsx`
    });
  };
  const ticketMedio = cards && cards.qtd_vendas_periodo > 0 ? toNum(cards.total_periodo) / toNum(cards.qtd_vendas_periodo) : 0;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(AppLayout, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative space-y-6", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { show: loading, title: "Carregando Ranking de Vendas...", subtitle: "Aguarde, estamos montando os gráficos." }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-end justify-between gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "text-2xl font-bold tracking-tight", children: "Ranking de Vendas" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: cliente ? `Cliente: ${cliente.fantasyName}` : "Selecione um cliente ativo" })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-wrap items-end gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-xs", children: "De" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "date", value: dataIni, onChange: (e) => setDataIni(e.target.value), className: "h-9 w-[150px]" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-xs", children: "Até" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "date", value: dataFim, onChange: (e) => setDataFim(e.target.value), className: "h-9 w-[150px]" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-xs", children: "Loja" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Select, { value: loja, onValueChange: setLoja, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { className: "h-9 w-[200px]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder: "Todas as lojas" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "__all__", children: "Todas as lojas" }),
              lojas.map((l) => /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: String(l.id), children: l.nome }, String(l.id)))
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", className: "h-9", onClick: () => {
          lastLoadKeyRef.current = "";
          buscarGraficos();
        }, disabled: loading, children: loading ? "Carregando…" : "Atualizar" })
      ] })
    ] }),
    erro && /* @__PURE__ */ jsxRuntimeExports.jsx(ClienteDbStatus, { code: erro.code, message: erro.message }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(CalendarDays, { className: "h-4 w-4" }), label: "Total Vendas Hoje", value: cards ? formatBRL(cards.total_hoje) : null, accent: "primary", loading: loading && !cards }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(TrendingUp, { className: "h-4 w-4" }), label: "Total do Período", value: cards ? formatBRL(cards.total_periodo) : null, accent: "success", loading: loading && !cards }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ShoppingCart, { className: "h-4 w-4" }), label: "Qtd. Vendas no Período", value: cards ? formatNumber(cards.qtd_vendas_periodo) : null, accent: "warning", loading: loading && !cards }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Receipt, { className: "h-4 w-4" }), label: "Ticket Médio", value: cards ? formatBRL(ticketMedio) : null, accent: "info", loading: loading && !cards })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Vendas por dia", subtitle: "Faturamento e quantidade no período", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ChartColumn, { className: "h-4 w-4 text-primary" }), onExportPDF: () => exportSerie("pdf"), onExportExcel: () => exportSerie("xlsx"), contentClassName: "h-[300px] pt-2", children: loading && serieData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-full w-full" }) : serieData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(AreaChart, { data: serieData, margin: {
      left: -6,
      right: 12,
      top: 8,
      bottom: 0
    }, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("linearGradient", { id: "rkVD", x1: "0", y1: "0", x2: "0", y2: "1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("stop", { offset: "0%", stopColor: COLOR_PRIMARY, stopOpacity: 0.45 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("stop", { offset: "100%", stopColor: COLOR_PRIMARY, stopOpacity: 0 })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartesianGrid, { strokeDasharray: "3 3", stroke: "var(--border)", vertical: false }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(XAxis, { dataKey: "diaLabel", fontSize: 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)", interval: "preserveStartEnd" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(YAxis, { fontSize: 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)", tickFormatter: (v) => formatBRLCompact(v), width: 70 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { contentStyle: tooltipStyle, labelStyle: tooltipLabelStyle, labelFormatter: (_label, payload) => {
        const d = payload?.[0]?.payload?.dia;
        return d ? formatDateBR(d) : "";
      }, formatter: (v) => [formatBRL(Number(v)), "Total"] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Area, { type: "monotone", dataKey: "total", stroke: COLOR_PRIMARY, strokeWidth: 2.5, fill: "url(#rkVD)" })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Faturamento últimos 12 meses", subtitle: "Comparativo de faturamento mensal", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(TrendingUp, { className: "h-4 w-4 text-success" }), onExportPDF: () => exportMes("pdf"), onExportExcel: () => exportMes("xlsx"), contentClassName: "h-[300px] pt-2", children: loading && mesData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-full w-full" }) : mesData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(BarChart, { data: mesData, margin: {
      left: -6,
      right: 12,
      top: 8,
      bottom: 0
    }, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("defs", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("linearGradient", { id: "rkMes", x1: "0", y1: "0", x2: "0", y2: "1", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("stop", { offset: "0%", stopColor: COLOR_SUCCESS, stopOpacity: 1 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("stop", { offset: "100%", stopColor: COLOR_SUCCESS, stopOpacity: 0.65 })
      ] }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(CartesianGrid, { strokeDasharray: "3 3", stroke: "var(--border)", vertical: false }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(XAxis, { dataKey: "mes", fontSize: 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(YAxis, { fontSize: 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)", tickFormatter: (v) => formatBRLCompact(v), width: 70 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { contentStyle: tooltipStyle, labelStyle: tooltipLabelStyle, formatter: (v) => [formatBRL(v), "Faturamento"] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Bar, { dataKey: "total", fill: "url(#rkMes)", radius: [8, 8, 0, 0], maxBarSize: 48 })
    ] }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-3 gap-4", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(RankCard, { title: "Top Vendedores", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Users, { className: "h-4 w-4 text-primary" }), rows: vend, loading: loading && vend.length === 0, color: COLOR_PRIMARY, onExportPDF: () => exportRank("Top Vendedores", "ranking-top-vendedores", vend, "pdf", "Vendedor"), onExportExcel: () => exportRank("Top Vendedores", "ranking-top-vendedores", vend, "xlsx", "Vendedor") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(RankCard, { title: "Top Clientes", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(SquareUserRound, { className: "h-4 w-4 text-info" }), rows: cli, loading: loading && cli.length === 0, color: COLOR_INFO, onExportPDF: () => exportRank("Top Clientes", "ranking-top-clientes", cli, "pdf", "Cliente"), onExportExcel: () => exportRank("Top Clientes", "ranking-top-clientes", cli, "xlsx", "Cliente") }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(RankCard, { title: "Top Produtos", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "h-4 w-4 text-warning" }), rows: prod, loading: loading && prod.length === 0, color: COLOR_WARNING, onExportPDF: () => exportRank("Top Produtos", "ranking-top-produtos", prod, "pdf", "Produto"), onExportExcel: () => exportRank("Top Produtos", "ranking-top-produtos", prod, "xlsx", "Produto") })
    ] })
  ] }) });
}
function EmptyState() {
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-full flex items-center justify-center", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "text-sm text-muted-foreground", children: "Sem dados para o período selecionado." }) });
}
const accentMap = {
  primary: {
    from: "from-primary/15",
    to: "to-primary/5",
    text: "text-primary"
  },
  success: {
    from: "from-success/15",
    to: "to-success/5",
    text: "text-success"
  },
  warning: {
    from: "from-warning/20",
    to: "to-warning/5",
    text: "text-warning"
  },
  info: {
    from: "from-info/15",
    to: "to-info/5",
    text: "text-info"
  }
};
function KCard({
  icon,
  label,
  value,
  loading,
  accent = "primary"
}) {
  const a = accentMap[accent];
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-border/60 shadow-sm hover:shadow-md transition-shadow", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CardContent, { className: "p-5", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start justify-between", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-1", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-medium text-muted-foreground", children: label }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-2xl font-bold tracking-tight", children: loading ? /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-7 w-28" }) : value ?? "—" })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `flex h-11 w-11 items-center justify-center rounded-xl bg-gradient-to-br ${a.from} ${a.to} ${a.text}`, children: icon })
  ] }) }) });
}
function RankCard({
  title,
  icon,
  rows,
  loading,
  color,
  onExportPDF,
  onExportExcel
}) {
  const top = rows.slice(0, 8);
  const max = Math.max(1, ...top.map((r) => toNum(r.total)));
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title, subtitle: `${rows.length} resultados`, icon, onExportPDF, onExportExcel, children: loading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "space-y-2", children: Array.from({
    length: 6
  }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-9 w-full" }, i)) }) : top.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-3", children: top.map((r, i) => {
    const total = toNum(r.total);
    const pct = total / max * 100;
    const palette = PIE_PALETTE[i % PIE_PALETTE.length];
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: "space-y-1.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-2 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "truncate flex items-center gap-2 min-w-0", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold text-primary-foreground", style: {
            background: color
          }, children: i + 1 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: r.label })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold tabular-nums shrink-0", children: formatBRL(total) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-1.5 flex-1 rounded-full bg-muted overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-full rounded-full transition-all", style: {
          width: `${pct}%`,
          background: palette
        } }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-[11px] text-muted-foreground tabular-nums w-16 text-right", children: [
          formatNumber(r.qtd),
          " un."
        ] })
      ] })
    ] }, r.label + i);
  }) }) });
}
export {
  Page as component
};
