"use client";

import { useEffect, useState } from "react";
import { formDataToObject, useFormSubmit } from "@/lib/forms";

export interface WaitlistText {
  emailPlaceholder: string;
  statePlaceholder: string;
  submitLabel: string;
  successText: string;
  source: string;
}

/**
 * Email (+ optional state) waitlist form. Posts to the CMS form given by
 * `formKey` (default "waitlist"); `source` records which page/section it came
 * from. `fixedState` hides the state box and sends that state instead.
 * Listens for "msc:waitlist-state" so the states grid can prefill the state.
 */
export default function WaitlistForm({
  formKey,
  text,
  fixedState,
  hideState,
  className = "waitlist-form",
  successClassName = "form-success",
  successStyle
}: {
  formKey: string;
  text: WaitlistText;
  fixedState?: string;
  hideState?: boolean;
  className?: string;
  successClassName?: string;
  successStyle?: React.CSSProperties;
}) {
  const { state, error, send } = useFormSubmit(formKey);
  const [stateValue, setStateValue] = useState("");

  useEffect(() => {
    const on = (e: Event) => setStateValue(String((e as CustomEvent).detail || ""));
    window.addEventListener("msc:waitlist-state", on);
    return () => window.removeEventListener("msc:waitlist-state", on);
  }, []);

  if (state === "done") {
    return (
      <div className={successClassName} style={{ display: "block", ...successStyle }}>
        {text.successText}
      </div>
    );
  }

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = formDataToObject(e.currentTarget);
    if (data._hp) return; // honeypot
    delete data._hp;
    await send({ ...data, ...(fixedState ? { state: fixedState } : {}), source: text.source });
  };

  return (
    <>
      <form className={className} onSubmit={onSubmit}>
        <input type="text" name="_hp" tabIndex={-1} autoComplete="off" style={{ position: "absolute", left: -9999 }} aria-hidden="true" />
        <input type="email" name="email" placeholder={text.emailPlaceholder} required />
        {!fixedState && !hideState && (
          <input
            type="text"
            name="state"
            placeholder={text.statePlaceholder}
            value={stateValue}
            onChange={(e) => setStateValue(e.target.value)}
            required
          />
        )}
        <button type="submit" disabled={state === "sending"}>
          {state === "sending" ? "Sending…" : text.submitLabel}
        </button>
      </form>
      {state === "error" && <p className="msc-form-error">{error}</p>}
    </>
  );
}
