export interface CaptchaClientProviderDefinition {
  name: "turnstile" | "recaptcha" | "hcaptcha";
  scriptUrl: string;
  responseField: string;
  globalName: string;
}

export const captchaClientProviders: Record<string, CaptchaClientProviderDefinition> = {
  turnstile: {
    name: "turnstile",
    scriptUrl: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",
    responseField: "cf-turnstile-response",
    globalName: "turnstile",
  },
  recaptcha: {
    name: "recaptcha",
    scriptUrl: "https://www.google.com/recaptcha/api.js?render=explicit",
    responseField: "g-recaptcha-response",
    globalName: "grecaptcha",
  },
  hcaptcha: {
    name: "hcaptcha",
    scriptUrl: "https://js.hcaptcha.com/1/api.js?render=explicit",
    responseField: "h-captcha-response",
    globalName: "hcaptcha",
  },
};

export function getCaptchaResponse(form: HTMLFormElement, field = "wrn-captcha-response"): string {
  const value = new FormData(form).get(field);
  return typeof value === "string" ? value : "";
}

export function resetCaptchaElement(element: Element): void {
  element.dispatchEvent(new CustomEvent("captcha-reset", { bubbles: true }));
}
