"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  DateRangeSelect,
  InlineDateRangeSelect
} 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("staff");
function minutesToHours(minutes) {
  const hours = minutes / 60;
  return hours % 1 === 0 ? String(hours) : hours.toFixed(1);
}
async function fetchData(settings) {
  const body = {
    entityType: "staff:staff_time_entries",
    metric: { field: "durationMinutes", aggregate: "sum" },
    groupBy: { field: "timeProjectId", limit: 20, resolveLabels: true },
    dateRange: { field: "date", preset: settings.dateRange }
  };
  const res = await apiCall("/api/dashboards/widgets/data", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  if (!res.ok) {
    const err = res.result?.error;
    throw new Error(typeof err === "string" ? err : "Failed to fetch data");
  }
  return res.result;
}
const HoursByProjectWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const hydrated = React.useMemo(() => hydrateSettings(settings), [settings]);
  const [data, setData] = React.useState([]);
  const [totalMinutes, setTotalMinutes] = React.useState(0);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const refresh = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const result = await fetchData(hydrated);
      const sorted = [...result.data].sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
      setData(sorted);
      setTotalMinutes(sorted.reduce((sum, item) => sum + (item.value ?? 0), 0));
    } catch (err) {
      logger.error("staff.timesheets.hoursByProject", { err });
      setError(t("staff.timesheets.widgets.hoursByProject.error", "Failed to load data"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [hydrated, onRefreshStateChange, t]);
  React.useEffect(() => {
    void refresh();
  }, [refresh, refreshToken]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsx("div", { className: "space-y-4 text-sm", children: /* @__PURE__ */ jsx(
      DateRangeSelect,
      {
        id: "hours-by-project-date-range",
        label: t("staff.timesheets.widgets.hoursByProject.settings.dateRange", "Date Range"),
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
      }
    ) });
  }
  if (loading) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.widgets.hoursByProject.loading", "Loading...") }) });
  }
  if (error) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: error }) });
  }
  const maxValue = data.length > 0 ? Math.max(...data.map((d) => d.value ?? 0)) : 0;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end", children: /* @__PURE__ */ jsx(
      InlineDateRangeSelect,
      {
        value: hydrated.dateRange,
        onChange: (dateRange) => onSettingsChange({ ...hydrated, dateRange })
      }
    ) }),
    data.length === 0 ? /* @__PURE__ */ jsx("p", { className: "py-4 text-center text-sm text-muted-foreground", children: t("staff.timesheets.widgets.hoursByProject.empty", "No hours tracked in this period.") }) : /* @__PURE__ */ jsxs("div", { className: "space-y-2.5", children: [
      data.map((item) => {
        const barWidth = maxValue > 0 ? (item.value ?? 0) / maxValue * 100 : 0;
        return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-sm", children: [
            /* @__PURE__ */ jsx("span", { className: "truncate font-medium", children: item.groupLabel || item.groupKey }),
            /* @__PURE__ */ jsxs("span", { className: "shrink-0 tabular-nums text-muted-foreground", children: [
              minutesToHours(item.value ?? 0),
              " h"
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "h-2 w-full rounded-full bg-muted", children: /* @__PURE__ */ jsx(
            "div",
            {
              className: "h-2 rounded-full bg-primary transition-all",
              style: { width: `${barWidth}%` }
            }
          ) })
        ] }, item.groupKey);
      }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between border-t pt-2 text-sm font-semibold", children: [
        /* @__PURE__ */ jsx("span", { children: t("staff.timesheets.widgets.hoursByProject.total", "Total") }),
        /* @__PURE__ */ jsxs("span", { className: "tabular-nums", children: [
          minutesToHours(totalMinutes),
          " h"
        ] })
      ] })
    ] })
  ] });
};
var widget_client_default = HoursByProjectWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
