import { jsxs as te, jsx as b } from "react/jsx-runtime";
import { c as pe, a as fe } from "../index-BmAFn37q.mjs";
import { createContext as me, useContext as be, useId as ve, useRef as Z, useState as L, useEffect as $, useMemo as H, Children as ne, isValidElement as re, cloneElement as ee } from "react";
import { useFormFieldControl as Ie } from "../form-field/index.mjs";
import { I as xe } from "../Icon-D1RueiPY.mjs";
import { Minus as he } from "@spark-ui/icons/Minus";
const se = me(null), ye = () => {
  const e = be(se);
  if (!e)
    throw new Error("InputOTP components must be used within InputOTP");
  return e;
}, ae = pe(
  [
    // Base slot styles
    "relative",
    "border-sm first:rounded-l-lg last:rounded-r-lg",
    "size-sz-44",
    "text-center text-body-1",
    "text-on-surface",
    "outline-hidden",
    "transition-colors",
    "flex items-center justify-center",
    // Active state (when focused)
    "data-[active=true]:ring-1",
    "data-[active=true]:ring-inset",
    "data-[active=true]:ring-l-2",
    "data-[active=true]:border-focus",
    // 'data-[active=true]:ring-focus',
    // 'data-[active=true]:border-focus',
    "data-[active=true]:z-raised ring-focus",
    // Disabled state
    "data-[disabled=true]:cursor-not-allowed",
    "data-[disabled=true]:border-outline",
    "data-[disabled=true]:bg-on-surface/dim-5",
    "data-[disabled=true]:text-on-surface/dim-3"
  ],
  {
    variants: {
      /**
       * Color scheme of the slot
       */
      intent: {
        neutral: ["bg-surface border-outline"],
        success: ["border-success bg-success-container text-on-success-container"],
        alert: ["border-alert bg-alert-container text-on-alert-container"],
        error: ["border-error bg-error-container text-on-error-container"]
      }
    },
    defaultVariants: {
      intent: "neutral"
    }
  }
), Ke = ae, E = ({ index: e, className: a, ...t }) => {
  const o = ye(), r = e ?? 0, l = o.slots[r];
  if (!l)
    return null;
  const { char: p, isActive: v, hasFakeCaret: h } = l, I = !p && !h && o.placeholder;
  return /* @__PURE__ */ te(
    "div",
    {
      className: ae({
        intent: o.intent,
        className: a
      }),
      "data-active": v,
      "data-disabled": o.disabled,
      "data-valid": o.intent !== "error",
      ...t,
      children: [
        /* @__PURE__ */ b("span", { className: I ? "text-on-surface/dim-3" : "", children: o.type === "password" && p ? "•" : p || (!h && o.placeholder ? o.placeholder : "") }),
        h && /* @__PURE__ */ b(
          "span",
          {
            className: "pointer-events-none absolute inset-0 flex items-center justify-center",
            "aria-hidden": "true",
            children: /* @__PURE__ */ b("span", { className: "bg-on-surface animate-standalone-caret-blink h-sz-24 w-px" })
          }
        )
      ]
    }
  );
};
E.displayName = "InputOTP.Slot";
const Pe = "Backspace", ge = "ArrowLeft", Te = "ArrowUp", Oe = "ArrowRight", we = "ArrowDown", Ne = "e", Re = ({
  maxLength: e,
  type: a,
  value: t,
  defaultValue: o,
  onValueChange: r,
  isValid: l,
  disabledProp: p,
  autoFocus: v,
  forceUppercase: h,
  filterKeys: g,
  pattern: I,
  placeholder: C,
  nameProp: G
}) => {
  const z = ve(), s = Z(null), B = Z(null), c = Ie(), T = c.id ?? z, D = G ?? c.name, x = c.disabled ?? p, _ = c.isInvalid ?? !l, V = c.isRequired ?? !1, W = c.labelId, k = c.description, O = c.state, w = ["success", "alert", "error"].includes(O ?? "") ? O : _ ? "error" : "neutral", y = t !== void 0 ? t : o, F = h ? y.toUpperCase() : y, [q, N] = L(F), [R, K] = L(!1), u = t !== void 0 ? t : q, f = Math.min(u.length, e - 1);
  $(() => {
    s.current && s.current.setSelectionRange(f, f);
  }, [f, u.length, e]);
  const M = H(
    () => Array.from({ length: e }, (i, n) => ({
      char: u[n] || "",
      isActive: n === f && R,
      hasFakeCaret: n === f && !u[n] && !x && R
    })),
    [e, u, f, R, x]
  );
  $(() => {
    s.current && t !== void 0 && (s.current.value = t);
  }, [t]), $(() => {
    v && s.current && s.current.focus();
  }, [v]);
  const S = (i) => {
    let n = i;
    if (h && (n = n.toUpperCase()), a === "number" && (n = n.replace(/[^\d]/g, "")), I)
      try {
        let m = I;
        I.startsWith("^") || (m = `^${I}$`);
        const d = new RegExp(m);
        n = n.split("").filter((P) => d.test(P)).join("");
      } catch (m) {
        console.error("Invalid pattern provided to InputOTP:", I, m);
      }
    return n;
  };
  return {
    uuid: T,
    inputRef: s,
    containerRef: B,
    name: D,
    disabled: x,
    isInvalid: _,
    isRequired: V,
    description: k,
    maxLength: e,
    intent: w,
    currentValue: u,
    activeIndex: f,
    slots: M,
    contextValue: {
      value: u,
      maxLength: e,
      slots: M,
      activeIndex: f,
      intent: w,
      disabled: x,
      placeholder: C,
      type: a
    },
    handleChange: (i) => {
      if (x) return;
      const n = i.target.value, d = S(n).slice(0, e);
      r && r(d), t === void 0 && N(d);
      const P = Math.min(d.length, e - 1);
      s.current && s.current.setSelectionRange(P, P);
    },
    handleKeyDown: (i) => {
      if (!x) {
        if (g.length > 0 && g.includes(i.key)) {
          i.preventDefault();
          return;
        }
        switch (i.key) {
          case Pe:
            i.preventDefault();
            const n = u.length;
            if (n > 0) {
              const m = u.slice(0, n - 1);
              r && r(m), t === void 0 && N(m);
              const d = Math.max(0, m.length);
              s.current && s.current.setSelectionRange(d, d);
            }
            break;
          case ge:
          case Oe:
            i.preventDefault();
            break;
          case Te:
          case we:
            i.preventDefault();
            break;
          case Ne:
          case "E":
            a === "number" && i.preventDefault();
            break;
        }
      }
    },
    handlePaste: (i) => {
      if (x) return;
      i.preventDefault();
      const n = i.clipboardData.getData("text");
      if (!n) return;
      const d = S(n).slice(0, e);
      r && r(d), t === void 0 && N(d);
      const P = Math.min(d.length, e - 1);
      s.current && s.current.setSelectionRange(P, P);
    },
    handleFocus: () => {
      if (K(!0), s.current) {
        const i = Math.min(u.length, e - 1);
        s.current.setSelectionRange(i, i);
      }
    },
    handleBlur: () => {
      K(!1);
    },
    handleClick: () => {
      s.current && s.current.focus();
    },
    labelId: W
  };
}, ie = (e) => {
  let a = 0;
  return ne.forEach(e, (t) => {
    if (re(t)) {
      const o = t.props;
      t.type === E || t.type?.displayName === "InputOTP.Slot" ? a++ : o.children && (a += ie(o.children));
    }
  }), a;
}, oe = (e, a = 0) => {
  let t = a;
  return [ne.map(e, (r) => {
    if (re(r)) {
      const l = r.props;
      if (r.type === E || r.type?.displayName === "InputOTP.Slot") {
        const p = typeof l.index == "number" ? l.index : t++;
        return ee(r, {
          ...l,
          index: p
        });
      } else if (l.children) {
        const [p, v] = oe(l.children, t);
        return t = v, ee(r, {
          ...r.props,
          children: p
        });
      }
    }
    return r;
  }), t];
}, ce = ({
  maxLength: e,
  type: a = "text",
  value: t,
  defaultValue: o = "",
  onValueChange: r,
  isValid: l = !0,
  disabled: p = !1,
  autoFocus: v = !1,
  autoComplete: h = "off",
  forceUppercase: g = !1,
  filterKeys: I = ["-", "."],
  pattern: C,
  inputMode: G,
  placeholder: z = "",
  name: s,
  className: B,
  children: c,
  ...T
}) => {
  const D = H(() => {
    if (e !== void 0)
      return e;
    const A = ie(c);
    return A > 0 ? A : 4;
  }, [e, c]), x = H(() => {
    const [A] = oe(c);
    return A;
  }, [c]), {
    uuid: _,
    inputRef: V,
    containerRef: W,
    name: k,
    disabled: O,
    isInvalid: Y,
    isRequired: w,
    description: y,
    currentValue: F,
    contextValue: q,
    handleChange: N,
    handleKeyDown: R,
    handlePaste: K,
    handleFocus: u,
    handleBlur: f,
    handleClick: M,
    labelId: S
  } = Re({
    maxLength: D,
    type: a,
    value: t,
    defaultValue: o,
    onValueChange: r,
    isValid: l,
    disabledProp: p,
    autoFocus: v,
    forceUppercase: g,
    filterKeys: I,
    pattern: C,
    placeholder: z,
    nameProp: s
  }), U = "aria-label" in T ? T["aria-label"] : void 0, { "aria-label": le, ...Q } = T, j = S ? { "aria-labelledby": S } : U ? { "aria-label": U } : {};
  return /* @__PURE__ */ b(se.Provider, { value: q, children: /* @__PURE__ */ te(
    "div",
    {
      ref: W,
      "data-spark-component": "input-otp",
      role: "group",
      ...j,
      ...y ? { "aria-describedby": y } : {},
      className: fe(
        "gap-md relative inline-flex items-center",
        O ? "cursor-not-allowed" : "cursor-text",
        B
      ),
      onClick: M,
      ...Q,
      children: [
        k && /* @__PURE__ */ b(
          "input",
          {
            type: "hidden",
            name: k,
            value: F,
            required: w,
            "aria-required": w,
            "aria-invalid": Y,
            ...j
          }
        ),
        /* @__PURE__ */ b(
          "input",
          {
            ref: V,
            id: _,
            type: a === "password" ? "password" : "text",
            value: F,
            maxLength: D,
            autoFocus: v,
            autoComplete: h,
            disabled: O,
            pattern: C,
            inputMode: G,
            ...j,
            ...y ? { "aria-describedby": y } : {},
            "aria-invalid": Y,
            onChange: N,
            onKeyDown: R,
            onPaste: K,
            onFocus: u,
            onBlur: f,
            className: "bg-success z-raised absolute inset-0 m-0 p-0 opacity-0 disabled:cursor-not-allowed",
            tabIndex: 0
          }
        ),
        x
      ]
    }
  ) });
};
ce.displayName = "InputOTP";
const X = ({ children: e, className: a, ...t }) => /* @__PURE__ */ b("div", { className: `inline-flex [&>*:not(:first-child)]:-ml-px ${a || ""}`, ...t, children: e });
X.displayName = "InputOTP.Group";
const J = ({ className: e, ...a }) => /* @__PURE__ */ b(
  "div",
  {
    className: `text-on-surface flex items-center justify-center ${e || ""}`,
    ...a,
    children: /* @__PURE__ */ b(xe, { size: "md", children: /* @__PURE__ */ b(he, {}) })
  }
);
J.displayName = "InputOTP.Separator";
const Se = Object.assign(ce, {
  Group: X,
  Slot: E,
  Separator: J
});
Se.displayName = "InputOTP";
X.displayName = "InputOTP.Group";
E.displayName = "InputOTP.Slot";
J.displayName = "InputOTP.Separator";
export {
  Se as InputOTP,
  ae as inputOTPSlotStyles,
  Ke as inputOTPStyles
};
//# sourceMappingURL=index.mjs.map
