"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronDown, ChevronUp, Loader2, CheckCircle, XCircle, X } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { Progress } from "../../primitives/progress.js";
import { cn } from "@open-mercato/shared/lib/utils";
import { useProgress } from "./useProgress.js";
import { apiCall } from "../utils/apiCall.js";
function ProgressTopBar({ className, t }) {
  const { activeJobs, recentlyCompleted, refresh } = useProgress();
  const [expanded, setExpanded] = React.useState(false);
  React.useEffect(() => {
    const saved = localStorage.getItem("om:progress:expanded");
    if (saved === "true") setExpanded(true);
  }, []);
  React.useEffect(() => {
    localStorage.setItem("om:progress:expanded", String(expanded));
  }, [expanded]);
  const hasActiveJobs = activeJobs.length > 0;
  const hasRecentJobs = recentlyCompleted.length > 0;
  if (!hasActiveJobs && !hasRecentJobs) return null;
  return /* @__PURE__ */ jsxs("div", { className: cn("border-b bg-background", className), children: [
    /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "ghost",
        onClick: () => setExpanded(!expanded),
        className: "h-auto w-full justify-between rounded-none bg-background px-4 py-2 hover:bg-muted",
        children: [
          /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 text-sm", children: hasActiveJobs ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin text-primary" }),
            /* @__PURE__ */ jsx("span", { children: t("progress.activeCount", "{count} operations running", { count: activeJobs.length }) }),
            activeJobs[0] && /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
              "\u2014 ",
              activeJobs[0].name,
              " ",
              activeJobs[0].totalCount && activeJobs[0].totalCount > 0 ? `(${activeJobs[0].progressPercent}%)` : `(${activeJobs[0].processedCount.toLocaleString()} ${t("progress.processed", "processed")})`
            ] })
          ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(CheckCircle, { className: "h-4 w-4 text-status-success-icon" }),
            /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("progress.recentlyCompleted", "{count} operations completed", { count: recentlyCompleted.length }) })
          ] }) }),
          expanded ? /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
        ]
      }
    ),
    expanded && /* @__PURE__ */ jsxs("div", { className: "space-y-2 bg-background px-4 pb-3", children: [
      activeJobs.map((job) => /* @__PURE__ */ jsx(ProgressJobCard, { job, t, onCancel: refresh }, job.id)),
      recentlyCompleted.map((job) => /* @__PURE__ */ jsx(ProgressJobCard, { job, t }, job.id))
    ] })
  ] });
}
function ProgressJobCard({ job, t, onCancel }) {
  const [cancelling, setCancelling] = React.useState(false);
  const handleCancel = async () => {
    if (!job.cancellable || cancelling) return;
    setCancelling(true);
    try {
      await apiCall(`/api/progress/jobs/${job.id}`, { method: "DELETE" });
      onCancel?.();
    } finally {
      setCancelling(false);
    }
  };
  const isActive = job.status === "pending" || job.status === "running";
  const isFailed = job.status === "failed";
  const isCompleted = job.status === "completed";
  return /* @__PURE__ */ jsxs("div", { className: cn(
    "rounded-md border bg-card p-3",
    isFailed && "border-destructive/50 bg-destructive/5",
    isCompleted && "border-status-success-border bg-status-success-bg"
  ), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          isActive && /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin text-primary flex-shrink-0" }),
          isCompleted && /* @__PURE__ */ jsx(CheckCircle, { className: "h-4 w-4 text-status-success-icon flex-shrink-0" }),
          isFailed && /* @__PURE__ */ jsx(XCircle, { className: "h-4 w-4 text-destructive flex-shrink-0" }),
          /* @__PURE__ */ jsx("span", { className: "font-medium truncate", children: job.name })
        ] }),
        job.description && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mt-1 truncate", children: job.description }),
        isFailed && job.errorMessage && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive mt-1", children: job.errorMessage })
      ] }),
      isActive && job.cancellable && /* @__PURE__ */ jsx(
        Button,
        {
          variant: "ghost",
          size: "icon",
          onClick: handleCancel,
          disabled: cancelling,
          className: "flex-shrink-0",
          "aria-label": t("progress.actions.cancel", "Cancel"),
          children: /* @__PURE__ */ jsx(X, { className: "h-4 w-4" })
        }
      )
    ] }),
    isActive && /* @__PURE__ */ jsxs("div", { className: "mt-2 space-y-1", children: [
      job.totalCount && job.totalCount > 0 ? /* @__PURE__ */ jsx(Progress, { value: job.progressPercent, className: "h-2" }) : /* @__PURE__ */ jsx(IndeterminateProgressBar, { className: "h-2" }),
      /* @__PURE__ */ jsxs("div", { className: "flex justify-between text-xs text-muted-foreground", children: [
        /* @__PURE__ */ jsx("span", { children: job.totalCount ? `${job.processedCount.toLocaleString()} / ${job.totalCount.toLocaleString()}` : `${job.processedCount.toLocaleString()} ${t("progress.processed", "processed")}` }),
        job.etaSeconds != null && job.etaSeconds > 0 && /* @__PURE__ */ jsx("span", { children: formatEta(job.etaSeconds, t) })
      ] })
    ] })
  ] });
}
function IndeterminateProgressBar({ className }) {
  return /* @__PURE__ */ jsxs("div", { className: cn("relative w-full overflow-hidden rounded-full bg-secondary", className), children: [
    /* @__PURE__ */ jsx("div", { className: "absolute inset-y-0 left-0 w-1/2 animate-pulse rounded-full bg-primary/80" }),
    /* @__PURE__ */ jsx("div", { className: "absolute inset-y-0 right-0 w-1/3 rounded-full bg-primary/10" })
  ] });
}
function formatEta(seconds, t) {
  if (seconds < 60) {
    return t("progress.eta.seconds", "{count}s remaining", { count: seconds });
  }
  if (seconds < 3600) {
    const minutes = Math.ceil(seconds / 60);
    return t("progress.eta.minutes", "{count}m remaining", { count: minutes });
  }
  const hours = Math.floor(seconds / 3600);
  const mins = Math.ceil(seconds % 3600 / 60);
  return t("progress.eta.hoursMinutes", "{hours}h {minutes}m remaining", { hours, minutes: mins });
}
export {
  ProgressTopBar
};
//# sourceMappingURL=ProgressTopBar.js.map
