"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { extractPhoneDigits, validatePhoneNumber } from "@open-mercato/shared/lib/phone";
import { cn } from "@open-mercato/shared/lib/utils";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectItemLeading,
  SelectTrigger
} from "../../primitives/select.js";
const PHONE_COUNTRIES = [
  { iso2: "US", dialCode: "+1", label: "United States", flag: "\u{1F1FA}\u{1F1F8}" },
  { iso2: "CA", dialCode: "+1", label: "Canada", flag: "\u{1F1E8}\u{1F1E6}" },
  { iso2: "GB", dialCode: "+44", label: "United Kingdom", flag: "\u{1F1EC}\u{1F1E7}" },
  { iso2: "PL", dialCode: "+48", label: "Poland", flag: "\u{1F1F5}\u{1F1F1}" },
  { iso2: "DE", dialCode: "+49", label: "Germany", flag: "\u{1F1E9}\u{1F1EA}" },
  { iso2: "FR", dialCode: "+33", label: "France", flag: "\u{1F1EB}\u{1F1F7}" },
  { iso2: "ES", dialCode: "+34", label: "Spain", flag: "\u{1F1EA}\u{1F1F8}" },
  { iso2: "IT", dialCode: "+39", label: "Italy", flag: "\u{1F1EE}\u{1F1F9}" },
  { iso2: "NL", dialCode: "+31", label: "Netherlands", flag: "\u{1F1F3}\u{1F1F1}" },
  { iso2: "SE", dialCode: "+46", label: "Sweden", flag: "\u{1F1F8}\u{1F1EA}" },
  { iso2: "AT", dialCode: "+43", label: "Austria", flag: "\u{1F1E6}\u{1F1F9}" },
  { iso2: "CH", dialCode: "+41", label: "Switzerland", flag: "\u{1F1E8}\u{1F1ED}" },
  { iso2: "PT", dialCode: "+351", label: "Portugal", flag: "\u{1F1F5}\u{1F1F9}" },
  { iso2: "CZ", dialCode: "+420", label: "Czechia", flag: "\u{1F1E8}\u{1F1FF}" },
  { iso2: "RO", dialCode: "+40", label: "Romania", flag: "\u{1F1F7}\u{1F1F4}" },
  { iso2: "UA", dialCode: "+380", label: "Ukraine", flag: "\u{1F1FA}\u{1F1E6}" }
];
const DEFAULT_COUNTRY = PHONE_COUNTRIES[0];
const COUNTRIES_BY_DIAL_LENGTH = [...PHONE_COUNTRIES].sort(
  (a, b) => b.dialCode.length - a.dialCode.length
);
function findCountryByIso(iso2) {
  return PHONE_COUNTRIES.find((c) => c.iso2 === iso2);
}
function parseCountryFromValue(value) {
  if (!value) return null;
  const trimmed = value.trim();
  if (!trimmed.startsWith("+")) return null;
  for (const country of COUNTRIES_BY_DIAL_LENGTH) {
    if (trimmed.startsWith(country.dialCode)) return country;
  }
  return null;
}
function extractLocalNumber(value, dialCode) {
  if (!value) return "";
  const trimmed = value.trim();
  if (!trimmed.startsWith(dialCode)) return trimmed;
  return trimmed.slice(dialCode.length).trim();
}
function composeValue(country, localNumber) {
  const trimmed = localNumber.trim();
  if (!trimmed) return "";
  if (trimmed.startsWith("+")) return trimmed;
  return `${country.dialCode} ${trimmed}`;
}
const DEFAULT_MIN_DIGITS = 6;
const DEFAULT_PLACEHOLDER = "(555) 000-0000";
function PhoneNumberField({
  id,
  value,
  onValueChange,
  onDigitsChange,
  externalError,
  disabled = false,
  autoFocus,
  ariaLabel,
  ariaDescribedBy,
  placeholder,
  minDigits = DEFAULT_MIN_DIGITS,
  checkingLabel,
  duplicateLabel,
  duplicateLinkLabel,
  invalidLabel,
  onDuplicateLookup,
  countries: countriesProp,
  defaultCountryIso2
}) {
  const t = useT();
  const resolvedInvalidLabel = invalidLabel ?? t(
    "ui.inputs.phoneNumberField.invalid",
    "Enter a valid phone number with country code (e.g. +1 212 555 1234)"
  );
  const resolvedCheckingLabel = checkingLabel ?? t(
    "ui.inputs.phoneNumberField.checking",
    "Checking for duplicates\u2026"
  );
  const resolvedDuplicateLinkLabel = duplicateLinkLabel ?? t(
    "ui.inputs.phoneNumberField.duplicateLink",
    "Open record"
  );
  const resolvedPlaceholder = placeholder ?? DEFAULT_PLACEHOLDER;
  const countries = countriesProp ?? PHONE_COUNTRIES;
  const fallbackCountry = React.useMemo(
    () => defaultCountryIso2 && findCountryByIso(defaultCountryIso2) || DEFAULT_COUNTRY,
    [defaultCountryIso2]
  );
  const initialCountry = React.useMemo(
    () => parseCountryFromValue(value) ?? fallbackCountry,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );
  const [country, setCountry] = React.useState(initialCountry);
  const [localNumber, setLocalNumber] = React.useState(
    () => extractLocalNumber(value, initialCountry.dialCode)
  );
  const [duplicate, setDuplicate] = React.useState(null);
  const [checking, setChecking] = React.useState(false);
  const [validationHint, setValidationHint] = React.useState(null);
  const [focused, setFocused] = React.useState(false);
  const userEditingRef = React.useRef(false);
  const externalFieldError = externalError && externalError.trim().length > 0 ? externalError : null;
  const errorMessage = externalFieldError ?? validationHint;
  const errorId = errorMessage && id ? `${id}-error` : void 0;
  const describedBy = [ariaDescribedBy, errorId].filter((part) => Boolean(part)).join(" ") || void 0;
  const composedValue = composeValue(country, localNumber);
  React.useEffect(() => {
    if (userEditingRef.current) return;
    if (value == null || value === "") {
      setLocalNumber("");
      onDigitsChange?.(null);
      return;
    }
    const parsed = parseCountryFromValue(value);
    if (parsed) setCountry(parsed);
    const next = extractLocalNumber(value, parsed?.dialCode ?? country.dialCode);
    setLocalNumber(next);
    onDigitsChange?.(extractPhoneDigits(String(value)) || null);
  }, [value]);
  React.useEffect(() => {
    if (!onDuplicateLookup || disabled) {
      setDuplicate(null);
      setChecking(false);
      return;
    }
    const digits = extractPhoneDigits(composedValue);
    if (!digits || digits.length < minDigits) {
      setDuplicate(null);
      setChecking(false);
      return;
    }
    let cancelled = false;
    setChecking(true);
    const handle = window.setTimeout(async () => {
      try {
        const match = await onDuplicateLookup(digits);
        if (!cancelled) setDuplicate(match);
      } catch {
        if (!cancelled) setDuplicate(null);
      } finally {
        if (!cancelled) setChecking(false);
      }
    }, 350);
    return () => {
      cancelled = true;
      window.clearTimeout(handle);
    };
  }, [composedValue, disabled, minDigits, onDuplicateLookup]);
  const emit = React.useCallback(
    (nextCountry, nextLocal) => {
      const composed = composeValue(nextCountry, nextLocal);
      onValueChange(composed.length ? composed : void 0);
      onDigitsChange?.(extractPhoneDigits(composed) || null);
    },
    [onDigitsChange, onValueChange]
  );
  const handleCountryChange = React.useCallback(
    (iso2) => {
      const next = findCountryByIso(iso2);
      if (!next) return;
      userEditingRef.current = true;
      setCountry(next);
      setValidationHint(null);
      emit(next, localNumber);
    },
    [emit, localNumber]
  );
  const handleLocalChange = React.useCallback(
    (event) => {
      const next = event.target.value;
      userEditingRef.current = true;
      setLocalNumber(next);
      setValidationHint(null);
      emit(country, next);
    },
    [country, emit]
  );
  const handleBlur = React.useCallback(() => {
    userEditingRef.current = false;
    setFocused(false);
    const trimmed = localNumber.trim();
    if (!trimmed) {
      setLocalNumber("");
      setValidationHint(null);
      onValueChange(void 0);
      onDigitsChange?.(null);
      return;
    }
    const composed = composeValue(country, trimmed);
    const result = validatePhoneNumber(composed);
    if (result.valid) {
      const normalizedLocal = extractLocalNumber(result.normalized ?? composed, country.dialCode);
      setLocalNumber(normalizedLocal);
      setValidationHint(null);
      onValueChange(result.normalized || void 0);
      onDigitsChange?.(result.digits || null);
    } else {
      setValidationHint(resolvedInvalidLabel);
      onValueChange(composed);
      onDigitsChange?.(result.digits || null);
    }
  }, [country, localNumber, onDigitsChange, onValueChange, resolvedInvalidLabel]);
  const containerErrorBorder = errorMessage ? "border-status-error-icon" : "border-input";
  const containerFocusBorder = errorMessage ? "border-status-error-icon shadow-focus" : "border-brand-violet shadow-focus";
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(
          "flex items-stretch w-full rounded-md border bg-background shadow-xs transition-colors",
          disabled ? "bg-bg-disabled border-border-disabled cursor-not-allowed" : focused ? containerFocusBorder : `${containerErrorBorder} hover:border-foreground/30`
        ),
        "aria-invalid": errorMessage ? "true" : void 0,
        children: [
          /* @__PURE__ */ jsxs(Select, { value: country.iso2, onValueChange: handleCountryChange, disabled, children: [
            /* @__PURE__ */ jsxs(
              SelectTrigger,
              {
                "aria-label": ariaLabel ? `${ariaLabel} country` : "Country code",
                className: cn(
                  "h-auto w-auto shrink-0 gap-1.5 rounded-none rounded-l-md border-0 bg-transparent px-2.5 py-2 shadow-none",
                  "hover:bg-muted/40 focus:bg-muted/40 focus-visible:shadow-none focus-visible:border-0",
                  "disabled:bg-transparent disabled:hover:bg-transparent"
                ),
                onFocus: () => setFocused(true),
                onBlur: () => setFocused(false),
                children: [
                  /* @__PURE__ */ jsx("span", { className: "text-base leading-none", "aria-hidden": "true", children: country.flag }),
                  /* @__PURE__ */ jsx("span", { className: "text-sm text-foreground tabular-nums", children: country.dialCode })
                ]
              }
            ),
            /* @__PURE__ */ jsx(SelectContent, { align: "start", children: countries.map((c) => /* @__PURE__ */ jsxs(SelectItem, { value: c.iso2, children: [
              /* @__PURE__ */ jsx(SelectItemLeading, { children: /* @__PURE__ */ jsx("span", { className: "text-base leading-none", children: c.flag }) }),
              /* @__PURE__ */ jsx("span", { className: "flex-1 truncate", children: c.label }),
              /* @__PURE__ */ jsx("span", { className: "ml-2 text-xs text-muted-foreground tabular-nums", children: c.dialCode })
            ] }, `${c.iso2}-${c.dialCode}`)) })
          ] }),
          /* @__PURE__ */ jsx("div", { "aria-hidden": "true", className: "w-px self-stretch bg-input" }),
          /* @__PURE__ */ jsx(
            "input",
            {
              type: "tel",
              inputMode: "tel",
              autoComplete: "tel-national",
              value: localNumber,
              onChange: handleLocalChange,
              onBlur: handleBlur,
              onFocus: () => setFocused(true),
              placeholder: resolvedPlaceholder,
              autoFocus,
              disabled,
              id,
              "aria-label": ariaLabel,
              "aria-describedby": describedBy,
              "aria-invalid": errorMessage ? "true" : void 0,
              "data-crud-focus-target": "",
              className: cn(
                "flex-1 min-w-0 bg-transparent px-3 py-2 text-sm leading-5 outline-none",
                "placeholder:text-muted-foreground",
                "disabled:cursor-not-allowed disabled:text-muted-foreground"
              )
            }
          )
        ]
      }
    ),
    errorMessage ? /* @__PURE__ */ jsx("p", { id: errorId, role: "alert", className: "text-xs text-status-error-text", children: errorMessage }) : null,
    !disabled && duplicate && duplicateLabel ? /* @__PURE__ */ jsxs("p", { className: "text-xs text-status-warning-text", children: [
      duplicateLabel(duplicate),
      " ",
      /* @__PURE__ */ jsx("a", { className: "font-medium text-brand-violet underline underline-offset-2", href: duplicate.href, children: resolvedDuplicateLinkLabel })
    ] }) : null,
    !disabled && !duplicate && checking ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: resolvedCheckingLabel }) : null
  ] });
}
export {
  PHONE_COUNTRIES,
  PhoneNumberField
};
//# sourceMappingURL=PhoneNumberField.js.map
