// Demo request modal — hooked to /api/demo (Resend backend)
function Waitlist({ lang }) {
  const [open, setOpen] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [pending, setPending] = React.useState(false);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const handler = (e) => {
      const a = e.target.closest && e.target.closest('a[href="#demo"], button[data-waitlist]');
      if (!a) return;
      e.preventDefault();
      setOpen(true);
      setSubmitted(false);
      setError(null);
    };
    document.addEventListener("click", handler);
    const esc = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", esc);
    return () => {
      document.removeEventListener("click", handler);
      document.removeEventListener("keydown", esc);
    };
  }, []);

  if (!open) return null;
  const tr = lang === "tr";

  const onSubmit = async (e) => {
    e.preventDefault();
    if (pending) return;
    setError(null);
    setPending(true);

    const fd = new FormData(e.currentTarget);
    const payload = {
      name: fd.get("name") || "",
      company: fd.get("company") || "",
      email: fd.get("email") || "",
      message: fd.get("message") || "",
    };

    try {
      const res = await fetch("/api/demo", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success) {
        setSubmitted(true);
      } else {
        setError(
          data.error ||
            (tr
              ? "Talep iletilemedi. Lütfen info@grendex.co adresine yazın."
              : "We couldn't deliver your request. Please email info@grendex.co.")
        );
      }
    } catch {
      setError(
        tr
          ? "Bağlantı hatası. Lütfen tekrar deneyin."
          : "Network error. Please try again."
      );
    } finally {
      setPending(false);
    }
  };

  return (
    <div role="dialog" aria-modal="true" onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      style={{
        position: "fixed", inset: 0, zIndex: 1000,
        background: "rgba(20,20,15,0.45)",
        display: "grid", placeItems: "center", padding: 24,
        animation: "wlfade .18s ease-out",
      }}>
      <style>{`@keyframes wlfade { from { opacity: 0 } to { opacity: 1 } } @keyframes wlpop { from { transform: translateY(8px) scale(.98); opacity: 0 } to { transform: none; opacity: 1 } }`}</style>
      <div style={{
        background: "var(--paper)", border: "1px solid var(--rule)", borderRadius: 12,
        width: "100%", maxWidth: 520, padding: 32,
        boxShadow: "0 30px 80px -20px rgba(20,20,15,0.5)",
        animation: "wlpop .22s ease-out",
        position: "relative",
      }}>
        <button onClick={() => setOpen(false)} aria-label="Close"
          style={{
            position: "absolute", top: 14, right: 14,
            width: 28, height: 28, borderRadius: 6,
            border: "1px solid var(--rule)", background: "transparent",
            color: "var(--ink-3)", fontSize: 14, lineHeight: 1,
          }}>×</button>

        {!submitted ? (
          <>
            <div className="mono" style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 10 }}>
              {tr ? "DEMO TALEBİ" : "REQUEST DEMO"}
            </div>
            <h3 className="serif" style={{ fontSize: 32, lineHeight: 1.1, letterSpacing: "-0.02em", margin: "0 0 8px", fontWeight: 400 }}>
              {tr ? "Demo talep edin" : "Request a demo"}
            </h3>
            <p style={{ fontSize: 14, color: "var(--ink-3)", lineHeight: 1.55, margin: "0 0 22px", textWrap: "pretty" }}>
              {tr
                ? "Formu doldurun, ekibimiz 24 saat içinde sizinle iletişime geçsin."
                : "Fill in the form and our team will reach out within 24 hours."}
            </p>

            {error && (
              <div style={{
                marginBottom: 16,
                padding: "10px 12px",
                border: "1px solid color-mix(in srgb, var(--accent) 35%, transparent)",
                background: "color-mix(in srgb, var(--accent) 8%, transparent)",
                color: "var(--ink-2)",
                borderRadius: 6,
                fontSize: 13,
                lineHeight: 1.5,
              }}>
                {error}
              </div>
            )}

            <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <Field label={tr ? "İsim Soyisim" : "Full name"} required>
                <input type="text" name="name" required placeholder={tr ? "Adınız Soyadınız" : "Your name"}
                  style={inputStyle}/>
              </Field>
              <Field label={tr ? "Kurum" : "Company"}>
                <input type="text" name="company" placeholder={tr ? "Banka / Şirket" : "Bank / Company"}
                  style={inputStyle}/>
              </Field>
              <Field label={tr ? "Kurumsal e-posta" : "Work email"} required>
                <input type="email" name="email" required placeholder="ad@sirket.com"
                  style={inputStyle}/>
              </Field>
              <Field label={tr ? "Mesaj (opsiyonel)" : "Message (optional)"}>
                <textarea name="message" rows={3}
                  placeholder={tr
                    ? "Hangi modüller ilginizi çekiyor? Portföy büyüklüğünüz?"
                    : "Which modules interest you? Portfolio size?"}
                  style={{ ...inputStyle, resize: "vertical", minHeight: 80, fontFamily: "inherit" }}/>
              </Field>
              <button type="submit" disabled={pending} className="btn" style={{
                marginTop: 6, alignSelf: "flex-start",
                opacity: pending ? 0.6 : 1,
                cursor: pending ? "not-allowed" : "pointer",
              }}>
                {pending
                  ? (tr ? "Gönderiliyor..." : "Sending...")
                  : (tr ? "Demo talep et" : "Request demo")}{" "}
                <span aria-hidden>→</span>
              </button>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.04em", marginTop: 4, lineHeight: 1.5 }}>
                {tr
                  ? "Bilgileriniz KVKK kapsamında işlenir, üçüncü taraflarla paylaşılmaz."
                  : "Your data is processed per KVKK and never shared with third parties."}
              </div>
            </form>
          </>
        ) : (
          <>
            <div className="mono" style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 10 }}>
              {tr ? "ALINDI" : "RECEIVED"}
            </div>
            <h3 className="serif" style={{ fontSize: 32, lineHeight: 1.1, letterSpacing: "-0.02em", margin: "0 0 12px", fontWeight: 400 }}>
              {tr ? "Teşekkürler." : "Thank you."}
            </h3>
            <p style={{ fontSize: 14, color: "var(--ink-3)", lineHeight: 1.55, margin: "0 0 22px" }}>
              {tr
                ? "Demo talebinizi aldık. Ekibimiz 24 saat içinde size dönüş yapacak."
                : "We received your demo request. Our team will reach out within 24 hours."}
            </p>
            <button onClick={() => setOpen(false)} className="btn">{tr ? "Kapat" : "Close"}</button>
          </>
        )}
      </div>
    </div>
  );
}

const inputStyle = {
  width: "100%", padding: "11px 14px",
  border: "1px solid var(--rule)", borderRadius: 6,
  background: "var(--bg)", color: "var(--ink)",
  fontSize: 14, fontFamily: "inherit", outline: "none",
};

function Field({ label, required, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3)" }}>
        {label}{required && <span style={{ color: "var(--accent)" }}> *</span>}
      </span>
      {children}
    </label>
  );
}

window.Waitlist = Waitlist;
