"use client";

import { useState, type FormEvent } from "react";

type Status = "idle" | "submitting" | "success" | "error";

/**
 * Minimal contact form for the marketing site. Posts to /api/contact.
 * Turnstile is optional: render the widget only if you set
 * NEXT_PUBLIC_TURNSTILE_SITE_KEY, and the server checks it when
 * TURNSTILE_SECRET_KEY is set. Without either, it's a no-op.
 */
export function ContactForm({ locale = "en" }: { locale?: string }) {
  const [status, setStatus] = useState<Status>("idle");
  const [reference, setReference] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("submitting");
    setError(null);

    const form = e.currentTarget;
    const fd = new FormData(form);
    const turnstileToken = (fd.get("cf-turnstile-response") as string) || undefined;

    const res = await fetch("/api/contact", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        firstName: fd.get("firstName"),
        lastName: fd.get("lastName") || undefined,
        email: fd.get("email"),
        subject: fd.get("subject") || undefined,
        message: fd.get("message"),
        company: fd.get("company") || "", // honeypot
        locale,
        page: typeof window !== "undefined" ? window.location.pathname : undefined,
        turnstileToken,
      }),
    }).catch(() => null);

    if (res && res.ok) {
      const json = (await res.json()) as { reference?: string };
      setReference(json.reference ?? null);
      setStatus("success");
      form.reset();
    } else {
      const json = res ? ((await res.json().catch(() => null)) as { error?: string } | null) : null;
      setError(json?.error ?? "Something went wrong. Please try again.");
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div role="status">
        <p>Thanks — we got your message and will reply by email.</p>
        {reference && <p>Your reference: <strong>{reference}</strong></p>}
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate>
      <label>
        First name*
        <input name="firstName" required maxLength={100} autoComplete="given-name" />
      </label>
      <label>
        Last name
        <input name="lastName" maxLength={100} autoComplete="family-name" />
      </label>
      <label>
        Email*
        <input name="email" type="email" required maxLength={254} autoComplete="email" />
      </label>
      <label>
        Subject
        <input name="subject" maxLength={200} />
      </label>
      <label>
        Message*
        <textarea name="message" required minLength={10} maxLength={5000} rows={6} />
      </label>

      {/* Honeypot — visually hidden, must stay empty. */}
      <div aria-hidden="true" style={{ position: "absolute", left: "-9999px" }}>
        <label>
          Company
          <input name="company" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      {/* Optional Turnstile widget: uncomment + load the script if you enable it.
          <div
            className="cf-turnstile"
            data-sitekey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY}
          />
      */}

      <button type="submit" disabled={status === "submitting"}>
        {status === "submitting" ? "Sending…" : "Send"}
      </button>

      {status === "error" && error && (
        <p role="alert" style={{ color: "crimson" }}>{error}</p>
      )}
    </form>
  );
}
