// inquiry-form.jsx — Hale Lumina lead intake form.
// Progressive enhancement: Inquiry.html ships a working native <form> inside
// #root; on mount React replaces it with this enhanced version (inline
// validation, honeypot + min-time spam gate, fetch with REAL success/error,
// no page navigation). Posts JSON to the same-origin /api/inquiry function,
// which forwards server-to-side to the GoHighLevel inbound webhook.

const { useState: inqUseState, useRef: inqUseRef, useEffect: inqFormUseEffect } = React;

// Option values are BYTE-IDENTICAL to the existing GHL custom-field picklists.
// Do not "tidy" the spacing — an unmatched string is silently dropped by the
// GHL inbound-webhook field mapping.
const REL_OPTIONS = ["Homeowner", "Architect", "Designer", "Contractor", "Developer"];
const PHASE_OPTIONS = [
  "Planning & Design", "Waiting On Permit", "Permit has been issued", "Dirt Work",
  "Foundation", "Framing", "Rough-In", "Drywall & Paint", "Finish/Install", "Finishing Touches",
];
const LIGHTING_OPTIONS = [
  "Lighting layout & design", "Fixture selection", "Fixture supply", "Recessed lighting",
  "LED tape lighting", "Ceiling fans", "Landscape lighting", "Decorative lighting", "All of the above",
];
const BUDGET_OPTIONS = [
  "$0- $10,000", "$10,000-$25,000", "$25,000- $50,000", "$50,000- $100,000",
  "$100,000- $200,000", "$200,000-$500,000", "$500,000+",
];
const DRAWINGS_OPTIONS = ["Yes", "No", "Working On It"];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function InquiryForm() {
  const [form, setForm] = inqUseState({
    first_name: "", last_name: "", email: "", phone: "",
    your_relationship_with_the_project: "",
    your_projects_current_build_phase: "",
    your_lightning_needs: [],
    project_budget: "",
    do_you_have_construction_drawings: "",
    message: "",
    company: "", // honeypot
  });
  const [errors, setErrors] = inqUseState({});
  const [status, setStatus] = inqUseState("idle"); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = inqUseState("");
  const mountedAt = inqUseRef(0);

  inqFormUseEffect(() => { mountedAt.current = Date.now(); }, []);

  const set = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((e) => ({ ...e, [k]: undefined }));
  };

  const toggleLighting = (val) => {
    setForm((f) => {
      const has = f.your_lightning_needs.includes(val);
      return { ...f, your_lightning_needs: has
        ? f.your_lightning_needs.filter((x) => x !== val)
        : [...f.your_lightning_needs, val] };
    });
  };

  const validate = () => {
    const e = {};
    if (!form.first_name.trim()) e.first_name = "Required";
    if (!form.last_name.trim()) e.last_name = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!EMAIL_RE.test(form.email.trim())) e.email = "Enter a valid email";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    if (status === "sending") return;
    if (!validate()) return;

    setStatus("sending");
    setErrorMsg("");

    const payload = {
      ...form,
      // join multi-select to a comma string — most compatible with GHL
      // CHECKBOX field mapping (the array is also sent for flexibility).
      your_lightning_needs: form.your_lightning_needs.join(", "),
      lighting_needs_list: form.your_lightning_needs,
      source: "halelumina.com intake form",
      submitted_at: new Date().toISOString(),
      _ts: mountedAt.current,
    };

    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (res.ok) {
        setStatus("success");
        if (typeof window !== "undefined" && window.scrollTo) window.scrollTo({ top: 0, behavior: "smooth" });
      } else {
        const data = await res.json().catch(() => ({}));
        throw new Error(data && data.error ? data.error : "Request failed (" + res.status + ")");
      }
    } catch (err) {
      setStatus("error");
      setErrorMsg(
        "We couldn't send your inquiry just now. Please email us directly at hello@halelumina.com and we'll respond personally."
      );
    }
  };

  if (status === "success") {
    return (
      <div className="inq-main">
        <div className="inq-success" data-reveal>
          <span className="label">Inquiry Received</span>
          <h2>Thank you — your inquiry is <em>in our hands.</em></h2>
          <p>
            We review every inquiry personally and will reply within about two business days.
            A confirmation is on its way to <b>{form.email}</b>. In the meantime, you're welcome to
            explore our selected work.
          </p>
          <div className="inq-next">
            <a className="btn btn-primary" href="Portfolio.html">View Selected Work <span className="arrow">→</span></a>
          </div>
          <p className="inq-foothint" style={{ marginTop: 34 }}>
            <a href="Home.html">Return to halelumina.com</a>
          </p>
        </div>
      </div>
    );
  }

  const sending = status === "sending";

  return (
    <div className="inq-main">
      <div className="inq-head">
        <a href="Home.html" className="label" style={{ textDecoration: "none" }}>← Hale Lumina</a>
        <h1>Begin a <em>consultation.</em></h1>
        <p>Tell us about your residence and your goals. We review every inquiry personally and reply within about two business days.</p>
      </div>

      <form className="inq-form" onSubmit={onSubmit} noValidate>
        {status === "error" && (
          <div className="inq-error" role="alert">{errorMsg}</div>
        )}

        <div className="inq-row">
          <div className="inq-field">
            <label htmlFor="first_name">First name <span className="req">*</span></label>
            <input
              className={"inq-input" + (errors.first_name ? " invalid" : "")}
              id="first_name" type="text" autoComplete="given-name"
              value={form.first_name} onChange={(e) => set("first_name", e.target.value)}
            />
            {errors.first_name && <span className="inq-field-error">{errors.first_name}</span>}
          </div>
          <div className="inq-field">
            <label htmlFor="last_name">Last name <span className="req">*</span></label>
            <input
              className={"inq-input" + (errors.last_name ? " invalid" : "")}
              id="last_name" type="text" autoComplete="family-name"
              value={form.last_name} onChange={(e) => set("last_name", e.target.value)}
            />
            {errors.last_name && <span className="inq-field-error">{errors.last_name}</span>}
          </div>
        </div>

        <div className="inq-row">
          <div className="inq-field">
            <label htmlFor="email">Email <span className="req">*</span></label>
            <input
              className={"inq-input" + (errors.email ? " invalid" : "")}
              id="email" type="email" autoComplete="email"
              value={form.email} onChange={(e) => set("email", e.target.value)}
            />
            {errors.email && <span className="inq-field-error">{errors.email}</span>}
          </div>
          <div className="inq-field">
            <label htmlFor="phone">Phone <span className="inq-hint">(optional)</span></label>
            <input
              className="inq-input" id="phone" type="tel" autoComplete="tel"
              value={form.phone} onChange={(e) => set("phone", e.target.value)}
            />
          </div>
        </div>

        <div className="inq-field">
          <label htmlFor="rel">Your relationship with the project</label>
          <select className="inq-select" id="rel"
            value={form.your_relationship_with_the_project}
            onChange={(e) => set("your_relationship_with_the_project", e.target.value)}>
            <option value="">Select one…</option>
            {REL_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>

        <div className="inq-field">
          <label htmlFor="phase">Your project's current build phase</label>
          <select className="inq-select" id="phase"
            value={form.your_projects_current_build_phase}
            onChange={(e) => set("your_projects_current_build_phase", e.target.value)}>
            <option value="">Select one…</option>
            {PHASE_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>

        <fieldset className="inq-fieldset">
          <legend>Your lighting needs</legend>
          <div className="inq-checks">
            {LIGHTING_OPTIONS.map((o) => (
              <label className="inq-check" key={o}>
                <input type="checkbox"
                  checked={form.your_lightning_needs.includes(o)}
                  onChange={() => toggleLighting(o)} />
                {o}
              </label>
            ))}
          </div>
        </fieldset>

        <div className="inq-field">
          <label htmlFor="budget">Project budget</label>
          <select className="inq-select" id="budget"
            value={form.project_budget} onChange={(e) => set("project_budget", e.target.value)}>
            <option value="">Select one…</option>
            {BUDGET_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>

        <div className="inq-field">
          <label htmlFor="draw">Do you have construction drawings?</label>
          <select className="inq-select" id="draw"
            value={form.do_you_have_construction_drawings}
            onChange={(e) => set("do_you_have_construction_drawings", e.target.value)}>
            <option value="">Select one…</option>
            {DRAWINGS_OPTIONS.map((o) => <option key={o} value={o}>{o}</option>)}
          </select>
        </div>

        <div className="inq-field">
          <label htmlFor="message">Your vision <span className="inq-hint">(optional)</span></label>
          <textarea className="inq-textarea" id="message"
            placeholder="A few words about the residence, the rooms, and the atmosphere you're hoping to create."
            value={form.message} onChange={(e) => set("message", e.target.value)} />
        </div>

        {/* Honeypot — hidden from humans, attractive to bots */}
        <div className="inq-gotcha" aria-hidden="true">
          <label>Company
            <input type="text" name="company" tabIndex={-1} autoComplete="off"
              value={form.company} onChange={(e) => set("company", e.target.value)} />
          </label>
        </div>

        <div className="inq-actions">
          <button className="btn btn-primary" type="submit" disabled={sending}>
            {sending ? "Sending…" : <>Schedule a Consultation <span className="arrow">→</span></>}
          </button>
          <span className="inq-fallback-note">Prefer email? <a href="mailto:hello@halelumina.com">hello@halelumina.com</a></span>
        </div>
      </form>

      <p className="inq-foothint">Maui · Hawai‘i &nbsp;·&nbsp; <a href="Home.html">Return to halelumina.com</a></p>
    </div>
  );
}

Object.assign(window, { InquiryForm });
