// Signup funnel events. Every event goes through trackSignupEvent so the
// in-app-webview flag is attached consistently and no call site can forget it.
//
// PRIVACY: these events must never carry PII — no email, name or password.
// Only the shapes below are sent, and API error text is sanitised first.

import { trackGAEvent } from "@/lib/google-analytics";
import { isInAppWebview } from "@/lib/webview";

export const SIGNUP_EVENTS = {
  formView: "signup_form_view",
  formStart: "signup_form_start",
  submitClick: "signup_submit_click",
  apiError: "signup_api_error",
  success: "signup_success",
  renderError: "signup_render_error",
  // GA4 recommended event, pre-dating this funnel and likely backing a
  // conversion in the GA property. Routed through the same helper so it carries
  // in_app_webview too — otherwise segmenting by that param would silently drop
  // the one event a conversion may be configured on.
  signUp: "sign_up",
} as const;

const EMAIL_PATTERN = /[^\s@]+@[^\s@]+\.[^\s@]+/g;
const MAX_ERROR_MESSAGE_LENGTH = 120;

/**
 * API messages can echo what the user typed (e.g. "user@example.com already
 * exists"), so redact anything email-shaped and cap the length before it
 * reaches analytics.
 */
export function sanitizeErrorMessage(message: unknown): string {
  if (typeof message !== "string" || !message) return "unknown";
  return message.replace(EMAIL_PATTERN, "[redacted]").slice(0, MAX_ERROR_MESSAGE_LENGTH);
}

export function trackSignupEvent(
  eventName: (typeof SIGNUP_EVENTS)[keyof typeof SIGNUP_EVENTS],
  params?: Record<string, unknown>
): void {
  trackGAEvent(eventName, { ...params, in_app_webview: isInAppWebview() });
}
