import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Clock, X } from "lucide-react";
import { cn } from "../../lib/utils.js";
import { EMPTY_DISPLAY, fieldDisplayTextClass, bareInputStyles, fieldWrapperStyles } from "../Field/field-wrapper.js";
import { ICON_SIZE, ItemSuffix, ItemInlineAction } from "../../patterns/element-anatomy/item-anatomy.js";
import { Popover, PopoverTrigger, PopoverContent } from "../Popover/popover.js";
import { useFieldContext, useResolvedFieldSize, useResolvedFieldInvalid, useResolvedFieldDisabled, useResolvedFieldMode, useResolvedFieldVariant } from "../Field/field-context.js";
import { Button } from "../Button/button.js";
import { isoToTimeParts, TimeColumns, timePartsToString } from "./time-columns.js";
function formatTime(iso, options = {}) {
  const parts = isoToTimeParts(iso);
  if (!parts) return iso;
  const {
    formatOptions = { hour: "2-digit", minute: "2-digit", hour12: false },
    locale = "en-US"
  } = options;
  const d = /* @__PURE__ */ new Date();
  d.setHours(parts.hours, parts.minutes, parts.seconds, 0);
  return new Intl.DateTimeFormat(locale, formatOptions).format(d);
}
const TimePicker = React.forwardRef(
  ({
    mode,
    variant: variantProp,
    error: errorProp = false,
    size: sizeProp,
    value,
    onChange,
    placeholder,
    className,
    disabled: disabledProp,
    clearable = false,
    showSeconds = false,
    minuteStep = 1,
    secondStep = 1,
    disabledTime,
    endIcon,
    showDisplayEndIcon = false,
    formatOptions,
    locale,
    defaultOpen = false,
    onOpenChange,
    id: idProp,
    "aria-describedby": ariaDescribedByProp,
    "aria-errormessage": ariaErrorMessageProp,
    ...props
  }, ref) => {
    const fieldCtx = useFieldContext();
    const size = useResolvedFieldSize(sizeProp);
    const error = useResolvedFieldInvalid(errorProp);
    const disabled = useResolvedFieldDisabled(disabledProp);
    const resolvedMode = useResolvedFieldMode({ mode, disabled });
    const variant = useResolvedFieldVariant(variantProp);
    const isEditable = resolvedMode === "edit";
    const iconSize = ICON_SIZE[size];
    const EndIconCmp = endIcon === null ? null : endIcon ?? Clock;
    const defaultPlaceholder = showSeconds ? "HH:MM:SS" : "HH:MM";
    const resolvedPlaceholder = placeholder ?? defaultPlaceholder;
    const showClear = clearable && !!value && isEditable;
    const [open, setOpenState] = React.useState(defaultOpen);
    const setOpen = React.useCallback((next) => {
      setOpenState(next);
      onOpenChange == null ? void 0 : onOpenChange(next);
    }, [onOpenChange]);
    const currentParts = React.useMemo(() => isoToTimeParts(value), [value]);
    const [draft, setDraft] = React.useState(
      () => currentParts ?? { hours: 0, minutes: 0, seconds: 0 }
    );
    React.useEffect(() => {
      if (open) {
        setDraft(currentParts ?? { hours: 0, minutes: 0, seconds: 0 });
      }
    }, [open, currentParts]);
    const disabledForColumns = React.useMemo(() => {
      if (!disabledTime) return void 0;
      const res = disabledTime(draft);
      return {
        hours: res.disabledHours,
        minutes: res.disabledMinutes,
        seconds: res.disabledSeconds
      };
    }, [disabledTime, draft]);
    const commitDraft = (next) => {
      setDraft(next);
      onChange == null ? void 0 : onChange(timePartsToString(next, showSeconds));
    };
    const handleNow = () => {
      const now = /* @__PURE__ */ new Date();
      const m = Math.round(now.getMinutes() / minuteStep) * minuteStep;
      const s = showSeconds ? Math.round(now.getSeconds() / secondStep) * secondStep : 0;
      const next = {
        hours: now.getHours(),
        minutes: Math.min(m, 59),
        seconds: Math.min(s, 59)
      };
      commitDraft(next);
      setOpen(false);
    };
    if (resolvedMode === "display") {
      if (!showDisplayEndIcon) {
        if (!value) return /* @__PURE__ */ jsx("span", { className: cn(fieldDisplayTextClass(size), "text-fg-muted", className), children: EMPTY_DISPLAY });
        return /* @__PURE__ */ jsx("span", { className: cn(fieldDisplayTextClass(size), "truncate", className), children: formatTime(value, { formatOptions, locale }) });
      }
      return /* @__PURE__ */ jsxs(
        "div",
        {
          className: cn(fieldWrapperStyles({ mode: "display", variant, size }), className),
          "data-field-mode": "display",
          children: [
            /* @__PURE__ */ jsx("span", { className: cn(bareInputStyles, "flex-1 min-w-0 truncate", !value && "text-fg-muted"), children: value ? formatTime(value, { formatOptions, locale }) : EMPTY_DISPLAY }),
            EndIconCmp && /* @__PURE__ */ jsx(ItemSuffix, { className: "pointer-events-none", children: /* @__PURE__ */ jsx(EndIconCmp, { size: iconSize, className: "text-fg-muted", "aria-hidden": true }) })
          ]
        }
      );
    }
    if (!isEditable) {
      return /* @__PURE__ */ jsxs(
        "div",
        {
          className: cn(fieldWrapperStyles({ mode: resolvedMode, variant, size }), className),
          "data-field-mode": resolvedMode,
          ...props,
          children: [
            /* @__PURE__ */ jsx(
              "span",
              {
                className: cn(
                  "flex-1 min-w-0",
                  resolvedMode === "disabled" && "text-fg-disabled"
                ),
                children: value ? formatTime(value, { formatOptions, locale }) : /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: EMPTY_DISPLAY })
              }
            ),
            EndIconCmp && /* @__PURE__ */ jsx(ItemSuffix, { className: "pointer-events-none", children: /* @__PURE__ */ jsx(
              EndIconCmp,
              {
                size: iconSize,
                className: resolvedMode === "disabled" ? "text-fg-disabled" : "text-fg-muted",
                "aria-hidden": true
              }
            ) })
          ]
        }
      );
    }
    const displayText = value ? formatTime(value, { formatOptions, locale }) : /* @__PURE__ */ jsx("span", { className: "text-fg-muted", children: resolvedPlaceholder });
    return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
      /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        "div",
        {
          ref,
          id: idProp ?? (fieldCtx == null ? void 0 : fieldCtx.id),
          role: "combobox",
          tabIndex: disabled ? -1 : 0,
          "aria-disabled": disabled || void 0,
          "aria-labelledby": fieldCtx == null ? void 0 : fieldCtx.labelId,
          "aria-invalid": error || void 0,
          "aria-required": (fieldCtx == null ? void 0 : fieldCtx.required) || void 0,
          "aria-describedby": ariaDescribedByProp ?? (fieldCtx == null ? void 0 : fieldCtx.descriptionId),
          "aria-errormessage": ariaErrorMessageProp ?? (error ? fieldCtx == null ? void 0 : fieldCtx.errorId : void 0),
          "aria-haspopup": "dialog",
          "aria-expanded": open,
          onKeyDown: (e) => {
            if (disabled) return;
            if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
              e.preventDefault();
              setOpen(true);
            }
            if (e.key === "Escape") setOpen(false);
          },
          "data-field-mode": "edit",
          "data-error": error ? "" : void 0,
          className: cn(
            fieldWrapperStyles({ mode: "edit", variant, size }),
            "text-left cursor-pointer",
            "focus-visible:outline-none",
            error && [
              "border-error hover:border-error-hover",
              "focus-within:border-error focus-within:hover:border-error"
            ],
            className
          ),
          ...props,
          children: [
            /* @__PURE__ */ jsx("span", { className: cn(bareInputStyles, "truncate", !value && "text-fg-muted"), children: displayText }),
            showClear && /* @__PURE__ */ jsx(
              ItemInlineAction,
              {
                size: size ?? "md",
                action: {
                  icon: X,
                  label: "清除時間",
                  // i18n-allow: DS default inline-action label
                  onClick: (e) => {
                    e == null ? void 0 : e.stopPropagation();
                    onChange == null ? void 0 : onChange("");
                  }
                }
              }
            ),
            EndIconCmp && /* @__PURE__ */ jsx(ItemSuffix, { className: "pointer-events-none", children: /* @__PURE__ */ jsx(EndIconCmp, { size: iconSize, className: "text-fg-muted", "aria-hidden": true }) })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-[216px]", children: [
        /* @__PURE__ */ jsx(
          TimeColumns,
          {
            value: draft,
            onChange: commitDraft,
            showSeconds,
            minuteStep,
            secondStep,
            disabled: disabledForColumns,
            className: "flex-1 min-h-0"
          }
        ),
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "flex items-center justify-between gap-2",
              "border-t border-divider",
              "px-[var(--layout-space-tight)] py-[var(--layout-space-tight)]"
            ),
            children: [
              /* @__PURE__ */ jsx(Button, { variant: "text", size: "sm", onClick: handleNow, children: "此刻" }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "primary",
                  size: "sm",
                  onClick: () => setOpen(false),
                  children: "確定"
                }
              )
            ]
          }
        )
      ] }) })
    ] });
  }
);
TimePicker.displayName = "TimePicker";
const timePickerMeta = {
  component: "TimePicker",
  family: 4,
  variants: {},
  sizes: {},
  states: ["default", "hover", "active", "focus-visible", "disabled"],
  tokens: {
    bg: ["bg-neutral-hover", "bg-primary", "bg-transparent"],
    fg: ["text-fg-disabled", "text-fg-muted", "text-foreground"],
    ring: []
  }
};
export {
  TimePicker,
  timePickerMeta
};
//# sourceMappingURL=time-picker.js.map
