"use client";

import PhoneInput from "react-phone-number-input";
import flags from "react-phone-number-input/flags";
import "react-phone-number-input/style.css";

// The library requires a strict E.164 value (e.g. +971501234567). Stored or
// prefilled numbers may contain spaces/dashes — strip everything but a leading
// "+" and digits so they parse without warnings.
function toE164(v: string): string | undefined {
  if (!v) return undefined;
  const s = v.replace(/[^\d+]/g, "");
  if (!s) return undefined;
  return s.startsWith("+") ? s : `+${s}`;
}

export default function PhoneField({
  id,
  value,
  onChange,
  required,
  autoFocus,
}: {
  id?: string;
  value: string;
  onChange: (full: string) => void;
  required?: boolean;
  autoFocus?: boolean;
}) {
  return (
    <PhoneInput
      className="pb-phone2"
      international
      defaultCountry="AE"
      countryCallingCodeEditable={false}
      flags={flags}
      value={toE164(value)}
      onChange={(v) => onChange((v as string) || "")}
      numberInputProps={{ id, required, autoFocus }}
      placeholder="50 123 4567"
    />
  );
}
