// packages/components/src/date-time/utils.ts
import { UTCDateMini } from "@date-fns/utc";
import { date as formatDate, getDate } from "@wordpress/date";
import { COMMIT, PRESS_DOWN, PRESS_UP } from "../input-control/reducer/actions.js";
function inputToDate(input) {
  if (typeof input === "string") {
    const hasTimezone = /Z|[+-]\d{2}(:?\d{2})?$/.test(input);
    if (hasTimezone) {
      return new UTCDateMini(new Date(input));
    }
    return new UTCDateMini(getDate(input).getTime());
  }
  const time = input instanceof Date ? input.getTime() : input;
  return new UTCDateMini(time);
}
function startOfDayInConfiguredTimezone(date) {
  const year = Number(formatDate("Y", date));
  const month = Number(formatDate("n", date)) - 1;
  const day = Number(formatDate("j", date));
  return new Date(year, month, day, 0, 0, 0, 0);
}
function from12hTo24h(hours, isPm) {
  return isPm ? (hours % 12 + 12) % 24 : hours % 12;
}
function from24hTo12h(hours) {
  return hours % 12 || 12;
}
function buildPadInputStateReducer(pad) {
  return (state, action) => {
    const nextState = {
      ...state
    };
    if (action.type === COMMIT || action.type === PRESS_UP || action.type === PRESS_DOWN) {
      if (nextState.value !== void 0) {
        nextState.value = nextState.value.toString().padStart(pad, "0");
      }
    }
    return nextState;
  };
}
function setInConfiguredTimezone(date, updates) {
  const values = {
    year: Number(formatDate("Y", date)),
    month: Number(formatDate("n", date)) - 1,
    date: Number(formatDate("j", date)),
    hours: Number(formatDate("H", date)),
    minutes: Number(formatDate("i", date)),
    seconds: Number(formatDate("s", date)),
    ...updates
  };
  const year = String(values.year);
  const month = String(values.month + 1).padStart(2, "0");
  const day = String(values.date).padStart(2, "0");
  const hours = String(values.hours).padStart(2, "0");
  const minutes = String(values.minutes).padStart(2, "0");
  const seconds = String(values.seconds).padStart(2, "0");
  const timezoneless = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
  return new UTCDateMini(getDate(timezoneless).getTime());
}
function validateInputElementTarget(event) {
  var _ownerDocument$defaul;
  const HTMLInputElementInstance = (_ownerDocument$defaul = event.target?.ownerDocument.defaultView?.HTMLInputElement) !== null && _ownerDocument$defaul !== void 0 ? _ownerDocument$defaul : HTMLInputElement;
  if (!(event.target instanceof HTMLInputElementInstance)) {
    return false;
  }
  return event.target.validity.valid;
}
export {
  buildPadInputStateReducer,
  from12hTo24h,
  from24hTo12h,
  inputToDate,
  setInConfiguredTimezone,
  startOfDayInConfiguredTimezone,
  validateInputElementTarget
};
//# sourceMappingURL=utils.js.map
