"use client";
import { useRef, useState, type FormEvent } from "react";
export function useLittleReply(
  formKey: string,
  apiUrl = "https://littlereply.com",
) {
  const [state, setState] = useState<{
      busy: boolean;
      success: boolean;
      error: string;
      fields: Record<string, string>;
    }>({ busy: false, success: false, error: "", fields: {} }),
    attempt = useRef(crypto.randomUUID()),
    fingerprint = useRef("");
  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    if (!form.reportValidity()) return;
    setState({ busy: true, success: false, error: "", fields: {} });
    try {
      const data = new FormData(form),
        fields: Record<string, string | string[]> = {};
      for (const key of new Set(data.keys())) {
        if (
          [
            "_fq_key",
            "form_key",
            "access_key",
            "_subject",
            "_fq_captcha",
            "_fq_captcha_provider",
            "g-recaptcha-response",
            "cf-turnstile-response",
            "h-captcha-response",
          ].includes(key)
        )
          continue;
        const values = data.getAll(key);
        if (values.some((v) => v instanceof File && v.size))
          throw Error("Use LittleReply’s direct upload client for file forms.");
        fields[key] =
          values.length === 1 ? String(values[0]) : values.map(String);
      }
      const subject = data.get("_subject") || undefined,
        captcha =
          data.get("_fq_captcha") ||
          data.get("g-recaptcha-response") ||
          data.get("cf-turnstile-response") ||
          data.get("h-captcha-response");
      const next = JSON.stringify({ fields, subject });
      if (fingerprint.current && fingerprint.current !== next)
        attempt.current = crypto.randomUUID();
      fingerprint.current = next;
      const response = await fetch(apiUrl + "/api/submit", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Idempotency-Key": attempt.current,
        },
        body: JSON.stringify({
          form_key: formKey,
          fields,
          subject,
          ...(captcha
            ? { captcha: { provider: "", token: String(captcha) } }
            : {}),
        }),
      });
      const r = await response.json();
      if (!response.ok) {
        setState({
          busy: false,
          success: false,
          error: r.error.message,
          fields: r.error.fields || {},
        });
        return;
      }
      if (r.data.redirect) location.assign(r.data.redirect);
      form.reset();
      attempt.current = crypto.randomUUID();
      fingerprint.current = "";
      setState({ busy: false, success: true, error: "", fields: {} });
    } catch (e) {
      setState({
        busy: false,
        success: false,
        error: e instanceof Error ? e.message : "Please try again.",
        fields: {},
      });
    }
  }
  return { submit, ...state };
}

// Compatibility for existing installations. New integrations use useLittleReply.
export const useFormQuay = useLittleReply;
