"use server";

export type SubscribeState = {
  status: "idle" | "success" | "error";
  message: string;
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export async function subscribe(
  _prev: SubscribeState,
  formData: FormData,
): Promise<SubscribeState> {
  const email = String(formData.get("email") ?? "").trim();
  const honeypot = String(formData.get("website") ?? "");

  if (honeypot) {
    return { status: "success", message: "Thanks — we'll keep you posted." };
  }

  if (!email || !EMAIL_RE.test(email)) {
    return {
      status: "error",
      message: "Please enter a valid email address.",
    };
  }

  // TODO: wire to a real provider (Buttondown, ConvertKit, Mailchimp, Resend Audiences).
  // For now we just log the signup so you can collect addresses from server logs.
  console.log(`[newsletter] new signup: ${email}`);

  return {
    status: "success",
    message: "Welcome to the climb. Check your inbox soon.",
  };
}
