"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useWidgetData } from "@open-mercato/ui/backend/dashboard/widgetData";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { BarChart } from "@open-mercato/ui/backend/charts";
import {
  DateRangeSelect,
  InlineDateRangeSelect
} from "@open-mercato/ui/backend/date-range";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { formatCurrencyCompact } from "../../../lib/formatters.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "pipeline-summary" });
async function fetchPipelineData(settings, fetchWidgetData) {
  const body = {
    entityType: "customers:deals",
    metric: {
      field: "valueAmount",
      aggregate: "sum"
    },
    groupBy: {
      field: "pipelineStage",
      resolveLabels: true
    },
    dateRange: {
      field: "createdAt",
      preset: settings.dateRange
    }
  };
  return fetchWidgetData(body);
}
function formatStageLabel(stage, t) {
  if (stage == null || stage === "") return t("dashboards.analytics.labels.unknown", "Unknown");
  const stageStr = String(stage);
  if (stageStr === "0" || stageStr === "null" || stageStr === "undefined") {
    return t("dashboards.analytics.labels.unknown", "Unknown");
  }
  return stageStr.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
}
const PipelineSummaryWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateSettings(settings), [settings]);
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const fetchWidgetData = useWidgetData();
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const result = await fetchPipelineData(hydrated, fetchWidgetData);
      const chartData = result.data.filter((item) => item.groupKey != null && item.groupKey !== "" && String(item.groupKey) !== "0").map((item) => ({
        stage: formatStageLabel(item.groupLabel ?? item.groupKey, t),
        Value: item.value ?? 0
      }));
      setData(chartData);
    } catch (err) {
      logger.error("Failed to load pipeline data", { err });
      setError(t("dashboards.analytics.widgets.pipelineSummary.error", "Failed to load data"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, fetchWidgetData, onRefreshStateChange, t]);
  React.useEffect(() => {
    refresh().catch(() => {
    });
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsx("div", { className: "space-y-4 text-sm", children: /* @__PURE__ */ jsx(
      DateRangeSelect,
      {
        id: "pipeline-summary-date-range",
        label: t("dashboards.analytics.settings.dateRange", "Date Range"),
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
      }
    ) });
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full", children: [
    /* @__PURE__ */ jsx("div", { className: "flex justify-end mb-2", children: /* @__PURE__ */ jsx(
      InlineDateRangeSelect,
      {
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
      }
    ) }),
    /* @__PURE__ */ jsx("div", { className: "flex-1 min-h-0", children: /* @__PURE__ */ jsx(
      BarChart,
      {
        data,
        index: "stage",
        categories: ["Value"],
        categoryLabels: { Value: t("dashboards.analytics.labels.value", "Value") },
        loading,
        error,
        valueFormatter: formatCurrencyCompact,
        colors: ["violet"],
        showLegend: false,
        emptyMessage: t("dashboards.analytics.widgets.pipelineSummary.empty", "No deal data for this period")
      }
    ) })
  ] });
};
var widget_client_default = PipelineSummaryWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
