import { isNumber as h, clampStepwise as g } from "../../utils.js";
import { NumberInputActionTypes as i } from "./NumberInputActions.js";
function w(n, e) {
  const { min: l, max: u, step: t, withDecimal: a } = e, r = n === null ? null : g(n, l, u, t, a), c = r === null ? "" : String(r);
  return {
    value: r,
    inputValue: c
  };
}
function d(n, e = 6) {
  const l = Math.pow(10, e);
  return Math.round(n * l) / l;
}
function M(n, e, l, u) {
  const { value: t } = n, { step: a = 1, min: r, max: c } = e;
  return h(t) ? {
    up: d(t + (a ?? 1) * u),
    down: d(t - (a ?? 1) * u)
  }[l] : {
    up: r ?? 1,
    down: c ?? -1
  }[l];
}
function S(n, e, l) {
  const { getInputValueAsString: u } = e, t = u(l), a = t === "" || t === "-" ? null : Number(t), r = w(a, e);
  return {
    ...n,
    ...r,
    noControlledValue: r.value
  };
}
function b(n, e, l) {
  const { getInputValueAsString: u, min: t, max: a, step: r, withDecimal: c } = e, o = u(l);
  if (o.match(c ? /^-?(?:\d+(\.\d*)?|\.\d+)$/ : /^-?\d+?$/) || o === "" || o === "." || o === "-") {
    const p = o === "" || o === "-" || o === "." ? null : Number(o), m = p === null ? null : g(p, t, a, r, c), s = p !== null && m === Number(o) ? m : n.value;
    return {
      ...n,
      value: s,
      inputValue: o,
      noControlledValue: s
    };
  }
  return n;
}
function V(n, e, l, u) {
  const t = l ? e.shiftMultiplier : 1, a = M(n, e, u, t), r = w(a, e);
  return {
    ...n,
    ...r,
    noControlledValue: r.value
  };
}
function f(n, e, l) {
  const u = e[l];
  return h(u) ? {
    ...n,
    value: u,
    inputValue: String(u),
    noControlledValue: u
  } : n;
}
function x(n, e) {
  const { type: l, context: u } = e;
  switch (l) {
    case i.clamp:
      return S(n, u, e.inputValue);
    case i.inputChange:
      return b(n, u, e.inputValue);
    case i.increment:
      return V(n, u, e.applyMultiplier, "up");
    case i.decrement:
      return V(n, u, e.applyMultiplier, "down");
    case i.incrementToMax:
      return f(n, u, "max");
    case i.decrementToMin:
      return f(n, u, "min");
    case i.resetInputValue:
      return {
        ...n,
        inputValue: String(n.value)
      };
    default:
      return n;
  }
}
export {
  x as numberInputReducer
};
