/**
 * Tiny progressive-enhancement helper for forms that POST JSON to the Laravel API.
 * Handles: Turnstile token, loading state, 422 field errors, error codes, network errors.
 */
import { site } from '../config/site';

declare global {
  interface Window { turnstile?: { reset: (el?: string | HTMLElement) => void; getResponse: (el?: string | HTMLElement) => string | undefined } }
}

type Json = Record<string, unknown>;

interface Options {
  endpoint: string; // path after apiUrl, e.g. '/public/signup'
  body: (fd: FormData) => Json;
  validate?: (fd: FormData) => Record<string, string>;
  onSuccess: (data: any, res: Response) => void;
}

/** page language (<html lang>): 'en' | 'es' */
const lang = document.documentElement.lang === 'es' ? 'es' : 'en';

const MESSAGES = {
  en: {
    captcha_failed: 'The security check failed. Please complete it again.',
    captcha_required: 'Please complete the security check.',
    too_many_requests: 'Too many attempts. Please wait a minute and try again.',
    validation_failed: 'Please fix the highlighted fields.',
    signup_disabled: 'New signups are paused right now. Please contact us.',
    server: 'Something went wrong on our side. Please try again in a moment.',
    failed: 'Request failed. Please try again.',
    network: "We couldn't reach the server. Check your internet connection and try again.",
  },
  es: {
    captcha_failed: 'La verificación de seguridad falló. Complétala de nuevo.',
    captcha_required: 'Completa la verificación de seguridad.',
    too_many_requests: 'Demasiados intentos. Espera un minuto y vuelve a intentarlo.',
    validation_failed: 'Corrige los campos marcados.',
    signup_disabled: 'Los registros nuevos están pausados por ahora. Contáctanos.',
    server: 'Algo salió mal de nuestro lado. Vuelve a intentarlo en un momento.',
    failed: 'La solicitud falló. Vuelve a intentarlo.',
    network: 'No pudimos conectar con el servidor. Revisa tu conexión a internet y vuelve a intentarlo.',
  },
};
const { server: SERVER_ERROR, failed: REQUEST_FAILED, network: NETWORK_ERROR, ...codes } = MESSAGES[lang];
const CODE_MESSAGES: Record<string, string> = codes;

export function initApiForm(form: HTMLFormElement, opts: Options) {
  const submit = form.querySelector<HTMLButtonElement>('button[type="submit"]');
  const alertBox = form.querySelector<HTMLElement>('[data-form-alert]');
  const captchaEl = form.querySelector<HTMLElement>('.cf-turnstile');

  const clear = () => {
    form.querySelectorAll<HTMLElement>('[data-error-for]').forEach((el) => (el.textContent = ''));
    form.querySelectorAll('[aria-invalid="true"]').forEach((el) => el.removeAttribute('aria-invalid'));
    if (alertBox) { alertBox.hidden = true; alertBox.textContent = ''; }
  };

  const showAlert = (msg: string) => {
    if (!alertBox) return;
    alertBox.textContent = msg;
    alertBox.hidden = false;
    alertBox.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
  };

  const showFieldErrors = (errors: Record<string, string[] | string>) => {
    let first: HTMLElement | null = null;
    let unplaced: string[] = [];
    for (const [field, msgs] of Object.entries(errors)) {
      const msg = Array.isArray(msgs) ? msgs[0] : msgs;
      const key = field === 'captcha_token' || field === 'cf-turnstile-response' ? 'captcha_token' : field;
      const slot = form.querySelector<HTMLElement>(`[data-error-for="${key}"]`);
      const input = form.querySelector<HTMLElement>(`[name="${key}"]`);
      if (slot) slot.textContent = msg; else unplaced.push(msg);
      if (input) { input.setAttribute('aria-invalid', 'true'); first ??= input; }
    }
    if (unplaced.length) showAlert(unplaced.join(' '));
    first?.focus();
  };

  const setLoading = (on: boolean) => {
    if (!submit) return;
    submit.disabled = on;
    submit.classList.toggle('is-loading', on);
    submit.setAttribute('aria-busy', String(on));
  };

  const resetCaptcha = () => { try { if (captchaEl) window.turnstile?.reset(captchaEl); } catch { /* widget not loaded */ } };

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    clear();
    const fd = new FormData(form);

    const local = opts.validate?.(fd) ?? {};
    const token = String(fd.get('cf-turnstile-response') ?? '');
    if (captchaEl && !token) local.captcha_token = local.captcha_token ?? CODE_MESSAGES.captcha_required;
    if (Object.keys(local).length) { showFieldErrors(local); return; }

    setLoading(true);
    try {
      const res = await fetch(`${site.apiUrl}${opts.endpoint}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Accept-Language': lang, 'X-Client': 'web' },
        body: JSON.stringify({ ...opts.body(fd), captcha_token: token }),
      });
      let json: any = null;
      try { json = await res.json(); } catch { /* empty body */ }

      if (res.ok) { opts.onSuccess(json?.data ?? json, res); return; }

      resetCaptcha();
      const code: string | undefined = json?.code;
      if (res.status === 422 && json?.errors) {
        showFieldErrors(json.errors);
        if (code && code !== 'validation_failed' && CODE_MESSAGES[code]) showAlert(CODE_MESSAGES[code]);
      } else if (res.status === 429) {
        showAlert(CODE_MESSAGES.too_many_requests);
      } else if (code && CODE_MESSAGES[code]) {
        if (code.startsWith('captcha')) showFieldErrors({ captcha_token: CODE_MESSAGES[code] });
        else showAlert(CODE_MESSAGES[code]);
      } else {
        showAlert(json?.message || (res.status >= 500 ? SERVER_ERROR : REQUEST_FAILED));
      }
    } catch {
      resetCaptcha();
      showAlert(NETWORK_ERROR);
    } finally {
      setLoading(false);
    }
  });

  // Clear a field's error as soon as the user edits it
  form.addEventListener('input', (e) => {
    const t = e.target as HTMLInputElement;
    if (t?.name) {
      t.removeAttribute('aria-invalid');
      const slot = form.querySelector<HTMLElement>(`[data-error-for="${t.name}"]`);
      if (slot) slot.textContent = '';
    }
  });
}

/** 0–4 password strength score */
export function passwordScore(pw: string) {
  if (!pw) return 0;
  let s = 0;
  if (pw.length >= 8) s++;
  if (pw.length >= 12) s++;
  if (/[a-z]/.test(pw) && /[A-Z]/.test(pw)) s++;
  if (/\d/.test(pw) && /[^A-Za-z0-9]/.test(pw)) s++;
  return Math.min(4, Math.max(1, s));
}

export const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
