"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { ProjectColorDot } from "./ProjectColorDot.js";
function getLocalDateStr(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
function formatDayLabel(dateStr, translate) {
  const today = /* @__PURE__ */ new Date();
  const todayStr = getLocalDateStr(today);
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const yesterdayStr = getLocalDateStr(yesterday);
  if (dateStr === todayStr) return translate("staff.timesheets.my.list.today", "Today");
  if (dateStr === yesterdayStr) return translate("staff.timesheets.my.list.yesterday", "Yesterday");
  const date = /* @__PURE__ */ new Date(dateStr + "T00:00:00");
  const dayName = date.toLocaleDateString(void 0, { weekday: "short" });
  const day = date.getDate();
  const month = date.toLocaleDateString(void 0, { month: "short" });
  return `${dayName}, ${day} ${month}`;
}
function formatDuration(minutes) {
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  if (remainingMinutes === 0) return `${hours}h`;
  return `${hours}h ${remainingMinutes}m`;
}
function formatTimeRange(startedAt, endedAt) {
  const start = new Date(startedAt);
  const end = new Date(endedAt);
  const format = (date) => date.toLocaleTimeString(void 0, {
    hour: "numeric",
    minute: "2-digit",
    hour12: true
  });
  return `${format(start)} - ${format(end)}`;
}
function InlineDescription({
  entryId,
  initialValue,
  placeholder,
  onSaved
}) {
  const t = useT();
  const [editing, setEditing] = React.useState(false);
  const [value, setValue] = React.useState(initialValue ?? "");
  const [saving, setSaving] = React.useState(false);
  const inputRef = React.useRef(null);
  React.useEffect(() => {
    if (editing && inputRef.current) inputRef.current.focus();
  }, [editing]);
  const save = React.useCallback(async () => {
    const trimmed = value.trim();
    if (trimmed === (initialValue ?? "")) {
      setEditing(false);
      return;
    }
    setSaving(true);
    try {
      await apiCallOrThrow(`/api/staff/timesheets/time-entries`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: entryId, notes: trimmed || null })
      });
      setSaving(false);
      setEditing(false);
      onSaved?.();
    } catch (err) {
      setSaving(false);
      if (!surfaceRecordConflict(err, t)) {
        flash(
          t("staff.timesheets.my.list.saveError", "Failed to save description. Please try again."),
          "error"
        );
      }
    }
  }, [entryId, value, initialValue, onSaved, t]);
  if (!editing) {
    return /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick: () => setEditing(true),
        className: `text-sm text-left cursor-pointer hover:underline ${initialValue ? "" : "text-muted-foreground italic"}`,
        children: initialValue || placeholder
      }
    );
  }
  return /* @__PURE__ */ jsx(
    "input",
    {
      ref: inputRef,
      type: "text",
      value,
      disabled: saving,
      onChange: (e) => setValue(e.target.value),
      onBlur: () => {
        void save();
      },
      onKeyDown: (e) => {
        if (e.key === "Enter") {
          void save();
        }
        if (e.key === "Escape") {
          setValue(initialValue ?? "");
          setEditing(false);
        }
      },
      placeholder,
      className: "text-sm w-full bg-transparent border-b border-primary/40 outline-none py-0.5 placeholder:text-muted-foreground/50"
    }
  );
}
function ListView({ entries, onEntryUpdated }) {
  const t = useT();
  if (entries.length === 0) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-12 text-sm text-muted-foreground", children: t("staff.timesheets.my.list.noEntries", "No entries for this period.") });
  }
  const grouped = /* @__PURE__ */ new Map();
  for (const entry of entries) {
    const existing = grouped.get(entry.date);
    if (existing) {
      existing.push(entry);
    } else {
      grouped.set(entry.date, [entry]);
    }
  }
  const sortedDays = [...grouped.keys()].sort((a, b) => b.localeCompare(a));
  return /* @__PURE__ */ jsx("div", { children: sortedDays.map((dateStr) => {
    const dayEntries = grouped.get(dateStr);
    const dailyTotal = dayEntries.reduce(
      (sum, entry) => sum + entry.durationMinutes,
      0
    );
    return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border mb-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex justify-between items-center p-4 border-b bg-muted/30 font-medium text-sm", children: [
        /* @__PURE__ */ jsx("span", { children: formatDayLabel(dateStr, t) }),
        /* @__PURE__ */ jsx("span", { className: "font-mono tabular-nums", children: formatDuration(dailyTotal) })
      ] }),
      dayEntries.map((entry) => /* @__PURE__ */ jsxs(
        "div",
        {
          className: "flex items-center justify-between p-3 border-b last:border-0 hover:bg-muted/20",
          children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 min-w-0 flex-1 mr-4", children: [
              /* @__PURE__ */ jsx(
                InlineDescription,
                {
                  entryId: entry.id,
                  initialValue: entry.notes,
                  placeholder: t("staff.timesheets.my.list.addDescription", "Add description"),
                  onSaved: onEntryUpdated
                }
              ),
              /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 text-xs font-medium text-muted-foreground", children: [
                /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: entry.projectColor, projectName: entry.projectName, size: "xs" }),
                entry.projectName
              ] })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-end gap-1 shrink-0", children: [
              entry.source === "timer" && entry.startedAt && entry.endedAt ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: formatTimeRange(entry.startedAt, entry.endedAt) }) : null,
              /* @__PURE__ */ jsx("span", { className: "text-sm font-mono tabular-nums", children: formatDuration(entry.durationMinutes) })
            ] })
          ]
        },
        entry.id
      ))
    ] }, dateStr);
  }) });
}
export {
  ListView
};
//# sourceMappingURL=ListView.js.map
