"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "@open-mercato/ui/primitives/popover";
import { Button } from "@open-mercato/ui/primitives/button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
import { ChipButton } from "./ChipButton.js";
import { FilterPopoverShell } from "./FilterPopoverShell.js";
function ymd(date) {
  return date.toISOString().slice(0, 10);
}
function startOfMonth() {
  const d = /* @__PURE__ */ new Date();
  d.setUTCHours(0, 0, 0, 0);
  d.setUTCDate(1);
  return d;
}
function endOfMonth() {
  const d = startOfMonth();
  d.setUTCMonth(d.getUTCMonth() + 1);
  d.setUTCDate(0);
  return d;
}
function startOfQuarter() {
  const d = /* @__PURE__ */ new Date();
  d.setUTCHours(0, 0, 0, 0);
  d.setUTCDate(1);
  const m = d.getUTCMonth();
  d.setUTCMonth(m - m % 3);
  return d;
}
function endOfQuarter() {
  const d = startOfQuarter();
  d.setUTCMonth(d.getUTCMonth() + 3);
  d.setUTCDate(0);
  return d;
}
function buildPresetRange(key) {
  const now = /* @__PURE__ */ new Date();
  now.setUTCHours(0, 0, 0, 0);
  switch (key) {
    case "next-30": {
      const to = new Date(now);
      to.setUTCDate(to.getUTCDate() + 30);
      return { from: ymd(now), to: ymd(to) };
    }
    case "next-90": {
      const to = new Date(now);
      to.setUTCDate(to.getUTCDate() + 90);
      return { from: ymd(now), to: ymd(to) };
    }
    case "this-month":
      return { from: ymd(startOfMonth()), to: ymd(endOfMonth()) };
    case "this-quarter":
      return { from: ymd(startOfQuarter()), to: ymd(endOfQuarter()) };
    case "overdue": {
      const yesterday = new Date(now);
      yesterday.setUTCDate(yesterday.getUTCDate() - 1);
      return { from: null, to: ymd(yesterday) };
    }
    default:
      return { from: null, to: null };
  }
}
function CloseDateFilterPopover({ value, onApply }) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [draft, setDraft] = React.useState(value);
  React.useEffect(() => {
    if (open) setDraft(value);
  }, [open, value]);
  const isActive = !!(value.from || value.to);
  const chipLabel = translateWithFallback(t, "customers.deals.kanban.filter.close", "Close");
  const chipValue = React.useMemo(() => {
    if (!isActive) return translateWithFallback(t, "customers.deals.kanban.filter.any", "Any");
    if (value.from && value.to) {
      const f = new Date(value.from).toLocaleDateString(void 0, { month: "short", day: "2-digit" });
      const tt = new Date(value.to).toLocaleDateString(void 0, { month: "short", day: "2-digit" });
      return `${f} \u2013 ${tt}`;
    }
    if (value.from && !value.to)
      return translateWithFallback(t, "customers.deals.kanban.filter.from", "From {date}", {
        date: new Date(value.from).toLocaleDateString(void 0, { month: "short", day: "2-digit" })
      });
    if (!value.from && value.to)
      return translateWithFallback(t, "customers.deals.kanban.filter.until", "Until {date}", {
        date: new Date(value.to).toLocaleDateString(void 0, { month: "short", day: "2-digit" })
      });
    return "";
  }, [value.from, value.to, isActive, t]);
  const applyPreset = (key) => setDraft(buildPresetRange(key));
  const handleApply = () => {
    onApply({
      from: draft.from && draft.from.length ? draft.from : null,
      to: draft.to && draft.to.length ? draft.to : null
    });
    setOpen(false);
  };
  const handleClear = () => setDraft({ from: null, to: null });
  const handleKeyDown = (event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
      event.preventDefault();
      handleApply();
    }
  };
  const hasDraft = !!(draft.from || draft.to);
  const footerLeft = /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
    /* @__PURE__ */ jsx("span", { children: hasDraft ? translateWithFallback(t, "customers.deals.kanban.filter.dateRange.applied", "Range set") : translateWithFallback(t, "customers.deals.kanban.filter.any", "Any") }),
    hasDraft ? /* @__PURE__ */ jsx(
      Button,
      {
        variant: "link",
        size: "sm",
        type: "button",
        onClick: handleClear,
        className: "h-auto px-0 py-0 text-xs font-medium leading-normal",
        children: translateWithFallback(t, "customers.deals.kanban.filter.clear", "Clear")
      }
    ) : null
  ] });
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(ChipButton, { label: chipLabel, value: chipValue, active: isActive }) }),
    /* @__PURE__ */ jsx(
      PopoverContent,
      {
        className: "w-80 rounded-2xl border-border bg-transparent p-0 shadow-xl",
        align: "start",
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxs(
          FilterPopoverShell,
          {
            title: translateWithFallback(t, "customers.deals.kanban.filter.close.title", "Filter \xB7 Expected close"),
            onClose: () => setOpen(false),
            onCancel: () => setOpen(false),
            onApply: handleApply,
            footerLeft,
            children: [
              /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: [
                { key: "next-30", label: translateWithFallback(t, "customers.deals.kanban.filter.preset.next30", "Next 30 days") },
                { key: "next-90", label: translateWithFallback(t, "customers.deals.kanban.filter.preset.next90", "Next 90 days") },
                { key: "this-month", label: translateWithFallback(t, "customers.deals.kanban.filter.preset.thisMonth", "This month") },
                { key: "this-quarter", label: translateWithFallback(t, "customers.deals.kanban.filter.preset.thisQuarter", "This quarter") },
                { key: "overdue", label: translateWithFallback(t, "customers.deals.kanban.filter.preset.overdue", "Overdue") }
              ].map((preset) => /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "outline",
                  size: "sm",
                  type: "button",
                  onClick: () => applyPreset(preset.key),
                  className: "h-auto rounded-full border-border bg-card px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground",
                  children: preset.label
                },
                preset.key
              )) }),
              /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
                /* @__PURE__ */ jsxs("label", { className: "flex flex-col gap-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
                  translateWithFallback(t, "customers.deals.kanban.filter.fromLabel", "From"),
                  /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "date",
                      value: draft.from ?? "",
                      onChange: (event) => setDraft((previous) => ({ ...previous, from: event.target.value || null })),
                      className: "rounded-md border border-input bg-card px-2.5 py-1.5 text-sm font-normal leading-normal text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxs("label", { className: "flex flex-col gap-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: [
                  translateWithFallback(t, "customers.deals.kanban.filter.toLabel", "To"),
                  /* @__PURE__ */ jsx(
                    "input",
                    {
                      type: "date",
                      value: draft.to ?? "",
                      onChange: (event) => setDraft((previous) => ({ ...previous, to: event.target.value || null })),
                      className: "rounded-md border border-input bg-card px-2.5 py-1.5 text-sm font-normal leading-normal text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                    }
                  )
                ] })
              ] })
            ]
          }
        )
      }
    )
  ] });
}
var CloseDateFilterPopover_default = CloseDateFilterPopover;
export {
  CloseDateFilterPopover,
  CloseDateFilterPopover_default as default
};
//# sourceMappingURL=CloseDateFilterPopover.js.map
