/* global React, ReactDOM */

// ============================================================================
//  Contact modal — multi-step form → Make.com webhook
//  Open by calling window.openContactModal() or dispatching 'vg:open-contact'
// ============================================================================

const CF_CONFIG = {
  // Replace with real Make.com webhook URL before going live
  WEBHOOK_URL: "https://hook.eu1.make.com/0b2f112fl9gk55lkqr0jqoaaokkjytwe",
  GITHUB_URL:  "https://github.com/volograms",
  TOPICS: [
    { label: "Vologram Studio",               sub: "Multi-camera volumetric capture"  },
    { label: "Vologram Creator",              sub: "Single-camera volumetric content" },
    { label: "Licensing our technology",      sub: ""                                  },
    { label: "Developer resources / plugins", sub: ""                                  },
    { label: "Something else",                sub: ""                                  }
  ]
};

const CF_OTHER    = "Something else";
const CF_DEV      = "Developer resources / plugins";
const CF_EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const CF_STEPS    = 5;
const CF_BLANK    = { email: "", topic: "", otherText: "", idea: "", consent: null };

function ContactModal() {
  const [open,       setOpen]       = React.useState(false);
  const [step,       setStep]       = React.useState(0);
  const [form,       setForm]       = React.useState(CF_BLANK);
  const [emailErr,   setEmailErr]   = React.useState("");
  const [submitErr,  setSubmitErr]  = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [done,       setDone]       = React.useState(false);

  const emailRef    = React.useRef(null);
  const honeypotRef = React.useRef(null);

  function openModal() {
    setOpen(true);
    setStep(0);
    setForm(Object.assign({}, CF_BLANK));
    setEmailErr(""); setSubmitErr(""); setDone(false);
  }

  React.useEffect(function() {
    window.openContactModal = openModal;
    window.addEventListener("vg:open-contact", openModal);
    return function() { window.removeEventListener("vg:open-contact", openModal); };
  }, []);

  React.useEffect(function() {
    document.body.style.overflow = open ? "hidden" : "";
    return function() { document.body.style.overflow = ""; };
  }, [open]);

  React.useEffect(function() {
    if (open && step === 1) {
      var t = setTimeout(function() { emailRef.current && emailRef.current.focus(); }, 60);
      return function() { clearTimeout(t); };
    }
  }, [open, step]);

  function set(key, val) {
    setForm(function(f) { return Object.assign({}, f, { [key]: val }); });
  }

  function advance() {
    if (step === 1) {
      var v = form.email.trim();
      if (!CF_EMAIL_RE.test(v)) {
        setEmailErr("Please enter a valid email address.");
        emailRef.current && emailRef.current.focus();
        return;
      }
      setEmailErr("");
      setForm(function(f) { return Object.assign({}, f, { email: v }); });
    }
    if (step === 2 && !form.topic) return;
    if (step === 4) { doSubmit(); return; }
    setStep(function(s) { return s + 1; });
  }

  // Single document-level keyboard handler — works regardless of focus
  React.useEffect(function() {
    if (!open) return;
    function onKey(e) {
      if (e.key === "Escape") { setOpen(false); return; }

      // Number shortcuts on the topic step
      if (step === 2 && e.key >= "1" && e.key <= "5") {
        var idx = parseInt(e.key, 10) - 1;
        if (idx < CF_CONFIG.TOPICS.length) set("topic", CF_CONFIG.TOPICS[idx].label);
        return;
      }
      // 1/2 shortcuts on the consent step
      if (step === 4 && (e.key === "1" || e.key === "2")) {
        set("consent", e.key === "1");
        return;
      }

      if (e.key !== "Enter") return;

      if (e.target.tagName === "TEXTAREA") {
        if (e.shiftKey) return; // Shift+Enter → newline
        e.preventDefault();
        advance();
        return;
      }
      // cf-opt and cf-consent buttons handle their own Enter (select/toggle)
      // but shouldn't advance — user presses Enter again from elsewhere to advance
      if (e.target.classList.contains("cf-opt")) return;
      if (e.target.classList.contains("cf-consent")) return;
      if (e.target.classList.contains("cf-back")) return;
      if (e.target.classList.contains("cf-close")) return;

      e.preventDefault();
      advance();
    }
    document.addEventListener("keydown", onKey);
    return function() { document.removeEventListener("keydown", onKey); };
  }, [open, step, form, submitting, done]);

  async function doSubmit() {
    if (honeypotRef.current && honeypotRef.current.value) {
      setDone(true); return;
    }
    setSubmitting(true); setSubmitErr("");
    var payload = {
      email:       form.email,
      topic:       form.topic,
      otherText:   form.topic === CF_OTHER ? form.otherText : "",
      idea:        form.idea,
      consent:     form.consent === true,
      submittedAt: new Date().toISOString()
    };
    try {
      var res = await fetch(CF_CONFIG.WEBHOOK_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      setDone(true);
    } catch (e) {
      setSubmitErr("Something went wrong. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  if (!open) return null;

  var modal = (
    <div
      className="cf-backdrop"
      onClick={function(e) { if (e.target === e.currentTarget) setOpen(false); }}
    >
      {/* Honeypot — hidden from humans, bots fill it */}
      <div style={{ position: "absolute", left: "-9999px", width: "1px", overflow: "hidden" }} aria-hidden="true">
        <label>Leave this empty <input ref={honeypotRef} type="text" tabIndex="-1" autoComplete="off"/></label>
      </div>

      <div className="cf-modal" role="dialog" aria-modal="true" aria-label="Get in touch">

        <button className="cf-close" type="button" onClick={function() { setOpen(false); }} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M18 6 6 18M6 6l12 12"/>
          </svg>
        </button>

        {!done && (
          <div className="cf-progress" aria-hidden="true">
            {Array.from({ length: CF_STEPS }).map(function(_, i) {
              return <span key={i} className={i <= step ? "on" : ""}/>;
            })}
          </div>
        )}

        <div className="cf-body" aria-live="polite">
          {done ? (
            <div className="cf-done">
              <div className="cf-done__icon">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 6 9 17l-5-5"/>
                </svg>
              </div>
              <h2 className="cf-done__title">Thanks — we'll be in touch!</h2>
              <p className="cf-done__sub">Your details have been sent. Expect a reply within a business day.</p>
              <button className="btn btn--primary btn--sm" style={{ marginTop: "24px" }} type="button" onClick={function() { setOpen(false); }}>
                Close
              </button>
            </div>

          ) : step === 0 ? (
            <div>
              <p className="cf-q">Interested in one of our products?</p>
              <p className="cf-sub">Answer a few short questions and we'll get in touch with you.</p>
            </div>

          ) : step === 1 ? (
            <div>
              <label className="cf-q" htmlFor="cf-email">
                What's your professional email? <span className="cf-req">*</span>
              </label>
              <p className="cf-sub">We'll only use this to reply to you.</p>
              <input
                ref={emailRef}
                className={"cf-input" + (emailErr ? " cf-input--err" : "")}
                id="cf-email"
                type="email"
                autoComplete="email"
                placeholder="you@company.com"
                value={form.email}
                onChange={function(e) { set("email", e.target.value); setEmailErr(""); }}
              />
              {emailErr && <p className="cf-err" role="alert">{emailErr}</p>}
            </div>

          ) : step === 2 ? (
            <div>
              <p className="cf-q">What can we help you with?</p>
              <p className="cf-sub">Choose the main thing.</p>
              <div className="cf-options" role="radiogroup" aria-label="Topic">
                {CF_CONFIG.TOPICS.map(function(t, i) {
                  var sel = form.topic === t.label;
                  return (
                    <button
                      key={t.label}
                      type="button"
                      role="radio"
                      aria-checked={sel}
                      className={"cf-opt" + (sel ? " sel" : "")}
                      onClick={function() { set("topic", t.label); }}
                    >
                      <span className="cf-opt__num">{i + 1}</span>
                      <span className="cf-opt__dot"/>
                      <span>
                        <span className="cf-opt__label">{t.label}</span>
                        {t.sub && <span className="cf-opt__sub">{t.sub}</span>}
                      </span>
                    </button>
                  );
                })}
              </div>
              {form.topic === CF_OTHER && (
                <input
                  className="cf-input"
                  style={{ marginTop: "10px" }}
                  type="text"
                  placeholder="Tell us what you're after…"
                  value={form.otherText}
                  onChange={function(e) { set("otherText", e.target.value); }}
                  autoFocus
                />
              )}
              {!form.topic && <p className="cf-hint">Choose one to continue.</p>}
            </div>

          ) : step === 3 ? (
            <div>
              {form.topic === CF_DEV && (
                <div className="cf-devnote">
                  <p className="cf-devnote__title">This might be all you need</p>
                  <p className="cf-devnote__body">
                    Our plugins and developer resources live on GitHub:{" "}
                    <a href={CF_CONFIG.GITHUB_URL} target="_blank" rel="noopener">github.com/volograms</a>.
                    {" "}Head there now — or tell us more below if you'd like us to follow up.
                  </p>
                </div>
              )}
              <label className="cf-q" htmlFor="cf-idea">Anything specific you have in mind?</label>
              <p className="cf-sub">Tell us a bit more so we can respond better. Optional.</p>
              <textarea
                className="cf-textarea"
                id="cf-idea"
                rows="4"
                placeholder="A few sentences is plenty…"
                value={form.idea}
                onChange={function(e) { set("idea", e.target.value); }}
              />
            </div>

          ) : step === 4 ? (
            <div>
              <p className="cf-q">Last one — would you like to stay in touch?</p>
              <p className="cf-sub">We'll send occasional updates about Volograms. Unsubscribe anytime.</p>
              <div className="cf-options" role="radiogroup" aria-label="Marketing consent">
                <button
                  type="button"
                  role="radio"
                  aria-checked={form.consent === true}
                  className={"cf-opt" + (form.consent === true ? " sel" : "")}
                  onClick={function() { set("consent", true); }}
                >
                  <span className="cf-opt__num">1</span>
                  <span className="cf-opt__dot"/>
                  <span><span className="cf-opt__label">Yes, keep me in the loop</span></span>
                </button>
                <button
                  type="button"
                  role="radio"
                  aria-checked={form.consent === false}
                  className={"cf-opt" + (form.consent === false ? " sel" : "")}
                  onClick={function() { set("consent", false); }}
                >
                  <span className="cf-opt__num">2</span>
                  <span className="cf-opt__dot"/>
                  <span><span className="cf-opt__label">No thanks</span></span>
                </button>
              </div>
              {submitErr && <p className="cf-err" role="alert">{submitErr}</p>}
            </div>

          ) : null}
        </div>

        {!done && (
          <div className="cf-foot">
            <button
              type="button"
              className="cf-back"
              style={{ visibility: step > 0 ? "visible" : "hidden" }}
              onClick={function() { setStep(function(s) { return s - 1; }); }}
            >
              ← Back
            </button>
            <span className="cf-count">{step + 1} / {CF_STEPS}</span>
            <button
              type="button"
              className={"btn btn--sm " + (step === 4 ? "btn--gradient" : "btn--primary")}
              onClick={advance}
              disabled={submitting || (step === 2 && !form.topic)}
            >
              {step === 0
                ? "Let's go"
                : step === 4
                  ? (submitting ? "Sending…" : "Submit")
                  : "Next →"}
            </button>
          </div>
        )}
      </div>
    </div>
  );

  return ReactDOM.createPortal(modal, document.body);
}

Object.assign(window, { ContactModal });
