'use client';
import { jsx as o, jsxs as b } from "react/jsx-runtime";
import i from "react";
import { Chip as te, Button as re, Select as oe, SelectItem as le, Input as ae } from "@heroui/react";
import { useConfig as ne } from "../../hooks/use-config.js";
import { useFormField as se } from "./form-wrapper.js";
import { FieldError as de } from "./field-error.js";
const P = [
  { code: "US", name: "United States", dialCode: "+1", flag: "🇺🇸", format: "(###) ###-####" },
  { code: "CA", name: "Canada", dialCode: "+1", flag: "🇨🇦", format: "(###) ###-####" },
  { code: "GB", name: "United Kingdom", dialCode: "+44", flag: "🇬🇧", format: "#### ### ####" },
  { code: "AU", name: "Australia", dialCode: "+61", flag: "🇦🇺", format: "#### ### ###" },
  { code: "DE", name: "Germany", dialCode: "+49", flag: "🇩🇪", format: "### ### ####" },
  { code: "FR", name: "France", dialCode: "+33", flag: "🇫🇷", format: "## ## ## ## ##" },
  { code: "ES", name: "Spain", dialCode: "+34", flag: "🇪🇸", format: "### ### ###" },
  { code: "IT", name: "Italy", dialCode: "+39", flag: "🇮🇹", format: "### ### ####" },
  { code: "JP", name: "Japan", dialCode: "+81", flag: "🇯🇵", format: "###-####-####" },
  { code: "KR", name: "South Korea", dialCode: "+82", flag: "🇰🇷", format: "###-####-####" },
  { code: "CN", name: "China", dialCode: "+86", flag: "🇨🇳", format: "### #### ####" },
  { code: "IN", name: "India", dialCode: "+91", flag: "🇮🇳", format: "##### #####" },
  { code: "BR", name: "Brazil", dialCode: "+55", flag: "🇧🇷", format: "(##) #####-####" },
  { code: "MX", name: "Mexico", dialCode: "+52", flag: "🇲🇽", format: "### ### ####" },
  { code: "AR", name: "Argentina", dialCode: "+54", flag: "🇦🇷", format: "### ###-####" },
  { code: "RU", name: "Russia", dialCode: "+7", flag: "🇷🇺", format: "### ###-##-##" },
  { code: "ZA", name: "South Africa", dialCode: "+27", flag: "🇿🇦", format: "## ### ####" },
  { code: "EG", name: "Egypt", dialCode: "+20", flag: "🇪🇬", format: "### ### ####" },
  { code: "NG", name: "Nigeria", dialCode: "+234", flag: "🇳🇬", format: "### ### ####" },
  { code: "SG", name: "Singapore", dialCode: "+65", flag: "🇸🇬", format: "#### ####" }
];
function J(c, l) {
  const a = [], r = c.replace(/[^\d+]/g, "");
  let t = r, h = r;
  r.startsWith("+") ? (h = r, r.startsWith(l.dialCode) ? t = r.substring(l.dialCode.length) : a.push("Phone number does not match selected country")) : (h = l.dialCode + r, t = r), t.length < 7 ? a.push("Phone number is too short") : t.length > 15 && a.push("Phone number is too long");
  let g = t;
  return l.format && t.length >= 7 && (g = ie(t, l.format)), {
    isValid: a.length === 0,
    e164: h,
    national: t,
    formatted: `${l.dialCode} ${g}`,
    errors: a
  };
}
function ie(c, l) {
  let a = l, r = 0;
  for (let t = 0; t < l.length && r < c.length; t++)
    l[t] === "#" && (a = a.substring(0, t) + c[r] + a.substring(t + 1), r++);
  return a.substring(0, a.lastIndexOf("#") + 1);
}
function O(c) {
  const l = c.replace(/[^\d+]/g, "");
  if (!l.startsWith("+")) return null;
  const a = [...P].sort((r, t) => t.dialCode.length - r.dialCode.length);
  for (const r of a)
    if (l.startsWith(r.dialCode))
      return r;
  return null;
}
function Ce({
  name: c = "phone",
  label: l = "Phone Number",
  placeholder: a = "Enter your phone number",
  value: r = "",
  onChange: t,
  onBlur: h,
  onFocus: g,
  defaultCountry: E = "US",
  preferredCountries: x = ["US", "CA", "GB"],
  allowedCountries: I = [],
  blockedCountries: v = [],
  required: D = !1,
  disabled: k = !1,
  validateFormat: B = !0,
  size: F = "md",
  variant: R = "bordered",
  className: K = "",
  autoFocus: L = !1,
  autoComplete: T = "tel",
  error: C,
  description: $,
  showVerificationStatus: U = !1,
  isVerified: G = !1,
  onRequestVerification: y,
  endContent: A
}) {
  const { components: V, organizationSettings: M } = ne(), f = se(c), w = V.PhoneField;
  if (w)
    return /* @__PURE__ */ o(w, { name: c, label: l, placeholder: a, value: r, onChange: t, onBlur: h, onFocus: g, defaultCountry: E, preferredCountries: x, allowedCountries: I, blockedCountries: v, required: D, disabled: k, validateFormat: B, size: F, variant: R, className: K, autoFocus: L, autoComplete: T, error: C, description: $, showVerificationStatus: U, isVerified: G, onRequestVerification: y, endContent: A });
  const [X, Z] = i.useState(r), [p, z] = i.useState(() => {
    if (r) {
      const e = O(r);
      if (e) return e;
    }
    return P.find((e) => e.code === E) || P[0];
  }), m = t ? r : X, S = i.useMemo(() => {
    const e = M?.phoneRestrictions?.allowedCountries;
    return e && e.length > 0 ? e : I;
  }, [I, M]), W = i.useMemo(() => {
    const e = M?.phoneRestrictions?.blockedCountries;
    return e && e.length > 0 ? [...v, ...e] : v;
  }, [v, M]), N = i.useMemo(() => {
    let e = P;
    S.length > 0 && (e = e.filter((u) => S.includes(u.code))), W.length > 0 && (e = e.filter((u) => !W.includes(u.code)));
    const s = e.filter((u) => x.includes(u.code)), d = e.filter((u) => !x.includes(u.code));
    return [...s, ...d];
  }, [S, W, x]), n = i.useMemo(() => !m || !B ? null : J(m, p), [m, p, B]), j = i.useMemo(() => {
    const e = [];
    return C && (Array.isArray(C) ? e.push(...C) : e.push(C)), f.error && (Array.isArray(f.error) ? e.push(...f.error) : e.push(f.error)), n && !n.isValid && e.push(...n.errors), e.length > 0 ? e : null;
  }, [C, f.error, n]), H = i.useCallback((e) => {
    const s = O(e);
    if (s && N.includes(s) && z(s), t && n)
      t(n.e164, n.formatted);
    else if (t) {
      const d = e.replace(/[^\d+]/g, ""), u = d.startsWith("+") ? d : p.dialCode + d.replace(/^\d/, "");
      t(u, e);
    } else
      Z(e);
    f.clearError && f.clearError();
  }, [t, n, f, p, N]), Q = i.useCallback((e) => {
    const s = N.find((d) => d.code === e);
    if (s && (z(s), m)) {
      const d = J(m, s);
      t && t(d.e164, d.formatted);
    }
  }, [N, m, t]), Y = i.useCallback(() => {
    f.setTouched && f.setTouched(!0), h?.();
  }, [f, h]), _ = i.useCallback(() => {
    g?.();
  }, [g]), q = i.useMemo(() => !U || A ? null : G ? /* @__PURE__ */ o(
    te,
    {
      size: "sm",
      color: "success",
      variant: "flat",
      startContent: /* @__PURE__ */ o("svg", { className: "w-3 h-3", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ o("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }),
      children: "Verified"
    }
  ) : m && n?.isValid && y ? /* @__PURE__ */ o(
    re,
    {
      size: "sm",
      variant: "flat",
      color: "primary",
      onPress: y,
      children: "Send SMS"
    }
  ) : null, [U, A, G, m, n, y]), ee = /* @__PURE__ */ o(
    oe,
    {
      value: p.code,
      onChange: (e) => Q(e.target.value),
      className: "min-w-32",
      size: F,
      variant: R,
      isDisabled: k,
      placeholder: "Country",
      renderValue: (e) => {
        const s = N.find((d) => d.code === p.code);
        return s ? /* @__PURE__ */ b("div", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ o("span", { children: s.flag }),
          /* @__PURE__ */ o("span", { className: "text-sm", children: s.dialCode })
        ] }) : null;
      },
      children: N.map((e) => /* @__PURE__ */ o(
        le,
        {
          value: e.code,
          startContent: /* @__PURE__ */ o("span", { className: "text-lg", children: e.flag }),
          children: /* @__PURE__ */ b("div", { className: "flex items-center justify-between w-full", children: [
            /* @__PURE__ */ o("span", { children: e.name }),
            /* @__PURE__ */ o("span", { className: "text-sm text-default-500", children: e.dialCode })
          ] })
        },
        e.code
      ))
    }
  );
  return /* @__PURE__ */ b("div", { className: `space-y-2 ${K}`, children: [
    /* @__PURE__ */ b("div", { className: "flex gap-2", children: [
      /* @__PURE__ */ o("div", { className: "shrink-0", children: ee }),
      /* @__PURE__ */ o("div", { className: "flex-1", children: /* @__PURE__ */ o(
        ae,
        {
          name: c,
          label: l,
          placeholder: a,
          value: m,
          onValueChange: H,
          onBlur: Y,
          onFocus: _,
          type: "tel",
          isRequired: D,
          isDisabled: k,
          size: F,
          variant: R,
          autoFocus: L,
          autoComplete: T,
          description: $,
          isInvalid: !!j,
          errorMessage: "",
          endContent: A || q
        }
      ) })
    ] }),
    j && /* @__PURE__ */ o(de, { error: j, fieldName: c }),
    n && n.isValid && /* @__PURE__ */ b("div", { className: "text-xs text-default-500", children: [
      /* @__PURE__ */ o("span", { className: "font-medium", children: "Format:" }),
      " ",
      n.formatted
    ] }),
    S.length > 0 && /* @__PURE__ */ b("div", { className: "text-xs text-default-500", children: [
      /* @__PURE__ */ o("span", { className: "font-medium", children: "Allowed countries:" }),
      " ",
      S.join(", ")
    ] })
  ] });
}
export {
  Ce as PhoneField
};
//# sourceMappingURL=phone-field.js.map
