"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { extractPhoneDigits, validatePhoneNumber } from "@open-mercato/shared/lib/phone";
const DEFAULT_MIN_DIGITS = 6;
const DEFAULT_INVALID_LABEL = "Enter a valid phone number with country code (e.g. +1 212 555 1234)";
function PhoneNumberField({
  value,
  onValueChange,
  onDigitsChange,
  externalError,
  disabled = false,
  autoFocus,
  placeholder,
  minDigits = DEFAULT_MIN_DIGITS,
  checkingLabel,
  duplicateLabel,
  duplicateLinkLabel,
  invalidLabel,
  onDuplicateLookup
}) {
  const [local, setLocal] = React.useState(() => {
    if (value == null || value === "") return "";
    return String(value);
  });
  const [duplicate, setDuplicate] = React.useState(null);
  const [checking, setChecking] = React.useState(false);
  const [validationHint, setValidationHint] = React.useState(null);
  const userEditingRef = React.useRef(false);
  const visibleValidationHint = externalError ? null : validationHint;
  React.useEffect(() => {
    if (userEditingRef.current) return;
    if (value == null || value === "") {
      setLocal("");
      onDigitsChange?.(null);
      return;
    }
    const nextValue = String(value);
    setLocal(nextValue);
    onDigitsChange?.(extractPhoneDigits(nextValue) || null);
  }, [value, onDigitsChange]);
  React.useEffect(() => {
    if (!onDuplicateLookup || disabled) {
      setDuplicate(null);
      setChecking(false);
      return;
    }
    const digits = extractPhoneDigits(local);
    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);
    };
  }, [local, disabled, minDigits, onDuplicateLookup]);
  const handleChange = React.useCallback(
    (event) => {
      const next = event.target.value;
      const cleanDigits = extractPhoneDigits(next);
      userEditingRef.current = true;
      setLocal(next);
      setValidationHint(null);
      onValueChange(next.length ? next : void 0);
      onDigitsChange?.(cleanDigits.length ? cleanDigits : null);
    },
    [onValueChange, onDigitsChange]
  );
  const handleBlur = React.useCallback(() => {
    userEditingRef.current = false;
    const trimmed = local.trim();
    if (!trimmed) {
      setLocal("");
      setValidationHint(null);
      onValueChange(void 0);
      onDigitsChange?.(null);
      return;
    }
    const result = validatePhoneNumber(trimmed);
    if (result.valid) {
      setLocal(result.normalized ?? "");
      setValidationHint(null);
      onValueChange(result.normalized || void 0);
      onDigitsChange?.(result.digits || null);
    } else {
      setLocal(trimmed);
      setValidationHint(invalidLabel ?? DEFAULT_INVALID_LABEL);
      onValueChange(trimmed);
      onDigitsChange?.(result.digits || null);
    }
  }, [invalidLabel, local, onDigitsChange, onValueChange]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsx(
      "input",
      {
        type: "tel",
        className: "w-full h-9 rounded border px-2 text-sm",
        value: local,
        onChange: handleChange,
        onBlur: handleBlur,
        placeholder,
        autoFocus,
        disabled,
        "data-crud-focus-target": ""
      }
    ),
    visibleValidationHint ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: visibleValidationHint }) : null,
    !disabled && duplicate && duplicateLabel && duplicateLinkLabel ? /* @__PURE__ */ jsxs("p", { className: "text-xs text-amber-600", children: [
      duplicateLabel(duplicate),
      " ",
      /* @__PURE__ */ jsx("a", { className: "font-medium text-primary underline underline-offset-2", href: duplicate.href, children: duplicateLinkLabel })
    ] }) : null,
    !disabled && !duplicate && checking && checkingLabel ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: checkingLabel }) : null
  ] });
}
export {
  PhoneNumberField
};
//# sourceMappingURL=PhoneNumberField.js.map
