/* global React */
const { useState: useRF } = React;

/* =========================================================================
   RequestForm — shared lead-capture modal for gated downloads + (later) the
   configurator Revit request. Route B (form service): posts to Web3Forms,
   which emails the submission (and any attachment) to OFFICE_EMAIL.

   ── SETUP (one place) ──────────────────────────────────────────────────
   WEB3FORMS_KEY: paste the access key from web3forms.com (free; sign up with
   contact@derlotgroup.com). Until it's set, the form falls back to opening a
   pre-filled email to OFFICE_EMAIL so nothing is lost. Your developer can
   also point REQUEST_ENDPOINT at their own handler/CRM later.
   ========================================================================= */
// Credentials live in one shared place — src/data/forms-config.js (window.DERLOT_FORMS).
const _CFG = (typeof window !== "undefined" && window.DERLOT_FORMS) || {};
const REQUEST_ENDPOINT = _CFG.ENDPOINT     || "https://api.web3forms.com/submit";
const WEB3FORMS_KEY     = _CFG.WEB3FORMS_KEY || "";
const OFFICE_EMAIL      = _CFG.OFFICE_EMAIL || "contact@derlotgroup.com";
const PRIVACY_URL       = "/policy/privacy";  // opens the Privacy page in a new tab

const ROLES = ["Architect", "Interior Designer", "Specifier", "Builder / Contractor", "Developer", "Other"];
const COUNTRIES = ["Australia", "New Zealand", "United States", "Canada", "United Kingdom", "Ireland",
  "France", "Germany", "Netherlands", "United Arab Emirates", "Saudi Arabia", "Singapore", "Hong Kong",
  "Japan", "China", "India", "Other"];

const INK = "#1a1917", STONE = "#6c6862", RULE = "rgba(26,25,23,0.22)", BONE = "#f5f3ef";

function RequestForm({ context, onClose }) {
  // context: { kind:"file"|"revit", label, scope, format, attachment? }
  const ctx = context || { kind: "file", label: "Derlot resources" };
  const [f, setF] = useRF({ firstName: "", lastName: "", email: "", company: "", role: "", country: "", project: "", consent: false, marketing: false, hp: "" });
  const [status, setStatus] = useRF("idle");  // idle | sending | sent | error
  const [err, setErr] = useRF("");
  const set = (k) => (e) => { const v = e.target.type === "checkbox" ? e.target.checked : e.target.value; setF(p => ({ ...p, [k]: v })); };

  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email);
  const valid = f.firstName.trim() && f.lastName.trim() && emailOk && f.company.trim() && f.country && f.consent;

  async function submit(e) {
    e.preventDefault();
    if (f.hp) return;                          // honeypot — silently drop bots
    if (!valid) { setErr("Please complete the required fields and accept the privacy policy."); return; }
    setErr(""); setStatus("sending");

    const title = (ctx.kind === "revit" ? "Revit request" : "File request") + " — " + ctx.label;
    try { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: "request_submit", request_type: ctx.kind, requested: ctx.label }); } catch (_) {}

    const payload = {
      access_key: WEB3FORMS_KEY,
      subject: "Derlot — " + title,
      from_name: (f.firstName + " " + f.lastName).trim(),
      first_name: f.firstName, last_name: f.lastName, email: f.email, company: f.company,
      role: f.role || "—", country: f.country, project: f.project || "—",
      request_type: ctx.kind, requested: ctx.label, scope: ctx.scope || "—", format: ctx.format || "—",
      marketing_opt_in: f.marketing ? "Yes" : "No",
    };
    if (ctx.attachment) { payload.attachment = ctx.attachment; }   // configurator PDF (Part 2)

    if (WEB3FORMS_KEY) {
      try {
        const r = await fetch(REQUEST_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(payload) });
        const j = await r.json().catch(() => ({}));
        if (j && j.success) { setStatus("sent"); }
        else { setErr((j && j.message) || "Something went wrong. Please email " + OFFICE_EMAIL + "."); setStatus("error"); }
      } catch (_) { setErr("Network error — please email " + OFFICE_EMAIL + "."); setStatus("error"); }
    } else {
      // Fallback until the key is set: open a pre-filled email so nothing is lost.
      // Use a transient anchor (not location.href) so the SPA stays mounted and
      // the confirmation renders even as the mail client opens.
      const body = ["Name: " + payload.from_name, "Email: " + f.email, "Company: " + f.company,
        "Role: " + payload.role, "Country: " + f.country, "Project: " + payload.project,
        "Requested: " + ctx.label, "Marketing opt-in: " + payload.marketing_opt_in].join("\n");
      try {
        const a = document.createElement("a");
        a.href = "mailto:" + OFFICE_EMAIL + "?subject=" + encodeURIComponent(payload.subject) + "&body=" + encodeURIComponent(body);
        a.style.display = "none";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (_) { /* no mail handler — submission already logged to dataLayer */ }
      setStatus("sent");
    }
  }

  const field = { fontFamily: "inherit", fontSize: 14, color: INK, background: "#fff", border: "0.5px solid " + RULE, borderRadius: 0, padding: "11px 12px", width: "100%", outline: "none" };
  const labelS = { fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: STONE, fontWeight: 500, marginBottom: 6, display: "block" };
  const Group = ({ label, req, children }) => (
    <label style={{ display: "block" }}><span style={labelS}>{label}{req && <span style={{ color: INK }}> *</span>}</span>{children}</label>
  );

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(26,25,23,0.45)", zIndex: 1000, display: "flex", alignItems: "flex-start", justifyContent: "center", overflowY: "auto", padding: "5vh 16px" }}>
      <div onClick={e => e.stopPropagation()} style={{ background: BONE, width: "100%", maxWidth: 520, padding: "32px 32px 36px", position: "relative", boxShadow: "0 24px 60px rgba(0,0,0,0.25)" }}>
        <button onClick={onClose} aria-label="Close" style={{ position: "absolute", top: 18, right: 18, background: "transparent", border: "none", fontSize: 22, lineHeight: 1, color: INK, cursor: "pointer" }}>×</button>

        {status === "sent" ? (
          <div>
            <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: STONE, fontWeight: 500 }}>{ctx.kind === "revit" ? "Revit request" : "Request received"}</div>
            <h2 style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.015em", margin: "10px 0 12px", lineHeight: 1.15 }}>Thank you.</h2>
            <p style={{ fontSize: 14, color: STONE, lineHeight: 1.55 }}>Your request is with our team. Files and Revit models are sent from {OFFICE_EMAIL}, usually within one business day.</p>
            <button onClick={onClose} style={{ marginTop: 22, fontFamily: "inherit", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 500, color: INK, background: "transparent", border: "0.5px solid " + INK, borderRadius: 0, padding: "10px 18px", cursor: "pointer" }}>Close</button>
          </div>
        ) : (
          <form onSubmit={submit}>
            <div style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: STONE, fontWeight: 500 }}>{ctx.kind === "revit" ? "Request Revit model" : "Request files"}</div>
            <h2 style={{ fontSize: 21, fontWeight: 500, letterSpacing: "-0.015em", margin: "8px 0 6px", lineHeight: 1.15 }}>{ctx.label}</h2>
            <p style={{ fontSize: 13, color: STONE, lineHeight: 1.5, marginBottom: 22 }}>A few details and the files are yours — we use them only to share resources and respond to your enquiry.</p>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Group label="First name" req><input style={field} value={f.firstName} onChange={set("firstName")} autoComplete="given-name" /></Group>
              <Group label="Last name" req><input style={field} value={f.lastName} onChange={set("lastName")} autoComplete="family-name" /></Group>
            </div>
            <div style={{ marginBottom: 14 }}><Group label="Work email" req><input type="email" style={field} value={f.email} onChange={set("email")} autoComplete="email" /></Group></div>
            <div style={{ marginBottom: 14 }}><Group label="Company / Firm" req><input style={field} value={f.company} onChange={set("company")} autoComplete="organization" /></Group></div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
              <Group label="Role"><select style={field} value={f.role} onChange={set("role")}><option value="">Select…</option>{ROLES.map(r => <option key={r} value={r}>{r}</option>)}</select></Group>
              <Group label="Country" req><select style={field} value={f.country} onChange={set("country")}><option value="">Select…</option>{COUNTRIES.map(c => <option key={c} value={c}>{c}</option>)}</select></Group>
            </div>
            <div style={{ marginBottom: 18 }}><Group label="Project name (optional)"><input style={field} value={f.project} onChange={set("project")} /></Group></div>

            {/* honeypot */}
            <input tabIndex={-1} autoComplete="off" value={f.hp} onChange={set("hp")} style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} aria-hidden="true" />

            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12.5, color: STONE, lineHeight: 1.5, marginBottom: 12, cursor: "pointer" }}>
              <input type="checkbox" checked={f.consent} onChange={set("consent")} style={{ marginTop: 2 }} />
              <span>I agree to Derlot storing and using my details to respond to this request, in line with our <a href={PRIVACY_URL} target="_blank" rel="noopener" style={{ color: INK, textDecoration: "underline", textUnderlineOffset: 2 }}>Privacy Policy</a>. <span style={{ color: INK }}>*</span></span>
            </label>
            <label style={{ display: "flex", gap: 10, alignItems: "flex-start", fontSize: 12.5, color: STONE, lineHeight: 1.5, marginBottom: 20, cursor: "pointer" }}>
              <input type="checkbox" checked={f.marketing} onChange={set("marketing")} style={{ marginTop: 2 }} />
              <span>Keep me posted on new collections, projects and specifier resources from Derlot.</span>
            </label>

            {err && <div style={{ fontSize: 12.5, color: "#a3372f", marginBottom: 14 }}>{err}</div>}

            <button type="submit" disabled={status === "sending"} style={{ width: "100%", fontFamily: "inherit", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", fontWeight: 500, color: BONE, background: INK, border: "0.5px solid " + INK, borderRadius: 0, padding: "14px 18px", cursor: status === "sending" ? "default" : "pointer", opacity: status === "sending" ? 0.6 : 1 }}>
              {status === "sending" ? "Sending…" : (ctx.kind === "revit" ? "Send request" : "Request files")}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

window.RequestForm = RequestForm;
