/* global React, useViewport */

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

  // Credentials from the shared config (src/data/forms-config.js).
  const CFG = (typeof window !== "undefined" && window.DERLOT_FORMS) || {};
  const OFFICE = CFG.OFFICE_EMAIL || "contact@derlotgroup.com";

  async function handleSubmit(e) {
    e.preventDefault();
    if (busy) return;
    const fd = new FormData(e.target);
    const get = (k) => (fd.get(k) || "").toString().trim();
    // Honeypot — bots fill the hidden field; treat as a silent success.
    if (get("_gotcha")) { setSent(true); return; }
    const payload = {
      name: get("name"), firm: get("firm"), email: get("email"),
      project: get("project"), brief: get("brief"),
    };
    try { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: "enquiry_submit", collection }); } catch (_) {}
    setErr(""); setBusy(true);

    // Subject is a clean, consistent "Derlot Enquiry"; the collection and
    // project still travel in the body fields below for the team's context.
    const subject = "Derlot Enquiry";
    // Formspree AJAX submission. Special fields: _subject sets the email
    // subject; `email` becomes the reply-to. No _cc: the Formspree dashboard's
    // primary recipient is already contact@derlotgroup.com, and CC-ing the same
    // address makes Formspree reject the submission as a duplicate recipient.
    const formId = (CFG.FORMSPREE && CFG.FORMSPREE.enquiry) || "";
    if (formId) {
      try {
        const r = await fetch((CFG.FORMSPREE_ENDPOINT || "https://formspree.io/f/") + formId, {
          method: "POST",
          headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify({
            _subject: subject,
            name: payload.name,
            firm: payload.firm || "—",
            email: payload.email,
            project: payload.project || "—",
            collection,
            brief: payload.brief || "—",
          }),
        });
        if (r.ok) { setBusy(false); setSent(true); return; }
        // Formspree returns { errors: [{ field, message }] } on validation/form
        // errors — surface them and let the user fix and retry.
        const j = await r.json().catch(() => ({}));
        const msg = (j && Array.isArray(j.errors) && j.errors.map((x) => x && x.message).filter(Boolean).join(", "))
          || (j && j.error) || "Something went wrong. Please try again, or email us directly.";
        setBusy(false); setErr(msg); return;
      } catch (_) { /* network error — fall through to email so nothing is lost */ }
    }
    // Fallback: open a pre-filled email so nothing is lost.
    const body = ["Name: " + payload.name, "Firm: " + payload.firm, "Email: " + payload.email,
      "Project: " + payload.project, "Collection: " + collection, "", payload.brief].join("\n");
    try {
      const a = document.createElement("a");
      a.href = "mailto:" + OFFICE + "?subject=" + encodeURIComponent(subject) + "&body=" + encodeURIComponent(body);
      a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a);
    } catch (_) { /* no mail handler — already logged to dataLayer */ }
    setBusy(false); setSent(true);
  }
  const inputStyle = {
    width: "100%", background: "transparent", border: 0,
    borderBottom: "0.5px solid #1a1917",
    padding: "12px 0", fontFamily: "Poppins", fontSize: 16, color: "#1a1917", outline: "none",
  };
  const labelStyle = { fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 8, display: "block" };

  if (sent) {
    return (
      <section style={{ padding: "160px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 20 }}>Enquiry received</div>
        <h2 style={{ fontWeight: 500, fontSize: "clamp(28px, 3vw, 44px)", lineHeight: 1.1, letterSpacing: "-0.02em", color: "#1a1917", margin: 0, maxWidth: "20ch" }}>
          Thank you. A member of the Derlot team will be in touch within one business day.
        </h2>
      </section>
    );
  }

  return (
    <section id="enquire" style={{ padding: isMobile ? "72px 20px" : "120px max(24px, 3vw)", maxWidth: 1440, margin: "0 auto", scrollMarginTop: 80 }}>
      <div style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "#6c6862", fontWeight: 500, marginBottom: 14 }}>Enquire</div>
      <h2 style={{ fontWeight: 500, fontSize: isMobile ? "clamp(26px, 6vw, 32px)" : "clamp(30px, 3vw, 48px)", lineHeight: 1.02, letterSpacing: "-0.02em", color: "#1a1917", margin: isMobile ? "0 0 20px 0" : "0 0 28px 0", maxWidth: "14ch" }}>
        Specify {collection} for your project.
      </h2>
      <p style={{ fontSize: isMobile ? 15 : 17, lineHeight: 1.5, color: "#1a1917", fontWeight: 400, maxWidth: "58ch", margin: isMobile ? "0 0 32px 0" : "0 0 56px 0" }}>
        Tell us about the project. A member of the Derlot team will respond with drawings, finish libraries, and a tailored proposal.
      </p>
      <form onSubmit={handleSubmit} style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? "28px 0" : "40px 32px", maxWidth: 900 }}>
        {/* Honeypot — hidden from users, catches bots. */}
        <input type="text" name="_gotcha" tabIndex={-1} autoComplete="off" aria-hidden="true"
          style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0, pointerEvents: "none" }} />
        <label><div style={labelStyle}>Name</div><input name="name" required style={inputStyle} defaultValue="" autoComplete="name" /></label>
        <label><div style={labelStyle}>Firm</div><input name="firm" style={inputStyle} defaultValue="" autoComplete="organization" /></label>
        <label><div style={labelStyle}>Email</div><input name="email" type="email" required style={inputStyle} defaultValue="" autoComplete="email" /></label>
        <label><div style={labelStyle}>Project</div><input name="project" style={inputStyle} defaultValue="" /></label>
        <label style={{ gridColumn: "1 / -1" }}>
          <div style={labelStyle}>Brief</div>
          <textarea name="brief" rows={3} style={{ ...inputStyle, resize: "vertical", fontFamily: "Poppins" }} defaultValue="" />
        </label>
        {err && (
          <div style={{ gridColumn: "1 / -1", fontSize: 13, color: "#9a2f2f", letterSpacing: "0.01em" }} role="alert">
            {err}
          </div>
        )}
        <div style={{ gridColumn: "1 / -1", display: "flex", flexDirection: isMobile ? "column" : "row", justifyContent: "space-between", alignItems: isMobile ? "flex-start" : "center", gap: isMobile ? 16 : 0, marginTop: 8 }}>
          <div style={{ fontSize: 12, color: "#6c6862", letterSpacing: "0.02em" }}>For architects, designers and end users · response within 24 hours</div>
          <button type="submit" disabled={busy} style={{ background: "#1a1917", color: "#f5f3ef", border: 0, padding: "16px 28px", fontFamily: "Poppins", fontSize: 13, fontWeight: 500, letterSpacing: "0.08em", textTransform: "uppercase", cursor: busy ? "default" : "pointer", opacity: busy ? 0.6 : 1 }}>
            {busy ? "Sending…" : "Send enquiry"}
          </button>
        </div>
      </form>
    </section>
  );
}

window.EnquiryBlock = EnquiryBlock;
