/* Early-access modal — opens via window.openEarlyAccess() */

const { useState, useEffect, useRef } = React;

function EarlyAccessModal() {
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState("");
  const [context, setContext] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [touched, setTouched] = useState(false);
  const [networkError, setNetworkError] = useState("");
  const inputRef = useRef(null);

  useEffect(() => {
    window.openEarlyAccess = () => { setSubmitted(false); setTouched(false); setNetworkError(""); setOpen(true); };
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
      return () => { document.body.style.overflow = ""; clearTimeout(t); };
    }
  }, [open, submitted]);

  const valid = /^\S+@\S+\.\S+$/.test(email.trim());

  const FORMSPREE_ENDPOINT = "https://formspree.io/f/maqkvlzk";

  async function submit(e) {
    e.preventDefault();
    setTouched(true);
    setNetworkError("");
    if (!valid || submitting) return;
    setSubmitting(true);
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          email: email.trim(),
          building: context.trim(),
          _subject: "Audia early access request",
          source: "audia.ai landing — early-access modal",
        }),
      });
      if (!res.ok) {
        let msg = "Couldn't send right now. Try again in a moment?";
        try {
          const data = await res.json();
          if (data && data.errors && data.errors.length) {
            msg = data.errors.map((er) => er.message).join(" ");
          }
        } catch (_) {}
        setNetworkError(msg);
        setSubmitting(false);
        return;
      }
      // Backup copy locally in case we ever need it client-side
      try {
        const list = JSON.parse(localStorage.getItem("audia_waitlist") || "[]");
        list.push({ email: email.trim(), context: context.trim(), ts: Date.now() });
        localStorage.setItem("audia_waitlist", JSON.stringify(list));
      } catch (_) {}
      setSubmitted(true);
    } catch (err) {
      setNetworkError("Network hiccup — check your connection and try again.");
    } finally {
      setSubmitting(false);
    }
  }

  function close() {
    setOpen(false);
    setTimeout(() => {
      setEmail(""); setContext(""); setSubmitted(false);
      setTouched(false); setSubmitting(false); setNetworkError("");
    }, 220);
  }

  if (!open) return null;

  return (
    <div className="ea-backdrop" onClick={close} role="dialog" aria-modal="true" aria-label="Request early access">
      <div className="ea-card" onClick={(e) => e.stopPropagation()}>
        <button type="button" className="ea-close" onClick={close} aria-label="Close">
          <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
            <path d="M2 2 L10 10 M10 2 L2 10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
          </svg>
        </button>

        {!submitted ? (
          <React.Fragment>
            <div className="ea-eyebrow"><span className="ea-pulse"/>Early access</div>
            <h2 className="ea-title">Get on the list.</h2>
            <p className="ea-sub">
              We're admitting voice teams in small batches. Drop your email and a note on what you're running.
            </p>

            <form className="ea-form" onSubmit={submit} noValidate>
              <label className="ea-label" htmlFor="ea-email">Email</label>
              <input
                id="ea-email"
                ref={inputRef}
                className={"ea-input" + (touched && !valid ? " invalid" : "")}
                type="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                onBlur={() => setTouched(true)}
                placeholder="you@company.com"
                autoComplete="email"
                spellCheck="false"
              />
              {touched && !valid && (
                <span className="ea-error">Enter a valid email so we can route your request.</span>
              )}

              <label className="ea-label" htmlFor="ea-ctx">
                What are you running? <span className="ea-opt">optional</span>
              </label>
              <input
                id="ea-ctx"
                className="ea-input"
                type="text"
                value={context}
                onChange={(e) => setContext(e.target.value)}
                placeholder="e.g. Vapi · 12K calls/day · healthcare intake"
                autoComplete="off"
              />

              <button type="submit" className="ea-submit" disabled={submitting} aria-busy={submitting}>
                {submitting ? (
                  <span className="ea-submit-inner">
                    <span className="ea-spinner" aria-hidden="true"/>
                    Sending…
                  </span>
                ) : "Request access"}
              </button>
              {networkError && <span className="ea-error ea-error-net">{networkError}</span>}
            </form>
          </React.Fragment>
        ) : (
          <div className="ea-success">
            <div className="ea-check" aria-hidden="true">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <circle cx="11" cy="11" r="10" stroke="currentColor" strokeWidth="1.1" opacity=".28"/>
                <path d="M6 11.5 L9.5 15 L16 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <div className="ea-eyebrow"><span className="ea-pulse"/>Confirmed</div>
            <h2 className="ea-title">You're on the list.</h2>
            <p className="ea-sub">
              We'll reach out at <span className="ea-email-echo">{email.trim()}</span> within 1-2 days.
            </p>
            <button type="button" className="ea-submit" onClick={close}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { EarlyAccessModal });
