// ContactForm.jsx — shared form used by both the inline section and the modal.
// Pass `presetInterests` to pre-check certain service checkboxes.

const CONTACT_INTERESTS = [
  "AI Email Assistant",
  "AI Phone Assistant",
  "AI Receptionist",
  "AI Paperwork Assistant",
  "AI Fit-Out Session",
  "Custom Build",
];

function ContactForm({ presetInterests = [], compact = false }) {
  useLucide();
  const [form, setForm] = useState({ name: "", phone: "", email: "", interests: presetInterests, message: "" });
  const [errors, setErrors] = useState({});
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  // Allow parent (modal) to push new presets in as it reopens.
  useEffect(() => {
    if (!presetInterests || !presetInterests.length) return;
    setForm((f) => {
      const merged = Array.from(new Set([...(f.interests || []), ...presetInterests]));
      return { ...f, interests: merged };
    });
    setSent(false);
  }, [presetInterests.join("|")]);

  function toggleInterest(label) {
    setForm((f) => ({
      ...f,
      interests: f.interests.includes(label)
        ? f.interests.filter((x) => x !== label)
        : [...f.interests, label],
    }));
  }

  async function submit(e) {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim())  errs.name = "We need a name to call back.";
    if (!form.phone.trim()) errs.phone = "A phone is the quickest way.";
    if (!form.email.trim()) errs.email = "We need an email to reply.";
    else if (!/\S+@\S+\.\S+/.test(form.email)) errs.email = "Doesn't look like an email.";
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    setSubmitError("");
    setSubmitting(true);

    const cfg = window.AF_CONFIG || {};
    const payload = {
      subject: "Webform request",
      name: form.name.trim(),
      phone: form.phone.trim(),
      email: form.email.trim(),
      interests: form.interests.join(", "),
      message: form.message.trim(),
    };

    try {
      const headers = { "Content-Type": "application/json" };
      if (cfg.contactWebhookHeader && cfg.contactWebhookKey) {
        headers[cfg.contactWebhookHeader] = cfg.contactWebhookKey;
      }
      const res = await fetch(cfg.contactWebhookUrl, {
        method: "POST",
        headers,
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Server responded " + res.status);
      setSent(true);
    } catch (err) {
      console.error("Contact form submit failed:", err);
      setSubmitError("Couldn't send just now — give us a call or message on WhatsApp.");
    } finally {
      setSubmitting(false);
    }
  }

  if (sent) {
    return (
      <div style={{
        background: "#fff", borderRadius: compact ? 0 : 20, padding: 40,
        textAlign: "center",
        display: "flex", flexDirection: "column", alignItems: "center", gap: 16,
      }}>
        <div style={{
          width: 64, height: 64, borderRadius: 16, background: "var(--success-bg)",
          color: "var(--success)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>
          <i data-lucide="check" style={{ width: 32, height: 32, strokeWidth: 2.5 }}></i>
        </div>
        <h3 style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.02em",
                     lineHeight: 1.15, margin: 0, color: "var(--ink)" }}>
          Got it. We'll be in touch today.
        </h3>
        <p style={{ fontSize: 15.5, color: "var(--ink-soft)", margin: 0,
                    maxWidth: 420, lineHeight: 1.55 }}>
          We'll reply by email to <span style={{ fontFamily: "var(--font-mono)" }}>{form.email}</span> — usually within a couple of minutes.
        </p>
        <button onClick={() => { setSent(false); setForm({name:"",phone:"",email:"",interests:[],message:""}); }}
          style={{
            marginTop: 8, background: "transparent",
            border: "1px solid var(--line)", borderRadius: 10,
            padding: "10px 16px", fontSize: 14, fontWeight: 600,
            color: "var(--ink)", cursor: "pointer",
          }}>Send another</button>
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="contact-form" style={{
      background: "#fff", borderRadius: compact ? 0 : 20, padding: 32,
      display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18,
      boxSizing: "border-box", width: "100%", maxWidth: "100%",
    }}>
      <div style={{ gridColumn: "1 / -1", marginBottom: 4 }}>
        <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: ".08em",
                      textTransform: "uppercase", color: "var(--muted)",
                      marginBottom: 6 }}>Short form</div>
        <div style={{ fontSize: 18, fontWeight: 700, color: "var(--ink)",
                      letterSpacing: "-0.01em" }}>
          Four fields. We'll do the rest.
        </div>
      </div>

      <Field label="Your name" value={form.name}
             onChange={v => setForm({ ...form, name: v })}
             placeholder="Dave Henderson"
             help={!errors.name && "As your customers know you."}
             error={errors.name} required />
      <Field label="Phone" type="tel" value={form.phone}
             onChange={v => setForm({ ...form, phone: v })}
             placeholder="07XXX XXXXXX"
             help={!errors.phone && "The quickest way to reach you."}
             error={errors.phone} required />
      <div style={{ gridColumn: "1 / -1" }}>
        <Field label="Email" type="email" value={form.email}
               onChange={v => setForm({ ...form, email: v })}
               placeholder="you@business.co.uk"
               help={!errors.email && "We'll send a written summary here."}
               error={errors.email} required />
      </div>

      {/* Interest checkboxes */}
      <div style={{ gridColumn: "1 / -1", marginTop: 4 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)",
                      marginBottom: 12 }}>
          I want to talk about:
        </div>
        <div style={{ display: "grid",
                      gridTemplateColumns: "repeat(2, minmax(0, 1fr))",
                      gap: "10px 16px" }}>
          {CONTACT_INTERESTS.map((label) => {
            const on = form.interests.includes(label);
            return (
              <label key={label} style={{
                display: "flex", alignItems: "center", gap: 10,
                cursor: "pointer", userSelect: "none",
              }}>
                <input type="checkbox" checked={on}
                       onChange={() => toggleInterest(label)}
                       style={{ position: "absolute", opacity: 0, pointerEvents: "none" }} />
                <span style={{
                  width: 18, height: 18, flexShrink: 0,
                  borderRadius: 5,
                  border: on ? "1px solid var(--blue)" : "1px solid var(--line)",
                  background: on ? "var(--blue)" : "#fff",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  color: "#fff",
                  transition: "background .12s, border-color .12s",
                }}>
                  {on && <i data-lucide="check" style={{ width: 12, height: 12, strokeWidth: 3 }}></i>}
                </span>
                <span style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.3 }}>{label}</span>
              </label>
            );
          })}
        </div>
      </div>

      <div style={{ gridColumn: "1 / -1", marginTop: 4 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)",
                      marginBottom: 8 }}>
          Something else:
        </div>
        <Field label="" multiline rows={3}
               value={form.message}
               onChange={v => setForm({ ...form, message: v })}
               placeholder="Quotes are eating my Sundays…" />
      </div>
      <div style={{ gridColumn: "1 / -1", display: "flex",
                    justifyContent: "space-between", alignItems: "center",
                    gap: 16, flexWrap: "wrap", paddingTop: 4 }}>
        <span style={{ fontSize: 12, color: submitError ? "var(--danger)" : "var(--muted)",
                       maxWidth: 320, lineHeight: 1.45 }}>
          {submitError || "We'll only use this to reply. No marketing list."}
        </span>
        <button type="submit" disabled={submitting} style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "12px 20px", borderRadius: 12,
          background: "var(--orange)", color: "#fff",
          fontSize: 15, fontWeight: 600,
          border: "1px solid var(--orange)",
          cursor: submitting ? "wait" : "pointer",
          opacity: submitting ? 0.7 : 1,
          transition: "transform .12s var(--t-ease), opacity .12s",
        }}
          onMouseEnter={e => { if (!submitting) e.currentTarget.style.transform = "translateY(-1px)"; }}
          onMouseLeave={e => e.currentTarget.style.transform = "translateY(0)"}>
          {submitting ? "Sending…" : "Send it over"}
          <i data-lucide={submitting ? "loader" : "arrow-right"}
             style={{ width: 14, height: 14, strokeWidth: 2.25 }}></i>
        </button>
      </div>
    </form>
  );
}

window.ContactForm = ContactForm;
window.CONTACT_INTERESTS = CONTACT_INTERESTS;
