// phone.jsx — phone-number normalization mirror of api/src/lib/phone.js.
// Attaches to window.Phone. Keep behavior in sync with the API library.

(function () {
  const TOLLFREE_PREFIXES = ["800","833","844","855","866","877","888"];

  function stripFormatting(input) {
    if (input == null) return "";
    let s = String(input).trim();
    const plus = s.startsWith("+");
    s = s.replace(/\D+/g, "");
    return plus ? "+" + s : s;
  }

  // Loose user input → E.164 (+1XXXXXXXXXX), or null if it can't be coerced.
  function toE164(input) {
    let raw = stripFormatting(input);
    if (!raw) return null;
    if (raw.startsWith("+")) raw = raw.slice(1);

    let national;
    if (raw.length === 10) national = raw;
    else if (raw.length === 11 && raw[0] === "1") national = raw.slice(1);
    else return null;

    // NANP rules: NPA[0] and NXX[0] must each be 2-9.
    if (national[0] < "2" || national[0] > "9") return null;
    if (national[3] < "2" || national[3] > "9") return null;

    return "+1" + national;
  }

  function toE164TollFree(input) {
    const e = toE164(input);
    if (!e) return null;
    const npa = e.slice(2, 5);
    return TOLLFREE_PREFIXES.includes(npa) ? e : null;
  }

  function format(e164) {
    if (!e164) return "";
    const m = String(e164).match(/^\+1(\d{3})(\d{3})(\d{4})$/);
    return m ? "(" + m[1] + ") " + m[2] + "-" + m[3] : String(e164);
  }

  // Pretty as the user types: forward-only, never reformats characters
  // they haven't typed yet. Returns the original input if not enough
  // digits to start formatting.
  function formatLive(input) {
    if (!input) return "";
    let s = stripFormatting(input);
    const plus = s.startsWith("+");
    if (plus) s = s.slice(1);
    if (s.startsWith("1") && s.length > 10) s = s.slice(1); // drop leading 1
    if (s.length > 10) s = s.slice(0, 10);
    if (s.length === 0) return "";
    if (s.length <= 3) return "(" + s;
    if (s.length <= 6) return "(" + s.slice(0,3) + ") " + s.slice(3);
    return "(" + s.slice(0,3) + ") " + s.slice(3,6) + "-" + s.slice(6);
  }

  // Returns { ok: [E164...], bad: [raw...] }
  function parseList(input) {
    if (!input) return { ok: [], bad: [] };
    const parts = String(input).split(/[,\n;]+/).map((s) => s.trim()).filter(Boolean);
    const ok = [], bad = [];
    for (const p of parts) {
      const e = toE164(p);
      if (e) ok.push(e); else bad.push(p);
    }
    return { ok, bad };
  }

  // Lightweight check: is this a complete-looking phone number?
  function isValid(input) { return toE164(input) !== null; }

  // Lightweight check used while typing — empty string is "not invalid yet"
  function isInvalidIfFilled(input) {
    if (input == null || String(input).trim() === "") return false;
    return !isValid(input);
  }

  window.Phone = {
    TOLLFREE_PREFIXES,
    toE164, toE164TollFree,
    format, formatLive,
    parseList,
    isValid, isInvalidIfFilled,
    stripFormatting,
  };
})();
