import { T as reactExports, K as jsxRuntimeExports } from "./server-ChzsfjB9.js";
import { X, P as Package, x as Skeleton, C as Card, f as CardContent, Q as useIsMobile, a as AppLayout, i as ChartPie } from "./card-HyNxoILF.js";
import { e as createLucideIcon, B as Button, I as Input, 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 { l as useCurrentClienteId, a as executeClienteQuery, t as toNum, g as formatDateBR, f as formatBRL, j as formatNumber, k as formatPercent, C as ClienteDbStatus, b as exportChartToExcel, c as exportChartToPDF, u as useCurrentCliente, L as LoadingOverlay, d as formatBRLCompact, i as formatDateToSQL, e as executeClienteBatchQuery } from "./exporters-Br36eL2f.js";
import { C as ChartCard } from "./ChartCard-C25D4EJU.js";
import { D as Dialog, a as DialogContent, d as DialogHeader, e as DialogTitle } from "./dialog-B868fIfK.js";
import { L as Layers } from "./layers-CNNG_TMf.js";
import { S as Sheet, F as FileText } from "./sheet-CpXgBl29.js";
import { D as DollarSign, P as Percent, S as ShoppingBag, b as PieChart, a as Pie } from "./PieChart-DFpMmo8M.js";
import { t as toast } from "./index-DhnCtKbR.js";
import { R as ResponsiveContainer, a as BarChart, C as CartesianGrid, X as XAxis, Y as YAxis, g as Tooltip, f as Legend, B as Bar, b as Cell } from "./BarChart-BhbIu8Yo.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";
const __iconNode$2 = [
  [
    "path",
    {
      d: "M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",
      key: "lc1i9w"
    }
  ],
  ["path", { d: "m7 16.5-4.74-2.85", key: "1o9zyk" }],
  ["path", { d: "m7 16.5 5-3", key: "va8pkn" }],
  ["path", { d: "M7 16.5v5.17", key: "jnp8gn" }],
  [
    "path",
    {
      d: "M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",
      key: "8zsnat"
    }
  ],
  ["path", { d: "m17 16.5-5-3", key: "8arw3v" }],
  ["path", { d: "m17 16.5 4.74-2.85", key: "8rfmw" }],
  ["path", { d: "M17 16.5v5.17", key: "k6z78m" }],
  [
    "path",
    {
      d: "M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",
      key: "1xygjf"
    }
  ],
  ["path", { d: "M12 8 7.26 5.15", key: "1vbdud" }],
  ["path", { d: "m12 8 4.74-2.85", key: "3rx089" }],
  ["path", { d: "M12 13.5V8", key: "1io7kd" }]
];
const Boxes = createLucideIcon("boxes", __iconNode$2);
const __iconNode$1 = [
  ["path", { d: "M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2", key: "wrbu53" }],
  ["path", { d: "M15 18H9", key: "1lyqi6" }],
  [
    "path",
    {
      d: "M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",
      key: "lysw3i"
    }
  ],
  ["circle", { cx: "17", cy: "18", r: "2", key: "332jqn" }],
  ["circle", { cx: "7", cy: "18", r: "2", key: "19iecd" }]
];
const Truck = createLucideIcon("truck", __iconNode$1);
const __iconNode = [
  [
    "path",
    {
      d: "M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",
      key: "18etb6"
    }
  ],
  ["path", { d: "M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4", key: "xoc0q4" }]
];
const Wallet = createLucideIcon("wallet", __iconNode);
function ComprasGrupoDetalheDialog({
  open,
  onOpenChange,
  grupo,
  codGrupo,
  dataIni,
  dataFimExcl,
  dataFim,
  loja,
  fornecedor = null,
  tipoData = "emissao",
  totalGeralGrupos
}) {
  const clienteId = useCurrentClienteId();
  const [rows, setRows] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [erro, setErro] = reactExports.useState(null);
  reactExports.useEffect(() => {
    if (!open || !clienteId || codGrupo == null) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      setErro(null);
      setRows([]);
      const r = await executeClienteQuery(
        "compras.grupo_detalhe",
        { data_ini: dataIni, data_fim: dataFim, data_fim_excl: dataFimExcl, loja, fornecedor, tipo_data: tipoData, cod_grupo: codGrupo },
        clienteId
      );
      if (cancelled) return;
      if (r.code === "OK") setRows(r.rows);
      else setErro({ code: r.code, message: r.message || "Falha ao carregar detalhamento." });
      setLoading(false);
    })();
    return () => {
      cancelled = true;
    };
  }, [open, clienteId, dataIni, dataFim, dataFimExcl, loja, fornecedor, tipoData, codGrupo]);
  const { totalGrupo, qtdItens, percentual } = reactExports.useMemo(() => {
    const total = rows.reduce((a, r) => a + toNum(r.total), 0);
    const qi = rows.reduce((a, r) => a + toNum(r.quantidade), 0);
    const p = totalGeralGrupos > 0 ? total / totalGeralGrupos * 100 : 0;
    return { totalGrupo: total, qtdItens: qi, percentual: p };
  }, [rows, totalGeralGrupos]);
  const safeGrupo = (grupo || "grupo").toLowerCase().replace(/[^a-z0-9]+/gi, "-");
  const baseName = `detalhamento-compras-grupo-${safeGrupo}-${dataIni}-${dataFim}`;
  const columns = [
    { header: "Cód.", key: "cod_produto", format: "text" },
    { header: "Produto", key: "produto", format: "text" },
    { header: "Qtd", key: "quantidade", format: "int" },
    { header: "Valor total", key: "total", format: "brl" },
    { header: "Fornecedor", key: "fornecedor", format: "text" }
  ];
  const handlePDF = () => exportChartToPDF({
    title: `Detalhamento - Grupo: ${grupo}`,
    subtitle: `${formatDateBR(dataIni)} a ${formatDateBR(dataFim)} • ${rows.length} produtos • ${formatBRL(totalGrupo)}`,
    columns,
    rows,
    filename: baseName,
    totals: { produto: "Total", total: totalGrupo, quantidade: qtdItens }
  });
  const handleExcel = () => exportChartToExcel({ sheetName: "Detalhamento", columns, rows, filename: baseName });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { className: "p-0 gap-0 overflow-hidden w-[95vw] max-w-5xl max-h-[90vh] sm:w-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { className: "px-4 sm:px-6 py-3 sm:py-4 border-b border-border bg-gradient-to-r from-primary/5 to-transparent", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogTitle, { className: "text-base sm:text-lg flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Layers, { className: "h-5 w-5 text-primary shrink-0" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: "Detalhamento - Grupo" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-muted-foreground mt-1 truncate", children: [
          grupo,
          " • ",
          formatDateBR(dataIni),
          " até ",
          formatDateBR(dataFim)
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5 sm:mr-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            size: "sm",
            variant: "outline",
            onClick: handleExcel,
            disabled: loading || rows.length === 0,
            className: "h-8 gap-1 border-success/30 text-success hover:bg-success/10 hover:text-success",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Sheet, { className: "h-3.5 w-3.5" }),
              "Excel"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            size: "sm",
            variant: "outline",
            onClick: handlePDF,
            disabled: loading || rows.length === 0,
            className: "h-8 gap-1 border-destructive/30 text-destructive hover:bg-destructive/10 hover:text-destructive",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "h-3.5 w-3.5" }),
              "PDF"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { size: "sm", variant: "ghost", onClick: () => onOpenChange(false), className: "h-8 gap-1 sm:hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-3.5 w-3.5" }),
          "Fechar"
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-4 sm:px-6 py-4 space-y-4 max-h-[calc(90vh-110px)] overflow-y-auto sm:overflow-hidden flex flex-col", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard$1, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Layers, { className: "h-4 w-4" }), label: "Grupo", value: grupo, accent: "primary" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard$1, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(DollarSign, { className: "h-4 w-4" }), label: "Total comprado", value: loading ? "..." : formatBRL(totalGrupo), accent: "success" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard$1, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "h-4 w-4" }), label: "Quantidade itens", value: loading ? "..." : formatNumber(qtdItens), accent: "info" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard$1, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Percent, { className: "h-4 w-4" }), label: "% sobre o total", value: loading ? "..." : formatPercent(percentual), accent: "warning" })
      ] }),
      erro && /* @__PURE__ */ jsxRuntimeExports.jsx(ClienteDbStatus, { code: erro.code, message: erro.message }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "md:hidden space-y-2", children: loading ? Array.from({ length: 5 }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-28 w-full" }, i)) : rows.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center py-10 text-sm text-muted-foreground", children: "Nenhum produto encontrado para este grupo." }) : rows.map((r, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-border/60", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-3 space-y-1.5 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-start gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold truncate", children: r.produto }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground tabular-nums shrink-0", children: [
            "#",
            String(r.cod_produto)
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground truncate", children: [
          "Fornecedor: ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-foreground", children: r.fornecedor })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center pt-1.5 border-t border-border/40", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-muted-foreground", children: "Qtd" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "tabular-nums", children: formatNumber(r.quantidade) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-muted-foreground", children: "Valor total" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold tabular-nums text-success", children: formatBRL(r.total) })
        ] })
      ] }) }, String(r.cod_produto) + i)) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "hidden md:flex flex-1 min-h-0 rounded-lg border border-border overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-auto max-h-[55vh] w-full", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "sticky top-0 z-10 bg-muted/80 backdrop-blur", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "text-left text-xs text-muted-foreground uppercase tracking-wide", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Cód." }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Produto" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium text-right", children: "Qtd" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium text-right", children: "Valor total" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Fornecedor" })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: loading ? Array.from({ length: 8 }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { className: "border-t border-border/40", children: /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 5, className: "p-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-7 w-full" }) }) }, i)) : rows.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 5, className: "text-center py-10 text-sm text-muted-foreground", children: "Nenhum produto encontrado para este grupo." }) }) : rows.map((r, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "border-t border-border/40 hover:bg-muted/40 transition-colors", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 tabular-nums", children: String(r.cod_produto) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 max-w-[260px] truncate", title: r.produto, children: r.produto }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums", children: formatNumber(r.quantidade) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums font-medium", children: formatBRL(r.total) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 max-w-[220px] truncate", title: r.fornecedor, children: r.fornecedor })
        ] }, String(r.cod_produto) + i)) }),
        !loading && rows.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("tfoot", { className: "sticky bottom-0 bg-muted/80 backdrop-blur", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "border-t border-border text-sm font-semibold", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 2, className: "py-2.5 px-3 text-right", children: "Total" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums", children: formatNumber(qtdItens) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums", children: formatBRL(totalGrupo) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", {})
        ] }) })
      ] }) }) })
    ] })
  ] }) });
}
function SummaryCard$1({
  icon,
  label,
  value,
  accent
}) {
  const tone = accent === "success" ? "from-success/15 to-success/0 text-success" : accent === "info" ? "from-info/15 to-info/0 text-info" : accent === "warning" ? "from-warning/15 to-warning/0 text-warning" : "from-primary/15 to-primary/0 text-primary";
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-border/60", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: `p-3 bg-gradient-to-br ${tone} rounded-xl`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[11px] uppercase tracking-wide text-muted-foreground font-medium", children: label }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "opacity-80", children: icon })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1 text-lg font-bold text-foreground truncate", title: value, children: value })
  ] }) });
}
function ComprasFormaPagamentoDetalheDialog({
  open,
  onOpenChange,
  forma,
  codDoc,
  dataIni,
  dataFimExcl,
  dataFim,
  loja,
  fornecedor = null,
  tipoData = "emissao",
  totalGeralFormas
}) {
  const clienteId = useCurrentClienteId();
  const [rows, setRows] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [erro, setErro] = reactExports.useState(null);
  reactExports.useEffect(() => {
    if (!open || !clienteId || codDoc == null) return;
    let cancelled = false;
    (async () => {
      setLoading(true);
      setErro(null);
      setRows([]);
      const r = await executeClienteQuery(
        "compras.forma_pagamento_detalhe",
        { data_ini: dataIni, data_fim: dataFim, data_fim_excl: dataFimExcl, loja, fornecedor, tipo_data: tipoData, cod_doc: codDoc },
        clienteId
      );
      if (cancelled) return;
      if (r.code === "OK") setRows(r.rows);
      else setErro({ code: r.code, message: r.message || "Falha ao carregar detalhamento." });
      setLoading(false);
    })();
    return () => {
      cancelled = true;
    };
  }, [open, clienteId, dataIni, dataFim, dataFimExcl, loja, fornecedor, tipoData, codDoc]);
  const { totalForma, qtd, percentual } = reactExports.useMemo(() => {
    const total = rows.reduce((a, r) => a + toNum(r.valor), 0);
    const p = totalGeralFormas > 0 ? total / totalGeralFormas * 100 : 0;
    return { totalForma: total, qtd: rows.length, percentual: p };
  }, [rows, totalGeralFormas]);
  const safeForma = (forma || "forma").toLowerCase().replace(/[^a-z0-9]+/gi, "-");
  const baseName = `detalhamento-compras-forma-${safeForma}-${dataIni}-${dataFim}`;
  const columns = [
    { header: "Data emissão", key: "data_emissao", format: "text" },
    { header: "Nº Entrada", key: "entrada", format: "text" },
    { header: "Fornecedor", key: "fornecedor", format: "text" },
    { header: "Loja", key: "loja", format: "text" },
    { header: "Forma pagamento", key: "forma_pagamento", format: "text" },
    { header: "Valor", key: "valor", format: "brl" }
  ];
  const exportRows = rows.map((r) => ({
    ...r,
    data_emissao: formatDateBR(r.data_emissao)
  }));
  const handlePDF = () => exportChartToPDF({
    title: `Detalhamento - Forma de Pagamento (Compras): ${forma}`,
    subtitle: `${formatDateBR(dataIni)} a ${formatDateBR(dataFim)} • ${qtd} compras • ${formatBRL(totalForma)}`,
    columns,
    rows: exportRows,
    filename: baseName,
    totals: { fornecedor: "Total", valor: totalForma }
  });
  const handleExcel = () => exportChartToExcel({ sheetName: "Detalhamento", columns, rows: exportRows, filename: baseName });
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogContent, { className: "p-0 gap-0 overflow-hidden w-[95vw] max-w-5xl max-h-[90vh] sm:w-full", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(DialogHeader, { className: "px-4 sm:px-6 py-3 sm:py-4 border-b border-border bg-gradient-to-r from-primary/5 to-transparent", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(DialogTitle, { className: "text-base sm:text-lg flex items-center gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Wallet, { className: "h-5 w-5 text-primary shrink-0" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: "Detalhamento - Forma de Pagamento" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: "text-xs text-muted-foreground mt-1 truncate", children: [
          forma,
          " • ",
          formatDateBR(dataIni),
          " até ",
          formatDateBR(dataFim)
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5 sm:mr-6", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            size: "sm",
            variant: "outline",
            onClick: handleExcel,
            disabled: loading || rows.length === 0,
            className: "h-8 gap-1 border-success/30 text-success hover:bg-success/10 hover:text-success",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Sheet, { className: "h-3.5 w-3.5" }),
              "Excel"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Button,
          {
            size: "sm",
            variant: "outline",
            onClick: handlePDF,
            disabled: loading || rows.length === 0,
            className: "h-8 gap-1 border-destructive/30 text-destructive hover:bg-destructive/10 hover:text-destructive",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(FileText, { className: "h-3.5 w-3.5" }),
              "PDF"
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { size: "sm", variant: "ghost", onClick: () => onOpenChange(false), className: "h-8 gap-1 sm:hidden", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-3.5 w-3.5" }),
          "Fechar"
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "px-4 sm:px-6 py-4 space-y-4 max-h-[calc(90vh-110px)] overflow-y-auto sm:overflow-hidden flex flex-col", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid gap-3 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Wallet, { className: "h-4 w-4" }), label: "Forma", value: forma, accent: "primary" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(DollarSign, { className: "h-4 w-4" }), label: "Total", value: loading ? "..." : formatBRL(totalForma), accent: "success" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ShoppingBag, { className: "h-4 w-4" }), label: "Qtd compras", value: loading ? "..." : formatNumber(qtd), accent: "info" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Percent, { className: "h-4 w-4" }), label: "% sobre o total", value: loading ? "..." : formatPercent(percentual), accent: "warning" })
      ] }),
      erro && /* @__PURE__ */ jsxRuntimeExports.jsx(ClienteDbStatus, { code: erro.code, message: erro.message }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "md:hidden space-y-2", children: loading ? Array.from({ length: 5 }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-32 w-full" }, i)) : rows.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-center py-10 text-sm text-muted-foreground", children: "Nenhuma compra encontrada para esta forma de pagamento." }) : rows.map((r, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-border/60", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: "p-3 space-y-1.5 text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-start gap-2", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "font-semibold tabular-nums", children: [
            "#",
            String(r.entrada)
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-xs text-muted-foreground tabular-nums", children: formatDateBR(r.data_emissao) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground truncate", children: [
          "Fornecedor: ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-foreground", children: r.fornecedor })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground", children: [
          "Loja: ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-foreground", children: r.loja })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-xs text-muted-foreground", children: [
          "Forma: ",
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-foreground", children: r.forma_pagamento })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between items-center pt-1.5 border-t border-border/40", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs text-muted-foreground", children: "Valor" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold tabular-nums text-success", children: formatBRL(r.valor) })
        ] })
      ] }) }, String(r.entrada) + i)) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "hidden md:flex flex-1 min-h-0 rounded-lg border border-border overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "overflow-auto max-h-[55vh] w-full", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: "w-full text-sm", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { className: "sticky top-0 z-10 bg-muted/80 backdrop-blur", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "text-left text-xs text-muted-foreground uppercase tracking-wide", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Data" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Nº Entrada" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Fornecedor" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Loja" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium", children: "Forma" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("th", { className: "py-2.5 px-3 font-medium text-right", children: "Valor" })
        ] }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: loading ? Array.from({ length: 8 }).map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { className: "border-t border-border/40", children: /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 6, className: "p-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-7 w-full" }) }) }, i)) : rows.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("tr", { children: /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 6, className: "text-center py-10 text-sm text-muted-foreground", children: "Nenhuma compra encontrada para esta forma de pagamento." }) }) : rows.map((r, i) => /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "border-t border-border/40 hover:bg-muted/40 transition-colors", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 tabular-nums", children: formatDateBR(r.data_emissao) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 tabular-nums", children: String(r.entrada) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 max-w-[220px] truncate", title: r.fornecedor, children: r.fornecedor }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3", children: r.loja }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3", children: r.forma_pagamento }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums font-medium", children: formatBRL(r.valor) })
        ] }, String(r.entrada) + i)) }),
        !loading && rows.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("tfoot", { className: "sticky bottom-0 bg-muted/80 backdrop-blur", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { className: "border-t border-border text-sm font-semibold", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { colSpan: 5, className: "py-2.5 px-3 text-right", children: "Total" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("td", { className: "py-2.5 px-3 text-right tabular-nums", children: formatBRL(totalForma) })
        ] }) })
      ] }) }) })
    ] })
  ] }) });
}
function SummaryCard({
  icon,
  label,
  value,
  accent
}) {
  const tone = accent === "success" ? "from-success/15 to-success/0 text-success" : accent === "info" ? "from-info/15 to-info/0 text-info" : accent === "warning" ? "from-warning/15 to-warning/0 text-warning" : "from-primary/15 to-primary/0 text-primary";
  return /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "border-border/60", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(CardContent, { className: `p-3 bg-gradient-to-br ${tone} rounded-xl`, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-[11px] uppercase tracking-wide text-muted-foreground font-medium", children: label }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "opacity-80", children: icon })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-1 text-lg font-bold text-foreground truncate", title: value, children: value })
  ] }) });
}
const today = () => formatDateToSQL(/* @__PURE__ */ new Date());
const daysAgo = (n) => {
  const d = /* @__PURE__ */ new Date();
  d.setDate(d.getDate() - n);
  return formatDateToSQL(d);
};
const PIE_PALETTE = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)", "var(--primary)", "var(--success)", "var(--warning)", "var(--info)", "var(--destructive)"];
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(7));
  const [dataFim, setDataFim] = reactExports.useState(today());
  const [tipoData, setTipoData] = reactExports.useState("entrada");
  const [loja, setLoja] = reactExports.useState("__all__");
  const [fornecedor, setFornecedor] = reactExports.useState("__all__");
  const [lojas, setLojas] = reactExports.useState([]);
  const [fornecedores, setFornecedores] = reactExports.useState([]);
  const [cards, setCards] = reactExports.useState(null);
  const [cxv, setCxv] = reactExports.useState([]);
  const [grupos, setGrupos] = reactExports.useState([]);
  const [formas, setFormas] = reactExports.useState([]);
  const [fornRank, setFornRank] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [erro, setErro] = reactExports.useState(null);
  const isMobile = useIsMobile();
  const [grupoSel, setGrupoSel] = reactExports.useState(null);
  const [formaSel, setFormaSel] = reactExports.useState(null);
  const lastLoadKeyRef = reactExports.useRef("");
  const params = reactExports.useMemo(() => ({
    data_ini: dataIni,
    data_fim: dataFim,
    tipo_data: tipoData,
    loja: loja === "__all__" ? null : Number(loja) || loja,
    fornecedor: fornecedor === "__all__" ? null : Number(fornecedor) || fornecedor
  }), [dataIni, dataFim, tipoData, loja, fornecedor]);
  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 fornecedorNome = reactExports.useMemo(() => {
    if (fornecedor === "__all__") return "Todos os fornecedores";
    return fornecedores.find((f) => String(f.id) === String(fornecedor))?.nome ?? `Fornecedor ${fornecedor}`;
  }, [fornecedor, fornecedores]);
  const tipoDataLabel = tipoData === "entrada" ? "entrada" : "emissão";
  const reportSubtitle = reactExports.useMemo(() => `Período (${tipoDataLabel}): ${formatDateBR(dataIni)} a ${formatDateBR(dataFim)}  •  Loja: ${lojaNome}  •  Fornecedor: ${fornecedorNome}${cliente ? `  •  Cliente: ${cliente.fantasyName}` : ""}`, [dataIni, dataFim, tipoDataLabel, lojaNome, fornecedorNome, cliente]);
  async function carregar() {
    if (!clienteId) {
      setErro({
        code: "NO_ACTIVE_CLIENT",
        message: "Nenhum cliente ativo selecionado."
      });
      return;
    }
    setLoading(true);
    setErro(null);
    setCards(null);
    setCxv([]);
    setGrupos([]);
    setFormas([]);
    setFornRank([]);
    try {
      const queries = [{
        key: "compras.cards",
        params
      }, {
        key: "compras.compra_x_venda_top10",
        params
      }, {
        key: "compras.grupos",
        params
      }, {
        key: "compras.forma_pagamento",
        params
      }, {
        key: "compras.fornecedor",
        params
      }];
      if (lojas.length === 0) queries.push({
        key: "compras.lojas"
      });
      if (fornecedores.length === 0) queries.push({
        key: "compras.fornecedores"
      });
      const batch = await executeClienteBatchQuery(queries, clienteId);
      const falhas = [];
      const apply = (key, fn) => {
        const r = batch.results[key];
        if (!r || r.code !== "OK") {
          falhas.push(`${key}: ${r?.code ?? "ERR"} - ${r?.message || "Falha na consulta."}`);
          return;
        }
        fn(r.rows);
      };
      apply("compras.cards", (rows) => setCards(rows[0] ? {
        total_compras: toNum(rows[0].total_compras),
        qtd_compras: toNum(rows[0].qtd_compras),
        qtd_produtos: toNum(rows[0].qtd_produtos)
      } : {
        total_compras: 0,
        qtd_compras: 0,
        qtd_produtos: 0
      }));
      apply("compras.compra_x_venda_top10", (rows) => setCxv(rows.map((r) => ({
        cod_prod: r.cod_prod,
        produto: String(r.produto ?? "Produto"),
        qtd_compra: toNum(r.qtd_compra),
        valor_compra: toNum(r.valor_compra),
        valor_venda_total: toNum(r.valor_venda_total),
        valor_venda_liquida: toNum(r.valor_venda_liquida)
      }))));
      apply("compras.grupos", (rows) => setGrupos(rows.map((r) => ({
        id: r.cod_grupo,
        label: String(r.grupo ?? "Sem grupo"),
        total: toNum(r.total_compra)
      }))));
      apply("compras.forma_pagamento", (rows) => setFormas(rows.map((r) => ({
        id: r.id_documento,
        label: String(r.forma ?? "Forma"),
        total: toNum(r.total_compra)
      }))));
      apply("compras.fornecedor", (rows) => setFornRank(rows.map((r) => ({
        id: r.id,
        fornecedor: String(r.fornecedor ?? "Fornecedor"),
        total_compra: toNum(r.total_compra)
      }))));
      if (lojas.length === 0) {
        const r = batch.results["compras.lojas"];
        if (r?.code === "OK") setLojas(r.rows);
      }
      if (fornecedores.length === 0) {
        const r = batch.results["compras.fornecedores"];
        if (r?.code === "OK") setFornecedores(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,
      tipoData,
      loja,
      fornecedor
    });
    if (lastLoadKeyRef.current === loadKey) return;
    const t = setTimeout(() => {
      lastLoadKeyRef.current = loadKey;
      carregar();
    }, 300);
    return () => clearTimeout(t);
  }, [clienteId, dataIni, dataFim, tipoData, loja, fornecedor]);
  const cxvLimit = isMobile ? 8 : 10;
  const truncLen = isMobile ? 16 : 28;
  const cxvData = reactExports.useMemo(() => cxv.slice(0, cxvLimit).map((r) => ({
    ...r,
    produtoCurto: r.produto.length > truncLen ? r.produto.slice(0, truncLen) + "…" : r.produto
  })), [cxv, cxvLimit, truncLen]);
  const totalGrupos = reactExports.useMemo(() => grupos.reduce((a, r) => a + r.total, 0), [grupos]);
  const totalFormas = reactExports.useMemo(() => formas.reduce((a, r) => a + r.total, 0), [formas]);
  const exportCxv = (fmt) => {
    const columns = [{
      header: "Cód.",
      key: "cod_prod",
      format: "text"
    }, {
      header: "Produto",
      key: "produto",
      format: "text"
    }, {
      header: "Valor Compra (R$)",
      key: "valor_compra",
      format: "brl"
    }, {
      header: "Valor Venda Total (R$)",
      key: "valor_venda_total",
      format: "brl"
    }, {
      header: "Valor Venda Líquida (R$)",
      key: "valor_venda_liquida",
      format: "brl"
    }];
    const rows = cxv.map((r) => ({
      cod_prod: String(r.cod_prod),
      produto: r.produto,
      valor_compra: r.valor_compra,
      valor_venda_total: r.valor_venda_total,
      valor_venda_liquida: r.valor_venda_liquida
    }));
    const totals = {
      valor_compra: rows.reduce((a, r) => a + r.valor_compra, 0),
      valor_venda_total: rows.reduce((a, r) => a + r.valor_venda_total, 0),
      valor_venda_liquida: rows.reduce((a, r) => a + r.valor_venda_liquida, 0)
    };
    if (fmt === "pdf") exportChartToPDF({
      title: "Top 10 Compra x Venda por Produto",
      subtitle: reportSubtitle,
      columns,
      rows,
      totals,
      filename: "compras-compra-x-venda.pdf"
    });
    else exportChartToExcel({
      sheetName: "Compra x Venda",
      columns,
      rows,
      filename: "compras-compra-x-venda.xlsx"
    });
  };
  const exportPie = (title, file, rowsIn, fmt, labelHeader) => {
    const total = rowsIn.reduce((a, r) => a + r.total, 0);
    const columns = [{
      header: labelHeader,
      key: "label",
      format: "text"
    }, {
      header: "Total (R$)",
      key: "total",
      format: "brl"
    }, {
      header: "%",
      key: "perc",
      format: "percent"
    }];
    const rows = rowsIn.map((r) => ({
      label: r.label,
      total: r.total,
      perc: total > 0 ? r.total / total * 100 : 0
    }));
    const totals = {
      total,
      perc: 100
    };
    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 exportFornRank = (fmt) => {
    const columns = [{
      header: "#",
      key: "pos",
      format: "int"
    }, {
      header: "Fornecedor",
      key: "fornecedor",
      format: "text"
    }, {
      header: "Total Compra (R$)",
      key: "total_compra",
      format: "brl"
    }];
    const rows = fornRank.map((r, i) => ({
      pos: i + 1,
      fornecedor: r.fornecedor,
      total_compra: r.total_compra
    }));
    const totals = {
      total_compra: rows.reduce((a, r) => a + r.total_compra, 0)
    };
    if (fmt === "pdf") exportChartToPDF({
      title: "Compras por Fornecedor",
      subtitle: reportSubtitle,
      columns,
      rows,
      totals,
      filename: "compras-por-fornecedor.pdf"
    });
    else exportChartToExcel({
      sheetName: "Compras por fornecedor",
      columns,
      rows,
      filename: "compras-por-fornecedor.xlsx"
    });
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(AppLayout, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative space-y-6", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingOverlay, { show: loading, title: "Carregando Compras...", 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: "Compras" }),
          /* @__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: "Tipo de data" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Select, { value: tipoData, onValueChange: (v) => {
              const next = v;
              setTipoData(next);
              toast.info(`Filtro alterado para data de ${next === "entrada" ? "entrada" : "emissão"}. Apenas um critério é aplicado por consulta.`);
            }, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { className: "h-9 w-[160px]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "emissao", children: "Data de emissão" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "entrada", children: "Data de entrada" })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Label, { className: "text-xs", children: [
              "Data ",
              tipoDataLabel,
              " início"
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "date", value: dataIni, onChange: (e) => setDataIni(e.target.value), className: "h-9 w-[170px]" })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Label, { className: "text-xs", children: [
              "Data ",
              tipoDataLabel,
              " fim"
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "date", value: dataFim, onChange: (e) => setDataFim(e.target.value), className: "h-9 w-[170px]" })
          ] }),
          /* @__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-[180px]", 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.jsxs("div", { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Label, { className: "text-xs", children: "Fornecedor" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(Select, { value: fornecedor, onValueChange: setFornecedor, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SelectTrigger, { className: "h-9 w-[220px]", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SelectValue, { placeholder: "Todos os fornecedores" }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: "__all__", children: "Todos os fornecedores" }),
                fornecedores.map((f) => /* @__PURE__ */ jsxRuntimeExports.jsx(SelectItem, { value: String(f.id), children: f.nome }, String(f.id)))
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", className: "h-9", onClick: () => {
            lastLoadKeyRef.current = "";
            carregar();
          }, disabled: loading, children: loading ? "Carregando…" : "Aplicar" })
        ] })
      ] }),
      erro && /* @__PURE__ */ jsxRuntimeExports.jsx(ClienteDbStatus, { code: erro.code, message: erro.message }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ShoppingBag, { className: "h-4 w-4" }), label: "Total de Compras", value: cards ? formatBRL(cards.total_compras) : null, accent: "primary", loading: loading && !cards }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Package, { className: "h-4 w-4" }), label: "Qtd. de Compras", value: cards ? formatNumber(cards.qtd_compras) : null, accent: "info", loading: loading && !cards }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(KCard, { icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Boxes, { className: "h-4 w-4" }), label: "Qtd. de Produtos", value: cards ? formatNumber(cards.qtd_produtos) : null, accent: "warning", loading: loading && !cards })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Top 10 Compra x Venda por Produto", subtitle: "Comparativo de compra e venda no período", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ChartColumn, { className: "h-4 w-4 text-primary" }), onExportPDF: () => exportCxv("pdf"), onExportExcel: () => exportCxv("xlsx"), contentClassName: `${isMobile ? "h-[460px]" : "h-[420px]"} pt-2`, children: loading && cxvData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-full w-full" }) : cxvData.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(BarChart, { data: cxvData, layout: "vertical", margin: isMobile ? {
        left: 4,
        right: 12,
        top: 8,
        bottom: 0
      } : {
        left: 10,
        right: 24,
        top: 8,
        bottom: 0
      }, barGap: isMobile ? 2 : 4, barCategoryGap: isMobile ? "20%" : "25%", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(CartesianGrid, { strokeDasharray: "3 3", stroke: "var(--border)", horizontal: false }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(XAxis, { type: "number", fontSize: isMobile ? 10 : 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)", tickFormatter: (v) => formatBRLCompact(v) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(YAxis, { type: "category", dataKey: "produtoCurto", width: isMobile ? 100 : 180, fontSize: isMobile ? 10 : 11, tickLine: false, axisLine: false, stroke: "var(--muted-foreground)", interval: 0 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { cursor: {
          fill: "var(--muted)",
          opacity: 0.4
        }, wrapperStyle: {
          outline: "none",
          zIndex: 50
        }, content: /* @__PURE__ */ jsxRuntimeExports.jsx(CxVTooltip, {}) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Legend, { wrapperStyle: {
          fontSize: isMobile ? 11 : 12
        }, formatter: (v) => v === "valor_compra" ? "Valor Compra" : v === "valor_venda_total" ? "Valor Venda Total" : "Valor Venda Líquida" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Bar, { dataKey: "valor_compra", fill: "var(--primary)", radius: [0, 6, 6, 0], maxBarSize: isMobile ? 10 : 14 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Bar, { dataKey: "valor_venda_total", fill: "var(--success)", radius: [0, 6, 6, 0], maxBarSize: isMobile ? 10 : 14 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Bar, { dataKey: "valor_venda_liquida", fill: "var(--info)", radius: [0, 6, 6, 0], maxBarSize: isMobile ? 10 : 14 })
      ] }) }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-4", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Compras por Grupo", subtitle: totalGrupos > 0 ? `Total: ${formatBRL(totalGrupos)}` : "Distribuição por grupo", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(ChartPie, { className: "h-4 w-4 text-info" }), onExportPDF: () => exportPie("Compras por Grupo", "compras-por-grupo", grupos, "pdf", "Grupo"), onExportExcel: () => exportPie("Compras por Grupo", "compras-por-grupo", grupos, "xlsx", "Grupo"), contentClassName: "h-[360px] pt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(DonutChart, { data: grupos, loading, onSliceClick: (row) => {
          if (row.id == null) return;
          setGrupoSel({
            cod: row.id,
            nome: row.label
          });
        } }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Compras por Forma de Pagamento", subtitle: totalFormas > 0 ? `Total: ${formatBRL(totalFormas)}` : "Distribuição por forma", icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Wallet, { className: "h-4 w-4 text-warning" }), onExportPDF: () => exportPie("Compras por Forma de Pagamento", "compras-por-forma-pagamento", formas, "pdf", "Forma"), onExportExcel: () => exportPie("Compras por Forma de Pagamento", "compras-por-forma-pagamento", formas, "xlsx", "Forma"), contentClassName: "h-[360px] pt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(DonutChart, { data: formas, loading, onSliceClick: (row) => {
          if (row.id == null) return;
          setFormaSel({
            cod: row.id,
            nome: row.label
          });
        } }) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ChartCard, { title: "Compras por Fornecedor", subtitle: `${fornRank.length} fornecedores`, icon: /* @__PURE__ */ jsxRuntimeExports.jsx(Truck, { className: "h-4 w-4 text-primary" }), onExportPDF: () => exportFornRank("pdf"), onExportExcel: () => exportFornRank("xlsx"), contentClassName: "pt-2", children: /* @__PURE__ */ jsxRuntimeExports.jsx(FornecedorRank, { rows: fornRank, loading }) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ComprasGrupoDetalheDialog, { open: !!grupoSel, onOpenChange: (o) => !o && setGrupoSel(null), grupo: grupoSel?.nome ?? "", codGrupo: grupoSel?.cod ?? null, dataIni, dataFimExcl: dataFim, dataFim, loja: params.loja, fornecedor: params.fornecedor, tipoData, totalGeralGrupos: totalGrupos }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(ComprasFormaPagamentoDetalheDialog, { open: !!formaSel, onOpenChange: (o) => !o && setFormaSel(null), forma: formaSel?.nome ?? "", codDoc: formaSel?.cod ?? null, dataIni, dataFimExcl: dataFim, dataFim, loja: params.loja, fornecedor: params.fornecedor, tipoData, totalGeralFormas: totalFormas })
  ] });
}
function CxVTooltip({
  active,
  payload
}) {
  if (!active || !payload?.length) return null;
  const p = payload[0]?.payload ?? {};
  const compra = Number(payload.find((x) => x.dataKey === "valor_compra")?.value ?? 0);
  const vendaTotal = Number(payload.find((x) => x.dataKey === "valor_venda_total")?.value ?? 0);
  const vendaLiq = Number(payload.find((x) => x.dataKey === "valor_venda_liquida")?.value ?? 0);
  const row = (color, label, value) => /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center justify-between gap-3", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "flex items-center gap-1.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "inline-block h-2 w-2 rounded-sm", style: {
        background: color
      } }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-muted-foreground", children: label })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "tabular-nums font-medium", children: formatBRL(value) })
  ] });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "rounded-lg border border-border/60 bg-popover/95 backdrop-blur shadow-lg px-3 py-2 text-xs max-w-[260px]", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "font-semibold text-foreground line-clamp-2 leading-snug", children: p.produto ?? "Produto" }),
    p.cod_prod != null && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "text-[10px] text-muted-foreground mt-0.5", children: [
      "Cód: ",
      String(p.cod_prod)
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mt-2 space-y-1", children: [
      row("var(--primary)", "Valor Compra", compra),
      row("var(--success)", "Valor Venda Total", vendaTotal),
      row("var(--info)", "Valor Venda Líquida", vendaLiq)
    ] })
  ] });
}
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 DonutChart({
  data,
  loading,
  onSliceClick
}) {
  const total = data.reduce((a, r) => a + r.total, 0);
  if (loading && data.length === 0) return /* @__PURE__ */ jsxRuntimeExports.jsx(Skeleton, { className: "h-full w-full" });
  if (data.length === 0) return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {});
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ResponsiveContainer, { width: "100%", height: "100%", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(PieChart, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Pie, { data, dataKey: "total", nameKey: "label", innerRadius: "55%", outerRadius: "85%", paddingAngle: 2, stroke: "var(--background)", strokeWidth: 2, onClick: (d) => onSliceClick?.(d?.payload), style: {
      cursor: onSliceClick ? "pointer" : "default"
    }, children: data.map((_, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(Cell, { fill: PIE_PALETTE[i % PIE_PALETTE.length] }, i)) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { contentStyle: tooltipStyle, labelStyle: tooltipLabelStyle, formatter: (v, _name, item) => {
      const n = Number(v);
      const pct = total > 0 ? n / total * 100 : 0;
      return [`${formatBRL(n)} (${pct.toLocaleString("pt-BR", {
        maximumFractionDigits: 1
      })}%)`, item?.payload?.label];
    } }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Legend, { wrapperStyle: {
      fontSize: 11
    }, formatter: (_v, entry) => entry?.payload?.label ?? "" })
  ] }) });
}
function FornecedorRank({
  rows,
  loading
}) {
  if (loading && rows.length === 0) {
    return /* @__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)) });
  }
  if (rows.length === 0) return /* @__PURE__ */ jsxRuntimeExports.jsx(EmptyState, {});
  const max = Math.max(1, ...rows.map((r) => r.total_compra));
  return /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: "space-y-3", children: rows.map((r, i) => {
    const pct = r.total_compra / 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: palette
          }, children: i + 1 }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: r.fornecedor })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "font-semibold tabular-nums shrink-0", children: formatBRL(r.total_compra) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-1.5 rounded-full bg-muted overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-full rounded-full transition-all", style: {
        width: `${pct}%`,
        background: palette
      } }) })
    ] }, String(r.id) + i);
  }) });
}
export {
  Page as component
};
