"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 { KpiCard } from "@open-mercato/ui/backend/charts";
import {
  DateRangeSelect,
  InlineDateRangeSelect,
  getComparisonLabelKey
} from "@open-mercato/ui/backend/date-range";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("dashboards").child({ component: "new-customers-kpi" });
async function fetchNewCustomersData(settings, fetchWidgetData) {
  const body = {
    entityType: "customers:entities",
    metric: {
      field: "id",
      aggregate: "count"
    },
    dateRange: {
      field: "createdAt",
      preset: settings.dateRange
    },
    comparison: settings.showComparison ? { type: "previous_period" } : void 0
  };
  return fetchWidgetData(body);
}
const NewCustomersKpiWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateSettings(settings), [settings]);
  const [value, setValue] = React.useState(null);
  const [trend, setTrend] = React.useState(void 0);
  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 data = await fetchNewCustomersData(hydrated, fetchWidgetData);
      setValue(data.value);
      if (data.comparison) {
        setTrend({
          value: data.comparison.change,
          direction: data.comparison.direction
        });
      } else {
        setTrend(void 0);
      }
    } catch (err) {
      logger.error("Failed to load new customers KPI data", { err });
      setError(t("dashboards.analytics.widgets.newCustomersKpi.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__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
      /* @__PURE__ */ jsx(
        DateRangeSelect,
        {
          id: "new-customers-kpi-date-range",
          label: t("dashboards.analytics.settings.dateRange", "Date Range"),
          value: hydrated.dateRange,
          onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
        }
      ),
      /* @__PURE__ */ jsx("div", { className: "space-y-1.5", children: /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            checked: hydrated.showComparison,
            onChange: (e) => onSettingsChange({ ...hydrated, showComparison: e.target.checked }),
            className: "h-4 w-4 rounded border focus-visible:ring-ring"
          }
        ),
        t("dashboards.analytics.settings.showComparison", "Show comparison")
      ] }) })
    ] });
  }
  const comparisonLabelInfo = getComparisonLabelKey(hydrated.dateRange);
  const comparisonLabel = hydrated.showComparison ? t(comparisonLabelInfo.key, comparisonLabelInfo.fallback) : void 0;
  return /* @__PURE__ */ jsx(
    KpiCard,
    {
      value,
      trend,
      comparisonLabel,
      loading,
      error,
      headerAction: /* @__PURE__ */ jsx(
        InlineDateRangeSelect,
        {
          value: hydrated.dateRange,
          onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
        }
      )
    }
  );
};
var widget_client_default = NewCustomersKpiWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
