import { jsxs as c, jsx as a, Fragment as Re } from "@emotion/react/jsx-runtime";
import { DateTimeClockOutlined as Ee } from "@m4l/icons";
import be from "clsx";
import { forwardRef as Oe, useRef as B, useMemo as xe, Fragment as Ae } from "react";
import { useForkRef as M } from "@mui/material/utils";
import { useComponentSize as De } from "../../hooks/useComponentSize/index.js";
import { getComponentClasses as Fe } from "../../utils/getComponentSlotRoot.js";
import { getPropDataTestId as n } from "../../test/getNameDataTestId.js";
import { SegmentFieldStyled as _e, SeparatorStyled as ke, RootStyled as Ke, InlineLayoutStyled as ze, PeriodGroupStyled as ve, SegmentsStyled as w, EndAdornmentStyled as Be, PopoverStyled as Me, ContentStyled as we, SummaryStyled as Le, ActionsContainerStyled as Ne, ActionCancelStyled as Ue, ActionIntroStyled as Ve } from "./slots/TimePickerSlots.js";
import { Select as $e } from "../extended/mui/Select/Select.js";
import { TextField as Ge } from "../extended/mui/TextField/TextField.js";
import { DEFAULT_TIME_PICKER_GRANULARITY as je, TIME_PICKER_KEY_COMPONENT as t, TIME_PICKER_PERIOD_GROUP_LABEL as He, TIME_PICKER_OPEN_BUTTON_LABEL as We } from "./constants.js";
import { useTimePicker as Ye } from "./hooks/useTimePicker/useTimePicker.js";
import { TimePickerSlots as r } from "./slots/TimePickerEnum.js";
import { Radio as Je } from "../extended/mui/Radio/Radio.js";
import { IconButton as qe } from "../extended/mui/IconButton/IconButton.js";
function Qe(m) {
  return !!m.closest('button,[role="button"],[role="listbox"],[role="option"]');
}
function Xe(m) {
  const f = m.closest('[role="combobox"]');
  return f instanceof HTMLElement && f.getAttribute("aria-expanded") !== "true";
}
const ht = Oe(function(f, L) {
  const {
    className: N,
    dataTestId: o,
    defaultValue: U,
    disabled: l = !1,
    displayVariant: V = "auto",
    error: u = !1,
    granularity: $ = je,
    InputProps: S,
    inputProps: O,
    inputRef: G,
    onBlur: j,
    onFocus: H,
    onChange: W,
    onKeyDown: Y,
    onMouseUp: J,
    openOnFocus: x = !0,
    pickerVariant: q = "field",
    placeholder: Q,
    readOnly: X = !1,
    size: Z = "medium",
    value: ee,
    variant: C = "outlined",
    ...te
  } = f, { currentSize: g } = De(Z), d = g === "small" || g === "medium" ? g : "medium", P = B(null), A = B(null), oe = M(P, L), re = M(A, G), p = X || !!S?.readOnly, {
    anchorEl: I,
    defaultPlaceholder: ne,
    displayParts: T,
    draftInputValue: ae,
    draftSummary: ie,
    open: h,
    resolvedDisplayVariant: le,
    segmentOptions: D,
    visibleSegments: R,
    commitDraftInputValue: de,
    commitDisplaySegmentChange: F,
    handleCancel: se,
    handleClose: ce,
    handleConfirm: ue,
    handleDisplaySegmentChange: pe,
    handleInputFocus: me,
    handleInputKeyDown: fe,
    handleInputMouseUp: he,
    handleInputPaste: ye,
    handleInputValueChange: Se,
    handleOpen: _,
    handlePopoverEnterShortcut: Ce
  } = Ye({
    defaultValue: U,
    disabled: l,
    displayVariant: V,
    granularity: $,
    inputElementRef: A,
    onChange: W,
    readOnly: p,
    value: ee
  }), i = xe(() => ({
    disabled: l,
    error: !!u,
    open: h,
    popoverWidth: I?.clientWidth,
    size: d,
    variant: C
  }), [d, I, l, u, h, C]), E = Fe(t, r), y = q === "inline", ge = y && R.includes("period"), k = y ? R.filter((e) => e !== "period") : R, K = k.map((e, s) => {
    const z = k[s + 1], Ie = e !== "period" && z && z !== "period", Te = `select${e.charAt(0).toUpperCase()}${e.slice(1)}`;
    return /* @__PURE__ */ c(Ae, { children: [
      /* @__PURE__ */ a(
        _e,
        {
          "data-segment": e,
          ownerState: i,
          children: /* @__PURE__ */ a(
            $e,
            {
              dataTestId: n(t, r[Te], o)["data-testid"],
              disabled: l,
              error: !!u,
              onChange: (b) => {
                if (!b || Array.isArray(b))
                  return;
                const v = String(b.id);
                if (y) {
                  F(e, v);
                  return;
                }
                pe(e, v);
              },
              options: D[e],
              readOnly: l || p,
              size: d,
              value: T[e],
              variant: "contained"
            }
          )
        }
      ),
      Ie && /* @__PURE__ */ a(
        ke,
        {
          color: "text.secondary",
          ownerState: i,
          variant: "body",
          ...n(t, r.separator, `${o ?? "default"}-${e}`),
          children: ":"
        }
      )
    ] }, e);
  });
  function Pe(e) {
    if (e.key !== "Enter" || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
      return;
    const s = e.target;
    s instanceof HTMLElement && (Qe(s) || !Xe(s) || (e.preventDefault(), e.stopPropagation(), Ce()));
  }
  return /* @__PURE__ */ a(
    Ke,
    {
      ref: oe,
      className: be(E.root, N),
      ownerState: i,
      ...n(t, r.root, o),
      children: y ? /* @__PURE__ */ c(ze, { ownerState: i, ...n(t, r.inlineLayout, o), children: [
        ge && /* @__PURE__ */ a(
          ve,
          {
            "aria-label": He,
            name: `${t}-${o ?? "default"}-period`,
            onChange: (e, s) => {
              F("period", s);
            },
            ownerState: i,
            row: !0,
            value: T.period,
            ...n(t, r.periodGroup, o),
            children: D.period.map((e) => /* @__PURE__ */ a(
              Je,
              {
                checked: T.period === e.id,
                disabled: l || p,
                error: !!u,
                inlineText: e.label,
                inputProps: {
                  "aria-label": e.label
                },
                size: d,
                value: e.id
              },
              String(e.id)
            ))
          }
        ),
        /* @__PURE__ */ a(w, { direction: "row", ownerState: i, ...n(t, r.segments, o), children: K })
      ] }) : /* @__PURE__ */ c(Re, { children: [
        /* @__PURE__ */ a(
          Ge,
          {
            ...te,
            ...n(t, r.textField, o),
            className: E.textField,
            disabled: l,
            error: u,
            inputMode: le === "ampm" ? "text" : "numeric",
            inputRef: re,
            inputProps: {
              ...O,
              /**
               * Allow pasting into the input while preventing non-conforming characters based on the display variant.
               */
              onPaste: (e) => {
                ye(e), O?.onPaste?.(e);
              },
              spellCheck: !1
            },
            InputProps: {
              ...S,
              readOnly: p,
              endAdornment: /* @__PURE__ */ c(Be, { ownerState: i, ...n(t, r.endAdornment, o), children: [
                S?.endAdornment,
                /* @__PURE__ */ a(
                  qe,
                  {
                    "aria-label": We,
                    dataTestId: n(t, r.iconButton, o)["data-testid"],
                    disabled: l || p,
                    icon: /* @__PURE__ */ a(Ee, {}),
                    onClick: (e) => _(P.current ?? e.currentTarget),
                    size: d
                  }
                )
              ] })
            },
            onBlur: (e) => {
              de(), j?.(e);
            },
            onChange: (e) => {
              Se(e.target.value);
            },
            onFocus: (e) => {
              me(e), x && !h && _(P.current ?? e.currentTarget), H?.(e);
            },
            onKeyDown: (e) => {
              fe(e), Y?.(e);
            },
            onMouseUp: (e) => {
              he(e), J?.(e);
            },
            placeholder: Q ?? ne,
            size: d,
            value: ae,
            variant: C
          }
        ),
        /* @__PURE__ */ a(
          Me,
          {
            ...n(t, r.popover, o),
            anchorEl: I,
            className: E.popover,
            anchorOrigin: {
              horizontal: "left",
              vertical: "bottom"
            },
            disableRestoreFocus: x,
            disableScrollLock: !0,
            onClose: ce,
            open: h,
            ownerState: i,
            transformOrigin: {
              horizontal: "left",
              vertical: "top"
            },
            children: /* @__PURE__ */ c(we, { onKeyDownCapture: Pe, ownerState: i, ...n(t, r.content, o), children: [
              /* @__PURE__ */ a(
                Le,
                {
                  color: "primary.semanticText",
                  ownerState: i,
                  variant: "paragraphDens",
                  fontFamily: "Jura",
                  ...n(t, r.summary, o),
                  children: ie
                }
              ),
              /* @__PURE__ */ a(w, { direction: "row", ownerState: i, ...n(t, r.segments, o), children: K }),
              /* @__PURE__ */ c(Ne, { ownerState: i, ...n(t, r.actionsContainer, o), children: [
                /* @__PURE__ */ a(
                  Ue,
                  {
                    ownerState: i,
                    onClick: se,
                    size: d,
                    type: "button",
                    ...n(t, r.actionCancel, o)
                  }
                ),
                /* @__PURE__ */ a(
                  Ve,
                  {
                    ownerState: i,
                    onClick: ue,
                    size: d,
                    type: "button",
                    ...n(t, r.actionIntro, o)
                  }
                )
              ] })
            ] })
          }
        )
      ] })
    }
  );
});
export {
  ht as TimePicker
};
