// src/data/validators.jsx — SPEC §10.1.1
//
// Shared field validators used by auth.jsx (LoginModal) and checkout.jsx
// (Panel 02 account completeness). Matches the backend rules in
// gf-backend/src/domain/normalize.ts so the frontend and backend agree on
// what counts as a valid email / password / phone.
//
// Load order: after api.jsx, before any component that validates input.

window.EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

window.isValidEmail = (s) =>
  typeof s === "string" && window.EMAIL_RE.test(s.trim());

// Supabase Auth enforces a 6 character minimum on passwords.
window.isValidPassword = (s) => typeof s === "string" && s.length >= 6;

window.phoneDigits = (s) =>
  typeof s === "string" ? s.replace(/\D/g, "").length : 0;

// SPEC §7.5.8: 7–15 digits after stripping non-digits.
window.isValidPhone = (s) => {
  const n = window.phoneDigits(s);
  return n >= 7 && n <= 15;
};

// Best-effort E.164 normalization for phone values sent to Stripe
// (`handle.updatePhoneNumber`, server-side `stripe.customers.create/update`).
// Mirrors integrations/stripe/customer.ts:toE164 on the backend.
window.toE164 = (raw) => {
  if (typeof raw !== "string") return "";
  const trimmed = raw.trim();
  if (trimmed.startsWith("+")) return `+${trimmed.slice(1).replace(/\D/g, "")}`;
  const digits = trimmed.replace(/\D/g, "");
  if (digits.length === 10) return `+1${digits}`;
  if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
  return `+${digits}`;
};
