/* global React, useViewport */

function EDM() {
  const vw = useViewport();
  const isMobile = vw < 720;
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");

  const CFG = (typeof window !== "undefined" && window.DERLOT_FORMS) || {};
  const OFFICE = CFG.OFFICE_EMAIL || "contact@derlotgroup.com";

  async function subscribe(e) {
    e.preventDefault();
    if (busy) return;
    const email = (new FormData(e.target).get("email") || "").toString().trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return;
    try { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: "journal_subscribe" }); } catch (_) {}
    setErr(""); setBusy(true);
    // Capture the lead via Formspree (same AJAX contract as the other Derlot
    // forms): POST { email } to https://formspree.io/f/<id> with Accept JSON.
    // Submissions collect in the Formspree dashboard and export to CSV for the
    // CRM. The form id is public-by-design, so no server function is needed.
    const FORM_ID = (CFG.FORMSPREE && CFG.FORMSPREE.newsletter) || "";
    if (FORM_ID) {
      try {
        const r = await fetch((CFG.FORMSPREE_ENDPOINT || "https://formspree.io/f/") + FORM_ID, {
          method: "POST",
          headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify({ email, _subject: "Website Subscription" }),
        });
        if (r.ok) { setBusy(false); setSent(true); return; }
        const j = await r.json().catch(() => ({}));
        const msg = (j && Array.isArray(j.errors) && j.errors[0] && j.errors[0].message) || "Couldn't subscribe — please try again.";
        setBusy(false); setErr(msg);
        return;
      } catch (_) { /* network error — fall through to email so the lead isn't lost */ }
    }
    // Fallback: open a pre-filled email so a lead is never lost.
    try {
      const a = document.createElement("a");
      a.href = "mailto:" + OFFICE + "?subject=" + encodeURIComponent("Website Subscription") + "&body=" + encodeURIComponent("Please add to the Journal list: " + email);
      a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a);
    } catch (_) { /* no-op */ }
    setBusy(false); setSent(true);
  }

  return (
    <section style={{ padding: isMobile ? "96px 20px" : "160px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto", borderTop: "0.5px solid rgba(26,25,23,0.18)" }}>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 32 : 80, alignItems: isMobile ? "flex-start" : "end" }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 14 }}>Journal</div>
          <h2 style={{ fontSize: isMobile ? 18 : 20, lineHeight: 1.3, letterSpacing: "-0.005em", color: "#1a1917", margin: 0, maxWidth: "30ch", fontWeight: 400 }}>
            Project releases, new collections, material studies.
          </h2>
          <p style={{ fontSize: isMobile ? 14 : 14, lineHeight: 1.55, color: "#6c6862", fontWeight: 400, maxWidth: "44ch", margin: "12px 0 0 0" }}>
            Considered updates, quarterly. No marketing filler.
          </p>
        </div>
        {sent ? (
          <div style={{ borderBottom: "0.5px solid #1a1917", padding: "14px 0", fontFamily: "Poppins", fontSize: 15, color: "#1a1917" }}>
            Thank you — you're on the list.
          </div>
        ) : (
          <div>
            <form onSubmit={subscribe} style={{ display: "flex", gap: 0, borderBottom: "0.5px solid #1a1917", alignItems: "center" }}>
              <input name="email" type="email" required placeholder="you@firm.com" autoComplete="email" style={{ flex: 1, background: "transparent", border: 0, padding: "14px 0", fontFamily: "Poppins", fontSize: 16, color: "#1a1917", outline: "none" }} />
              <button type="submit" disabled={busy} style={{ background: "transparent", color: "#1a1917", border: 0, padding: "14px 0 14px 16px", fontFamily: "Poppins", fontSize: 12, fontWeight: 500, letterSpacing: "0.12em", textTransform: "uppercase", cursor: busy ? "default" : "pointer", whiteSpace: "nowrap", opacity: busy ? 0.6 : 1 }}>{busy ? "Sending…" : "Subscribe →"}</button>
            </form>
            {err && <div style={{ marginTop: 10, fontSize: 13, color: "#9a2f2f" }} role="alert">{err}</div>}
          </div>
        )}
      </div>
    </section>
  );
}

window.EDM = EDM;
