import { getDefaultOptions as v } from "./_lib/defaultOptions.js";
import { formatters as D } from "./_lib/format/formatters.js";
import { longFormatters as C } from "./_lib/format/longFormatters.js";
import { isProtectedWeekYearToken as S, isProtectedDayOfYearToken as R, warnOrThrowProtectedError as W } from "./_lib/protectedTokens.js";
import { isValid as x } from "./isValid.js";
import { toDate as P } from "./toDate.js";
import { enUS as Y } from "./locale/en-US.js";
const z = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g, F = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g, y = /^'([^]*?)'?$/, A = /''/g, L = /[a-zA-Z]/;
function U(t, n, e) {
  var i, s, k, u, d, g, h, w;
  const c = v(), l = (e == null ? void 0 : e.locale) ?? c.locale ?? Y, T = (e == null ? void 0 : e.firstWeekContainsDate) ?? ((s = (i = e == null ? void 0 : e.locale) == null ? void 0 : i.options) == null ? void 0 : s.firstWeekContainsDate) ?? c.firstWeekContainsDate ?? ((u = (k = c.locale) == null ? void 0 : k.options) == null ? void 0 : u.firstWeekContainsDate) ?? 1, O = (e == null ? void 0 : e.weekStartsOn) ?? ((g = (d = e == null ? void 0 : e.locale) == null ? void 0 : d.options) == null ? void 0 : g.weekStartsOn) ?? c.weekStartsOn ?? ((w = (h = c.locale) == null ? void 0 : h.options) == null ? void 0 : w.weekStartsOn) ?? 0, o = P(t);
  if (!x(o))
    throw new RangeError("Invalid time value");
  let f = n.match(F).map((a) => {
    const r = a[0];
    if (r === "p" || r === "P") {
      const m = C[r];
      return m(a, l.formatLong);
    }
    return a;
  }).join("").match(z).map((a) => {
    if (a === "''")
      return { isToken: !1, value: "'" };
    const r = a[0];
    if (r === "'")
      return { isToken: !1, value: $(a) };
    if (D[r])
      return { isToken: !0, value: a };
    if (r.match(L))
      throw new RangeError(
        "Format string contains an unescaped latin alphabet character `" + r + "`"
      );
    return { isToken: !1, value: a };
  });
  l.localize.preprocessor && (f = l.localize.preprocessor(o, f));
  const E = {
    firstWeekContainsDate: T,
    weekStartsOn: O,
    locale: l
  };
  return f.map((a) => {
    if (!a.isToken)
      return a.value;
    const r = a.value;
    (!(e != null && e.useAdditionalWeekYearTokens) && S(r) || !(e != null && e.useAdditionalDayOfYearTokens) && R(r)) && W(r, n, String(t));
    const m = D[r[0]];
    return m(o, r, l.localize, E);
  }).join("");
}
function $(t) {
  const n = t.match(y);
  return n ? n[1].replace(A, "'") : t;
}
export {
  U as default,
  U as format,
  U as formatDate,
  D as formatters,
  C as longFormatters
};
